writeFileTool function
Creates the write tool: creates or overwrites a file, creating parent
directories as needed.
Implementation
AgentTool writeFileTool(ExecutionEnv env) {
return AgentTool(
name: 'write',
label: 'write',
tier: ApprovalTier.write,
description:
'Write content to a file, creating parent directories as needed. '
'Overwrites the file if it already exists.',
parameters: const {
'type': 'object',
'properties': {
'path': {
'type': 'string',
'description': 'Path to the file to write (relative or absolute)',
},
'content': {
'type': 'string',
'description': 'Content to write to the file',
},
},
'required': ['path', 'content'],
},
execute: (arguments, cancelToken, onUpdate) async {
cancelToken?.throwIfCancelled();
final path = arguments['path'] as String;
final content = arguments['content'] as String;
// Issue #1083: hold the per-path lock across the whole mutation so a
// concurrent same-file tool call queues behind it instead of racing.
return _pathMutationLock.run(await _canonicalPath(env, path), () async {
// Re-check after the lock wait: the queue can span a cancel, and a
// cancelled call must not run its mutation once its turn arrives.
cancelToken?.throwIfCancelled();
final written = await env.writeFile(path, content);
if (written.isErr) throw StateError('${written.errorOrNull}');
return ToolExecutionResult.text(
'Successfully wrote ${_byteLength(content)} bytes to $path',
);
});
},
);
}