operon-agents-core 0.1.0-alpha.32 → 0.1.0-alpha.34

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.
Files changed (125) hide show
  1. package/dist/agent/compose-hooks.js +6 -1
  2. package/dist/agent/profile-builtins.js +0 -1
  3. package/dist/agent/recovery.js +3 -1
  4. package/dist/agent/runner.js +2 -2
  5. package/dist/agent/sandbox-keepalive.d.ts +16 -0
  6. package/dist/agent/sandbox-keepalive.js +36 -0
  7. package/dist/agent/session.d.ts +3 -0
  8. package/dist/agent/session.js +13 -1
  9. package/dist/agent/subagent-tools.js +7 -6
  10. package/dist/agent/workflow/journal.d.ts +1 -1
  11. package/dist/agent/workflow/prompt.js +1 -1
  12. package/dist/agent/workflow/tool.js +28 -7
  13. package/dist/agent/worktree.js +1 -1
  14. package/dist/capabilities/background/agent-task.d.ts +11 -5
  15. package/dist/capabilities/background/agent-task.js +4 -0
  16. package/dist/capabilities/background/code-task.d.ts +3 -3
  17. package/dist/capabilities/background/code-task.js +3 -3
  18. package/dist/capabilities/background/command-task.d.ts +14 -14
  19. package/dist/capabilities/background/command-task.js +22 -14
  20. package/dist/capabilities/background/index.d.ts +5 -2
  21. package/dist/capabilities/background/index.js +7 -3
  22. package/dist/capabilities/background/manager.d.ts +15 -14
  23. package/dist/capabilities/background/manager.js +176 -160
  24. package/dist/capabilities/background/monitor-task.d.ts +116 -0
  25. package/dist/capabilities/background/monitor-task.js +283 -0
  26. package/dist/capabilities/background/monitor-tool.d.ts +10 -0
  27. package/dist/capabilities/background/monitor-tool.js +154 -0
  28. package/dist/capabilities/background/stall-watchdog.js +2 -2
  29. package/dist/capabilities/background/swappable-sink.d.ts +2 -0
  30. package/dist/capabilities/background/swappable-sink.js +1 -0
  31. package/dist/capabilities/background/task.d.ts +9 -0
  32. package/dist/capabilities/background/tools.d.ts +0 -1
  33. package/dist/capabilities/background/tools.js +1 -119
  34. package/dist/capabilities/background/workflow-task.d.ts +12 -3
  35. package/dist/capabilities/background/workflow-task.js +4 -0
  36. package/dist/capabilities/index.d.ts +2 -2
  37. package/dist/capabilities/index.js +1 -1
  38. package/dist/capabilities/plan/plan-mode.js +1 -1
  39. package/dist/capabilities/skills/scanner.js +2 -2
  40. package/dist/capabilities/user-hooks/engine.js +1 -1
  41. package/dist/config/file-source.d.ts +2 -0
  42. package/dist/config/file-source.js +19 -3
  43. package/dist/config/resolver.d.ts +3 -0
  44. package/dist/config/resolver.js +2 -0
  45. package/dist/config/schema.d.ts +6 -0
  46. package/dist/config/schema.js +7 -2
  47. package/dist/config/session-config.d.ts +4 -0
  48. package/dist/config/session-config.js +5 -1
  49. package/dist/index.d.ts +2 -0
  50. package/dist/loop/run-turn.js +4 -2
  51. package/dist/loop/steer.d.ts +7 -6
  52. package/dist/loop/steer.js +30 -11
  53. package/dist/loop/tool-call.js +9 -4
  54. package/dist/loop/types.d.ts +3 -0
  55. package/dist/mcp/config-loader.js +1 -1
  56. package/dist/mcp/manager.d.ts +10 -0
  57. package/dist/mcp/manager.js +13 -3
  58. package/dist/mcp/sdk-transport.d.ts +4 -0
  59. package/dist/mcp/sdk-transport.js +21 -1
  60. package/dist/permission/auto-approver/decision-auto-approver.d.ts +1 -1
  61. package/dist/permission/auto-approver/decision-auto-approver.js +7 -2
  62. package/dist/permission/auto-approver/index.d.ts +1 -1
  63. package/dist/permission/auto-approver/index.js +1 -1
  64. package/dist/permission/auto-approver/llm-auto-approver.d.ts +7 -5
  65. package/dist/permission/auto-approver/llm-auto-approver.js +41 -18
  66. package/dist/permission/auto-approver/prompts-data.d.ts +4 -8
  67. package/dist/permission/auto-approver/prompts-data.js +131 -85
  68. package/dist/permission/auto-approver/prompts.d.ts +27 -7
  69. package/dist/permission/auto-approver/prompts.js +49 -31
  70. package/dist/permission/auto-approver/rules-data.d.ts +9 -0
  71. package/dist/permission/auto-approver/rules-data.js +127 -0
  72. package/dist/permission/auto-approver/transcript.d.ts +19 -7
  73. package/dist/permission/auto-approver/transcript.js +99 -14
  74. package/dist/permission/auto-approver/xml.d.ts +2 -0
  75. package/dist/permission/auto-approver/xml.js +6 -0
  76. package/dist/permission/denial.d.ts +16 -0
  77. package/dist/permission/denial.js +17 -0
  78. package/dist/permission/index.d.ts +3 -2
  79. package/dist/permission/index.js +3 -2
  80. package/dist/permission/manager.d.ts +15 -0
  81. package/dist/permission/manager.js +62 -13
  82. package/dist/permission/policies.js +1 -1
  83. package/dist/permission/types.d.ts +14 -3
  84. package/dist/plugins/hooks.js +1 -1
  85. package/dist/plugins/manifest.js +2 -2
  86. package/dist/plugins/store.js +1 -1
  87. package/dist/tool/background.d.ts +33 -10
  88. package/dist/tool/builtin/ask-user-question.js +1 -2
  89. package/dist/tool/builtin/bash.d.ts +23 -4
  90. package/dist/tool/builtin/bash.js +63 -85
  91. package/dist/tool/builtin/edit.js +14 -1
  92. package/dist/tool/builtin/glob.js +1 -1
  93. package/dist/tool/builtin/grep.js +1 -1
  94. package/dist/tool/builtin/read.js +4 -4
  95. package/dist/tool/builtin/write.js +4 -4
  96. package/dist/tool/environment-base.d.ts +13 -1
  97. package/dist/tool/environment-base.js +47 -129
  98. package/dist/tool/environment-commands.d.ts +21 -0
  99. package/dist/tool/environment-commands.js +173 -0
  100. package/dist/tool/environment-files.d.ts +55 -0
  101. package/dist/tool/environment-files.js +139 -0
  102. package/dist/tool/environment-local.d.ts +11 -1
  103. package/dist/tool/environment-local.js +87 -4
  104. package/dist/tool/environment-null.d.ts +9 -0
  105. package/dist/tool/environment-null.js +9 -0
  106. package/dist/tool/environment-output.d.ts +11 -0
  107. package/dist/tool/environment-output.js +86 -0
  108. package/dist/tool/environment-pty.d.ts +36 -0
  109. package/dist/tool/environment-pty.js +43 -0
  110. package/dist/tool/environment-sandbox.d.ts +14 -0
  111. package/dist/tool/environment-sandbox.js +13 -0
  112. package/dist/tool/environment-ssh.js +2 -0
  113. package/dist/tool/environment.d.ts +180 -192
  114. package/dist/tool/git-context.js +1 -1
  115. package/dist/tool/index.d.ts +8 -1
  116. package/dist/tool/index.js +5 -0
  117. package/dist/tool/policies/path-access.d.ts +3 -1
  118. package/dist/tool/policies/path-access.js +1 -1
  119. package/dist/tool/support/environment-ops.d.ts +7 -3
  120. package/dist/tool/support/environment-ops.js +2 -2
  121. package/dist/tool/support/git-worktree.d.ts +1 -1
  122. package/dist/tool/support/git-worktree.js +1 -1
  123. package/dist/tool/support/ripgrep-run.js +1 -1
  124. package/dist/tool/workspace-spec.js +43 -56
  125. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import { toolInputGuardrailHook, toolOutputGuardrailHook } from "./guardrail.js";
2
2
  import { runCtxFor } from "./run-support.js";
3
3
  import { withToolCallRecoveryContext } from "./recovery.js";
4
+ import { permissionDenialDetails } from "../permission/denial.js";
4
5
  /**
5
6
  * The loop hooks for one turn of `active` under a frame: capability hook parts
6
7
  * (compaction beforeStep/afterStep …) → permission authorizer (single) → tool guardrails.
@@ -98,7 +99,11 @@ function buildAuthorizer(state, context, tools) {
98
99
  state.session.persistPermissionState();
99
100
  if (ok)
100
101
  return undefined;
101
- return { block: true, reason: answer.feedback ?? `Tool ${ctx.toolCall.name} was ${answer.decision}.` };
102
+ return {
103
+ block: true,
104
+ reason: answer.feedback ?? `Tool ${ctx.toolCall.name} was ${answer.decision}.`,
105
+ blockDetails: permissionDenialDetails("rejected-by-user"),
106
+ };
102
107
  }
103
108
  return base(ctx);
104
109
  };
@@ -49,7 +49,6 @@ tools:
49
49
  - GetGoal
50
50
  - SetGoalBudget
51
51
  - UpdateGoal
52
- - BackgroundOutput
53
52
  - BackgroundStop
54
53
  - TaskCreate
55
54
  - TaskUpdate
@@ -28,7 +28,9 @@ export async function withToolCallRecoveryContext(state, request) {
28
28
  lines.push("", `- tool_call_id: ${call.id}`, ` tool: ${call.name}`);
29
29
  const task = background.get(call.id);
30
30
  if (task !== undefined) {
31
- lines.push(` recovered_task_id: ${task.taskId}`, ` task_kind: ${task.kind}`, ` persisted_status: ${task.status}`, ` action: Inspect it with BackgroundOutput(task_id=\"${task.taskId}\", block=false) before retrying or resuming anything.`);
31
+ lines.push(` recovered_task_id: ${task.taskId}`, ` task_kind: ${task.kind}`, ` persisted_status: ${task.status}`, ...(task.outputRef?.kind === "file" ? [` output_log: ${task.outputRef.path}`] : []), task.outputRef?.kind === "file"
32
+ ? " action: Read its output log before retrying or resuming anything; a task still running reports its completion on its own."
33
+ : " action: Go by its persisted status before retrying or resuming anything; a task still running reports its completion on its own.");
32
34
  continue;
33
35
  }
34
36
  const agent = durable.agents.get(call.id);
@@ -298,7 +298,7 @@ export class Runner {
298
298
  assertGraphUnambiguous(rootAgent);
299
299
  // A normal post-crash continuation is a fresh prompt (for example "continue"), not the
300
300
  // HITL-specific Runner.resume path. Reconcile durable task ghosts before request recovery
301
- // inspects them so BackgroundOutput is given the truthful terminal `lost` status.
301
+ // inspects them so the recovery note states the truthful terminal `lost` status.
302
302
  await session.background?.reconcileSubagents() ?? [];
303
303
  if (session.store && (await session.store.getState(INTERRUPTION_STATE_KEY)) !== null) {
304
304
  throw new SessionInterruptedError(session.id);
@@ -805,7 +805,7 @@ class Engine {
805
805
  }
806
806
  // Terminal stop reasons.
807
807
  if (r.stopReason === "end_turn") {
808
- // A follow-up that landed during this turn (a background task finished, a cron fired)
808
+ // A follow-up that landed during this turn (a cron fired, an extension's follow-up)
809
809
  // makes the agent run one more turn to consume it instead of stopping — the boundary
810
810
  // drain above injects it. A user's follow-up ends this run instead, and the idle wake
811
811
  // starts its own. User steers can't reach here: runTurn keeps them in-turn.
@@ -0,0 +1,16 @@
1
+ import type { EnvironmentSandbox } from '../tool/environment.ts';
2
+ /** Renew only while a turn or a process task is active. No environment lifecycle ownership. */
3
+ export declare class SandboxKeepalive {
4
+ private sandbox;
5
+ private ttlMs;
6
+ private active;
7
+ private onError;
8
+ private unsupported;
9
+ private closed;
10
+ private timer?;
11
+ private pending?;
12
+ constructor(sandbox: EnvironmentSandbox, ttlMs: number, active: () => boolean, onError: (error: unknown) => void);
13
+ renew(): Promise<void>;
14
+ close(): void;
15
+ }
16
+ //# sourceMappingURL=sandbox-keepalive.d.ts.map
@@ -0,0 +1,36 @@
1
+ /** Renew only while a turn or a process task is active. No environment lifecycle ownership. */
2
+ export class SandboxKeepalive {
3
+ sandbox;
4
+ ttlMs;
5
+ active;
6
+ onError;
7
+ unsupported = false;
8
+ closed = false;
9
+ timer;
10
+ pending;
11
+ constructor(sandbox, ttlMs, active, onError) {
12
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0)
13
+ throw new RangeError('sandboxTtlMs must be positive');
14
+ this.sandbox = sandbox;
15
+ this.ttlMs = ttlMs;
16
+ this.active = active;
17
+ this.onError = onError;
18
+ }
19
+ async renew() {
20
+ if (this.closed || this.unsupported)
21
+ return;
22
+ if (this.timer)
23
+ clearTimeout(this.timer);
24
+ await (this.pending ??= this.sandbox.setTimeout(this.ttlMs).then(supported => { this.unsupported = !supported; }).catch(this.onError).finally(() => { this.pending = undefined; }));
25
+ if (this.closed || this.unsupported)
26
+ return;
27
+ this.timer = setTimeout(() => {
28
+ if (this.active())
29
+ void this.renew();
30
+ }, this.ttlMs / 3);
31
+ this.timer.unref();
32
+ }
33
+ close() { this.closed = true; if (this.timer)
34
+ clearTimeout(this.timer); }
35
+ }
36
+ //# sourceMappingURL=sandbox-keepalive.js.map
@@ -84,6 +84,7 @@ export interface SessionOpenOptions {
84
84
  * outlives any one session, so closing a session must not pull it out from under the others.
85
85
  */
86
86
  readonly environment?: Environment | EnvironmentFactory;
87
+ readonly sandboxTtlMs?: number;
87
88
  readonly events?: EventSink;
88
89
  readonly steer?: SteerBus;
89
90
  /** Answers permission prompts live (as opposed to the interrupt/resume path). */
@@ -461,6 +462,8 @@ export declare class Session implements SessionPort {
461
462
  get thinkingSetting(): ThinkingLevel | undefined;
462
463
  get permissionModeSetting(): PermissionMode | undefined;
463
464
  drainDiagnostics(): CapabilityDiagnostic[];
465
+ private readonly sandboxKeepalive;
466
+ private turnActive;
464
467
  withRunLock<T>(body: () => Promise<T>): Promise<T>;
465
468
  flushEvents(): Promise<void>;
466
469
  /**
@@ -1,3 +1,4 @@
1
+ import { SandboxKeepalive } from "./sandbox-keepalive.js";
1
2
  import { recoverOrphanedTurns } from "./lifecycle-recovery.js";
2
3
  import { readSessionTails } from "../events/projection.js";
3
4
  import { PermissionManager } from "../permission/manager.js";
@@ -128,6 +129,11 @@ export class Session {
128
129
  this.signal = signal;
129
130
  this.ownController = ownController;
130
131
  this.environment = environment;
132
+ this.sandboxKeepalive = new SandboxKeepalive(environment.sandbox, opts.sandboxTtlMs ?? 600_000, () => this.turnActive || (this.background?.list().some(task => task.kind === 'process') ?? false), error => {
133
+ const message = `sandbox renewal failed: ${messageOf(error)}`;
134
+ this.pendingDiagnostics.push({ capability: 'sandbox', phase: 'start', level: 'warn', message });
135
+ this.logger.log('warn', message);
136
+ });
131
137
  this.eventPublisher = publisher;
132
138
  // The publishing wrapper around the host's store: record-backed events surface on `events` when
133
139
  // the append commits, so everything in the session writes through THIS store. Beneath it, the
@@ -900,15 +906,20 @@ export class Session {
900
906
  drainDiagnostics() {
901
907
  return this.pendingDiagnostics.splice(0, this.pendingDiagnostics.length);
902
908
  }
909
+ sandboxKeepalive;
910
+ turnActive = false;
903
911
  async withRunLock(body) {
904
912
  const prev = this.runChain;
905
913
  let release;
906
914
  this.runChain = new Promise((resolve) => (release = resolve));
907
915
  await prev;
916
+ this.turnActive = true;
908
917
  try {
918
+ await this.sandboxKeepalive.renew();
909
919
  return await body();
910
920
  }
911
921
  finally {
922
+ this.turnActive = false;
912
923
  release();
913
924
  }
914
925
  }
@@ -928,6 +939,7 @@ export class Session {
928
939
  return this.closing;
929
940
  }
930
941
  async runClose() {
942
+ this.sandboxKeepalive.close();
931
943
  this.isOpen = false;
932
944
  // Nothing queued will be applied now; one already being applied finishes first, so the
933
945
  // capability it opens is on the list the teardown below walks.
@@ -983,7 +995,7 @@ export class Session {
983
995
  }
984
996
  /** Public URL for a port inside the environment, or undefined when the backend can't expose one. */
985
997
  async resolveExposedPort(port) {
986
- return await this.environment.exposedPortUrl?.(port);
998
+ return await this.environment.sandbox.getUrl(port);
987
999
  }
988
1000
  }
989
1001
  function normalizeGoalBudget(input) {
@@ -107,7 +107,7 @@ export function buildAgentTool(spawner, parent) {
107
107
  const defaultName = spawner.defaultType;
108
108
  const backgroundAvailable = asTaskRegistrar(parent.background) !== undefined && parent.store !== undefined;
109
109
  const backgroundNote = backgroundAvailable
110
- ? "When run_in_background=true, the subagent runs detached from this turn. A metadata-only completion notice arrives automatically; call BackgroundOutput(task_id) when you need the result. You do not need to poll or sleep. Continue with other work. Never fabricate or predict what the result will say."
110
+ ? "When run_in_background=true, the subagent runs detached from this turn. Its completion notice arrives automatically — between your tool calls if you are still working — and carries its final answer in <result>. You do not need to poll or sleep, and there is no tool to fetch the result early. Continue with other work. Never fabricate or predict what the result will say."
111
111
  : "Background execution requires both a BackgroundManager and a durable session store. Do not set run_in_background=true in this session.";
112
112
  const description = [
113
113
  "Launch a subagent to handle a task. The subagent runs as a same-session loop instance with its own context and journal shard.",
@@ -300,11 +300,11 @@ export function buildAgentTool(spawner, parent) {
300
300
  }
301
301
  const controller = new AbortController();
302
302
  // `agentStatus` rides the task into the settle notification, whose journaled
303
- // tag is the durable settle record the subagent fold reads.
304
- // Only the status: the run's own answer is already the last message of its shard,
305
- // which the task names as its output location rather than carrying a copy of.
303
+ // tag is the durable settle record the subagent fold reads. The answer rides with
304
+ // it: the notice is how the model gets it, as Claude Code's `<result>` is.
306
305
  const taskId = registrar.registerTask(new AgentBackgroundTask(() => runSubagent(controller.signal).then((result) => ({
307
306
  agentStatus: settleStatus(result.status),
307
+ result: result.output,
308
308
  })), args.description, {
309
309
  timeoutMs: AGENT_TIMEOUT_MS,
310
310
  subagentType: sub.name,
@@ -328,7 +328,7 @@ export function buildAgentTool(spawner, parent) {
328
328
  "",
329
329
  `description: ${args.description}`,
330
330
  "",
331
- `next_step: The completion arrives automatically in a later turn. BackgroundOutput(task_id="${taskId}", block=false) to peek; resume later with Agent(resume="${agentId}", prompt=...).`,
331
+ `next_step: The completion notice arrives automatically and carries the agent's final answer — do not poll. Resume it later with Agent(resume="${agentId}", prompt=...).`,
332
332
  ].join("\n"),
333
333
  },
334
334
  ],
@@ -391,6 +391,7 @@ export function buildAgentTool(spawner, parent) {
391
391
  clearTimeout(deadlineTimer);
392
392
  const completion = runPromise.then((result) => ({
393
393
  agentStatus: settleStatus(result.status),
394
+ result: result.output,
394
395
  }));
395
396
  const taskId = fgRegistrar.registerTask(new AgentBackgroundTask(() => completion, args.description, {
396
397
  subagentType: sub.name,
@@ -415,7 +416,7 @@ export function buildAgentTool(spawner, parent) {
415
416
  "",
416
417
  `description: ${args.description}`,
417
418
  "",
418
- `next_step: The completion arrives automatically in a later turn. BackgroundOutput(task_id="${taskId}", block=false) to peek; resume later with Agent(resume="${agentId}", prompt=...).`,
419
+ `next_step: The completion notice arrives automatically and carries the agent's final answer — do not poll. Resume it later with Agent(resume="${agentId}", prompt=...).`,
419
420
  ].join("\n"),
420
421
  },
421
422
  ],
@@ -29,7 +29,7 @@ import type { AgentHookOptions } from "./types.ts";
29
29
  * resume strictly needs:
30
30
  *
31
31
  * - RESUME reads `started` / `result` by key, exactly as before.
32
- * - EVERYONE ELSE (the model via BackgroundOutput, a UI seeding its progress view, someone
32
+ * - EVERYONE ELSE (a host reading a run's progress, a UI seeding its progress view, someone
33
33
  * asking why a run came back empty) reads them in append order as the run's story. That
34
34
  * audience needs the labels a human recognises, the phases the script declared, its own
35
35
  * narration, and — most of all — the failures, which used to be emitted to a live progress
@@ -6,7 +6,7 @@
6
6
  */
7
7
  export function workflowPrompt(availableAgents) {
8
8
  const agentList = availableAgents.length > 0 ? availableAgents.join(", ") : "(none configured)";
9
- return `Execute a workflow script that orchestrates multiple subagents deterministically. By default it runs to completion and returns the final value; pass run_in_background:true (recommended for long workflows) to get a task_id immediately; a completion notice arrives on its own, and BackgroundOutput(task_id, block=false) reads progress/result meanwhile. Live progress is reported either way. Pass tokenBudget to cap the run and enable budget.remaining()-guarded loops.
9
+ return `Execute a workflow script that orchestrates multiple subagents deterministically. By default it runs to completion and returns the final value; pass run_in_background:true (recommended for long workflows) to get a task_id immediately; a completion notice carrying the run's result arrives on its own — do not poll. Live progress is reported either way. Pass tokenBudget to cap the run and enable budget.remaining()-guarded loops.
10
10
 
11
11
  A workflow structures work across many agents — to be comprehensive (decompose and cover in parallel), to be confident (independent perspectives and adversarial checks before committing), or to take on scale one context can't hold (migrations, audits, broad sweeps). The script is where you encode that structure: what fans out, what verifies, what synthesizes.
12
12
 
@@ -11,6 +11,9 @@ import { resolveToolPath } from "../../tool/support/tool-path.js";
11
11
  import { readTextFile, writeTextFile } from "../../tool/support/environment-ops.js";
12
12
  import { joinAddress } from "../../events/index.js";
13
13
  import { WorkflowBackgroundTask } from "../../capabilities/background/workflow-task.js";
14
+ import { prepareBackgroundLog } from "../../tool/builtin/bash.js";
15
+ /** Claude Code's cap on a workflow result carried in its completion notice. */
16
+ const WORKFLOW_RESULT_MAX_CHARS = 8_000;
14
17
  import { asTaskRegistrar } from "../../capabilities/background/registrar.js";
15
18
  import { newAgentId } from "../subagent.js";
16
19
  import { guardSubagentInput } from "../subagent-tools.js";
@@ -150,7 +153,7 @@ export function buildWorkflowTool(spawner, parent) {
150
153
  args: z.unknown().optional().describe("Value exposed to the script as the global `args` (pass real JSON, not a stringified value)."),
151
154
  resumeFromRunId: z.string().optional().describe("Resume a prior run; unchanged agent() calls return cached results instantly."),
152
155
  tokenBudget: z.number().optional().describe("Output-token target for the run; enables budget.remaining()-guarded loops in the script."),
153
- run_in_background: z.boolean().optional().describe("Run detached and return a task_id immediately (recommended for long workflows). A completion notice arrives on its own; BackgroundOutput(task_id, block=false) reads progress or the result meanwhile. Requires a BackgroundManager."),
156
+ run_in_background: z.boolean().optional().describe("Run detached and return a task_id immediately (recommended for long workflows). A completion notice arrives on its own and carries the run's result — do not poll. Requires a BackgroundManager."),
154
157
  });
155
158
  return defineTool({
156
159
  name: "Workflow",
@@ -303,6 +306,24 @@ export function buildWorkflowTool(spawner, parent) {
303
306
  // Editable via Write/Edit; pass back as `scriptPath` to re-run without resending.
304
307
  scriptPath: persistedScriptPath,
305
308
  });
309
+ // What a background run's settle notice carries: the same payload the foreground call
310
+ // returns, cut at Claude Code's 8000 characters. The whole of a longer one goes to a task
311
+ // log on the environment, and the cut names it, so `Read` reaches the rest.
312
+ const settleReportOf = async (outcome) => {
313
+ const payload = payloadOf(outcome);
314
+ if (payload.length <= WORKFLOW_RESULT_MAX_CHARS)
315
+ return payload;
316
+ const kept = payload.slice(0, WORKFLOW_RESULT_MAX_CHARS);
317
+ const cut = payload.length - kept.length;
318
+ try {
319
+ const path = await prepareBackgroundLog(ctx.environment);
320
+ await writeTextFile(ctx.environment, path, payload);
321
+ return `${kept}\n... (truncated ${String(cut)} chars, full result in ${path})`;
322
+ }
323
+ catch {
324
+ return `${kept}\n... (truncated ${String(cut)} chars; the full result could not be saved)`;
325
+ }
326
+ };
306
327
  // ── Background path: register a task, return task_id, run detached ──
307
328
  if (args.run_in_background === true) {
308
329
  const registrar = asTaskRegistrar(parent.background);
@@ -311,7 +332,7 @@ export function buildWorkflowTool(spawner, parent) {
311
332
  }
312
333
  const controller = new AbortController();
313
334
  // `runStatus` rides the task into the settle notification, whose journaled tag
314
- // is the durable settle record the workflow fold reads.
335
+ // is the durable settle record the workflow fold reads; the run's report rides with it.
315
336
  const run = async (_sink) => {
316
337
  const journal = mkJournal(runId);
317
338
  const usageBox = { usage: emptyUsage() };
@@ -319,7 +340,7 @@ export function buildWorkflowTool(spawner, parent) {
319
340
  // append. Background execution has no attached courtesy update outlet.
320
341
  const hooks = buildHooks(() => undefined, controller.signal, tokenBudget, usageBox, ctx.toolCallId);
321
342
  const outcome = await executeJournaled(journal, hooks);
322
- return { runStatus: outcome.ok ? "completed" : "failed" };
343
+ return { runStatus: outcome.ok ? "completed" : "failed", result: await settleReportOf(outcome) };
323
344
  };
324
345
  const taskId = registrar.registerTask(new WorkflowBackgroundTask(run, meta.name, {
325
346
  timeoutMs: 60 * 60 * 1000,
@@ -346,7 +367,7 @@ export function buildWorkflowTool(spawner, parent) {
346
367
  ...(meta.phases ? [`phases: ${meta.phases.map((p) => p.title).join(" → ")}`] : []),
347
368
  ...(persistedScriptPath !== undefined ? [`persisted_script: ${persistedScriptPath} (edit with Write/Edit, re-run via scriptPath)`] : []),
348
369
  "",
349
- `next_step: A completion notice arrives automatically. BackgroundOutput(task_id="${taskId}", block=false) reads live progress or the final result; re-run cached with resumeFromRunId="${runId}".`,
370
+ `next_step: A completion notice arrives automatically with the run's result — do not poll. Re-run cached with resumeFromRunId="${runId}".`,
350
371
  ].join("\n"),
351
372
  },
352
373
  ],
@@ -421,7 +442,7 @@ export function buildWorkflowTool(spawner, parent) {
421
442
  ctx.signal.removeEventListener("abort", bridge); // turn-end must not kill the now-background run
422
443
  const taskId = fgRegistrar.registerTask(new WorkflowBackgroundTask(async () => {
423
444
  const oc = await outcomePromise;
424
- return { runStatus: oc.ok ? "completed" : "failed" };
445
+ return { runStatus: oc.ok ? "completed" : "failed", result: await settleReportOf(oc) };
425
446
  }, meta.name, {
426
447
  workflowName: meta.name,
427
448
  runId,
@@ -442,7 +463,7 @@ export function buildWorkflowTool(spawner, parent) {
442
463
  `workflow: ${meta.name}`,
443
464
  "automatic_notification: true",
444
465
  "",
445
- `next_step: A completion notice arrives automatically. BackgroundOutput(task_id="${taskId}", block=false) reads live progress or the final result; re-run cached with resumeFromRunId="${runId}".`,
466
+ `next_step: A completion notice arrives automatically with the run's result — do not poll. Re-run cached with resumeFromRunId="${runId}".`,
446
467
  ].join("\n"),
447
468
  },
448
469
  ],
@@ -497,7 +518,7 @@ async function persistRunScript(environment, name, runId, script) {
497
518
  const safeName = name.replace(/[^a-zA-Z0-9._-]/g, "_").replace(/^\.+/, "") || "workflow";
498
519
  const rel = `${WORKFLOW_RUNS_DIR}/${safeName}.${runId}.js`;
499
520
  try {
500
- await environment.mkdir(await resolveToolPath(WORKFLOW_RUNS_DIR, environment, "write"), { parents: true, existOk: true });
521
+ await environment.files.makeDir(await resolveToolPath(WORKFLOW_RUNS_DIR, environment, "write"));
501
522
  await writeTextFile(environment, await resolveToolPath(rel, environment, "write"), script);
502
523
  return rel;
503
524
  }
@@ -50,7 +50,7 @@ export async function createWorktree(environment, options) {
50
50
  /** Run `git <args>` on the environment's host; `ok` is stdout on exit 0, undefined otherwise. */
51
51
  async function runGit(environment, args) {
52
52
  // `.catch` covers git-not-found / the backend refusing to spawn at all.
53
- const result = await environment.run(["git", ...args]).catch(() => undefined);
53
+ const result = await environment.commands.run(["git", ...args]).catch(() => undefined);
54
54
  return result?.exitCode === 0 ? { ok: result.stdout } : {};
55
55
  }
56
56
  //# sourceMappingURL=worktree.js.map
@@ -5,6 +5,15 @@ export interface AgentBackgroundTaskInfo extends BackgroundTaskInfoBase {
5
5
  readonly subagentType?: string;
6
6
  /** The subagent run's own terminal status (finer than the task status), once settled. */
7
7
  readonly agentStatus?: string;
8
+ /** The sub-agent's final answer, carried into the settle notice so the model gets it there,
9
+ * as Claude Code's `<result>` does — there is no tool to fetch it afterwards. */
10
+ readonly result?: string;
11
+ }
12
+ /** What a background agent's run resolves with. */
13
+ export interface AgentRunOutcome {
14
+ readonly agentStatus: string;
15
+ /** Its final answer, if it gave one. */
16
+ readonly result?: string;
8
17
  }
9
18
  export interface AgentBackgroundTaskOptions {
10
19
  readonly timeoutMs?: number;
@@ -38,13 +47,10 @@ export declare class AgentBackgroundTask implements BackgroundTask {
38
47
  readonly toolCallId?: string;
39
48
  readonly outputLocation?: TaskOutputLocation;
40
49
  private agentStatus?;
50
+ private result?;
41
51
  private readonly run;
42
52
  private readonly abort?;
43
- constructor(run: Promise<{
44
- agentStatus: string;
45
- }> | (() => Promise<{
46
- agentStatus: string;
47
- }>), description: string, options: AgentBackgroundTaskOptions);
53
+ constructor(run: Promise<AgentRunOutcome> | (() => Promise<AgentRunOutcome>), description: string, options: AgentBackgroundTaskOptions);
48
54
  start(sink: BackgroundTaskSink): Promise<void>;
49
55
  toInfo(base: BackgroundTaskInfoBase): AgentBackgroundTaskInfo;
50
56
  }
@@ -21,6 +21,7 @@ export class AgentBackgroundTask {
21
21
  toolCallId;
22
22
  outputLocation;
23
23
  agentStatus;
24
+ result;
24
25
  run;
25
26
  abort;
26
27
  constructor(run, description, options) {
@@ -64,6 +65,8 @@ export class AgentBackgroundTask {
64
65
  return;
65
66
  }
66
67
  this.agentStatus = outcome.agentStatus;
68
+ if (outcome.result !== undefined && outcome.result.length > 0)
69
+ this.result = outcome.result;
67
70
  await sink.settle({ status: taskStatusFromAgent(outcome.agentStatus) });
68
71
  }
69
72
  catch (error) {
@@ -86,6 +89,7 @@ export class AgentBackgroundTask {
86
89
  agentId: this.agentId,
87
90
  subagentType: this.subagentType,
88
91
  agentStatus: this.agentStatus,
92
+ ...(this.result !== undefined ? { result: this.result } : {}),
89
93
  };
90
94
  }
91
95
  }
@@ -19,9 +19,9 @@ export interface CodeBackgroundTaskOptions {
19
19
  *
20
20
  * Holds no output of its own: the program's owner writes its console lines, each nested tool
21
21
  * call's outcome and the final result to a log file on the environment as they happen, the same
22
- * place a background command's bytes go, and this task names that file. `BackgroundOutput`
23
- * reads it like any other file-backed task; a detached program's progress is the same thing
24
- * an attached one's was, in the same place.
22
+ * place a background command's bytes go, and this task names that file. The model `Read`s it
23
+ * like any other task log; a detached program's progress is the same thing an attached one's
24
+ * was, in the same place.
25
25
  */
26
26
  export declare class CodeBackgroundTask implements BackgroundTask {
27
27
  readonly kind: "code";
@@ -4,9 +4,9 @@ import { errorMessage, isAbortError } from "../../loop/errors.js";
4
4
  *
5
5
  * Holds no output of its own: the program's owner writes its console lines, each nested tool
6
6
  * call's outcome and the final result to a log file on the environment as they happen, the same
7
- * place a background command's bytes go, and this task names that file. `BackgroundOutput`
8
- * reads it like any other file-backed task; a detached program's progress is the same thing
9
- * an attached one's was, in the same place.
7
+ * place a background command's bytes go, and this task names that file. The model `Read`s it
8
+ * like any other task log; a detached program's progress is the same thing an attached one's
9
+ * was, in the same place.
10
10
  */
11
11
  export class CodeBackgroundTask {
12
12
  kind = "code";
@@ -1,27 +1,22 @@
1
1
  import type { CommandStarter, ProcessSpawnOptions } from "../../tool/background.ts";
2
2
  import type { BackgroundTask, BackgroundTaskInfoBase, BackgroundTaskSink, TaskOutputLocation } from "./task.ts";
3
+ import type { MonitorTaskInfo } from "./monitor-task.ts";
3
4
  /** Why a command task that was asked to stop settled as failed rather than killed. */
4
5
  export declare const COMMAND_NOT_STOPPED_REASON = "a stop was requested, but the command could not be confirmed stopped and may still be running";
5
6
  export interface CommandBackgroundTaskInfo extends BackgroundTaskInfoBase {
6
7
  /** Wire value kept as "process" — persisted task records use it. */
7
8
  readonly kind: "process";
9
+ readonly process?: {
10
+ readonly pid: number;
11
+ readonly sandboxId: string;
12
+ };
8
13
  readonly command: string;
9
14
  readonly exitCode: number | null;
15
+ /** Present on a Monitor's task: its stdout is an event stream, not a result. */
16
+ readonly monitor?: MonitorTaskInfo;
10
17
  }
11
- /**
12
- * A shell command running as a background task.
13
- *
14
- * Driven by a {@link CommandStarter}, NOT by a process handle. The distinction is the whole
15
- * point: a background task needs to stream output, be stopped, and report how it ended —
16
- * all three of which are `run`'s intent fields, and all three of which every backend can
17
- * deliver natively. Requiring a live process handle instead would demand a capability that
18
- * sandbox transports cannot provide honestly, which is what used to force a fake handle
19
- * whose `kill()` did nothing.
20
- *
21
- * No `forceStop`: SIGTERM → grace → SIGKILL escalation belongs to the Environment layer, which
22
- * is where killing is real. Aborting the signal is the whole stop protocol — and the result's
23
- * `terminated` is the answer: only a confirmed stop settles as `killed`.
24
- */
18
+ /** A durable command task. The starter exposes its handle before waiting; identity is
19
+ * persisted immediately and the environment owns log capture and process termination. */
25
20
  export declare class CommandBackgroundTask implements BackgroundTask {
26
21
  readonly kind: "process";
27
22
  readonly idPrefix = "bash";
@@ -36,6 +31,11 @@ export declare class CommandBackgroundTask implements BackgroundTask {
36
31
  private readonly start_;
37
32
  readonly parentAddress?: string;
38
33
  readonly toolCallId?: string;
34
+ private handle?;
35
+ disconnectOutput(): Promise<void>;
36
+ private processValue?;
37
+ private outputListeners;
38
+ subscribeOutput(listener: (data: string) => void): () => void;
39
39
  private exitCodeValue;
40
40
  private stopUnconfirmedValue;
41
41
  constructor(start: CommandStarter, command: string, description: string, options?: ProcessSpawnOptions);
@@ -1,20 +1,9 @@
1
+ import { stopOutputSubscription } from "../../tool/environment-output.js";
1
2
  import { errorMessage } from "../../loop/errors.js";
2
3
  /** Why a command task that was asked to stop settled as failed rather than killed. */
3
4
  export const COMMAND_NOT_STOPPED_REASON = "a stop was requested, but the command could not be confirmed stopped and may still be running";
4
- /**
5
- * A shell command running as a background task.
6
- *
7
- * Driven by a {@link CommandStarter}, NOT by a process handle. The distinction is the whole
8
- * point: a background task needs to stream output, be stopped, and report how it ended —
9
- * all three of which are `run`'s intent fields, and all three of which every backend can
10
- * deliver natively. Requiring a live process handle instead would demand a capability that
11
- * sandbox transports cannot provide honestly, which is what used to force a fake handle
12
- * whose `kill()` did nothing.
13
- *
14
- * No `forceStop`: SIGTERM → grace → SIGKILL escalation belongs to the Environment layer, which
15
- * is where killing is real. Aborting the signal is the whole stop protocol — and the result's
16
- * `terminated` is the answer: only a confirmed stop settles as `killed`.
17
- */
5
+ /** A durable command task. The starter exposes its handle before waiting; identity is
6
+ * persisted immediately and the environment owns log capture and process termination. */
18
7
  export class CommandBackgroundTask {
19
8
  kind = "process";
20
9
  idPrefix = "bash";
@@ -29,6 +18,15 @@ export class CommandBackgroundTask {
29
18
  start_;
30
19
  parentAddress;
31
20
  toolCallId;
21
+ handle;
22
+ async disconnectOutput() {
23
+ // SDK disconnect also abandons wait(); retain lifecycle ownership until settlement.
24
+ if (this.handle)
25
+ await stopOutputSubscription(this.handle);
26
+ }
27
+ processValue;
28
+ outputListeners = new Set();
29
+ subscribeOutput(listener) { this.outputListeners.add(listener); return () => { this.outputListeners.delete(listener); }; }
32
30
  exitCodeValue = null;
33
31
  stopUnconfirmedValue = false;
34
32
  constructor(start, command, description, options = {}) {
@@ -67,6 +65,15 @@ export class CommandBackgroundTask {
67
65
  // shape this replaced — there is no trailing output to race a drain timer against.
68
66
  const result = await this.start_({
69
67
  signal: controller.signal,
68
+ onStart: async (handle) => {
69
+ this.handle = handle;
70
+ const location = this.outputLocation;
71
+ if (location?.kind === 'file')
72
+ this.processValue = { pid: handle.pid, sandboxId: location.environment.sandbox.id };
73
+ await sink.update?.();
74
+ },
75
+ onOutput: this.outputListeners.size ? data => { for (const cb of this.outputListeners)
76
+ cb(data); } : undefined,
70
77
  });
71
78
  this.exitCodeValue = result.exitCode ?? null;
72
79
  if (sink.signal.aborted && !result.terminated) {
@@ -95,6 +102,7 @@ export class CommandBackgroundTask {
95
102
  ...base,
96
103
  kind: "process",
97
104
  command: this.command,
105
+ process: this.processValue,
98
106
  exitCode: this.exitCodeValue,
99
107
  };
100
108
  }
@@ -1,7 +1,7 @@
1
1
  import type { Capability } from "../capability.ts";
2
2
  import { BackgroundManager } from "./manager.ts";
3
3
  export { BackgroundManager } from "./manager.ts";
4
- export type { BackgroundManagerOptions, BackgroundManagerRuntime, OutputFollowTiming, BackgroundTaskOutputDelta, BackgroundTaskOutputSnapshot, } from "./manager.ts";
4
+ export type { BackgroundManagerOptions, BackgroundManagerRuntime, BackgroundTaskOutputDelta, BackgroundTaskOutputSnapshot, } from "./manager.ts";
5
5
  export type { StallWatchdogTiming } from "./stall-watchdog.ts";
6
6
  export { CommandBackgroundTask } from "./command-task.ts";
7
7
  export type { CommandBackgroundTaskInfo } from "./command-task.ts";
@@ -18,7 +18,10 @@ export type { BackgroundTaskRegistrar } from "./registrar.ts";
18
18
  export { StoreBackgroundTaskPersistence, isPersistedTaskTerminal, isValidPersistedTask } from "./persist.ts";
19
19
  export type { BackgroundTaskPersistence, PersistedTask } from "./persist.ts";
20
20
  export { DiskBackgroundTaskPersistence } from "./persist-disk.ts";
21
- export { backgroundListTool, backgroundOutputTool, backgroundStopTool } from "./tools.ts";
21
+ export { backgroundListTool, backgroundStopTool } from "./tools.ts";
22
+ export { monitorTool } from "./monitor-tool.ts";
23
+ export { MonitorBackgroundTask, LineBatcher, EventLimiter, MONITOR_DEFAULT_TIMING } from "./monitor-task.ts";
24
+ export type { MonitorTaskInfo } from "./monitor-task.ts";
22
25
  export { TERMINAL_STATUSES, isBackgroundTaskTerminal, } from "./task.ts";
23
26
  export type { BackgroundTask, BackgroundTaskInfo, BackgroundTaskInfoBase, BackgroundTaskSink, BackgroundTaskSettlement, BackgroundTaskSettlementStatus, BackgroundTaskStatus, TaskOutputRef, TaskOutputLocation, } from "./task.ts";
24
27
  export declare function backgroundCapability(manager?: BackgroundManager): Capability;
@@ -1,7 +1,8 @@
1
1
  import { BackgroundManager } from "./manager.js";
2
2
  import { StoreBackgroundTaskPersistence } from "./persist.js";
3
3
  import { DiskBackgroundTaskPersistence } from "./persist-disk.js";
4
- import { backgroundListTool, backgroundOutputTool, backgroundStopTool } from "./tools.js";
4
+ import { backgroundStopTool } from "./tools.js";
5
+ import { monitorTool } from "./monitor-tool.js";
5
6
  export { BackgroundManager } from "./manager.js";
6
7
  export { CommandBackgroundTask } from "./command-task.js";
7
8
  export { AgentBackgroundTask } from "./agent-task.js";
@@ -11,7 +12,9 @@ export { CodeBackgroundTask } from "./code-task.js";
11
12
  export { asTaskRegistrar } from "./registrar.js";
12
13
  export { StoreBackgroundTaskPersistence, isPersistedTaskTerminal, isValidPersistedTask } from "./persist.js";
13
14
  export { DiskBackgroundTaskPersistence } from "./persist-disk.js";
14
- export { backgroundListTool, backgroundOutputTool, backgroundStopTool } from "./tools.js";
15
+ export { backgroundListTool, backgroundStopTool } from "./tools.js";
16
+ export { monitorTool } from "./monitor-tool.js";
17
+ export { MonitorBackgroundTask, LineBatcher, EventLimiter, MONITOR_DEFAULT_TIMING } from "./monitor-task.js";
15
18
  export { TERMINAL_STATUSES, isBackgroundTaskTerminal, } from "./task.js";
16
19
  export function backgroundCapability(manager = new BackgroundManager()) {
17
20
  return {
@@ -20,7 +23,7 @@ export function backgroundCapability(manager = new BackgroundManager()) {
20
23
  // Enumeration stays a host API (`session.listBackgroundTasks()`). The model already owns
21
24
  // every task id it successfully spawned, while cold recovery injects ids whose ack was lost;
22
25
  // exposing an unbounded list invites unrelated historical tasks into the reasoning path.
23
- tools: [backgroundOutputTool(manager), backgroundStopTool(manager)],
26
+ tools: [backgroundStopTool(manager), monitorTool()],
24
27
  service: manager,
25
28
  openSession: async (ctx) => {
26
29
  {
@@ -31,6 +34,7 @@ export function backgroundCapability(manager = new BackgroundManager()) {
31
34
  // + reconcile happen in the store-cutover step; here we attach the persistence so live
32
35
  // spawns start recording. Without a durable store the manager stays purely in memory.
33
36
  manager.attach({
37
+ environment: ctx.environment,
34
38
  steer,
35
39
  events,
36
40
  sessionId: ctx.sessionId,