strands-darwin 0.0.31 → 0.0.33

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 (62) hide show
  1. package/dist/src/agent/background-delegation.d.ts +69 -11
  2. package/dist/src/agent/background-delegation.js +156 -28
  3. package/dist/src/agent/background-delegation.js.map +1 -1
  4. package/dist/src/agent/runtime.d.ts +55 -1
  5. package/dist/src/agent/runtime.js +84 -11
  6. package/dist/src/agent/runtime.js.map +1 -1
  7. package/dist/src/agent/task-terminal-delivery.d.ts +43 -0
  8. package/dist/src/agent/task-terminal-delivery.js +115 -0
  9. package/dist/src/agent/task-terminal-delivery.js.map +1 -0
  10. package/dist/src/agents/subagent-tool.d.ts +6 -0
  11. package/dist/src/agents/subagent-tool.js +1 -1
  12. package/dist/src/agents/subagent-tool.js.map +1 -1
  13. package/dist/src/agents/workflow-tool.d.ts +2 -0
  14. package/dist/src/agents/workflow-tool.js +1 -1
  15. package/dist/src/agents/workflow-tool.js.map +1 -1
  16. package/dist/src/cli-main.js +5 -0
  17. package/dist/src/cli-main.js.map +1 -1
  18. package/dist/src/config.d.ts +14 -1
  19. package/dist/src/config.js +3 -0
  20. package/dist/src/config.js.map +1 -1
  21. package/dist/src/headless-protocol.d.ts +20 -1
  22. package/dist/src/headless-protocol.js +14 -0
  23. package/dist/src/headless-protocol.js.map +1 -1
  24. package/dist/src/headless-runner.js +18 -2
  25. package/dist/src/headless-runner.js.map +1 -1
  26. package/dist/src/headless.d.ts +18 -0
  27. package/dist/src/headless.js +25 -0
  28. package/dist/src/headless.js.map +1 -1
  29. package/dist/src/tools/background-bash.d.ts +11 -2
  30. package/dist/src/tools/background-bash.js +11 -5
  31. package/dist/src/tools/background-bash.js.map +1 -1
  32. package/dist/src/tools/background-tail.d.ts +1 -0
  33. package/dist/src/tools/background-tail.js +2 -1
  34. package/dist/src/tools/background-tail.js.map +1 -1
  35. package/dist/src/tools/background-wait-contract.d.ts +7 -0
  36. package/dist/src/tools/background-wait-contract.js +17 -0
  37. package/dist/src/tools/background-wait-contract.js.map +1 -1
  38. package/dist/src/trajectory/record.d.ts +45 -2
  39. package/dist/src/trajectory/record.js +3 -0
  40. package/dist/src/trajectory/record.js.map +1 -1
  41. package/dist/src/trajectory/replay.js +14 -0
  42. package/dist/src/trajectory/replay.js.map +1 -1
  43. package/dist/src/trajectory/writer.d.ts +13 -6
  44. package/dist/src/trajectory/writer.js +31 -7
  45. package/dist/src/trajectory/writer.js.map +1 -1
  46. package/dist/src/tui/App.js +154 -23
  47. package/dist/src/tui/App.js.map +1 -1
  48. package/dist/src/tui/background-tool-presentation.js +2 -2
  49. package/dist/src/tui/background-tool-presentation.js.map +1 -1
  50. package/dist/src/tui/prompt-queue.d.ts +52 -8
  51. package/dist/src/tui/prompt-queue.js +68 -8
  52. package/dist/src/tui/prompt-queue.js.map +1 -1
  53. package/dist/src/tui/subagent-format.d.ts +8 -0
  54. package/dist/src/tui/subagent-format.js +11 -0
  55. package/dist/src/tui/subagent-format.js.map +1 -1
  56. package/dist/src/tui/task-wake.d.ts +75 -0
  57. package/dist/src/tui/task-wake.js +201 -0
  58. package/dist/src/tui/task-wake.js.map +1 -0
  59. package/dist/src/tui/turn-state.d.ts +10 -1
  60. package/dist/src/tui/turn-state.js +17 -1
  61. package/dist/src/tui/turn-state.js.map +1 -1
  62. package/package.json +1 -1
@@ -15,6 +15,13 @@ export interface BackgroundDelegationConfigInput {
15
15
  readonly ordinaryToolNames: readonly string[];
16
16
  /** The SER-061 cap (`concurrencyCap(config)`); the SDK engine queues beyond it. */
17
17
  readonly maxConcurrency: number;
18
+ /**
19
+ * True only for a runtime whose driver drains completion wakes (the TUI with
20
+ * `backgroundTaskWake` on): the dispatching turn then ends after the ack and the
21
+ * report arrives in the next turn that runs. False keeps the SDK waiting inside the
22
+ * invocation, so a headless run's one cycle still contains the report.
23
+ */
24
+ readonly completionWakes: boolean;
18
25
  }
19
26
  /**
20
27
  * The `backgroundTasks` option for the parent Agent.
@@ -24,6 +31,8 @@ export interface BackgroundDelegationConfigInput {
24
31
  * plugin's own manage tool) is `never` as well rather than falling back to the SDK's
25
32
  * `agentic` default for unnamed tools. The SDK rejects a name listed under two modes,
26
33
  * so a delegation tool is removed from `never` if a caller passes it in both lists.
34
+ * `waitForCompletion` is the one per-runtime choice (SER-070): `false` when the driver
35
+ * wakes on settlement, `true` otherwise.
27
36
  */
28
37
  export declare function backgroundDelegationConfig(input: BackgroundDelegationConfigInput): BackgroundTasksConfig;
29
38
  /** True when a tool-use input asks for background execution (`_background_execution: true`). */
@@ -31,37 +40,86 @@ export declare function backgroundExecutionRequested(input: unknown): boolean;
31
40
  /**
32
41
  * The one sentence both delegation tool descriptions carry. The flag itself is
33
42
  * added to the spec by the SDK middleware, so the description only has to say when
34
- * to use it and when the result comes back.
43
+ * to use it and when the result comes back — which depends on the runtime
44
+ * (SER-070): a waking runtime lets the turn end and delivers the report in the next
45
+ * turn that runs; every other runtime delivers it before the next model call of the
46
+ * same turn, byte-identical to the pre-SER-070 sentence.
35
47
  */
36
- export declare function backgroundDelegationDescriptionClause(): string;
48
+ export declare function backgroundDelegationDescriptionClause(completionWakes?: boolean): string;
37
49
  /**
38
50
  * The task id inside the SDK's dispatch acknowledgement, or `undefined` for any
39
51
  * other tool result. Reads the ack's fixed text shape only; never a task registry.
40
52
  */
41
53
  export declare function backgroundAckTaskId(content: readonly unknown[]): string | undefined;
54
+ /** How far one background delegation has come; `running` until its run's body returns. */
55
+ export type BackgroundDelegationState = 'running' | 'succeeded' | 'failed';
56
+ /**
57
+ * One background delegation the SDK still tracks: dispatched (the ack named a task)
58
+ * and not yet delivered to the model as its result pair. Everything here came down
59
+ * the parent's own stream or hook — no SDK internals, no task registry.
60
+ */
61
+ export interface BackgroundDelegationStatus {
62
+ /** The SDK task id from the ack; the pair's tool-use id when it is delivered. */
63
+ readonly taskId: string;
64
+ /** The model's tool-use id for the dispatching call. */
65
+ readonly toolUseId: string;
66
+ /** `subagent` or `workflow`. */
67
+ readonly toolName: string;
68
+ /** The tool-use input as the stream showed it (the SDK strips the flag later). */
69
+ readonly input: unknown;
70
+ /** ISO time of the `beforeToolCallEvent`. */
71
+ readonly startedAt: string;
72
+ /** ISO time of the run's `AfterToolCallEvent`; `null` while running. */
73
+ readonly settledAt: string | null;
74
+ readonly state: BackgroundDelegationState;
75
+ }
76
+ export type BackgroundDelegationListener = (status: BackgroundDelegationStatus) => void;
77
+ /** The first eight characters of an SDK task id (a UUID) — enough to tell tasks apart in a row. */
78
+ export declare function shortBackgroundTaskId(taskId: string): string;
79
+ /**
80
+ * The one refusal `/clear` and `/rewind` give while a background delegation is
81
+ * tracked (SER-070): the live task ids and the two ways out. Never a partial restore,
82
+ * never a silent cancel of minutes of child work — the same rule as the SER-027 busy
83
+ * refusal. Shared by the TUI's local check and the runtime's own guard, so the two
84
+ * cannot word it differently.
85
+ */
86
+ export declare function liveBackgroundDelegationRefusal(command: '/clear' | '/rewind', tasks: readonly BackgroundDelegationStatus[]): string;
42
87
  /**
43
- * Forwards background runs' `AfterToolCallEvent`s into the parent's stream.
88
+ * Forwards background runs' `AfterToolCallEvent`s into the parent's stream and keeps
89
+ * the parent-side ledger of tracked delegations (SER-064, SER-070).
44
90
  *
45
91
  * One instance per parent Agent; {@link observe} wraps exactly one `Agent.stream()`
46
- * at a time (the runtime serializes turns). Per turn it remembers which tool-use ids
47
- * the stream showed as routed to the background — a `beforeToolCallEvent` for a
92
+ * at a time (the runtime serializes turns). It remembers which tool-use ids the
93
+ * stream showed as routed to the background — a `beforeToolCallEvent` for a
48
94
  * delegation tool whose input carries the flag and which no hook cancelled — and
49
95
  * yields the hook-observed `AfterToolCallEvent` for those ids in front of the next SDK
50
- * event. Ids a stream `afterToolCallEvent` closes are dropped (a denied or
51
- * foreground call). Anything left over when a turn ends — a task still cancelling
52
- * after Ctrl+C — is discarded at the start of the next turn: the SDK delivers that
53
- * task's result pair before the next model call itself, and the transcript already
54
- * shows the cancelled turn.
96
+ * event. Ids a stream `afterToolCallEvent` closes are dropped (a denied or foreground
97
+ * call); so is an id whose `toolResultEvent` is not an ack (admission failed: no run
98
+ * follows). The ledger is **not** reset per stream: with `waitForCompletion: false` a
99
+ * child outlives the turn that dispatched it, so an id stays pending across turns, an
100
+ * `AfterToolCallEvent` that arrives between turns is buffered and yielded at the next
101
+ * stream's start, and the recorder and every driver still see exactly one
102
+ * before/after pair per delegation. An entry leaves the ledger when the SDK delivers
103
+ * its result pair — the `messageAddedEvent` whose tool result carries the task id —
104
+ * which is also the moment the SDK stops tracking the task, so {@link list} is what
105
+ * `/clear` and `/rewind` consult before the SDK's `assertCanLoadSnapshot` would throw.
106
+ * Settlement listeners fire once per task, from the hook, with the terminal snapshot.
55
107
  */
56
108
  export declare class BackgroundDelegationObserver {
57
109
  private readonly delegationTools;
58
110
  private readonly pending;
111
+ private readonly listeners;
59
112
  private ready;
60
113
  constructor(delegationTools: readonly string[]);
61
114
  /** Registers the hook on the parent; call once, after construction. */
62
115
  install(agent: Agent): void;
63
- /** Tool-use ids routed to the background in the current turn and not yet settled. */
116
+ private publish;
117
+ /** Tool-use ids routed to the background and not yet settled. */
64
118
  get pendingCount(): number;
119
+ /** Every delegation the SDK still tracks, running or settled-undelivered, in dispatch order. */
120
+ list(): BackgroundDelegationStatus[];
121
+ /** Publishes each task's one terminal snapshot until the returned closure is called. */
122
+ subscribe(listener: BackgroundDelegationListener): () => void;
65
123
  observe(events: AsyncIterable<AgentStreamEvent>): AsyncIterable<AgentStreamEvent>;
66
124
  private drain;
67
125
  }
@@ -12,13 +12,24 @@
12
12
  * permission gate, plan-mode denial and the retry guard have already run —
13
13
  * `routeToolCall` strips the flag and `submitToolCall` returns an ack tool result
14
14
  * carrying a task id (`executor.js`, the `route === true` branch);
15
- * - with `waitForCompletion: true`, `AfterInvocationEvent` waits for every tracked
16
- * task, then `_deliverReady` appends one synthetic
17
- * `strands_background_task_result` tool-use/tool-result pair through
18
- * `continuations.addInput` and the same invocation makes another model call — so a
19
- * result never crosses into a later user turn;
15
+ * - delivers a finished task as one synthetic `strands_background_task_result`
16
+ * tool-use/tool-result pair through `continuations.addInput`, from two hooks: at
17
+ * every `BeforeModelCallEvent` (`_deliverReady`, so a task that settled since the
18
+ * last call rides the next request) and at `AfterInvocationEvent` — where, with
19
+ * `waitForCompletion: true`, it first waits for every tracked task so the same
20
+ * invocation makes another model call, and with `false` it delivers only what is
21
+ * already terminal and lets the invocation end;
20
22
  * - registers `strands_manage_background_task` (`list`/`get`/`cancel`) on the parent.
21
23
  *
24
+ * SER-070 chooses the mode per runtime: a driver that drains completion wakes (the
25
+ * TUI, `RuntimeOptions.backgroundCompletionWakes`) passes `false`, so the dispatching
26
+ * turn ends after the ack and the user keeps prompting; the child's settlement then
27
+ * starts one wake turn when the session is idle, and the SDK's own before-model-call
28
+ * delivery attaches the report to that turn's request. Headless runs have no later
29
+ * turn for a report to arrive in, so they keep `true` and the result stays inside the
30
+ * one `run.*` cycle. In both modes the report reaches the model through the SDK only —
31
+ * darwin never copies it.
32
+ *
22
33
  * Two of its events do not travel down the parent's stream, and that is what the
23
34
  * observer below exists for. The background run's real `AfterToolCallEvent` is
24
35
  * delivered to hook callbacks only (`ToolExecutor.executeBackground` → the agent's
@@ -32,9 +43,13 @@
32
43
  * SDK object, unmodified — into the stream `AgentRuntime.send()` hands to its
33
44
  * consumers, ahead of the next SDK event. Only calls the stream itself showed as
34
45
  * routed to the background are forwarded; every foreground `AfterToolCallEvent` is
35
- * yielded by the SDK and left alone.
46
+ * yielded by the SDK and left alone. The same hook is the settlement trigger for the
47
+ * wake: it fires once per background run, exactly when the run's body returns (the
48
+ * dispatch registry's listener fires per *child*, so a `workflow` of several nodes
49
+ * would fire several times for one task, and it knows dispatch ids, not task ids).
36
50
  */
37
51
  import { AfterToolCallEvent, HookOrder } from '@strands-agents/sdk';
52
+ import { shortDispatchId } from '../agents/dispatch-registry.js';
38
53
  /** The per-call selector the SDK middleware adds to `agentic` tool specs. */
39
54
  export const BACKGROUND_EXECUTION_FLAG = '_background_execution';
40
55
  /** The SDK's own management tool; parent-only, classified in `permission.ts`. */
@@ -52,6 +67,8 @@ const ACK_TASK_ID = /^Task ID: (\S+)$/mu;
52
67
  * plugin's own manage tool) is `never` as well rather than falling back to the SDK's
53
68
  * `agentic` default for unnamed tools. The SDK rejects a name listed under two modes,
54
69
  * so a delegation tool is removed from `never` if a caller passes it in both lists.
70
+ * `waitForCompletion` is the one per-runtime choice (SER-070): `false` when the driver
71
+ * wakes on settlement, `true` otherwise.
55
72
  */
56
73
  export function backgroundDelegationConfig(input) {
57
74
  const agentic = [...new Set(input.delegationTools)];
@@ -59,7 +76,7 @@ export function backgroundDelegationConfig(input) {
59
76
  return {
60
77
  agentic,
61
78
  never: [...never, '*'],
62
- waitForCompletion: true,
79
+ waitForCompletion: !input.completionWakes,
63
80
  maxConcurrency: input.maxConcurrency,
64
81
  };
65
82
  }
@@ -73,12 +90,20 @@ export function backgroundExecutionRequested(input) {
73
90
  /**
74
91
  * The one sentence both delegation tool descriptions carry. The flag itself is
75
92
  * added to the spec by the SDK middleware, so the description only has to say when
76
- * to use it and when the result comes back.
93
+ * to use it and when the result comes back — which depends on the runtime
94
+ * (SER-070): a waking runtime lets the turn end and delivers the report in the next
95
+ * turn that runs; every other runtime delivers it before the next model call of the
96
+ * same turn, byte-identical to the pre-SER-070 sentence.
77
97
  */
78
- export function backgroundDelegationDescriptionClause() {
79
- return (`Set ${BACKGROUND_EXECUTION_FLAG}: true to run this call in the background when you do not ` +
80
- 'need its result immediately (reads only): you get an acknowledgement at once and the ' +
81
- 'final report is delivered before your next model call in this same turn.');
98
+ export function backgroundDelegationDescriptionClause(completionWakes = false) {
99
+ const lead = `Set ${BACKGROUND_EXECUTION_FLAG}: true to run this call in the background when you do not ` +
100
+ 'need its result immediately (reads only): you get an acknowledgement at once and the ';
101
+ return completionWakes
102
+ ? lead +
103
+ 'final report arrives as a strands_background_task_result tool result in the next turn ' +
104
+ 'that runs — you may end this turn; once the session is idle, one <task-notification> ' +
105
+ 'turn starts with the report attached.'
106
+ : lead + 'final report is delivered before your next model call in this same turn.';
82
107
  }
83
108
  /**
84
109
  * The task id inside the SDK's dispatch acknowledgement, or `undefined` for any
@@ -97,23 +122,62 @@ export function backgroundAckTaskId(content) {
97
122
  }
98
123
  return undefined;
99
124
  }
125
+ /** The first eight characters of an SDK task id (a UUID) — enough to tell tasks apart in a row. */
126
+ export function shortBackgroundTaskId(taskId) {
127
+ return taskId.length > 8 ? taskId.slice(0, 8) : taskId;
128
+ }
100
129
  /**
101
- * Forwards background runs' `AfterToolCallEvent`s into the parent's stream.
130
+ * The one refusal `/clear` and `/rewind` give while a background delegation is
131
+ * tracked (SER-070): the live task ids and the two ways out. Never a partial restore,
132
+ * never a silent cancel of minutes of child work — the same rule as the SER-027 busy
133
+ * refusal. Shared by the TUI's local check and the runtime's own guard, so the two
134
+ * cannot word it differently.
135
+ */
136
+ export function liveBackgroundDelegationRefusal(command, tasks) {
137
+ const named = tasks
138
+ .map((task) => task.toolName === 'subagent'
139
+ ? `subagent #${shortDispatchId(task.toolUseId)} (task ${task.taskId}, ${task.state})`
140
+ : `${task.toolName} (task ${task.taskId}, ${task.state}; /agents lists its node ids)`)
141
+ .join(', ');
142
+ return (`${command} refused — ${tasks.length === 1 ? 'a background delegation is' : `${tasks.length} background delegations are`} ` +
143
+ `still tracked: ${named}. Cancel with /agents cancel <id>, or wait for the completion wake to deliver the report; then retry.`);
144
+ }
145
+ function snapshot(entry) {
146
+ return {
147
+ taskId: entry.taskId,
148
+ toolUseId: entry.toolUseId,
149
+ toolName: entry.toolName,
150
+ input: entry.input,
151
+ startedAt: entry.startedAt,
152
+ settledAt: entry.settledAt,
153
+ state: entry.state,
154
+ };
155
+ }
156
+ /**
157
+ * Forwards background runs' `AfterToolCallEvent`s into the parent's stream and keeps
158
+ * the parent-side ledger of tracked delegations (SER-064, SER-070).
102
159
  *
103
160
  * One instance per parent Agent; {@link observe} wraps exactly one `Agent.stream()`
104
- * at a time (the runtime serializes turns). Per turn it remembers which tool-use ids
105
- * the stream showed as routed to the background — a `beforeToolCallEvent` for a
161
+ * at a time (the runtime serializes turns). It remembers which tool-use ids the
162
+ * stream showed as routed to the background — a `beforeToolCallEvent` for a
106
163
  * delegation tool whose input carries the flag and which no hook cancelled — and
107
164
  * yields the hook-observed `AfterToolCallEvent` for those ids in front of the next SDK
108
- * event. Ids a stream `afterToolCallEvent` closes are dropped (a denied or
109
- * foreground call). Anything left over when a turn ends — a task still cancelling
110
- * after Ctrl+C — is discarded at the start of the next turn: the SDK delivers that
111
- * task's result pair before the next model call itself, and the transcript already
112
- * shows the cancelled turn.
165
+ * event. Ids a stream `afterToolCallEvent` closes are dropped (a denied or foreground
166
+ * call); so is an id whose `toolResultEvent` is not an ack (admission failed: no run
167
+ * follows). The ledger is **not** reset per stream: with `waitForCompletion: false` a
168
+ * child outlives the turn that dispatched it, so an id stays pending across turns, an
169
+ * `AfterToolCallEvent` that arrives between turns is buffered and yielded at the next
170
+ * stream's start, and the recorder and every driver still see exactly one
171
+ * before/after pair per delegation. An entry leaves the ledger when the SDK delivers
172
+ * its result pair — the `messageAddedEvent` whose tool result carries the task id —
173
+ * which is also the moment the SDK stops tracking the task, so {@link list} is what
174
+ * `/clear` and `/rewind` consult before the SDK's `assertCanLoadSnapshot` would throw.
175
+ * Settlement listeners fire once per task, from the hook, with the terminal snapshot.
113
176
  */
114
177
  export class BackgroundDelegationObserver {
115
178
  delegationTools;
116
- pending = new Set();
179
+ pending = new Map();
180
+ listeners = new Set();
117
181
  ready = [];
118
182
  constructor(delegationTools) {
119
183
  this.delegationTools = new Set(delegationTools);
@@ -121,28 +185,92 @@ export class BackgroundDelegationObserver {
121
185
  /** Registers the hook on the parent; call once, after construction. */
122
186
  install(agent) {
123
187
  agent.addHook(AfterToolCallEvent, (event) => {
124
- if (this.pending.delete(event.toolUse.toolUseId))
125
- this.ready.push(event);
188
+ const entry = this.pending.get(event.toolUse.toolUseId);
189
+ if (entry === undefined)
190
+ return;
191
+ this.ready.push(event);
192
+ entry.settledAt = new Date().toISOString();
193
+ entry.state = event.result.status === 'error' ? 'failed' : 'succeeded';
194
+ // A run so short that its body returned before the stream yielded the ack
195
+ // is published when the ack names the task (see `toolResultEvent` below).
196
+ if (entry.taskId !== undefined)
197
+ this.publish(snapshot({ ...entry, taskId: entry.taskId }));
126
198
  }, { order: HookOrder.SDK_LAST });
127
199
  }
128
- /** Tool-use ids routed to the background in the current turn and not yet settled. */
200
+ publish(status) {
201
+ for (const listener of this.listeners)
202
+ listener(status);
203
+ }
204
+ /** Tool-use ids routed to the background and not yet settled. */
129
205
  get pendingCount() {
130
- return this.pending.size;
206
+ let count = 0;
207
+ for (const entry of this.pending.values())
208
+ if (entry.state === 'running')
209
+ count += 1;
210
+ return count;
211
+ }
212
+ /** Every delegation the SDK still tracks, running or settled-undelivered, in dispatch order. */
213
+ list() {
214
+ const tracked = [];
215
+ for (const entry of this.pending.values()) {
216
+ if (entry.taskId !== undefined)
217
+ tracked.push(snapshot({ ...entry, taskId: entry.taskId }));
218
+ }
219
+ return tracked;
220
+ }
221
+ /** Publishes each task's one terminal snapshot until the returned closure is called. */
222
+ subscribe(listener) {
223
+ this.listeners.add(listener);
224
+ return () => {
225
+ this.listeners.delete(listener);
226
+ };
131
227
  }
132
228
  async *observe(events) {
133
- this.pending.clear();
134
- this.ready = [];
229
+ // A settlement that arrived between turns is the first thing the new stream shows.
230
+ yield* this.drain();
135
231
  for await (const event of events) {
136
232
  if (event.type === 'beforeToolCallEvent') {
137
233
  if (!event.cancel &&
138
234
  this.delegationTools.has(event.toolUse.name) &&
139
235
  backgroundExecutionRequested(event.toolUse.input)) {
140
- this.pending.add(event.toolUse.toolUseId);
236
+ this.pending.set(event.toolUse.toolUseId, {
237
+ taskId: undefined,
238
+ toolUseId: event.toolUse.toolUseId,
239
+ toolName: event.toolUse.name,
240
+ input: event.toolUse.input,
241
+ startedAt: new Date().toISOString(),
242
+ settledAt: null,
243
+ state: 'running',
244
+ });
141
245
  }
142
246
  }
143
247
  else if (event.type === 'afterToolCallEvent') {
144
248
  this.pending.delete(event.toolUse.toolUseId);
145
249
  }
250
+ else if (event.type === 'toolResultEvent') {
251
+ const entry = this.pending.get(event.result.toolUseId);
252
+ if (entry !== undefined && entry.taskId === undefined) {
253
+ const taskId = event.result.status === 'error' ? undefined : backgroundAckTaskId(event.result.content);
254
+ if (taskId === undefined) {
255
+ this.pending.delete(entry.toolUseId);
256
+ }
257
+ else {
258
+ entry.taskId = taskId;
259
+ if (entry.state !== 'running')
260
+ this.publish(snapshot({ ...entry, taskId }));
261
+ }
262
+ }
263
+ }
264
+ else if (event.type === 'messageAddedEvent' && event.message.role === 'user') {
265
+ for (const block of event.message.content) {
266
+ if (block.type !== 'toolResultBlock')
267
+ continue;
268
+ for (const entry of this.pending.values()) {
269
+ if (entry.taskId === block.toolUseId)
270
+ this.pending.delete(entry.toolUseId);
271
+ }
272
+ }
273
+ }
146
274
  yield* this.drain();
147
275
  yield event;
148
276
  }
@@ -1 +1 @@
1
- {"version":3,"file":"background-delegation.js","sourceRoot":"","sources":["../../../src/agent/background-delegation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAGpE,6EAA6E;AAC7E,MAAM,CAAC,MAAM,yBAAyB,GAAG,uBAAuB,CAAC;AAEjE,iFAAiF;AACjF,MAAM,CAAC,MAAM,gCAAgC,GAAG,gCAAgC,CAAC;AAEjF,iFAAiF;AACjF,MAAM,CAAC,MAAM,gCAAgC,GAAG,gCAAgC,CAAC;AAEjF,2EAA2E;AAC3E,MAAM,cAAc,GAAG,6BAA6B,CAAC;AACrD,MAAM,WAAW,GAAG,oBAAoB,CAAC;AAczC;;;;;;;;GAQG;AACH,MAAM,UAAU,0BAA0B,CAAC,KAAsC;IAC/E,MAAM,OAAO,GAAG,CAAC,G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k';
2
2
  import { type CompactResult } from './compact.js';
3
3
  import { DiagnosticsLog, type DiagnosticsStatus } from './diagnostics.js';
4
+ import { type BackgroundDelegationListener, type BackgroundDelegationStatus } from './background-delegation.js';
4
5
  import { type ModelRetryOutcome, type RetryWaitState } from './model-retry.js';
5
6
  import { type SubagentCancelResult, type SubagentDispatchListener, type SubagentDispatchProgressListener, type SubagentDispatchStatus } from '../agents/dispatch-registry.js';
6
7
  import { type ExpandedCustomCommand } from '../commands/custom-commands.js';
@@ -13,6 +14,7 @@ import { type ExpandedSkillCommand } from '../skills/plugin.js';
13
14
  import { type MemoryCommandResult } from '../memory/command.js';
14
15
  import { MemoryToolController } from '../memory/controller.js';
15
16
  import type { MemoryStatus } from '../memory/store.js';
17
+ import type { TaskNotificationFields } from '../trajectory/record.js';
16
18
  import { type RecorderOptions, type TrajectoryStatus } from '../trajectory/writer.js';
17
19
  import { type ProjectInstructionsSummary } from './instructions.js';
18
20
  import { type AllowRuleEntry, type ApprovalMode, type PermissionBridge, type PermissionModeChange } from './permission.js';
@@ -44,6 +46,18 @@ export interface RuntimeOptions {
44
46
  permissionModeOverride?: ApprovalMode;
45
47
  /** Process-local force-on override for ContextOffloader; never persisted. */
46
48
  contextOffloadOverride?: true;
49
+ /**
50
+ * The driver drains SER-069 task wakes at idle (the interactive TUI). The `bash` tool
51
+ * then tells the model, truthfully, that ending the turn is followed by one
52
+ * `<task-notification>` turn — effective only with config `backgroundTaskWake !== false`.
53
+ * The same promise switches background delegation to non-blocking (SER-070): the
54
+ * SDK `backgroundTasks` option gets `waitForCompletion: false`, the dispatching turn
55
+ * ends after the ack, and the child's settlement is delivered by a wake turn.
56
+ * Headless drivers have no queue and leave this unset, so their one run keeps the
57
+ * SDK waiting and the report inside it. Children never wake, so their catalogue keeps
58
+ * the no-wake wording whatever the parent says.
59
+ */
60
+ backgroundCompletionWakes?: boolean;
47
61
  /** Refuses the next parent-Agent SDK model call after this many in the process. */
48
62
  maxModelCalls?: number;
49
63
  /**
@@ -326,6 +340,13 @@ export declare class AgentRuntime {
326
340
  * `/context` to the plain heuristic line rather than to a wrong number.
327
341
  */
328
342
  private contextAnchorBroken;
343
+ /**
344
+ * Which background jobs' terminal states completed turns already carried to the
345
+ * model through `wait`/`status` results (SER-069): the interactive drain asks it
346
+ * before sending a wake, so a job the model already saw finish never starts a
347
+ * duplicate turn. Session-scoped like the anchor; a `/clear` successor starts empty.
348
+ */
349
+ private readonly terminalDelivery;
329
350
  /** Serializes the bounded list/save/list critical section across concurrent callers. */
330
351
  private rewindCaptureTail;
331
352
  /**
@@ -366,8 +387,15 @@ export declare class AgentRuntime {
366
387
  *
367
388
  * One `before` snapshot feeds both the meter and `lastTurnDelta`, so what the record
368
389
  * says a turn cost and what `/usage` says it cost cannot be two different readings.
390
+ *
391
+ * `origin` marks a turn the session started rather than the user (SER-069, a
392
+ * background-task wake): the opening record is then a `taskNotification` carrying
393
+ * the literal `userInput` text, no `userInput` line is written, no rewind
394
+ * checkpoint is catalogued (the chooser lists the user's prompts) and memory gets
395
+ * no user quote to anchor to. Everything else — hooks, gate, recording, delivery
396
+ * ledger — is the ordinary turn.
369
397
  */
370
- send(input: string, userInput?: string, image?: ImageBlock): AsyncIterable<AgentStreamEvent>;
398
+ send(input: string, userInput?: string, image?: ImageBlock, origin?: TaskNotificationFields): AsyncIterable<AgentStreamEvent>;
371
399
  /**
372
400
  * Adds one completed turn's delta to its model's share. Runs in `send`'s `finally`,
373
401
  * so it cannot throw: a tally that failed would replace the provider's error with
@@ -675,6 +703,14 @@ export declare class AgentRuntime {
675
703
  listBackgroundTasks(): Promise<BackgroundTaskStatus[]>;
676
704
  /** Publishes future terminal task snapshots until the returned closure is called. */
677
705
  subscribeToBackgroundTasks(listener: BackgroundTaskListener): () => void;
706
+ /**
707
+ * True once a *completed* turn of this session carried the task's terminal state
708
+ * to the model through a `wait`/`status`/`stop`/`list` result (SER-069). The
709
+ * interactive drain drops a queued wake for such a task instead of sending it: the
710
+ * conversation already knows, and a second turn about it would be the duplicate
711
+ * the peer design produces. Synchronous, no I/O.
712
+ */
713
+ terminalStateDelivered(taskId: string): boolean;
678
714
  /**
679
715
  * Every subagent dispatch of this run, in start order, running and finished
680
716
  * alike. Synchronous — unlike {@link listBackgroundTasks}, which snapshots live
@@ -694,6 +730,19 @@ export declare class AgentRuntime {
694
730
  subscribeToSubagentProgress(listener: SubagentDispatchProgressListener): () => void;
695
731
  /** User-only exact-id cancellation; no agent tool exposes this operation. */
696
732
  cancelSubagentDispatch(dispatchId: string): SubagentCancelResult;
733
+ /**
734
+ * Every background delegation the SDK still tracks (SER-070): dispatched with
735
+ * `_background_execution` and not yet delivered to the model as its result pair —
736
+ * running, or settled and waiting for the next model call. Synchronous, no I/O: the
737
+ * observer's ledger, fed by the parent's own stream and hook. Non-empty means
738
+ * `/clear` and `/rewind` must refuse (the SDK's `assertCanLoadSnapshot` would throw,
739
+ * and a successor would orphan the children).
740
+ */
741
+ listBackgroundDelegations(): BackgroundDelegationStatus[];
742
+ /** Publishes each background delegation's one settlement snapshot until the closure is called. */
743
+ subscribeToBackgroundDelegations(listener: BackgroundDelegationListener): () => void;
744
+ /** Synchronous, before any release: the same sentence the TUI's local check prints. */
745
+ private refuseWhileDelegationsTracked;
697
746
  /**
698
747
  * Asks the agent to stop the current turn at its next safe point. The stream
699
748
  * ends with `stopReason: 'cancelled'` rather than throwing.
@@ -752,6 +801,11 @@ export declare class AgentRuntime {
752
801
  * If assembling the successor fails, this runtime stays fully usable: nothing it owns
753
802
  * has been released yet, and the diagnostics tap it installed at startup is put back
754
803
  * (the failed successor's unwind clears the process-global sink).
804
+ *
805
+ * Refused while a background delegation is tracked (SER-070): `retire()` would cancel
806
+ * the children through `subagents.shutdown()`, destroying their work silently, and
807
+ * the result pair the SDK still owes would be orphaned. The user decided the exits are
808
+ * `/agents cancel <id>` or waiting for the completion wake — never an implicit cancel.
755
809
  */
756
810
  startNewSession(): Promise<AgentRuntime>;
757
811
  /**