operon-agents-core 0.1.0-alpha.2 → 0.1.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/agent.d.ts +8 -7
- package/dist/agent/compose-hooks.d.ts +10 -1
- package/dist/agent/compose-hooks.js +61 -6
- package/dist/agent/concurrency.js +1 -1
- package/dist/agent/context-report.d.ts +2 -2
- package/dist/agent/durable-state.d.ts +22 -0
- package/dist/agent/durable-state.js +54 -0
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +1 -1
- package/dist/agent/instruction-context.d.ts +6 -6
- package/dist/agent/instruction-context.js +23 -23
- package/dist/agent/profile-builtins.js +1 -1
- package/dist/agent/run-support.d.ts +1 -1
- package/dist/agent/run-support.js +6 -5
- package/dist/agent/runner.d.ts +25 -22
- package/dist/agent/runner.js +217 -121
- package/dist/agent/session.d.ts +262 -156
- package/dist/agent/session.js +590 -418
- package/dist/agent/subagent-tools.js +3 -3
- package/dist/agent/subagent.js +28 -13
- package/dist/agent/toolset.d.ts +1 -0
- package/dist/agent/toolset.js +13 -7
- package/dist/agent/workflow/journal.d.ts +2 -2
- package/dist/agent/workflow/journal.js +2 -2
- package/dist/agent/workflow/manager.d.ts +1 -1
- package/dist/agent/workflow/manager.js +1 -1
- package/dist/agent/workflow/prompt.js +2 -2
- package/dist/agent/workflow/sandbox.d.ts +1 -1
- package/dist/agent/workflow/sandbox.js +1 -1
- package/dist/agent/workflow/tool.js +30 -43
- package/dist/agent/worktree.d.ts +8 -8
- package/dist/agent/worktree.js +15 -15
- package/dist/capabilities/assembler.d.ts +29 -5
- package/dist/capabilities/assembler.js +85 -9
- package/dist/capabilities/background/code-task.d.ts +43 -0
- package/dist/capabilities/background/code-task.js +75 -0
- package/dist/capabilities/background/command-task.d.ts +9 -2
- package/dist/capabilities/background/command-task.js +22 -6
- package/dist/capabilities/background/index.d.ts +6 -1
- package/dist/capabilities/background/index.js +26 -20
- package/dist/capabilities/background/manager.d.ts +57 -1
- package/dist/capabilities/background/manager.js +210 -45
- package/dist/capabilities/background/persist-disk.d.ts +1 -1
- package/dist/capabilities/background/persist-disk.js +1 -1
- package/dist/capabilities/background/persist.js +4 -2
- package/dist/capabilities/background/projections.d.ts +16 -0
- package/dist/capabilities/background/projections.js +86 -0
- package/dist/capabilities/background/stall-watchdog.d.ts +41 -0
- package/dist/capabilities/background/stall-watchdog.js +85 -0
- package/dist/capabilities/background/task.d.ts +8 -7
- package/dist/capabilities/background/tools.js +33 -7
- package/dist/capabilities/capability-data.d.ts +52 -0
- package/dist/capabilities/capability-data.js +88 -0
- package/dist/capabilities/capability-state.d.ts +2 -4
- package/dist/capabilities/capability-state.js +5 -23
- package/dist/capabilities/capability.d.ts +203 -38
- package/dist/capabilities/compaction/index.js +10 -4
- package/dist/capabilities/compaction/service.d.ts +20 -5
- package/dist/capabilities/compaction/service.js +27 -11
- package/dist/capabilities/goal/goal-store.d.ts +76 -12
- package/dist/capabilities/goal/goal-store.js +137 -53
- package/dist/capabilities/goal/index.d.ts +1 -1
- package/dist/capabilities/goal/index.js +30 -7
- package/dist/capabilities/index.d.ts +9 -6
- package/dist/capabilities/index.js +4 -3
- package/dist/capabilities/plan/index.js +22 -5
- package/dist/capabilities/plan/plan-mode.d.ts +30 -9
- package/dist/capabilities/plan/plan-mode.js +57 -32
- package/dist/capabilities/plan/tools.js +1 -1
- package/dist/capabilities/skills/flow-provider.js +3 -3
- package/dist/capabilities/skills/index.d.ts +13 -1
- package/dist/capabilities/skills/index.js +30 -21
- package/dist/capabilities/skills/parser.d.ts +2 -2
- package/dist/capabilities/skills/parser.js +3 -3
- package/dist/capabilities/skills/registry.d.ts +5 -6
- package/dist/capabilities/skills/registry.js +6 -9
- package/dist/capabilities/skills/scanner.d.ts +3 -3
- package/dist/capabilities/skills/scanner.js +14 -14
- package/dist/capabilities/skills/service.d.ts +2 -1
- package/dist/capabilities/skills/service.js +3 -3
- package/dist/capabilities/skills/skill-tool.d.ts +2 -0
- package/dist/capabilities/skills/skill-tool.js +1 -1
- package/dist/capabilities/task/index.js +2 -1
- package/dist/capabilities/task/persist-disk.d.ts +1 -1
- package/dist/capabilities/task/persist-disk.js +1 -1
- package/dist/capabilities/task/persist.js +1 -1
- package/dist/capabilities/todo/index.js +11 -6
- package/dist/capabilities/todo/injector.js +2 -1
- package/dist/capabilities/todo/todo-store.d.ts +28 -7
- package/dist/capabilities/todo/todo-store.js +44 -11
- package/dist/capabilities/todo/tools.js +8 -3
- package/dist/capabilities/tool-provider.d.ts +3 -3
- package/dist/capabilities/user-hooks/engine.d.ts +3 -3
- package/dist/capabilities/user-hooks/engine.js +7 -7
- package/dist/capabilities/user-hooks/index.js +2 -1
- package/dist/capabilities/workflow/index.d.ts +5 -3
- package/dist/capabilities/workflow/index.js +3 -2
- package/dist/commands/index.js +34 -32
- package/dist/config/index.d.ts +1 -1
- package/dist/config/provider-manager.js +0 -28
- package/dist/config/schema.d.ts +53 -4
- package/dist/config/schema.js +53 -1
- package/dist/events/events.d.ts +43 -11
- package/dist/events/events.js +1 -0
- package/dist/events/index.d.ts +2 -2
- package/dist/events/index.js +1 -1
- package/dist/events/projection.d.ts +49 -1
- package/dist/events/projection.js +144 -19
- package/dist/events/publisher.js +2 -21
- package/dist/home.d.ts +1 -1
- package/dist/home.js +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/internal.d.ts +5 -2
- package/dist/internal.js +5 -2
- package/dist/llm/define-model.d.ts +4 -0
- package/dist/llm/define-model.js +63 -25
- package/dist/llm/index.d.ts +1 -0
- package/dist/llm/index.js +1 -0
- package/dist/llm/model.d.ts +2 -0
- package/dist/llm/provider.d.ts +17 -0
- package/dist/llm/provider.js +14 -0
- package/dist/llm/retry.js +1 -1
- package/dist/loop/context.d.ts +21 -1
- package/dist/loop/context.js +47 -9
- package/dist/loop/events.d.ts +5 -1
- package/dist/loop/index.d.ts +2 -2
- package/dist/loop/index.js +1 -1
- package/dist/loop/interruption.d.ts +9 -4
- package/dist/loop/interruption.js +11 -25
- package/dist/loop/run-turn.d.ts +16 -3
- package/dist/loop/run-turn.js +13 -4
- package/dist/loop/steer.d.ts +78 -12
- package/dist/loop/steer.js +101 -38
- package/dist/loop/tool-call.d.ts +13 -2
- package/dist/loop/tool-call.js +135 -5
- package/dist/loop/turn-step.d.ts +13 -2
- package/dist/loop/turn-step.js +29 -7
- package/dist/loop/types.d.ts +6 -0
- package/dist/mcp/auth-tool.d.ts +3 -1
- package/dist/mcp/auth-tool.js +2 -2
- package/dist/mcp/capability.d.ts +13 -0
- package/dist/mcp/capability.js +36 -17
- package/dist/mcp/config-loader.d.ts +5 -5
- package/dist/mcp/config-loader.js +17 -17
- package/dist/mcp/credentials.d.ts +35 -0
- package/dist/mcp/credentials.js +2 -0
- package/dist/mcp/filter.d.ts +2 -2
- package/dist/mcp/index.d.ts +4 -3
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/manager.d.ts +108 -6
- package/dist/mcp/manager.js +262 -18
- package/dist/mcp/oauth/callback-server.d.ts +10 -1
- package/dist/mcp/oauth/callback-server.js +82 -16
- package/dist/mcp/oauth/index.d.ts +2 -2
- package/dist/mcp/oauth/provider.d.ts +18 -0
- package/dist/mcp/oauth/provider.js +31 -1
- package/dist/mcp/oauth/service.d.ts +9 -3
- package/dist/mcp/oauth/service.js +29 -4
- package/dist/mcp/sdk-transport.js +1 -1
- package/dist/mcp/server.js +1 -1
- package/dist/permission/auto-approver/prompts-data.d.ts +1 -1
- package/dist/permission/auto-approver/prompts-data.js +1 -1
- package/dist/permission/manager.d.ts +5 -3
- package/dist/permission/manager.js +7 -3
- package/dist/permission/policies.d.ts +2 -2
- package/dist/permission/policies.js +4 -4
- package/dist/plugins/fields.d.ts +14 -0
- package/dist/plugins/fields.js +30 -0
- package/dist/plugins/hooks.d.ts +2 -2
- package/dist/plugins/hooks.js +12 -12
- package/dist/plugins/index.js +1 -0
- package/dist/plugins/manager.d.ts +8 -3
- package/dist/plugins/manager.js +18 -7
- package/dist/plugins/manifest.d.ts +2 -2
- package/dist/plugins/manifest.js +101 -91
- package/dist/plugins/marketplace.js +76 -57
- package/dist/plugins/store.d.ts +3 -3
- package/dist/plugins/store.js +6 -6
- package/dist/protocol/index.d.ts +1 -1
- package/dist/store/catalog-store.d.ts +4 -1
- package/dist/store/catalog-store.js +5 -1
- package/dist/store/checkpointing-store.d.ts +41 -0
- package/dist/store/checkpointing-store.js +86 -0
- package/dist/store/disk-store.d.ts +8 -0
- package/dist/store/disk-store.js +127 -5
- package/dist/store/index.d.ts +3 -2
- package/dist/store/index.js +2 -1
- package/dist/store/log-store.d.ts +9 -1
- package/dist/store/log-store.js +68 -4
- package/dist/store/migrate.d.ts +8 -2
- package/dist/store/migrate.js +9 -2
- package/dist/store/origin.d.ts +31 -6
- package/dist/store/origin.js +0 -14
- package/dist/store/pg.d.ts +1 -0
- package/dist/store/pg.js +37 -2
- package/dist/store/redis.d.ts +1 -0
- package/dist/store/redis.js +30 -0
- package/dist/store/repository.d.ts +13 -1
- package/dist/store/repository.js +45 -2
- package/dist/store/session-catalog.d.ts +4 -0
- package/dist/store/session-catalog.js +6 -0
- package/dist/store/storage.js +3 -0
- package/dist/store/store.d.ts +97 -34
- package/dist/store/store.js +64 -10
- package/dist/telemetry/appender.d.ts +43 -0
- package/dist/telemetry/appender.js +46 -0
- package/dist/telemetry/events.d.ts +142 -0
- package/dist/telemetry/events.js +141 -0
- package/dist/telemetry/index.d.ts +10 -0
- package/dist/telemetry/index.js +6 -0
- package/dist/telemetry/projection.d.ts +23 -0
- package/dist/telemetry/projection.js +185 -0
- package/dist/telemetry/redact.d.ts +20 -0
- package/dist/telemetry/redact.js +40 -0
- package/dist/telemetry/service.d.ts +49 -0
- package/dist/telemetry/service.js +137 -0
- package/dist/testing.d.ts +58 -0
- package/dist/testing.js +123 -0
- package/dist/tool/background.d.ts +9 -6
- package/dist/tool/background.js +7 -1
- package/dist/tool/builtin/ask-user-question.js +6 -5
- package/dist/tool/builtin/bash.d.ts +6 -0
- package/dist/tool/builtin/bash.js +79 -42
- package/dist/tool/builtin/edit.js +82 -109
- package/dist/tool/builtin/glob.js +13 -13
- package/dist/tool/builtin/grep.js +13 -13
- package/dist/tool/builtin/read.js +25 -15
- package/dist/tool/builtin/write.js +49 -33
- package/dist/tool/define.d.ts +14 -8
- package/dist/tool/define.js +8 -2
- package/dist/tool/{machine-base.d.ts → environment-base.d.ts} +37 -37
- package/dist/tool/{machine-base.js → environment-base.js} +45 -119
- package/dist/tool/{machine-local.d.ts → environment-local.d.ts} +9 -8
- package/dist/tool/{machine-local.js → environment-local.js} +60 -81
- package/dist/tool/{machine-null.d.ts → environment-null.d.ts} +9 -9
- package/dist/tool/{machine-null.js → environment-null.js} +9 -9
- package/dist/tool/{machine-ssh.d.ts → environment-ssh.d.ts} +33 -18
- package/dist/tool/{machine-ssh.js → environment-ssh.js} +118 -149
- package/dist/tool/{machine.d.ts → environment.d.ts} +53 -82
- package/dist/tool/environment.js +2 -0
- package/dist/tool/file-freshness.d.ts +33 -19
- package/dist/tool/file-freshness.js +39 -30
- package/dist/tool/filesystem-tools.d.ts +1 -1
- package/dist/tool/filesystem-tools.js +1 -1
- package/dist/tool/git-context.d.ts +2 -2
- package/dist/tool/git-context.js +8 -8
- package/dist/tool/index.d.ts +12 -12
- package/dist/tool/index.js +12 -10
- package/dist/tool/policies/path-access.d.ts +4 -4
- package/dist/tool/policies/path-access.js +12 -12
- package/dist/tool/questions.d.ts +8 -0
- package/dist/tool/search/catalog.d.ts +37 -0
- package/dist/tool/search/catalog.js +182 -0
- package/dist/tool/search/deferral.d.ts +3 -2
- package/dist/tool/search/loaded.d.ts +32 -0
- package/dist/tool/search/loaded.js +96 -0
- package/dist/tool/search/search-tool.d.ts +2 -6
- package/dist/tool/search/search-tool.js +16 -15
- package/dist/tool/shell-env.js +4 -0
- package/dist/tool/support/bash-paths.js +38 -7
- package/dist/tool/support/{machine-ops.d.ts → environment-ops.d.ts} +12 -14
- package/dist/tool/support/{machine-ops.js → environment-ops.js} +21 -2
- package/dist/tool/support/git-worktree.d.ts +3 -3
- package/dist/tool/support/git-worktree.js +6 -6
- package/dist/tool/support/rg-locator.d.ts +6 -6
- package/dist/tool/support/rg-locator.js +6 -6
- package/dist/tool/support/ripgrep-run.d.ts +5 -5
- package/dist/tool/support/ripgrep-run.js +3 -3
- package/dist/tool/support/tool-path.d.ts +3 -3
- package/dist/tool/support/tool-path.js +7 -7
- package/dist/tool/types.d.ts +54 -10
- package/dist/tool/web/fetch-url.js +1 -1
- package/dist/tool/web/web-search.js +1 -1
- package/dist/tool/workspace-spec.d.ts +3 -3
- package/dist/tool/workspace-spec.js +27 -27
- package/dist/tracing/bridge.d.ts +9 -1
- package/dist/tracing/bridge.js +307 -77
- package/dist/tracing/index.d.ts +2 -2
- package/dist/tracing/otel.d.ts +28 -1
- package/dist/tracing/otel.js +150 -38
- package/dist/tracing/processor.d.ts +22 -0
- package/dist/tracing/processor.js +2 -0
- package/dist/tracing/spans.d.ts +54 -0
- package/dist/tracing/spans.js +5 -0
- package/package.json +6 -2
- package/dist/tool/machine.js +0 -15
- package/dist/tool/search/activation.d.ts +0 -13
- package/dist/tool/search/activation.js +0 -31
package/dist/tool/background.js
CHANGED
|
@@ -27,8 +27,14 @@ export async function runCommandInline(start, options) {
|
|
|
27
27
|
onOutput: (chunk) => options.onLive?.(chunk),
|
|
28
28
|
});
|
|
29
29
|
// `run` reports its OWN timeout too; either route means the same thing to the caller.
|
|
30
|
+
const stopped = timedOut || result.timedOut || options.foregroundSignal.aborted;
|
|
30
31
|
const status = timedOut || result.timedOut ? "timed_out" : options.foregroundSignal.aborted ? "killed" : result.exitCode === 0 ? "completed" : "failed";
|
|
31
|
-
return {
|
|
32
|
+
return {
|
|
33
|
+
kind: "settled",
|
|
34
|
+
status,
|
|
35
|
+
exitCode: result.exitCode ?? null,
|
|
36
|
+
...(stopped && !result.terminated ? { stillRunning: true } : {}),
|
|
37
|
+
};
|
|
32
38
|
}
|
|
33
39
|
finally {
|
|
34
40
|
if (timer !== undefined)
|
|
@@ -92,11 +92,12 @@ export const askUserQuestionTool = defineTool({
|
|
|
92
92
|
"next_step: Use BackgroundOutput with this task_id for a non-blocking status/answer snapshot.",
|
|
93
93
|
].join("\n"));
|
|
94
94
|
}
|
|
95
|
-
// No responder at all (headless / durable session):
|
|
96
|
-
// questions surface on the paused run and the answer
|
|
97
|
-
// A responder WITHOUT requestQuestion stays the
|
|
98
|
-
//
|
|
99
|
-
|
|
95
|
+
// No responder at all, or one that says nobody is attached (headless / durable session):
|
|
96
|
+
// suspend instead of failing — the questions surface on the paused run and the answer
|
|
97
|
+
// comes back through Runner.resume. A LIVE responder WITHOUT requestQuestion stays the
|
|
98
|
+
// soft-failure path below: that client is present but cannot render questions, so
|
|
99
|
+
// pausing durably would hang the conversation.
|
|
100
|
+
if (ctx.responder === undefined || ctx.responder.isLiveQuestioner?.() === false) {
|
|
100
101
|
ctx.suspend({ kind: "question", display: { questions: toQuestionItems(args.questions) } });
|
|
101
102
|
// suspend() must interrupt (typed `never`); a non-conforming context falling
|
|
102
103
|
// through would misreport the pause as the "unsupported" soft failure below.
|
|
@@ -1,2 +1,8 @@
|
|
|
1
|
+
import type { Environment } from "../environment.ts";
|
|
1
2
|
export declare const bashTool: import("../types.ts").Tool;
|
|
3
|
+
/** Allocate the canonical command log before the user's process starts. The shell only owns
|
|
4
|
+
* appending command output; directory/file setup failures therefore fail the tool cleanly
|
|
5
|
+
* instead of escaping through an uncaptured outer stderr stream. */
|
|
6
|
+
/** Create an empty task log on the environment and return its path — where a background program or command writes its output. */
|
|
7
|
+
export declare function prepareBackgroundLog(environment: Environment): Promise<string>;
|
|
2
8
|
//# sourceMappingURL=bash.d.ts.map
|
|
@@ -53,6 +53,7 @@ const BASH_DESCRIPTION = [
|
|
|
53
53
|
"**Guidelines for safety and security:**",
|
|
54
54
|
"- Each shell tool call will be executed in a fresh shell environment. The shell variables, current working directory changes, and the shell history is not preserved between calls.",
|
|
55
55
|
`- The tool call will return after the command is finished. You shall not use this tool to execute an interactive command or a command that may run forever. For possibly long-running foreground commands, set the \`timeout\` argument in seconds. Foreground commands default to ${String(DEFAULT_TIMEOUT_S)}s and allow up to ${String(MAX_TIMEOUT_S)}s.`,
|
|
56
|
+
"- Commands get no terminal and stdin is empty, so nothing can answer a prompt. Never use interactive flags such as `git rebase -i` or `git add -i`; pass input up front instead (`--yes`/`-y`, `printf 'y\\n' | command`).",
|
|
56
57
|
"- Avoid using `..` to access files or directories outside of the working directory.",
|
|
57
58
|
"- Avoid modifying files outside of the working directory unless explicitly instructed to do so.",
|
|
58
59
|
"- Never run commands that require superuser privileges unless explicitly instructed to do so.",
|
|
@@ -93,7 +94,7 @@ export const bashTool = defineTool({
|
|
|
93
94
|
// What the command is read to touch. Best-effort by nature (see bash-paths.ts): this is
|
|
94
95
|
// what lets the sensitive-file / git-control-path / write-outside-cwd policies see a Bash
|
|
95
96
|
// call at all, which they otherwise skip entirely for want of anything to inspect.
|
|
96
|
-
accesses: commandAccesses(args, ctx.
|
|
97
|
+
accesses: commandAccesses(args, ctx.environment),
|
|
97
98
|
// `warning` is advisory only — nothing branches on it. It rides on the plan so whatever
|
|
98
99
|
// renders the approval can show the caller why this command deserves a second look.
|
|
99
100
|
display: {
|
|
@@ -103,7 +104,7 @@ export const bashTool = defineTool({
|
|
|
103
104
|
},
|
|
104
105
|
approvalRule: `Bash(${escapeRuleSubjectLiteral(args.command)})`,
|
|
105
106
|
matchesRule: (ruleArgs) => matchesBashRule(ruleArgs, args.command),
|
|
106
|
-
run: (runCtx) => execute(args, runCtx.
|
|
107
|
+
run: (runCtx) => execute(args, runCtx.environment, runCtx.signal, runCtx.background, runCtx.onUpdate, runCtx.detachSignal, runCtx.address, runCtx.toolCallId),
|
|
107
108
|
};
|
|
108
109
|
},
|
|
109
110
|
});
|
|
@@ -115,15 +116,15 @@ export const bashTool = defineTool({
|
|
|
115
116
|
* for the same reason. Anything that cannot be resolved is dropped rather than guessed at —
|
|
116
117
|
* see bash-paths.ts on why silence is the correct failure mode here.
|
|
117
118
|
*/
|
|
118
|
-
function commandAccesses(args,
|
|
119
|
+
function commandAccesses(args, environment) {
|
|
119
120
|
const found = extractBashPaths(args.command);
|
|
120
121
|
if (found.length === 0)
|
|
121
122
|
return ToolAccesses.none();
|
|
122
|
-
const pathClass =
|
|
123
|
-
const base = args.cwd ??
|
|
123
|
+
const pathClass = environment.pathClass();
|
|
124
|
+
const base = args.cwd ?? environment.getcwd();
|
|
124
125
|
let home;
|
|
125
126
|
try {
|
|
126
|
-
home =
|
|
127
|
+
home = environment.gethome();
|
|
127
128
|
}
|
|
128
129
|
catch {
|
|
129
130
|
home = undefined;
|
|
@@ -160,53 +161,53 @@ function toAbsolute(path, base, home, pathClass) {
|
|
|
160
161
|
return p.normalize(p.join(base, value));
|
|
161
162
|
}
|
|
162
163
|
/** The argv + env overrides every bash invocation shares, whichever path ends up running it. */
|
|
163
|
-
function shellInvocation(
|
|
164
|
-
const isWindowsBash =
|
|
164
|
+
function shellInvocation(environment, effectiveCwd, command) {
|
|
165
|
+
const isWindowsBash = environment.osInfo.osKind === "Windows";
|
|
165
166
|
const shellCwd = isWindowsBash ? windowsPathToPosixPath(effectiveCwd) : effectiveCwd;
|
|
166
167
|
return {
|
|
167
|
-
argv: [
|
|
168
|
-
// Non-interactive overrides only; the
|
|
168
|
+
argv: [environment.osInfo.shellPath, "-c", `cd ${shellQuote(shellCwd)} && ${command}`],
|
|
169
|
+
// Non-interactive overrides only; the environment layers these over its ambient env (PATH +
|
|
169
170
|
// proxy vars ride through), so we don't ship the whole process environment downstream.
|
|
170
|
-
env: nonInteractiveShellEnv({ shellPath:
|
|
171
|
+
env: nonInteractiveShellEnv({ shellPath: environment.osInfo.shellPath }),
|
|
171
172
|
};
|
|
172
173
|
}
|
|
173
174
|
/** The same invocation, packaged for a spawner that owns the run's lifecycle (background,
|
|
174
175
|
* or foreground-attached-then-detachable). No timeout: those runs are bounded by the
|
|
175
176
|
* spawner's own foreground timer, or not at all once detached. */
|
|
176
|
-
function commandStarter(
|
|
177
|
-
const { argv, env } = shellInvocation(
|
|
178
|
-
return ({ signal, onOutput }) =>
|
|
177
|
+
function commandStarter(environment, effectiveCwd, command) {
|
|
178
|
+
const { argv, env } = shellInvocation(environment, effectiveCwd, command);
|
|
179
|
+
return ({ signal, onOutput }) => environment.run(argv, {
|
|
179
180
|
env,
|
|
180
181
|
signal,
|
|
181
182
|
...(onOutput !== undefined ? { onOutput: (chunk) => onOutput(chunk.data) } : {}),
|
|
182
183
|
});
|
|
183
184
|
}
|
|
184
|
-
async function execute(args,
|
|
185
|
+
async function execute(args, environment, signal, background, onUpdate, detachSignal, parentAddress, toolCallId) {
|
|
185
186
|
if (signal.aborted)
|
|
186
187
|
return errorResult("Aborted before command started");
|
|
187
188
|
if (args.command.length === 0)
|
|
188
189
|
return errorResult("Command cannot be empty.");
|
|
189
|
-
const isWindowsBash =
|
|
190
|
+
const isWindowsBash = environment.osInfo.osKind === "Windows";
|
|
190
191
|
const command = isWindowsBash ? rewriteWindowsNullRedirect(args.command) : args.command;
|
|
191
192
|
if (args.run_in_background) {
|
|
192
193
|
if (background === undefined) {
|
|
193
194
|
return errorResult("Background execution is not available for this agent (Task tools not enabled).");
|
|
194
195
|
}
|
|
195
|
-
// Redirect output to
|
|
196
|
+
// Redirect output to an Environment log file: the OS captures the stream (survives this
|
|
196
197
|
// process; detached commands keep logging), and the file — not process memory — is
|
|
197
198
|
// the output's home. The ack carries the path so it stays readable across restarts.
|
|
198
199
|
let logPath;
|
|
199
200
|
try {
|
|
200
|
-
logPath = await prepareBackgroundLog(
|
|
201
|
+
logPath = await prepareBackgroundLog(environment);
|
|
201
202
|
}
|
|
202
203
|
catch (error) {
|
|
203
204
|
return errorResult(error instanceof Error ? error.message : String(error));
|
|
204
205
|
}
|
|
205
206
|
const wrapped = `{ ${command}\n} > ${shellQuote(logPath)} 2>&1`;
|
|
206
207
|
const preview = args.command.length > 50 ? `${args.command.slice(0, 50)}…` : args.command;
|
|
207
|
-
const taskId = background.spawnCommand(commandStarter(
|
|
208
|
+
const taskId = background.spawnCommand(commandStarter(environment, args.cwd ?? environment.getcwd(), wrapped), args.command, `bash: ${preview}`, {
|
|
208
209
|
logPath,
|
|
209
|
-
|
|
210
|
+
environment,
|
|
210
211
|
...(parentAddress !== undefined ? { parentAddress } : {}),
|
|
211
212
|
...(toolCallId !== undefined ? { toolCallId } : {}),
|
|
212
213
|
});
|
|
@@ -233,17 +234,17 @@ async function execute(args, machine, signal, background, onUpdate, detachSignal
|
|
|
233
234
|
// regardless of backend. The standard loop also supplies detachSignal, but storage does not
|
|
234
235
|
// depend on that routing seam: passing BackgroundManager alone is enough to select one
|
|
235
236
|
// canonical durable output path.
|
|
236
|
-
// Local
|
|
237
|
-
// shell then expose the growing file through
|
|
237
|
+
// Local environments can do this cheaply, and sandbox/remote environments redirect inside their own
|
|
238
|
+
// shell then expose the growing file through Environment.readBytes. Detach consequently changes
|
|
238
239
|
// lifecycle ownership only; it never has to migrate an already-running pipe into memory.
|
|
239
240
|
let logPath;
|
|
240
241
|
if (usesAttachedDriver) {
|
|
241
242
|
try {
|
|
242
|
-
logPath = await prepareBackgroundLog(
|
|
243
|
+
logPath = await prepareBackgroundLog(environment);
|
|
243
244
|
}
|
|
244
245
|
catch {
|
|
245
246
|
// The manager's attached driver refuses pipe-only commands (assertDurableOutput), so a
|
|
246
|
-
//
|
|
247
|
+
// environment that cannot host the log (unwritable home, quota) degrades to the inline pipe
|
|
247
248
|
// driver below: the command still runs, it just cannot be detached into a task.
|
|
248
249
|
logPath = undefined;
|
|
249
250
|
}
|
|
@@ -256,17 +257,17 @@ async function execute(args, machine, signal, background, onUpdate, detachSignal
|
|
|
256
257
|
: `{ ${command}\n} > ${shellQuote(logPath)} 2>&1`;
|
|
257
258
|
const preview = args.command.length > 50 ? `${args.command.slice(0, 50)}…` : args.command;
|
|
258
259
|
const builder = new ToolResultBuilder();
|
|
259
|
-
const start = commandStarter(
|
|
260
|
+
const start = commandStarter(environment, args.cwd ?? environment.getcwd(), fgCommand);
|
|
260
261
|
let outcome;
|
|
261
262
|
try {
|
|
262
263
|
outcome = await drive(start, args.command, `bash: ${preview}`, {
|
|
263
264
|
foregroundSignal: signal,
|
|
264
265
|
...(detachSignal !== undefined ? { detachSignal } : {}),
|
|
265
266
|
foregroundTimeoutMs: timeoutMs,
|
|
266
|
-
// Attached mode passes logPath+
|
|
267
|
+
// Attached mode passes logPath+environment so the driver knows WHERE this command's output
|
|
267
268
|
// lives; with the live tap below it tails that file while we stay attached, and stops
|
|
268
269
|
// the moment we detach. The no-manager inline path omits them and receives the pipe.
|
|
269
|
-
...(logPath !== undefined ? { logPath,
|
|
270
|
+
...(logPath !== undefined ? { logPath, environment } : {}),
|
|
270
271
|
...(parentAddress !== undefined ? { parentAddress } : {}),
|
|
271
272
|
...(toolCallId !== undefined ? { toolCallId } : {}),
|
|
272
273
|
onLive: (chunk) => {
|
|
@@ -307,13 +308,16 @@ async function execute(args, machine, signal, background, onUpdate, detachSignal
|
|
|
307
308
|
const overflow = logPath !== undefined && builder.truncated
|
|
308
309
|
? `\nThe untruncated output was also written to ${logPath} — Read that file to see what was dropped.`
|
|
309
310
|
: "";
|
|
311
|
+
// Said plainly when the backend could not confirm the stop: the model must not assume a
|
|
312
|
+
// server or build it just "killed" is gone and start another on the same port or files.
|
|
313
|
+
const survivor = outcome.stillRunning === true ? ". The command could not be confirmed stopped and may still be running." : "";
|
|
310
314
|
switch (outcome.status) {
|
|
311
315
|
case "completed":
|
|
312
316
|
return builder.ok(`Command executed successfully.${overflow}`);
|
|
313
317
|
case "timed_out":
|
|
314
|
-
return builder.error(`Command killed by timeout (${label})${overflow}`, { brief: `Killed by timeout (${label})` });
|
|
318
|
+
return builder.error(`Command killed by timeout (${label})${survivor}${overflow}`, { brief: `Killed by timeout (${label})` });
|
|
315
319
|
case "killed":
|
|
316
|
-
return builder.error(`Interrupted by user${overflow}`, { brief: "Interrupted by user" });
|
|
320
|
+
return builder.error(`Interrupted by user${survivor}${overflow}`, { brief: "Interrupted by user" });
|
|
317
321
|
case "failed": {
|
|
318
322
|
const code = outcome.exitCode === null ? "unknown" : String(outcome.exitCode);
|
|
319
323
|
if (builder.nChars === 0)
|
|
@@ -326,21 +330,54 @@ function shellQuote(s) {
|
|
|
326
330
|
return `'${s.replaceAll("'", "'\\''")}'`;
|
|
327
331
|
}
|
|
328
332
|
/** `<dir>/bash-<random>.log`; undefined = nowhere safe to put durable background output. */
|
|
329
|
-
function backgroundLogPath(
|
|
330
|
-
const dir = backgroundLogDir(
|
|
333
|
+
function backgroundLogPath(environment) {
|
|
334
|
+
const dir = backgroundLogDir(environment);
|
|
331
335
|
// Compose with '/' — both posix hosts and win32 Git-bash shells accept it.
|
|
332
336
|
return dir === undefined ? undefined : `${dir}/bash-${randomBytes(4).toString("hex")}.log`;
|
|
333
337
|
}
|
|
338
|
+
/**
|
|
339
|
+
* Task-log directories already created on a given environment. The directory is the same for every
|
|
340
|
+
* command of a session, so creating it once is enough — and on a remote environment that mkdir is a
|
|
341
|
+
* round trip (a whole command on some backends) paid by EVERY Bash call. Keyed by Environment and
|
|
342
|
+
* weak, so an environment that goes away takes its entry with it.
|
|
343
|
+
*
|
|
344
|
+
* Only ever an optimization: the entry is dropped the moment the log write fails, and the next
|
|
345
|
+
* call recreates the directory. So a directory removed mid-session (a `rm -rf`, a tmp reaper)
|
|
346
|
+
* costs one retry, not a broken session.
|
|
347
|
+
*/
|
|
348
|
+
const preparedLogDirs = new WeakMap();
|
|
334
349
|
/** Allocate the canonical command log before the user's process starts. The shell only owns
|
|
335
350
|
* appending command output; directory/file setup failures therefore fail the tool cleanly
|
|
336
351
|
* instead of escaping through an uncaptured outer stderr stream. */
|
|
337
|
-
|
|
338
|
-
|
|
352
|
+
/** Create an empty task log on the environment and return its path — where a background program or command writes its output. */
|
|
353
|
+
export async function prepareBackgroundLog(environment) {
|
|
354
|
+
const logPath = backgroundLogPath(environment);
|
|
339
355
|
if (logPath === undefined) {
|
|
340
|
-
throw new Error("Background Bash execution requires a durable output log, but this
|
|
356
|
+
throw new Error("Background Bash execution requires a durable output log, but this environment has no safe task-log directory.");
|
|
357
|
+
}
|
|
358
|
+
const dir = posixDirname(logPath);
|
|
359
|
+
let known = preparedLogDirs.get(environment);
|
|
360
|
+
if (known === undefined) {
|
|
361
|
+
known = new Set();
|
|
362
|
+
preparedLogDirs.set(environment, known);
|
|
363
|
+
}
|
|
364
|
+
if (!known.has(dir)) {
|
|
365
|
+
await environment.mkdir(dir, { parents: true });
|
|
366
|
+
known.add(dir);
|
|
367
|
+
}
|
|
368
|
+
try {
|
|
369
|
+
await environment.writeText(logPath, "");
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
// The directory we believed in is gone (or was never writable). Re-create it and try once
|
|
373
|
+
// more, so the cache can never turn a transient state into a hard failure.
|
|
374
|
+
known.delete(dir);
|
|
375
|
+
await environment.mkdir(dir, { parents: true });
|
|
376
|
+
known.add(dir);
|
|
377
|
+
await environment.writeText(logPath, "").catch(() => {
|
|
378
|
+
throw error;
|
|
379
|
+
});
|
|
341
380
|
}
|
|
342
|
-
await machine.mkdir(posixDirname(logPath), { parents: true });
|
|
343
|
-
await machine.writeText(logPath, "");
|
|
344
381
|
return logPath;
|
|
345
382
|
}
|
|
346
383
|
/**
|
|
@@ -354,15 +391,15 @@ async function prepareBackgroundLog(machine) {
|
|
|
354
391
|
* them. Conversely `cwd=/workspace/proj` with `home=/workspace` is perfectly fine, and a
|
|
355
392
|
* `home !== cwd` test would needlessly relocate it.
|
|
356
393
|
*
|
|
357
|
-
* The fallback is `/tmp`: still on the
|
|
358
|
-
* outside the workspace, and alive for as long as the
|
|
394
|
+
* The fallback is `/tmp`: still on the environment (so `Read` reaches it, sandbox included),
|
|
395
|
+
* outside the workspace, and alive for as long as the environment is. On win32 there is no
|
|
359
396
|
* equivalent worth guessing at, and a Windows home is never the workspace in practice, so it
|
|
360
397
|
* keeps the home path.
|
|
361
398
|
*/
|
|
362
|
-
function backgroundLogDir(
|
|
399
|
+
function backgroundLogDir(environment) {
|
|
363
400
|
let home;
|
|
364
401
|
try {
|
|
365
|
-
home =
|
|
402
|
+
home = environment.gethome();
|
|
366
403
|
}
|
|
367
404
|
catch {
|
|
368
405
|
return undefined;
|
|
@@ -372,12 +409,12 @@ function backgroundLogDir(machine) {
|
|
|
372
409
|
const candidate = `${home.replaceAll("\\", "/").replace(/\/+$/, "")}/${OPERON_HOME_DIRNAME}/tasks`;
|
|
373
410
|
let cwd;
|
|
374
411
|
try {
|
|
375
|
-
cwd =
|
|
412
|
+
cwd = environment.getcwd();
|
|
376
413
|
}
|
|
377
414
|
catch {
|
|
378
415
|
return candidate;
|
|
379
416
|
}
|
|
380
|
-
const pathClass =
|
|
417
|
+
const pathClass = environment.pathClass();
|
|
381
418
|
if (cwd.length === 0 || !isWithinDirectory(candidate, cwd.replaceAll("\\", "/"), pathClass))
|
|
382
419
|
return candidate;
|
|
383
420
|
return pathClass === "win32" ? candidate : `/tmp/${OPERON_HOME_DIRNAME}/tasks`;
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { ToolAccesses } from "../access.js";
|
|
3
3
|
import { defineTool } from "../define.js";
|
|
4
|
-
import { StaleFileError } from "../machine.js";
|
|
5
4
|
import { checkFreshness, FILE_MODIFIED_MESSAGE, FILE_NOT_READ_MESSAGE } from "../file-freshness.js";
|
|
6
|
-
import { fileVersionFromInfo, normalizeForCompare, readTextFile } from "../support/
|
|
5
|
+
import { fileVersionFromInfo, normalizeForCompare, readTextFile } from "../support/environment-ops.js";
|
|
7
6
|
import { pathApproval, resolveToolPath } from "../support/tool-path.js";
|
|
8
7
|
import { materializeModelText, toModelTextView } from "./line-endings.js";
|
|
9
8
|
// `old_string` must be non-empty: the non-replace_all branch walks occurrences with
|
|
@@ -32,8 +31,9 @@ const EDIT_DESCRIPTION = [
|
|
|
32
31
|
"- Prefer Edit for targeted changes to existing files; use Write only for new files or complete overwrites.",
|
|
33
32
|
"- To modify a file, always use Edit; do not run a Bash `sed` command for edits.",
|
|
34
33
|
"- Read the file first so Edit can use the latest text view and verify the file has not changed before writing.",
|
|
35
|
-
"-
|
|
36
|
-
"- When several
|
|
34
|
+
"- If the file changed on disk after your Read (a formatter, a script, the user) but old_string still matches exactly once, the edit applies and the result says the file holds other changes; otherwise Edit asks you to Read again. replace_all edits always require a fresh Read.",
|
|
35
|
+
"- When making several independent changes, issue multiple Edit calls in parallel within a single response; edits to the same file are serialized automatically.",
|
|
36
|
+
"- When several parallel Edit calls target the same file, they are serialized and apply in the order the calls appear in your response. An edit fails with `old_string not found` if its old_string was taken from text an earlier edit already replaced — base every old_string on the latest Read view and order dependent edits accordingly.",
|
|
37
37
|
"- For pure CRLF files, Read shows LF and Edit.old_string/new_string should use LF; Edit writes the file back with CRLF preserved.",
|
|
38
38
|
"- For mixed line endings or lone carriage returns, Read displays carriage returns as \\r; include actual \\r escapes in old_string/new_string for those positions.",
|
|
39
39
|
].join("\n");
|
|
@@ -50,59 +50,88 @@ export const editTool = defineTool({
|
|
|
50
50
|
// The replacement text is what lands in the file — that's the security-relevant part.
|
|
51
51
|
toAutoApprovalInput: (args) => `${args.path}: ${args.new_string}`,
|
|
52
52
|
async resolve(args, ctx) {
|
|
53
|
-
const path = await resolveToolPath(args.path, ctx.
|
|
53
|
+
const path = await resolveToolPath(args.path, ctx.environment, "write");
|
|
54
54
|
return {
|
|
55
55
|
accesses: ToolAccesses.readWriteFile(path),
|
|
56
|
-
display: { title: `Editing ${args.path}`, before: args.old_string, after: args.new_string },
|
|
57
|
-
...pathApproval("Edit", ctx.
|
|
56
|
+
display: { title: `Editing ${args.path}`, path: args.path, before: args.old_string, after: args.new_string },
|
|
57
|
+
...pathApproval("Edit", ctx.environment, path),
|
|
58
58
|
run: (runCtx) => execute(args, path, runCtx),
|
|
59
59
|
};
|
|
60
60
|
},
|
|
61
61
|
});
|
|
62
62
|
async function execute(args, safePath, ctx) {
|
|
63
|
-
const machine = ctx.machine;
|
|
64
63
|
if (args.old_string === args.new_string) {
|
|
65
64
|
return errorResult("No changes to make: old_string and new_string are exactly the same.");
|
|
66
65
|
}
|
|
67
66
|
try {
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
const ledger = requireLedger(ctx);
|
|
68
|
+
// Read-before-write asks "has this agent seen the file", which any ledger record
|
|
69
|
+
// answers. NOT `fullRead` — that says whether the digest covers the whole file, and
|
|
70
|
+
// gating on it locked Edit out of every file over the Read tool's line or byte cap,
|
|
71
|
+
// with no way back in (a paged re-read is not a full read either). Partial reads stay
|
|
72
|
+
// safe below: uniqueness is checked against the WHOLE file, so an old_string guessed
|
|
73
|
+
// from unseen text fails to match or fails to be unique.
|
|
74
|
+
if (ledger.get(safePath) === undefined)
|
|
75
|
+
return errorResult(FILE_NOT_READ_MESSAGE);
|
|
76
|
+
// Stat BEFORE reading: a change landing between the two then leaves the version
|
|
77
|
+
// older than the text, so the freshness check below sees the conflict instead of
|
|
78
|
+
// blessing it.
|
|
79
|
+
const info = await ctx.environment.fileInfo(safePath);
|
|
80
|
+
const observed = fileVersionFromInfo(info);
|
|
81
|
+
const raw = await readTextFile(ctx.environment, safePath);
|
|
82
|
+
const normalized = normalizeForCompare(raw);
|
|
83
|
+
const verdict = await checkFreshness({
|
|
84
|
+
ledger,
|
|
85
|
+
path: safePath,
|
|
86
|
+
current: observed,
|
|
87
|
+
currentContent: () => Promise.resolve(normalized),
|
|
88
|
+
});
|
|
89
|
+
if (verdict.kind === "not-read")
|
|
90
|
+
return errorResult(FILE_NOT_READ_MESSAGE);
|
|
91
|
+
const stale = verdict.kind === "stale";
|
|
70
92
|
const modelView = toModelTextView(raw);
|
|
71
93
|
const content = modelView.text;
|
|
72
94
|
const replaceAll = args.replace_all ?? false;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
}
|
|
83
|
-
if (count === 0) {
|
|
84
|
-
return errorResult(`old_string not found in ${args.path}, the file contents may be out of date. Please use the Read Tool to reload the content.\n`);
|
|
85
|
-
}
|
|
86
|
-
if (count > 1) {
|
|
87
|
-
return errorResult(`old_string is not unique in ${args.path} (found ${String(count)} occurrences). ` +
|
|
88
|
-
"To replace every occurrence, set replace_all=true. To replace only one occurrence, include more surrounding context in old_string.");
|
|
89
|
-
}
|
|
90
|
-
const newContent = replaceOnceLiteral(content, args.old_string, args.new_string);
|
|
91
|
-
await writeFreshText(ctx, safePath, materializeModelText(newContent, modelView.lineEndingStyle), modelView.lineEndingStyle);
|
|
92
|
-
return textResult(`Replaced 1 occurrence in ${args.path}`);
|
|
93
|
-
}
|
|
94
|
-
const parts = content.split(args.old_string);
|
|
95
|
-
const replacementCount = parts.length - 1;
|
|
96
|
-
if (replacementCount === 0) {
|
|
95
|
+
const count = countOccurrences(content, args.old_string);
|
|
96
|
+
// Changed since read, yet the edit still lands on exactly one place: apply it
|
|
97
|
+
// against the file as it is NOW and say so, rather than make the model re-read a
|
|
98
|
+
// file a formatter merely touched elsewhere. Anything short of one unambiguous
|
|
99
|
+
// match — including every replace_all, which would rewrite occurrences the model
|
|
100
|
+
// never saw — goes back for a Read.
|
|
101
|
+
if (stale && (replaceAll || count !== 1))
|
|
102
|
+
return errorResult(FILE_MODIFIED_MESSAGE);
|
|
103
|
+
if (count === 0) {
|
|
97
104
|
return errorResult(`old_string not found in ${args.path}, the file contents may be out of date. Please use the Read Tool to reload the content.\n`);
|
|
98
105
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
106
|
+
if (!replaceAll && count > 1) {
|
|
107
|
+
return errorResult(`old_string is not unique in ${args.path} (found ${String(count)} occurrences). ` +
|
|
108
|
+
"To replace every occurrence, set replace_all=true. To replace only one occurrence, include more surrounding context in old_string.");
|
|
109
|
+
}
|
|
110
|
+
const newContent = replaceAll
|
|
111
|
+
? content.split(args.old_string).join(args.new_string)
|
|
112
|
+
: replaceOnceLiteral(content, args.old_string, args.new_string);
|
|
113
|
+
const materialized = materializeModelText(newContent, modelView.lineEndingStyle);
|
|
114
|
+
// Everything this edit is allowed to assume was settled by the freshness check
|
|
115
|
+
// above, against the text read a few statements ago. The write is unconditional:
|
|
116
|
+
// an external writer landing in the gap between that read and this write is the
|
|
117
|
+
// same window every backend but the local one has anyway (see Environment.writeText),
|
|
118
|
+
// and the record below is what catches it on the NEXT edit.
|
|
119
|
+
const result = await ctx.environment.writeText(safePath, materialized);
|
|
120
|
+
ledger.recordWrite(safePath, {
|
|
121
|
+
// Present only where the backend knew it for free (local); elsewhere the record
|
|
122
|
+
// is decided by the digest below — which the next Edit compares against the text
|
|
123
|
+
// it has to read anyway.
|
|
124
|
+
...(result.version !== undefined ? { version: result.version } : {}),
|
|
125
|
+
content: normalizeForCompare(materialized),
|
|
126
|
+
lineEndings: toLedgerLineEndings(modelView.lineEndingStyle),
|
|
127
|
+
encoding: "utf8",
|
|
128
|
+
});
|
|
129
|
+
const summary = replaceAll
|
|
130
|
+
? `Replaced ${String(count)} occurrences in ${args.path}`
|
|
131
|
+
: `Replaced 1 occurrence in ${args.path}`;
|
|
132
|
+
return textResult(stale ? `${summary}${STALE_RECOVERED_NOTE}` : summary);
|
|
102
133
|
}
|
|
103
134
|
catch (error) {
|
|
104
|
-
if (error instanceof StaleFileError)
|
|
105
|
-
return errorResult(FILE_MODIFIED_MESSAGE);
|
|
106
135
|
const code = error?.code;
|
|
107
136
|
if (code === "EISDIR") {
|
|
108
137
|
return errorResult(`${args.path} is not a file.`);
|
|
@@ -110,82 +139,26 @@ async function execute(args, safePath, ctx) {
|
|
|
110
139
|
return errorResult(error instanceof Error ? error.message : String(error));
|
|
111
140
|
}
|
|
112
141
|
}
|
|
142
|
+
const STALE_RECOVERED_NOTE = " (note: the file had been modified on disk since you last read it — the edit applied cleanly, but the file contains other changes not in your context. Read it again before relying on the rest of its content.)";
|
|
143
|
+
/** Non-overlapping occurrences of `needle` — the same ones `split` replaces. */
|
|
144
|
+
function countOccurrences(haystack, needle) {
|
|
145
|
+
let count = 0;
|
|
146
|
+
let pos = 0;
|
|
147
|
+
while (pos < haystack.length) {
|
|
148
|
+
const idx = haystack.indexOf(needle, pos);
|
|
149
|
+
if (idx === -1)
|
|
150
|
+
break;
|
|
151
|
+
count++;
|
|
152
|
+
pos = idx + needle.length;
|
|
153
|
+
}
|
|
154
|
+
return count;
|
|
155
|
+
}
|
|
113
156
|
function requireLedger(ctx) {
|
|
114
157
|
if (ctx.fileLedger === undefined) {
|
|
115
158
|
throw new Error("File freshness tracking unavailable - cannot verify read-before-write safety for this session.");
|
|
116
159
|
}
|
|
117
160
|
return ctx.fileLedger;
|
|
118
161
|
}
|
|
119
|
-
async function validateEdit(args, path, ctx) {
|
|
120
|
-
if (args.old_string === args.new_string) {
|
|
121
|
-
throw new Error("No changes to make: old_string and new_string are exactly the same.");
|
|
122
|
-
}
|
|
123
|
-
const ledger = requireLedger(ctx);
|
|
124
|
-
// Read-before-write asks "has this agent seen the file", which any ledger record
|
|
125
|
-
// answers. NOT `fullRead` — that says whether the RETAINED CONTENT is the whole
|
|
126
|
-
// file, and gating on it locked Edit out of every file over the Read tool's line
|
|
127
|
-
// or byte cap, with no way back in (a paged re-read is not a full read either).
|
|
128
|
-
// Partial reads stay safe further down: the uniqueness check below runs against
|
|
129
|
-
// the WHOLE file, so an old_string guessed from unseen text fails to match or
|
|
130
|
-
// fails to be unique.
|
|
131
|
-
const record = ledger.get(path);
|
|
132
|
-
if (record === undefined)
|
|
133
|
-
throw new Error(FILE_NOT_READ_MESSAGE);
|
|
134
|
-
const raw = await readTextFile(ctx.machine, path);
|
|
135
|
-
const info = await ctx.machine.fileInfo(path);
|
|
136
|
-
const verdict = await checkFreshness({
|
|
137
|
-
ledger,
|
|
138
|
-
path,
|
|
139
|
-
current: fileVersionFromInfo(info),
|
|
140
|
-
currentContent: () => Promise.resolve(normalizeForCompare(raw)),
|
|
141
|
-
});
|
|
142
|
-
if (verdict.kind === "not-read")
|
|
143
|
-
throw new Error(FILE_NOT_READ_MESSAGE);
|
|
144
|
-
if (verdict.kind === "stale")
|
|
145
|
-
throw new Error(FILE_MODIFIED_MESSAGE);
|
|
146
|
-
const content = toModelTextView(raw).text;
|
|
147
|
-
const replaceAll = args.replace_all ?? false;
|
|
148
|
-
if (!replaceAll) {
|
|
149
|
-
let count = 0;
|
|
150
|
-
let pos = 0;
|
|
151
|
-
while (pos < content.length) {
|
|
152
|
-
const idx = content.indexOf(args.old_string, pos);
|
|
153
|
-
if (idx === -1)
|
|
154
|
-
break;
|
|
155
|
-
count++;
|
|
156
|
-
pos = idx + args.old_string.length;
|
|
157
|
-
}
|
|
158
|
-
if (count === 0) {
|
|
159
|
-
throw new Error(`old_string not found in ${args.path}, the file contents may be out of date. Please use the Read Tool to reload the content.\n`);
|
|
160
|
-
}
|
|
161
|
-
if (count > 1) {
|
|
162
|
-
throw new Error(`old_string is not unique in ${args.path} (found ${String(count)} occurrences). ` +
|
|
163
|
-
"To replace every occurrence, set replace_all=true. To replace only one occurrence, include more surrounding context in old_string.");
|
|
164
|
-
}
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
if (!content.includes(args.old_string)) {
|
|
168
|
-
throw new Error(`old_string not found in ${args.path}, the file contents may be out of date. Please use the Read Tool to reload the content.\n`);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
async function writeFreshText(ctx, path, materializedContent, lineEndingStyle) {
|
|
172
|
-
const ledger = requireLedger(ctx);
|
|
173
|
-
const record = ledger.get(path);
|
|
174
|
-
if (record === undefined)
|
|
175
|
-
throw new Error(FILE_NOT_READ_MESSAGE);
|
|
176
|
-
// `expectedContent` only rides along when the ledger kept the whole file — on a
|
|
177
|
-
// partial read the CAS has the mtime and nothing else, so a moved mtime is a
|
|
178
|
-
// conflict with no content review to overturn it.
|
|
179
|
-
const result = await ctx.machine.writeTextIfUnchanged(path, materializedContent, {
|
|
180
|
-
expected: record.version,
|
|
181
|
-
...(record.fullRead && record.content !== undefined ? { expectedContent: record.content } : {}),
|
|
182
|
-
});
|
|
183
|
-
ledger.recordWrite(path, result.version, {
|
|
184
|
-
content: normalizeForCompare(materializedContent),
|
|
185
|
-
lineEndings: toLedgerLineEndings(lineEndingStyle),
|
|
186
|
-
encoding: "utf8",
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
162
|
function toLedgerLineEndings(style) {
|
|
190
163
|
if (style === "crlf")
|
|
191
164
|
return "CRLF";
|
|
@@ -40,22 +40,22 @@ export const globTool = defineTool({
|
|
|
40
40
|
params: GlobInput,
|
|
41
41
|
async resolve(args, ctx) {
|
|
42
42
|
const root = args.path !== undefined
|
|
43
|
-
? await resolveToolPath(args.path, ctx.
|
|
44
|
-
: ctx.
|
|
43
|
+
? await resolveToolPath(args.path, ctx.environment, "search", SEARCH_ACCESS_POLICY)
|
|
44
|
+
: ctx.environment.getcwd();
|
|
45
45
|
return {
|
|
46
46
|
accesses: ToolAccesses.searchTree(root),
|
|
47
|
-
display: { title: `Searching ${args.pattern}`, detail: `pattern: ${args.pattern}
|
|
47
|
+
display: { title: `Searching ${args.pattern}`, detail: `pattern: ${args.pattern}`, pattern: args.pattern, ...(args.path !== undefined ? { path: args.path } : {}) },
|
|
48
48
|
...globApproval("Glob", args.pattern),
|
|
49
|
-
run: (runCtx) => execute(args, root, runCtx.
|
|
49
|
+
run: (runCtx) => execute(args, root, runCtx.environment, runCtx.signal),
|
|
50
50
|
};
|
|
51
51
|
},
|
|
52
52
|
});
|
|
53
|
-
async function execute(args, root,
|
|
53
|
+
async function execute(args, root, environment, signal) {
|
|
54
54
|
if (signal.aborted)
|
|
55
55
|
return err("Glob aborted");
|
|
56
56
|
let rgCommand;
|
|
57
57
|
try {
|
|
58
|
-
rgCommand = await resolveRgCommand(
|
|
58
|
+
rgCommand = await resolveRgCommand(environment, { signal });
|
|
59
59
|
}
|
|
60
60
|
catch (error) {
|
|
61
61
|
if (isAbortError(error))
|
|
@@ -65,7 +65,7 @@ async function execute(args, root, machine, signal) {
|
|
|
65
65
|
// Probe the root so a missing/non-dir root reports clearly. rg would otherwise emit a
|
|
66
66
|
// terse stderr; this single fileInfo gives the same ENOENT/ENOTDIR message Read/Grep do.
|
|
67
67
|
try {
|
|
68
|
-
const info = await
|
|
68
|
+
const info = await environment.fileInfo(root);
|
|
69
69
|
if (info.kind !== "dir")
|
|
70
70
|
return err(`${root} is not a directory`);
|
|
71
71
|
}
|
|
@@ -77,17 +77,17 @@ async function execute(args, root, machine, signal) {
|
|
|
77
77
|
return err(`${root} is not a directory`);
|
|
78
78
|
// Unknown failure: fall through and let rg run.
|
|
79
79
|
}
|
|
80
|
-
const pattern = relativizePattern(args.pattern, root,
|
|
80
|
+
const pattern = relativizePattern(args.pattern, root, environment.pathClass());
|
|
81
81
|
// Search target is "." with the process cwd at `root`, NOT the absolute root — see
|
|
82
82
|
// buildRgArgs. Everything downstream therefore sees paths like `./src/a.ts`.
|
|
83
83
|
const runOptions = { timeoutMs: DEFAULT_TIMEOUT_MS, maxOutputBytes: MAX_OUTPUT_BYTES, cwd: root };
|
|
84
|
-
let outcome = await runRipgrep(
|
|
84
|
+
let outcome = await runRipgrep(environment, buildRgArgs(rgCommand, pattern), signal, runOptions);
|
|
85
85
|
const earlyExit = mapNonResult(outcome);
|
|
86
86
|
if (earlyExit)
|
|
87
87
|
return earlyExit;
|
|
88
88
|
let runResult = outcome.result;
|
|
89
89
|
if (shouldRetryEagain(runResult)) {
|
|
90
|
-
outcome = await runRipgrep(
|
|
90
|
+
outcome = await runRipgrep(environment, buildRgArgs(rgCommand, pattern, true), signal, runOptions);
|
|
91
91
|
const retryExit = mapNonResult(outcome);
|
|
92
92
|
if (retryExit)
|
|
93
93
|
return retryExit;
|
|
@@ -116,8 +116,8 @@ async function execute(args, root, machine, signal) {
|
|
|
116
116
|
// Paths arrive relative to `root` (the target was "."). Keep them that way when the search
|
|
117
117
|
// stayed inside the workspace; otherwise re-absolutize, since a bare relative path would be
|
|
118
118
|
// read against the caller's cwd and point somewhere else entirely.
|
|
119
|
-
const pathClass =
|
|
120
|
-
const keepRelative = isWithinDirectory(root,
|
|
119
|
+
const pathClass = environment.pathClass();
|
|
120
|
+
const keepRelative = isWithinDirectory(root, environment.getcwd(), pathClass);
|
|
121
121
|
const displayLines = capped.map((p) => {
|
|
122
122
|
const relative = stripLeadingDotSlash(p);
|
|
123
123
|
return keepRelative ? relative : joinPath(pathClass, root, relative);
|
|
@@ -221,7 +221,7 @@ function stripLeadingDotSlash(value) {
|
|
|
221
221
|
return value.slice(2);
|
|
222
222
|
return value;
|
|
223
223
|
}
|
|
224
|
-
/** Join with the TARGET
|
|
224
|
+
/** Join with the TARGET environment's path flavour — a local process may drive a posix environment. */
|
|
225
225
|
function joinPath(pathClass, dir, name) {
|
|
226
226
|
return (pathClass === "win32" ? win32 : posix).join(dir, name);
|
|
227
227
|
}
|