zapagent 1.14.15 → 1.14.17

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.
@@ -1,3 +1,4 @@
1
+ import { readOnlyBashTool } from "../../zapsdk/builtin-tools/subagent.js"
1
2
  import { connectLocalServiceOwner } from "../../zapsdk/services/local-owner.js"
2
3
  import { createExecutionEnvironment, resolveExecutionBackend } from "../execution-environment.js"
3
4
  import { executionExitCode, OutcomeProtocolError, type AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
@@ -292,6 +293,8 @@ export interface HeadlessHost {
292
293
  subagentIsolationRoot?: string
293
294
  /** Enforce the workspace boundary even in permissive approval modes. */
294
295
  isolateWorkspace?: boolean
296
+ /** Independent Goal reviewers can inspect the real workspace, never write. */
297
+ readOnlyWorkspace?: boolean
295
298
  privateGit?: PrivateGitBinding
296
299
  privateGitOwnerDirectory?: string
297
300
  serializeSubagent?: boolean
@@ -518,10 +521,19 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
518
521
  : baseExecutor.policyEngine.evaluate(request),
519
522
  }, baseExecutor.checkpointMode) : baseExecutor
520
523
  const guardedExecutor = resultGuard ? scopedExecutor.withResultGuard(resultGuard) : scopedExecutor
521
- const isolatedExecutor = host.isolateWorkspace ? guardedExecutor.withWorkspace({ root: realpathSync(cwd), mode: "isolated-write", sandbox: sandboxConfined ? "enforced" : "none", ...(host.privateGit ? { privateGitDirectory: host.privateGit.directory, privateGitIdentity: { device: host.privateGit.device, inode: host.privateGit.inode } } : {}) }) : guardedExecutor
524
+ const isolatedExecutor = host.readOnlyWorkspace ? guardedExecutor.withWorkspace({ root: realpathSync(cwd), mode: "shared-readonly", sandbox: sandboxConfined ? "enforced" : "none" }) : host.isolateWorkspace ? guardedExecutor.withWorkspace({ root: realpathSync(cwd), mode: "isolated-write", sandbox: sandboxConfined ? "enforced" : "none", ...(host.privateGit ? { privateGitDirectory: host.privateGit.directory, privateGitIdentity: { device: host.privateGit.device, inode: host.privateGit.inode } } : {}) }) : guardedExecutor
522
525
  const executor = host.admitToolExecution ? isolatedExecutor.withExecutionAdmission(host.admitToolExecution) : isolatedExecutor
523
526
  approval.setSandboxConfined(sandboxConfined, config.autoAllowSandboxedCommands !== false)
524
527
  approval.setSandboxExcludedCommands(config.allowUnsandboxedCommands !== false ? config.sandboxExcludedCommands : undefined)
528
+ if (host.readOnlyWorkspace) {
529
+ // No network tools: read-only Goal roles take worker output and workspace
530
+ // files as untrusted input, and an injected URL could carry them off-host.
531
+ const names = new Set(["read_file", "list_tree", "read_document", "read_pdf", "read_docx", "read_tool_output", "current_time"])
532
+ if (sandboxConfined && registry.has("bash")) {
533
+ registry.unregister("bash"); registry.register(readOnlyBashTool(cwd)); names.add("bash")
534
+ }
535
+ for (const definition of registry.definitions()) if (!names.has(definition.name)) registry.unregister(definition.name)
536
+ }
525
537
  await host.prepareRegistry?.(registry)
526
538
  if (publicChecks) {
527
539
  // These tools start work outside the root provider admission budget.
@@ -653,7 +665,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
653
665
  storageSessionId: getCurrentSessionId(),
654
666
  storageProjectCwd: cwd,
655
667
  sessionId: getCurrentSessionId(),
656
- subagentFactory: publicChecks || host.disableSubagent ? undefined : host.serializeSubagent ? options => {
668
+ subagentFactory: publicChecks || host.disableSubagent || host.readOnlyWorkspace ? undefined : host.serializeSubagent ? options => {
657
669
  const tool = subagentTool(options)
658
670
  const resolveEffects = tool.definition.resolveEffects
659
671
  return { ...tool, definition: { ...tool.definition, resolveEffects: (args, context) => {
@@ -662,7 +674,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
662
674
  } } }
663
675
  } : subagentTool,
664
676
  },
665
- subagent: publicChecks || host.disableSubagent ? false : {
677
+ subagent: publicChecks || host.disableSubagent || host.readOnlyWorkspace ? false : {
666
678
  inheritedInstructions: inherited.instructions,
667
679
  publicPromptSections: inherited.publicPromptSections,
668
680
  onEvent: (event) => { formatter.onEvent(event); host.onEvent?.(event) },
@@ -0,0 +1,34 @@
1
+ import { goalPhaseFailureCode } from "../../zapsdk/goal/errors.js"
2
+ import type { GoalPhaseInput } from "./goalPhase.js"
3
+ import type { HeadlessFormatter, RunSummary } from "./formatter.js"
4
+ import { goalTurnMeter } from "../goal-turn.js"
5
+
6
+ /** Background execution uses the ordinary headless runtime: normal PATH,
7
+ * network, approvals, checkpointing, child isolation and lifecycle sealing. */
8
+ export async function runSharedGoalTurnWorker(input: GoalPhaseInput): Promise<number> {
9
+ const { runHeadless } = await import("./runHeadless.js")
10
+ const readonly = ["planner", "verifier", "finalization"].includes(input.role)
11
+ const meter = goalTurnMeter(input)
12
+ let summary: RunSummary | undefined
13
+ let toolCalls = 0
14
+ const formatter: HeadlessFormatter = {
15
+ init() {}, progress() {}, failure(error) { throw new Error(error.code) },
16
+ onEvent(event) {
17
+ if (event.type === "content_final" && event.kind === "tool_call") toolCalls++
18
+ if (input.streamEvents) process.stdout.write(JSON.stringify({ type: "event", event }) + "\n")
19
+ },
20
+ finalize(value) { summary = value },
21
+ }
22
+ try {
23
+ const code = await runHeadless({ prompt: input.prompt, permissionMode: input.permissionMode ?? "default", outputFormat: "json", resultSchema: "outcome-v1",
24
+ cwd: input.cwd, quiet: true, continueLast: false, continueOnToolDenial: false, dangerouslyDisableOsSandbox: false, ...(input.sessionId ? { sessionId: input.sessionId } : {}), noDevtools: true,
25
+ }, { formatter, ...meter, readOnlyWorkspace: readonly, disableRepoMap: true })
26
+ if (!summary?.outcome) throw new Error("GOAL_TURN_OUTCOME_MISSING")
27
+ const execution = summary.outcome.execution
28
+ // This is the ordinary Runtime's terminal outcome, not an OS process-seal
29
+ // claim. In-flight or pending background actions never clear ownership.
30
+ const settled = execution.unresolvedActions.length === 0 && !execution.backgroundTasks?.some(task => task.disposition === "pending")
31
+ process.stdout.write(JSON.stringify({ type: "result", summary, exitCode: code, runtimeSettled: settled, toolCalls, ...(code !== 0 ? { failureCode: goalPhaseFailureCode(summary.error ?? "") } : {}) }) + "\n")
32
+ return code
33
+ } finally { meter.close() }
34
+ }
@@ -1,4 +1,8 @@
1
+ import { goalTurnMeter, type GoalTurnInput } from "../goal-turn.js"
2
+ import { RetryProvider } from "../../zapsdk/core/retry.js"
3
+ import type { AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
1
4
  import { executeGoalCommand } from "../goal-session.js"
5
+ import { createGoalContentFilter } from "../goal-output.js"
2
6
  import { createGoalPresentation } from "../agent/goalPresentation.js"
3
7
  import { AgentBudget } from "../../zapsdk/agent/budget.js"
4
8
  import { RequestMeter } from "../../zapsdk/agent/request-meter.js"
@@ -538,7 +542,7 @@ export function useAgentRunner({
538
542
  systemPrompt?: string,
539
543
  images?: import("../../zapsdk/core/types.js").ImageContent[],
540
544
  memoryQueryText?: string,
541
- invocation?: { signal?: AbortSignal; propagateErrors?: boolean; resultSchema?: "outcome-v1" | "legacy" } & Pick<import("../../zapsdk/agent/loop.js").RunOptions,
545
+ invocation?: { goalTurn?: GoalTurnInput; goalController?: AbortController; onOutcome?: (outcome: AgentOutcomeV1) => void; signal?: AbortSignal; propagateErrors?: boolean; resultSchema?: "outcome-v1" | "legacy" } & Pick<import("../../zapsdk/agent/loop.js").RunOptions,
542
546
  "onInputAccepted" | "hasSteering" | "takeSteering" | "onSteeringAccepted">,
543
547
  ): Promise<LoopAgentResult | undefined> => {
544
548
  running.current = true
@@ -548,7 +552,7 @@ export function useAgentRunner({
548
552
  const forwardExternalAbort = () => controller.abort(externalSignal?.reason)
549
553
  if (externalSignal?.aborted) forwardExternalAbort()
550
554
  else externalSignal?.addEventListener("abort", forwardExternalAbort, { once: true })
551
- abortRef.current = controller
555
+ abortRef.current = invocation?.goalController ?? controller
552
556
  setStatus("preparing")
553
557
  setProviderRequest(undefined)
554
558
  setStep(0)
@@ -574,11 +578,17 @@ export function useAgentRunner({
574
578
  let outcomeExecutionError: Error | undefined
575
579
  let caughtError: unknown
576
580
  let completedResult: LoopAgentResult | undefined
581
+ let goalMeter: ReturnType<typeof goalTurnMeter> | undefined
577
582
  let preview: ReturnType<typeof createStreamingPreview> | null = null
578
583
  let handlers: ReturnType<typeof createRunHandlers> | null = null
579
584
 
580
585
  try {
581
- const { provider, registry, executor, createRegistryForCwd, executionFacts, executionCapacity } = agentRef.current
586
+ const objects = agentRef.current
587
+ const { registry, createRegistryForCwd, executionFacts, executionCapacity } = objects
588
+ goalMeter = invocation?.goalTurn ? goalTurnMeter(invocation.goalTurn) : undefined
589
+ const provider = goalMeter ? objects.provider instanceof RetryProvider
590
+ ? objects.provider.withInnerAdapter(goalMeter.providerAdapter) : goalMeter.providerAdapter(objects.provider) : objects.provider
591
+ const executor = goalMeter ? objects.executor.withExecutionAdmission(goalMeter.admitToolExecution) : objects.executor
582
592
  const currentConfig = config
583
593
  const cacheScope = makePromptCacheScope(
584
594
  currentConfig.active.providerId,
@@ -717,6 +727,7 @@ export function useAgentRunner({
717
727
  currentConfig,
718
728
  controller,
719
729
  preview: runPreview,
730
+ presentContent: invocation?.goalTurn ? createGoalContentFilter() : undefined,
720
731
  setStatus, setStep, setActiveTool, setActiveToolBytes,
721
732
  setProviderRequest, setOutputThroughput,
722
733
  setContextTokens, setContextPending, setContextDiagnostics: recordContextDiagnostics,
@@ -788,6 +799,7 @@ export function useAgentRunner({
788
799
  setPromptCacheDiagnostics(promptCacheDiagnosticsForRun)
789
800
 
790
801
  handlers.wire(agent)
802
+ if (invocation?.goalTurn) agent.on("*", invocation.goalTurn.onEvent)
791
803
 
792
804
  // ── Per-turn context attachments + turn-end guard ──
793
805
  const { contextPrefix, contextDelta, contextDiagnostics } = makeContextBuilders({
@@ -812,6 +824,7 @@ export function useAgentRunner({
812
824
  onSteeringAccepted: invocation?.onSteeringAccepted,
813
825
  }
814
826
  const execution = invocation?.resultSchema === "legacy" ? undefined : await agent.runWithOutcome(task, runOptions)
827
+ if (execution) invocation?.onOutcome?.(execution.outcome)
815
828
  const result = execution?.loopResult ?? await agent.run(task, runOptions)
816
829
  if (execution?.outcome.execution.status === "failed" || execution?.outcome.execution.status === "blocked") {
817
830
  runError = execution.outcome.execution.error?.message ?? execution.outcome.execution.stopReason
@@ -902,6 +915,7 @@ export function useAgentRunner({
902
915
  // has already ended. Nulling the callback in this finally re-introduces
903
916
  // the "ghost paragraph in tail" bug that commit 57a4bf2 fixed.
904
917
 
918
+ goalMeter?.close()
905
919
  running.current = false
906
920
  abortRef.current = null
907
921
  setActiveTool("")
@@ -946,6 +960,17 @@ export function useAgentRunner({
946
960
  let stateLabel = ""
947
961
  try {
948
962
  return await executeGoalCommand(args, cwd, {
963
+ runTurn: async input => {
964
+ presentation?.finish()
965
+ let outcome: AgentOutcomeV1 | undefined
966
+ try {
967
+ const result = await runAgent(input.prompt, undefined, undefined, input.prompt, {
968
+ signal: input.signal, goalTurn: input, goalController: controller, onOutcome: value => { outcome = value }, resultSchema: "outcome-v1", propagateErrors: true,
969
+ })
970
+ if (!result || !outcome) throw new Error("GOAL_TURN_OUTCOME_MISSING")
971
+ return { text: result.text, outcome, toolCalls: result.toolResults.length, sessionId: getCurrentSessionId() }
972
+ } finally { running.current = true; abortRef.current = controller }
973
+ },
949
974
  permissionMode: config.permissionMode, sessionId: getCurrentSessionId(), signal: controller.signal,
950
975
  onStart: () => {
951
976
  if (running.current) throw new Error("The current session is already running a task")
@@ -971,6 +996,7 @@ export function useAgentRunner({
971
996
  }
972
997
  },
973
998
  onMessage: text => addLog("system", text),
999
+ onResult: text => { presentation?.finish(); addLog("agent", text) },
974
1000
  })
975
1001
  } finally {
976
1002
  if (presentation) {
@@ -979,7 +1005,7 @@ export function useAgentRunner({
979
1005
  setGoalRunning(false); setStatus("ready"); setActiveTool(""); setStep(0); setProviderRequest(undefined)
980
1006
  }
981
1007
  }
982
- }, [config, cwd, addLog, replaceLog, peekNextLogId, getIsFrozen, registerStaticFlushCallback, agentRunStore])
1008
+ }, [config, cwd, addLog, replaceLog, peekNextLogId, getIsFrozen, registerStaticFlushCallback, agentRunStore, runAgent])
983
1009
 
984
1010
  const runAgentRef = useRef(runAgent)
985
1011
  runAgentRef.current = runAgent
package/src/index.tsx CHANGED
@@ -115,7 +115,7 @@ if (args[0] === "goal") {
115
115
  const [{ executeGoalCommand }, { loadAppConfig }, { getAppDataDir }] = await Promise.all([
116
116
  import("./goal-session.js"), import("./config.js"), import("../zapsdk/utils/platform.js"),
117
117
  ])
118
- const displayed = new Set<string>()
118
+ const displayed = new Map<string, string>()
119
119
  let lastPhase = ""
120
120
  try { process.exit(await executeGoalCommand(args.slice(1), process.cwd(), {
121
121
  permissionMode: loadAppConfig(join(getAppDataDir(), "config.json")).permissionMode,
@@ -123,9 +123,13 @@ if (args[0] === "goal") {
123
123
  onState: goal => { const phase = `${goal.status}/${goal.phase ?? "preparing"}`; if (phase !== lastPhase) { lastPhase = phase; process.stdout.write(`\nGoal ${phase} · ${goal.tasks.filter(t => t.status === "passed").length}/${goal.tasks.length} tasks\n`) } },
124
124
  onEvent: (event, scope) => {
125
125
  if ((event.type === "content_delta" || event.type === "content_final") && (event.kind === "text" || event.kind === "thinking")) {
126
- const key = `${scope}:${event.id}`
127
- if (event.type === "content_delta") { displayed.add(key); process.stdout.write(event.text) }
128
- else { if (!displayed.has(key)) process.stdout.write(event.text); process.stdout.write("\n") }
126
+ const key = JSON.stringify([scope, event.path ?? [], event.kind, event.id])
127
+ if (event.type === "content_delta") { displayed.set(key, (displayed.get(key) ?? "") + event.text); process.stdout.write(event.text) }
128
+ else {
129
+ const prior = displayed.get(key) ?? ""
130
+ if (event.text.startsWith(prior)) process.stdout.write(event.text.slice(prior.length))
131
+ displayed.delete(key); process.stdout.write("\n")
132
+ }
129
133
  } else if (event.type === "content_final" && event.kind === "tool_call") process.stdout.write(`\n${event.path?.length ? "Child " : ""}Tool ${event.toolName}: ${JSON.stringify(event.arguments)}\n`)
130
134
  else if (event.type === "content_final" && event.kind === "tool_result") process.stdout.write(`Tool ${event.toolName}: ${event.result.success ? "ok" : "failed"} ${event.result.output ?? event.result.error ?? ""}\n`)
131
135
  else if (event.type === "error") process.stderr.write(event.error + "\n")
@@ -109,7 +109,7 @@ const READONLY_BIN_ALLOWLIST = new Set([
109
109
  // Searching
110
110
  "find", "grep", "rg", "fgrep", "egrep",
111
111
  // Dir / file metadata
112
- "tree", "file", "stat", "pwd", "basename", "dirname", "readlink", "realpath",
112
+ "tree", "file", "stat", "pwd", "du", "basename", "dirname", "readlink", "realpath",
113
113
  // Text inspection (read-only flags only; no `sed -i`, no awk `system`)
114
114
  "sort", "uniq", "cut", "tr", "comm", "diff", "cmp",
115
115
  "column", "paste", "fold", "rev", "od", "hexdump", "strings",
@@ -137,9 +137,17 @@ const READONLY_BIN_ALLOWLIST = new Set([
137
137
  const READONLY_GIT_SUBCOMMANDS = new Set([
138
138
  "log", "diff", "status", "blame", "show", "ls-files", "ls-tree",
139
139
  "rev-parse", "rev-list", "describe", "grep", "shortlog", "whatchanged",
140
- "cat-file", "for-each-ref", "name-rev",
140
+ "cat-file", "for-each-ref", "name-rev", "merge-base", "worktree",
141
141
  ]);
142
142
 
143
+ /** getopt_long accepts any unique prefix of a long option (`sort --out=FILE`), so a plain
144
+ * `startsWith("--output")` check is bypassed by abbreviations. */
145
+ function isLongOptionAbbreviation(part: string, full: string, minLength: number): boolean {
146
+ if (!part.startsWith("--")) return false;
147
+ const name = part.split("=")[0]!;
148
+ return name.length >= minLength && full.startsWith(name);
149
+ }
150
+
143
151
  /** Returns null if safe, else a human-readable reject reason. */
144
152
  export function validateReadOnlyBash(cmd: string): string | null {
145
153
  const trimmed = cmd.trim();
@@ -147,8 +155,8 @@ export function validateReadOnlyBash(cmd: string): string | null {
147
155
 
148
156
  // Reject shell control that could chain unsafe commands or redirect output.
149
157
  // Pipes (|) are allowed because they compose read-only filters.
150
- if (/;|&&|\|\||>|<|\$\(|`/.test(trimmed)) {
151
- return "shell control (;, &&, ||, >, <, $(), backticks) is not allowed in read-only mode. Plain pipes (|) are allowed.";
158
+ if (/[\r\n&;]|\|\||>|<|\$\(|`/.test(trimmed)) {
159
+ return "shell control (;, &, &&, ||, >, <, $(), backticks, newlines) is not allowed in read-only mode. Plain pipes (|) are allowed.";
152
160
  }
153
161
  // Reject trailing `&` (background).
154
162
  if (/&\s*$/.test(trimmed)) return "background (&) is not allowed in read-only mode";
@@ -170,9 +178,13 @@ export function validateReadOnlyBash(cmd: string): string | null {
170
178
  if (!READONLY_GIT_SUBCOMMANDS.has(sub)) {
171
179
  return `git ${sub} is not in the read-only allowlist (allowed: log, diff, status, blame, show, ls-files, …)`;
172
180
  }
181
+ if (sub === "worktree" && parts[2] !== "list") return "only git worktree list is allowed in read-only mode";
173
182
  if (parts.some((part) => part === "--output" || part.startsWith("--output="))) {
174
183
  return "git --output is not allowed in read-only mode";
175
184
  }
185
+ if (sub === "grep" && parts.some((part) => part.startsWith("-O") || isLongOptionAbbreviation(part, "--open-files-in-pager", 4))) {
186
+ return "git grep -O / --open-files-in-pager run external programs and are not allowed";
187
+ }
176
188
  }
177
189
 
178
190
  if (first === "find") {
@@ -180,10 +192,33 @@ export function validateReadOnlyBash(cmd: string): string | null {
180
192
  if (/\s-(exec|delete|ok|execdir|okdir)\b/.test(seg)) {
181
193
  return "find -exec / -delete / -ok / -execdir / -okdir are not allowed";
182
194
  }
195
+ // -fprint* / -fls write their results to a file.
196
+ if (/\s-(fprint|fprint0|fprintf|fls)\b/.test(seg)) {
197
+ return "find -fprint / -fprint0 / -fprintf / -fls write files and are not allowed";
198
+ }
199
+ }
200
+
201
+ // Short-option clusters such as `-oFILE` or `-uo FILE` also select an output file.
202
+ if (first === "sort" && parts.slice(1).some((part) => /^-[A-Za-z]*o/.test(part) || isLongOptionAbbreviation(part, "--output", 3) || isLongOptionAbbreviation(part, "--compress-program", 4))) {
203
+ return "sort output-file / compress-program options are not allowed in read-only mode";
204
+ }
205
+
206
+ if (first === "tree" && parts.slice(1).some((part) => /^-[A-Za-z]*o/.test(part) || isLongOptionAbbreviation(part, "--output", 3))) {
207
+ return "tree output-file options are not allowed in read-only mode";
183
208
  }
184
209
 
185
- if (first === "sort" && parts.some((part) => part === "-o" || part.startsWith("--output"))) {
186
- return "sort output-file options are not allowed in read-only mode";
210
+ if (first === "rg" && parts.slice(1).some((part) => /^--(pre|hostname-bin)(=|$)/.test(part))) {
211
+ return "rg --pre / --hostname-bin run external programs and are not allowed";
212
+ }
213
+
214
+ if (first === "uniq") {
215
+ // `uniq INPUT OUTPUT` writes OUTPUT. Option values (-f/-s/-w N) are not files.
216
+ const operands: string[] = [];
217
+ for (let i = 1; i < parts.length; i++) {
218
+ if (/^-[fsw]$/.test(parts[i]!)) { i++; continue; }
219
+ if (!parts[i]!.startsWith("-")) operands.push(parts[i]!);
220
+ }
221
+ if (operands.length > 1) return "uniq with an output operand is not allowed in read-only mode";
187
222
  }
188
223
 
189
224
  if (first === "yq" && parts.some((part) => part === "-i" || part === "--inplace")) {
@@ -205,8 +240,8 @@ export function validateReadOnlyBash(cmd: string): string | null {
205
240
  * argument. Registered under the same name ("bash") so the subagent's
206
241
  * tool schema is indistinguishable from the main agent's — the model
207
242
  * doesn't need to learn a new tool name. */
208
- function readOnlyBashTool(defaultCwd?: string): Tool {
209
- const inner = executeCommandTool({ defaultCwd, allowUnsandboxed: false });
243
+ export function readOnlyBashTool(defaultCwd?: string): Tool {
244
+ const inner = executeCommandTool({ defaultCwd, allowUnsandboxed: false, sandboxNetwork: false, restrictedNetwork: false, disableBackgroundTasks: true });
210
245
  return {
211
246
  ...inner,
212
247
  definition: {
@@ -221,6 +256,7 @@ function readOnlyBashTool(defaultCwd?: string): Tool {
221
256
  kind: "process",
222
257
  operation: "spawn",
223
258
  commandClass: "read-only-shell",
259
+ readOnly: true,
224
260
  background: false,
225
261
  }],
226
262
  external: [],
@@ -229,16 +265,15 @@ function readOnlyBashTool(defaultCwd?: string): Tool {
229
265
  }),
230
266
  },
231
267
  handler: async (args, signal, context) => {
232
- const command = args.command as string;
233
- const reject = validateReadOnlyBash(command);
234
- if (reject) {
235
- return {
236
- success: false,
237
- output: "",
238
- error: `bash blocked in read-only mode: ${reject}`,
239
- };
268
+ const parsed = inner.definition.parameters.safeParse(args);
269
+ if (!parsed.success) return { success: false, output: "", error: `Invalid read-only bash arguments: ${parsed.error.message}` };
270
+ const checked = parsed.data as Record<string, unknown>;
271
+ const commands = Array.isArray(checked.check_steps) ? checked.check_steps : [checked.command];
272
+ for (const command of commands) {
273
+ const reject = typeof command === "string" ? validateReadOnlyBash(command) : "command or check_steps is required";
274
+ if (reject) return { success: false, output: "", error: `bash blocked in read-only mode: ${reject}` };
240
275
  }
241
- return inner.handler(args, signal, context);
276
+ return inner.handler(checked, signal, context);
242
277
  },
243
278
  };
244
279
  }
@@ -39,6 +39,15 @@ export class RetryProvider implements LLMProvider {
39
39
  this.onRetry = options.onRetry;
40
40
  }
41
41
 
42
+ /** Per-run instrumentation inside retries, without mutating a shared provider. */
43
+ withInnerAdapter(adapter: (provider: LLMProvider) => LLMProvider): RetryProvider {
44
+ return new RetryProvider(adapter(this.inner), {
45
+ maxRetries: this.maxRetries, initialDelayMs: this.initialDelayMs,
46
+ maxDelayMs: this.maxDelayMs, backoffMultiplier: this.backoffMultiplier,
47
+ retryableErrors: this.retryableErrors, onRetry: this.onRetry,
48
+ });
49
+ }
50
+
42
51
  getImageTokenContext(options?: LLMCallOptions) {
43
52
  return this.inner.getImageTokenContext?.(options) ?? { model: options?.model };
44
53
  }
@@ -28,6 +28,8 @@ export interface GoalReceipt {
28
28
  export interface GoalRecord {
29
29
  id: string;
30
30
  objective: string;
31
+ /** Absent on legacy Goals, whose isolated snapshots retain their old host. */
32
+ executionMode?: "session" | "isolated";
31
33
  deliveryPolicy: "artifact" | "workspace";
32
34
  machineCheck?: "bun" | "npm" | "pytest" | "go";
33
35
  /** User-authorized, host-managed dependency preparation. */
@@ -16,10 +16,10 @@ export class GoalStore {
16
16
  this.db.exec("CREATE TABLE IF NOT EXISTS goal_budget_extensions (id TEXT PRIMARY KEY, goal_id TEXT NOT NULL, at INTEGER NOT NULL, old_limits TEXT NOT NULL, new_limits TEXT NOT NULL)");
17
17
  }
18
18
  close(): void { this.db.close(); }
19
- create(input: { objective: string; cwd: string; sessionId?: string; deadlineAt?: number; deliveryPolicy?: "artifact" | "workspace"; machineCheck?: "bun" | "npm" | "pytest" | "go"; dependencyInstall?: "npm"; permissionMode?: "default" | "acceptEdits" | "plan" | "bypassPermissions" }): GoalRecord {
19
+ create(input: { executionMode?: "session" | "isolated"; objective: string; cwd: string; sessionId?: string; deadlineAt?: number; deliveryPolicy?: "artifact" | "workspace"; machineCheck?: "bun" | "npm" | "pytest" | "go"; dependencyInstall?: "npm"; permissionMode?: "default" | "acceptEdits" | "plan" | "bypassPermissions" }): GoalRecord {
20
20
  if (!input.objective.trim() || !input.cwd || (input.deadlineAt !== undefined && (!Number.isSafeInteger(input.deadlineAt) || input.deadlineAt <= Date.now())) || (input.dependencyInstall !== undefined && input.dependencyInstall !== "npm")) throw new Error("INVALID_GOAL");
21
21
  const now = Date.now();
22
- const value: GoalRecord = { id: `goal_${randomUUID()}`, objective: input.objective, deliveryPolicy: input.deliveryPolicy ?? "workspace", permissionMode: input.permissionMode ?? "default", ...(input.machineCheck ? { machineCheck: input.machineCheck } : {}), ...(input.dependencyInstall ? { dependencyInstall: input.dependencyInstall } : {}), cwd: input.cwd, ...(input.sessionId ? { sessionId: input.sessionId } : {}), stateRevision: 1, specRevision: 1, planRevision: 0, status: "created", createdAt: now, updatedAt: now, ...(input.deadlineAt === undefined ? {} : { deadlineAt: input.deadlineAt }), ownerEpoch: 0, tasks: [] };
22
+ const value: GoalRecord = { id: `goal_${randomUUID()}`, objective: input.objective, ...(input.executionMode ? { executionMode: input.executionMode } : {}), deliveryPolicy: input.deliveryPolicy ?? "workspace", permissionMode: input.permissionMode ?? "default", ...(input.machineCheck ? { machineCheck: input.machineCheck } : {}), ...(input.dependencyInstall ? { dependencyInstall: input.dependencyInstall } : {}), cwd: input.cwd, ...(input.sessionId ? { sessionId: input.sessionId } : {}), stateRevision: 1, specRevision: 1, planRevision: 0, status: "created", createdAt: now, updatedAt: now, ...(input.deadlineAt === undefined ? {} : { deadlineAt: input.deadlineAt }), ownerEpoch: 0, tasks: [] };
23
23
  this.db.query("INSERT INTO goals(id,revision,record) VALUES(?,?,?)").run(value.id, value.stateRevision, JSON.stringify(value));
24
24
  return value;
25
25
  }