@namzu/sdk 6.0.0 → 6.2.0

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 (107) hide show
  1. package/CHANGELOG.md +254 -0
  2. package/dist/agents/SupervisorAgent.d.ts.map +1 -1
  3. package/dist/agents/SupervisorAgent.js +18 -0
  4. package/dist/agents/SupervisorAgent.js.map +1 -1
  5. package/dist/agents/__tests__/supervisor-coordinator-registration.test.js +31 -0
  6. package/dist/agents/__tests__/supervisor-coordinator-registration.test.js.map +1 -1
  7. package/dist/gateway/__tests__/completion-inbox.test.d.ts +2 -0
  8. package/dist/gateway/__tests__/completion-inbox.test.d.ts.map +1 -0
  9. package/dist/gateway/__tests__/completion-inbox.test.js +275 -0
  10. package/dist/gateway/__tests__/completion-inbox.test.js.map +1 -0
  11. package/dist/gateway/completion-inbox.d.ts +113 -0
  12. package/dist/gateway/completion-inbox.d.ts.map +1 -0
  13. package/dist/gateway/completion-inbox.js +225 -0
  14. package/dist/gateway/completion-inbox.js.map +1 -0
  15. package/dist/public-runtime.d.ts +1 -0
  16. package/dist/public-runtime.d.ts.map +1 -1
  17. package/dist/public-runtime.js +4 -0
  18. package/dist/public-runtime.js.map +1 -1
  19. package/dist/registry/tool/__tests__/dialect.test.js +8 -5
  20. package/dist/registry/tool/__tests__/dialect.test.js.map +1 -1
  21. package/dist/registry/tool/dialect.js +11 -4
  22. package/dist/registry/tool/dialect.js.map +1 -1
  23. package/dist/registry/tool/execute.d.ts.map +1 -1
  24. package/dist/registry/tool/execute.js +34 -0
  25. package/dist/registry/tool/execute.js.map +1 -1
  26. package/dist/runtime/query/__tests__/completion-notification.test.d.ts +2 -0
  27. package/dist/runtime/query/__tests__/completion-notification.test.d.ts.map +1 -0
  28. package/dist/runtime/query/__tests__/completion-notification.test.js +168 -0
  29. package/dist/runtime/query/__tests__/completion-notification.test.js.map +1 -0
  30. package/dist/runtime/query/__tests__/run-survives-its-own-park.proc-test.d.ts +2 -0
  31. package/dist/runtime/query/__tests__/run-survives-its-own-park.proc-test.d.ts.map +1 -0
  32. package/dist/runtime/query/__tests__/run-survives-its-own-park.proc-test.js +122 -0
  33. package/dist/runtime/query/__tests__/run-survives-its-own-park.proc-test.js.map +1 -0
  34. package/dist/runtime/query/__tests__/step-allow-list.test.d.ts +2 -0
  35. package/dist/runtime/query/__tests__/step-allow-list.test.d.ts.map +1 -0
  36. package/dist/runtime/query/__tests__/step-allow-list.test.js +171 -0
  37. package/dist/runtime/query/__tests__/step-allow-list.test.js.map +1 -0
  38. package/dist/runtime/query/executor.d.ts +14 -0
  39. package/dist/runtime/query/executor.d.ts.map +1 -1
  40. package/dist/runtime/query/executor.js +20 -1
  41. package/dist/runtime/query/executor.js.map +1 -1
  42. package/dist/runtime/query/index.d.ts +9 -0
  43. package/dist/runtime/query/index.d.ts.map +1 -1
  44. package/dist/runtime/query/index.js +1 -0
  45. package/dist/runtime/query/index.js.map +1 -1
  46. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  47. package/dist/runtime/query/iteration/index.js +74 -1
  48. package/dist/runtime/query/iteration/index.js.map +1 -1
  49. package/dist/runtime/query/iteration/phases/context.d.ts +9 -0
  50. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  51. package/dist/runtime/query/iteration/phases/context.js +43 -13
  52. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  53. package/dist/tools/builtins/__tests__/bash.proc-test.d.ts +2 -0
  54. package/dist/tools/builtins/__tests__/bash.proc-test.d.ts.map +1 -0
  55. package/dist/tools/builtins/__tests__/bash.proc-test.js +115 -0
  56. package/dist/tools/builtins/__tests__/bash.proc-test.js.map +1 -0
  57. package/dist/tools/builtins/__tests__/bash.test.d.ts +2 -0
  58. package/dist/tools/builtins/__tests__/bash.test.d.ts.map +1 -0
  59. package/dist/tools/builtins/__tests__/bash.test.js +65 -0
  60. package/dist/tools/builtins/__tests__/bash.test.js.map +1 -0
  61. package/dist/tools/builtins/bash.d.ts.map +1 -1
  62. package/dist/tools/builtins/bash.js +89 -17
  63. package/dist/tools/builtins/bash.js.map +1 -1
  64. package/dist/tools/coordinator/__tests__/allow-delegation.test.d.ts +2 -0
  65. package/dist/tools/coordinator/__tests__/allow-delegation.test.d.ts.map +1 -0
  66. package/dist/tools/coordinator/__tests__/allow-delegation.test.js +94 -0
  67. package/dist/tools/coordinator/__tests__/allow-delegation.test.js.map +1 -0
  68. package/dist/tools/coordinator/__tests__/completion-delivery.test.d.ts +2 -0
  69. package/dist/tools/coordinator/__tests__/completion-delivery.test.d.ts.map +1 -0
  70. package/dist/tools/coordinator/__tests__/completion-delivery.test.js +255 -0
  71. package/dist/tools/coordinator/__tests__/completion-delivery.test.js.map +1 -0
  72. package/dist/tools/coordinator/__tests__/task-list.test.js +13 -7
  73. package/dist/tools/coordinator/__tests__/task-list.test.js.map +1 -1
  74. package/dist/tools/coordinator/index.d.ts +44 -0
  75. package/dist/tools/coordinator/index.d.ts.map +1 -1
  76. package/dist/tools/coordinator/index.js +239 -16
  77. package/dist/tools/coordinator/index.js.map +1 -1
  78. package/dist/types/agent/supervisor.d.ts +27 -0
  79. package/dist/types/agent/supervisor.d.ts.map +1 -1
  80. package/dist/types/tool/index.d.ts +13 -0
  81. package/dist/types/tool/index.d.ts.map +1 -1
  82. package/dist/types/tool/index.js.map +1 -1
  83. package/package.json +3 -2
  84. package/src/agents/SupervisorAgent.ts +19 -0
  85. package/src/agents/__tests__/supervisor-coordinator-registration.test.ts +37 -0
  86. package/src/gateway/__tests__/completion-inbox.test.ts +343 -0
  87. package/src/gateway/completion-inbox.ts +241 -0
  88. package/src/public-runtime.ts +4 -0
  89. package/src/registry/tool/__tests__/dialect.test.ts +8 -5
  90. package/src/registry/tool/dialect.ts +11 -4
  91. package/src/registry/tool/execute.ts +35 -0
  92. package/src/runtime/query/__tests__/completion-notification.test.ts +196 -0
  93. package/src/runtime/query/__tests__/run-survives-its-own-park.proc-test.ts +127 -0
  94. package/src/runtime/query/__tests__/step-allow-list.test.ts +205 -0
  95. package/src/runtime/query/executor.ts +21 -1
  96. package/src/runtime/query/index.ts +11 -0
  97. package/src/runtime/query/iteration/index.ts +77 -1
  98. package/src/runtime/query/iteration/phases/context.ts +51 -15
  99. package/src/tools/builtins/__tests__/bash.proc-test.ts +142 -0
  100. package/src/tools/builtins/__tests__/bash.test.ts +79 -0
  101. package/src/tools/builtins/bash.ts +100 -18
  102. package/src/tools/coordinator/__tests__/allow-delegation.test.ts +120 -0
  103. package/src/tools/coordinator/__tests__/completion-delivery.test.ts +347 -0
  104. package/src/tools/coordinator/__tests__/task-list.test.ts +13 -7
  105. package/src/tools/coordinator/index.ts +278 -21
  106. package/src/types/agent/supervisor.ts +28 -0
  107. package/src/types/tool/index.ts +13 -0
@@ -55,6 +55,7 @@ const hostTool = (name: string) =>
55
55
  async function runWith(options: {
56
56
  hostTools?: string[]
57
57
  runtimeToolOverrides?: Record<string, 'active' | 'deferred' | 'disabled'>
58
+ allowDelegation?: boolean
58
59
  }) {
59
60
  const agent = new SupervisorAgent({
60
61
  id: 'supervisor',
@@ -80,6 +81,9 @@ async function runWith(options: {
80
81
  {
81
82
  provider,
82
83
  agentIds: ['worker'],
84
+ ...(options.allowDelegation !== undefined
85
+ ? { allowDelegation: options.allowDelegation }
86
+ : {}),
83
87
  agentManager: stubManager(),
84
88
  tools,
85
89
  systemPrompt: 'You coordinate.',
@@ -146,3 +150,36 @@ describe('supervisor coordinator-tool registration', () => {
146
150
  expect(describedAs('create_task')).toBe(HOST_TOOL_DESCRIPTION)
147
151
  })
148
152
  })
153
+
154
+ /**
155
+ * The one hop between `SupervisorAgentConfig.allowDelegation` and the builder
156
+ * that acts on it.
157
+ *
158
+ * These go through `SupervisorAgent` rather than calling the builder directly,
159
+ * and that is the entire point. The builder has its own unit tests, and they
160
+ * pass whether or not the supervisor actually forwards the flag — measured:
161
+ * deleting the forward left the type-check clean and all 143 coordinator and
162
+ * agent tests green, with the field settable, documented, and read by nobody.
163
+ * That is the shape of a declaration this repository has had to go and delete
164
+ * before, so it gets a test that fails when the road is cut.
165
+ */
166
+ describe('allowDelegation reaches the tool surface', () => {
167
+ it('withholds the delegation tools when the run declines to delegate', async () => {
168
+ const { names } = await runWith({ allowDelegation: false })
169
+
170
+ expect(names, 'the flag never reached buildCoordinatorTools').not.toContain('create_task')
171
+ expect(names).not.toContain('wait_for_task')
172
+ expect(names).not.toContain('cancel_task')
173
+ })
174
+
175
+ it('keeps the listing, so a non-delegating run can still see what is running', async () => {
176
+ expect((await runWith({ allowDelegation: false })).names).toContain('agent_task_list')
177
+ })
178
+
179
+ it('leaves an opting-in run exactly as it was', async () => {
180
+ const { names } = await runWith({ allowDelegation: true })
181
+
182
+ expect(names).toContain('create_task')
183
+ expect(names).toContain('agent_task_list')
184
+ })
185
+ })
@@ -0,0 +1,343 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+
3
+ import type { TaskGateway, TaskHandle } from '../../types/agent/gateway.js'
4
+ import type { TaskId } from '../../types/ids/index.js'
5
+ import { CompletionInbox, formatCompletionNotification } from '../completion-inbox.js'
6
+
7
+ /**
8
+ * Who tells the supervisor a worker finished.
9
+ *
10
+ * Normally the `create_task` call does: it blocks, and the worker's output
11
+ * comes back as that call's `tool_result`. Two cases have no such call — a
12
+ * launch made in the background, and a blocking launch whose deadline passed
13
+ * while the worker kept going — and until this existed the result of those
14
+ * simply vanished. The gateway still held it; nothing ever read it.
15
+ *
16
+ * An earlier version of this channel was removed in `dc16d58` because it
17
+ * fired for completions the blocking tool had ALREADY delivered, so the
18
+ * supervisor saw every result twice: once as a `tool_result`, once as an
19
+ * orphan envelope. That removal is the reason the tests below care as much
20
+ * about what does NOT get delivered as about what does.
21
+ */
22
+
23
+ function handleFor(taskId: string, result?: string): TaskHandle {
24
+ return {
25
+ taskId: taskId as TaskId,
26
+ agentId: 'reviewer',
27
+ state: 'completed',
28
+ createdAt: 1_000,
29
+ completedAt: 3_500,
30
+ ...(result !== undefined
31
+ ? { result: { status: 'completed', result } as TaskHandle['result'] }
32
+ : {}),
33
+ }
34
+ }
35
+
36
+ /** A gateway that only does the one thing the inbox uses. */
37
+ function fakeGateway(): {
38
+ gateway: TaskGateway
39
+ settle: (h: TaskHandle) => void
40
+ listeners: number
41
+ } {
42
+ const listeners = new Set<(h: TaskHandle) => void>()
43
+ const gateway = {
44
+ onTaskCompleted(cb: (h: TaskHandle) => void) {
45
+ listeners.add(cb)
46
+ return () => listeners.delete(cb)
47
+ },
48
+ } as unknown as TaskGateway
49
+ return {
50
+ gateway,
51
+ settle: (h) => {
52
+ for (const cb of listeners) cb(h)
53
+ },
54
+ get listeners() {
55
+ return listeners.size
56
+ },
57
+ }
58
+ }
59
+
60
+ describe('a completion nobody waited for reaches the transcript', () => {
61
+ it('queues a settled task and hands it over once', () => {
62
+ const { gateway, settle } = fakeGateway()
63
+ const inbox = new CompletionInbox()
64
+ inbox.attach(gateway)
65
+
66
+ settle(handleFor('tsk_1', 'the report'))
67
+
68
+ expect(inbox.hasUnheard).toBe(true)
69
+ expect(inbox.drain().map((h) => h.taskId)).toEqual(['tsk_1'])
70
+ // Drained, not peeked: a notification that survives its own delivery
71
+ // is the duplicate bug wearing a different hat.
72
+ expect(inbox.drain()).toEqual([])
73
+ expect(inbox.hasUnheard).toBe(false)
74
+ })
75
+
76
+ it('queues nothing at all when no task settles', () => {
77
+ const { gateway } = fakeGateway()
78
+ const inbox = new CompletionInbox()
79
+ inbox.attach(gateway)
80
+
81
+ expect(inbox.hasUnheard).toBe(false)
82
+ expect(inbox.drain()).toEqual([])
83
+ })
84
+ })
85
+
86
+ describe('a completion the tool already delivered is never delivered twice', () => {
87
+ it('drops a claimed completion', () => {
88
+ // The `dc16d58` regression, pinned. `create_task` blocked, got the
89
+ // result, and returned it as its own tool_result — so the envelope
90
+ // must not also carry it.
91
+ const { gateway, settle } = fakeGateway()
92
+ const inbox = new CompletionInbox()
93
+ inbox.attach(gateway)
94
+
95
+ settle(handleFor('tsk_1', 'the report'))
96
+ inbox.claim('tsk_1' as TaskId)
97
+
98
+ expect(inbox.hasUnheard).toBe(false)
99
+ expect(inbox.drain()).toEqual([])
100
+ })
101
+
102
+ it('drops it even when the claim beats the announcement', () => {
103
+ // Ordering is not guaranteed: the tool's own `waitForTask` can resolve
104
+ // before the gateway's completion listener runs. A claim that only
105
+ // worked after the announcement would leak a duplicate exactly in the
106
+ // races that are hardest to reproduce.
107
+ const { gateway, settle } = fakeGateway()
108
+ const inbox = new CompletionInbox()
109
+ inbox.attach(gateway)
110
+
111
+ inbox.claim('tsk_1' as TaskId)
112
+ settle(handleFor('tsk_1', 'the report'))
113
+
114
+ expect(inbox.drain()).toEqual([])
115
+ })
116
+
117
+ it('still delivers the sibling that nobody claimed', () => {
118
+ // The mixed turn: one worker awaited to completion, one abandoned.
119
+ const { gateway, settle } = fakeGateway()
120
+ const inbox = new CompletionInbox()
121
+ inbox.attach(gateway)
122
+
123
+ settle(handleFor('tsk_awaited', 'delivered inline'))
124
+ settle(handleFor('tsk_abandoned', 'nobody heard this'))
125
+ inbox.claim('tsk_awaited' as TaskId)
126
+
127
+ expect(inbox.drain().map((h) => h.taskId)).toEqual(['tsk_abandoned'])
128
+ })
129
+
130
+ it('subscribes once no matter how often it is attached', () => {
131
+ // Two subscriptions would queue every completion twice and reproduce
132
+ // the duplicate delivery from the inside.
133
+ const { gateway, settle, ...rest } = fakeGateway()
134
+ const inbox = new CompletionInbox()
135
+ inbox.attach(gateway)
136
+ inbox.attach(gateway)
137
+
138
+ settle(handleFor('tsk_1', 'once'))
139
+
140
+ expect(inbox.drain()).toHaveLength(1)
141
+ void rest
142
+ })
143
+
144
+ it('stops listening when closed', () => {
145
+ const { gateway, settle } = fakeGateway()
146
+ const inbox = new CompletionInbox()
147
+ inbox.attach(gateway)
148
+ inbox.close()
149
+
150
+ settle(handleFor('tsk_1', 'too late'))
151
+
152
+ expect(inbox.drain()).toEqual([])
153
+ })
154
+ })
155
+
156
+ describe('a launch nobody is waiting for holds the run open', () => {
157
+ it('counts an expected task as pending work before it settles', () => {
158
+ // Without this the run settles while a background worker is still
159
+ // going and discards the result the launch existed to produce.
160
+ const { gateway } = fakeGateway()
161
+ const inbox = new CompletionInbox()
162
+ inbox.attach(gateway)
163
+
164
+ expect(inbox.hasPendingWork).toBe(false)
165
+ inbox.expect('tsk_1' as TaskId)
166
+ expect(inbox.hasPendingWork).toBe(true)
167
+ })
168
+
169
+ it('stops counting it once it settles', () => {
170
+ const { gateway, settle } = fakeGateway()
171
+ const inbox = new CompletionInbox()
172
+ inbox.attach(gateway)
173
+ inbox.expect('tsk_1' as TaskId)
174
+
175
+ settle(handleFor('tsk_1', 'done'))
176
+
177
+ // Still pending — as an UNHEARD completion now rather than an
178
+ // outstanding one, which is what the loop drains.
179
+ expect(inbox.hasPendingWork).toBe(true)
180
+ inbox.drain()
181
+ expect(inbox.hasPendingWork).toBe(false)
182
+ })
183
+
184
+ it('ignores a task already delivered inline', () => {
185
+ const { gateway } = fakeGateway()
186
+ const inbox = new CompletionInbox()
187
+ inbox.attach(gateway)
188
+
189
+ inbox.claim('tsk_1' as TaskId)
190
+ inbox.expect('tsk_1' as TaskId)
191
+
192
+ expect(inbox.hasPendingWork).toBe(false)
193
+ })
194
+
195
+ it('keeps a result that already arrived, even when the task is cancelled', () => {
196
+ // The window: a worker finishes, its completion is queued for the next
197
+ // drain, and the model — told nothing yet, and reading a tool that says
198
+ // it cancels a RUNNING task — cancels it. Clearing the queue here threw
199
+ // away work that was done and output that existed nowhere else.
200
+ //
201
+ // `forget` is about pending work. A finished result is not pending work.
202
+ const { gateway, settle } = fakeGateway()
203
+ const inbox = new CompletionInbox()
204
+ inbox.attach(gateway)
205
+ inbox.expect('tsk_1' as TaskId)
206
+
207
+ settle(handleFor('tsk_1', 'the worker finished before the cancel landed'))
208
+ inbox.forget('tsk_1' as TaskId)
209
+
210
+ const drained = inbox.drain()
211
+ expect(
212
+ drained.map((h) => h.taskId),
213
+ 'the finished result was discarded',
214
+ ).toEqual(['tsk_1'])
215
+ expect(drained[0]?.result?.result).toBe('the worker finished before the cancel landed')
216
+ })
217
+
218
+ it('stops expecting a task that was cancelled', () => {
219
+ // `expect` is only cleared by a COMPLETION, so a cancelled worker used
220
+ // to keep the run open for the whole grace period, every time it tried
221
+ // to settle, waiting for a result that had been called off.
222
+ const { gateway } = fakeGateway()
223
+ const inbox = new CompletionInbox()
224
+ inbox.attach(gateway)
225
+ inbox.expect('tsk_1' as TaskId)
226
+
227
+ inbox.forget('tsk_1' as TaskId)
228
+
229
+ expect(inbox.hasPendingWork).toBe(false)
230
+ })
231
+
232
+ it('waits for an arrival and returns as soon as one lands', async () => {
233
+ const { gateway, settle } = fakeGateway()
234
+ const inbox = new CompletionInbox()
235
+ inbox.attach(gateway)
236
+ inbox.expect('tsk_1' as TaskId)
237
+
238
+ const waited = inbox.waitForArrival(5_000)
239
+ settle(handleFor('tsk_1', 'done'))
240
+ await waited
241
+
242
+ expect(inbox.drain().map((h) => h.taskId)).toEqual(['tsk_1'])
243
+ })
244
+
245
+ it('does not wait at all when there is nothing outstanding', async () => {
246
+ const { gateway } = fakeGateway()
247
+ const inbox = new CompletionInbox()
248
+ inbox.attach(gateway)
249
+
250
+ // A deadline this long would hang the suite if it were honoured.
251
+ await inbox.waitForArrival(600_000)
252
+ })
253
+
254
+ it('gives up at the deadline rather than holding a run forever', async () => {
255
+ // The bound is the point: a worker that never finishes must not keep
256
+ // the run open indefinitely.
257
+ const { gateway } = fakeGateway()
258
+ const inbox = new CompletionInbox()
259
+ inbox.attach(gateway)
260
+ inbox.expect('tsk_never' as TaskId)
261
+
262
+ await inbox.waitForArrival(10)
263
+
264
+ expect(inbox.hasPendingWork).toBe(true)
265
+ })
266
+
267
+ it('releases a waiter when the inbox closes', async () => {
268
+ const { gateway } = fakeGateway()
269
+ const inbox = new CompletionInbox()
270
+ inbox.attach(gateway)
271
+ inbox.expect('tsk_1' as TaskId)
272
+
273
+ const waited = inbox.waitForArrival(600_000)
274
+ inbox.close()
275
+ await waited
276
+ })
277
+ })
278
+
279
+ describe('the notification says which task and what it produced', () => {
280
+ it('carries the id, the agent, the state and the output', () => {
281
+ // All four matter. Without the id the supervisor cannot say which of
282
+ // five workers this was; without the output it has to make the extra
283
+ // call this mechanism exists to remove.
284
+ const text = formatCompletionNotification([handleFor('tsk_42', 'the findings')])
285
+
286
+ expect(text).toContain('task_id: tsk_42')
287
+ expect(text).toContain('agent: reviewer')
288
+ expect(text).toContain('state: completed')
289
+ expect(text).toContain('duration_ms: 2500')
290
+ expect(text).toContain('the findings')
291
+ })
292
+
293
+ it('names the tool that fetches the rest when it truncates', () => {
294
+ const text = formatCompletionNotification([handleFor('tsk_42', 'x'.repeat(10_000))])
295
+
296
+ expect(text).toContain('truncated')
297
+ // The id is repeated in the truncation notice, so the follow-up call
298
+ // does not require scrolling back up through 4 kB of output.
299
+ expect(text).toContain('wait_for_task with task_id "tsk_42"')
300
+ expect(text.length).toBeLessThan(4_500)
301
+ })
302
+
303
+ it('says so rather than going blank when a task produced nothing', () => {
304
+ const text = formatCompletionNotification([handleFor('tsk_42')])
305
+
306
+ expect(text).toContain('task_id: tsk_42')
307
+ expect(text).toContain('produced no output')
308
+ })
309
+
310
+ it('groups a batch into one message', () => {
311
+ const text = formatCompletionNotification([
312
+ handleFor('tsk_1', 'first'),
313
+ handleFor('tsk_2', 'second'),
314
+ ])
315
+
316
+ expect(text).toContain('2 tasks')
317
+ expect(text).toContain('tsk_1')
318
+ expect(text).toContain('tsk_2')
319
+ })
320
+
321
+ it('explains why it is arriving here and not as a tool result', () => {
322
+ // Otherwise the model has to guess whether it missed a call, and the
323
+ // guess it makes is to go looking — which is the polling loop again.
324
+ const text = formatCompletionNotification([handleFor('tsk_1', 'done')])
325
+
326
+ expect(text).toContain('not waiting on it')
327
+ })
328
+ })
329
+
330
+ describe('the inbox does not require anything of a host gateway', () => {
331
+ it('uses only onTaskCompleted', () => {
332
+ // The whole point of attaching through the existing subscription: a
333
+ // host that implements TaskGateway keeps working untouched, and one
334
+ // that was already firing completions into an empty listener set now
335
+ // has a listener.
336
+ const onTaskCompleted = vi.fn(() => () => {})
337
+ const inbox = new CompletionInbox()
338
+
339
+ inbox.attach({ onTaskCompleted } as unknown as TaskGateway)
340
+
341
+ expect(onTaskCompleted).toHaveBeenCalledTimes(1)
342
+ })
343
+ })
@@ -0,0 +1,241 @@
1
+ import type { TaskGateway, TaskHandle } from '../types/agent/gateway.js'
2
+ import type { TaskId } from '../types/ids/index.js'
3
+
4
+ /**
5
+ * Completions that finished with nobody left to hear them.
6
+ *
7
+ * A worker's result reaches the supervisor as the `tool_result` of the
8
+ * `create_task` that launched it. That works whenever the launching call is
9
+ * still the live path — but it is not the only way a task ends:
10
+ *
11
+ * - the launching tool hit its deadline and the executor returned
12
+ * *"timed out… it may still be running"* to the model. The worker then
13
+ * finished normally, holding a result nothing would ever read.
14
+ * - the task was launched in the background on purpose, so there is no
15
+ * call waiting on it by design.
16
+ *
17
+ * In both cases the completion exists, the gateway remembers it, and the
18
+ * model is never told. That is the gap this closes: the run subscribes once,
19
+ * every settled task lands here, and anything a tool did NOT hand over
20
+ * inline is drained into the transcript as a notification the next turn can
21
+ * read.
22
+ *
23
+ * The disambiguation is the whole design. An earlier version of the envelope
24
+ * path was removed (`dc16d58`) because it fired for completions the blocking
25
+ * tool had ALREADY delivered, so the supervisor saw every result twice —
26
+ * once correctly as a `tool_result`, once as an orphan envelope. Removing it
27
+ * fixed the duplicate and left the abandoned case with no channel at all.
28
+ * Claiming is what tells the two apart: a tool that delivers a completion
29
+ * says so, and only unclaimed completions become envelopes.
30
+ *
31
+ * It attaches through `onTaskCompleted`, which every `TaskGateway` already
32
+ * has, so a host gateway needs no change to take part — a host that was
33
+ * firing completions into a listener set with no listeners now has one.
34
+ */
35
+ export class CompletionInbox {
36
+ private readonly unheard = new Map<TaskId, TaskHandle>()
37
+ private readonly claimed = new Set<TaskId>()
38
+ /** Launched with nothing waiting on it, and not settled yet. */
39
+ private readonly outstanding = new Set<TaskId>()
40
+ private readonly arrivals = new Set<() => void>()
41
+ private detach?: () => void
42
+
43
+ /**
44
+ * Start listening.
45
+ *
46
+ * Returns a detach function; calling `attach` twice is a no-op rather
47
+ * than a second subscription, because a doubly-attached inbox would
48
+ * queue every completion twice and reproduce the exact duplicate this
49
+ * class exists to prevent.
50
+ */
51
+ attach(gateway: TaskGateway): () => void {
52
+ if (this.detach) return this.detach
53
+ this.detach = gateway.onTaskCompleted((handle) => {
54
+ // A completion claimed before it was announced — a tool that
55
+ // finished its wait faster than the listener ran — is already
56
+ // delivered. Nothing to queue.
57
+ this.outstanding.delete(handle.taskId)
58
+ if (this.claimed.has(handle.taskId)) return
59
+ this.unheard.set(handle.taskId, handle)
60
+ for (const wake of this.arrivals) wake()
61
+ })
62
+ return this.detach
63
+ }
64
+
65
+ /**
66
+ * Say that a task was launched with nothing waiting on it.
67
+ *
68
+ * Without this the inbox can only see completions that have already
69
+ * happened, and a run whose supervisor launched a background worker and
70
+ * then answered would settle while the worker was still going — throwing
71
+ * away the very result the launch existed to produce. Knowing a task is
72
+ * outstanding is what lets the loop hold the run open for it.
73
+ */
74
+ expect(taskId: TaskId): void {
75
+ if (this.claimed.has(taskId)) return
76
+ this.outstanding.add(taskId)
77
+ }
78
+
79
+ /** Whether anything is either waiting to be told or still running. */
80
+ get hasPendingWork(): boolean {
81
+ return this.unheard.size > 0 || this.outstanding.size > 0
82
+ }
83
+
84
+ /**
85
+ * Wait for the next completion, or for the deadline, whichever comes first.
86
+ *
87
+ * Bounded on purpose. A worker that never finishes must not hold a run
88
+ * open forever, and the caller decides how long "long enough" is — the
89
+ * run's own budget is the only thing that knows.
90
+ */
91
+ waitForArrival(timeoutMs: number): Promise<void> {
92
+ if (this.unheard.size > 0) return Promise.resolve()
93
+ if (this.outstanding.size === 0) return Promise.resolve()
94
+
95
+ return new Promise((resolve) => {
96
+ const timer = setTimeout(finish, timeoutMs)
97
+ // `unref` where the runtime has it, so a pending wait never keeps
98
+ // a process alive past the work it was waiting for.
99
+ ;(timer as { unref?: () => void }).unref?.()
100
+
101
+ function finish(): void {
102
+ clearTimeout(timer)
103
+ wake.done = true
104
+ resolve()
105
+ }
106
+
107
+ const wake = Object.assign(
108
+ () => {
109
+ if (!wake.done) {
110
+ this.arrivals.delete(wake)
111
+ finish()
112
+ }
113
+ },
114
+ { done: false },
115
+ )
116
+ this.arrivals.add(wake)
117
+ })
118
+ }
119
+
120
+ /**
121
+ * Say that this completion reached the model as a `tool_result`.
122
+ *
123
+ * Idempotent, and safe to call before the completion is announced: the
124
+ * claim is remembered so a late announcement does not re-queue it.
125
+ */
126
+ claim(taskId: TaskId): void {
127
+ this.claimed.add(taskId)
128
+ this.unheard.delete(taskId)
129
+ this.outstanding.delete(taskId)
130
+ }
131
+
132
+ /** Whether anything is waiting to be told. */
133
+ get hasUnheard(): boolean {
134
+ return this.unheard.size > 0
135
+ }
136
+
137
+ /**
138
+ * Take every unheard completion, leaving the inbox empty.
139
+ *
140
+ * Draining rather than peeking: a notification that stays queued after
141
+ * being delivered is the duplicate-delivery bug in a different costume.
142
+ */
143
+ drain(): TaskHandle[] {
144
+ if (this.unheard.size === 0) return []
145
+ const handles = [...this.unheard.values()]
146
+ this.unheard.clear()
147
+ for (const handle of handles) this.claimed.add(handle.taskId)
148
+ return handles
149
+ }
150
+
151
+ /**
152
+ * Stop expecting a task that is never going to arrive.
153
+ *
154
+ * Cancelling is the case this exists for. `expect` puts a task on the
155
+ * outstanding list and only a COMPLETION takes it off, so a cancelled
156
+ * worker left `hasPendingWork` true for the rest of the run — and every
157
+ * attempt to settle then paid the full grace period waiting for a result
158
+ * that had been called off.
159
+ */
160
+ forget(taskId: TaskId): void {
161
+ this.outstanding.delete(taskId)
162
+ // `unheard` is deliberately NOT touched.
163
+ //
164
+ // The two sets mean different things. `outstanding` is pending WORK,
165
+ // and cancelling is exactly the statement that it should stop being
166
+ // waited for. `unheard` is a RESULT that already exists — the worker
167
+ // finished, the completion arrived, and it is queued for the next
168
+ // drain. Clearing it here destroyed that.
169
+ //
170
+ // The window is small and entirely reachable: nothing has told the
171
+ // model the worker finished, and `cancel_task` says it cancels a
172
+ // running task, so cancelling one that has just completed is the
173
+ // obvious move rather than a mistake. The run then reports "cancelled"
174
+ // over work that was done and output that no longer exists anywhere.
175
+ //
176
+ // Note the asymmetry with `claim`, which does clear `unheard` — and is
177
+ // right to, because there a tool has just handed the model the same
178
+ // result. This one hands over nothing.
179
+ for (const wake of [...this.arrivals]) wake()
180
+ }
181
+
182
+ /** Stop listening. Safe to call more than once. */
183
+ close(): void {
184
+ this.detach?.()
185
+ this.detach = undefined
186
+ this.unheard.clear()
187
+ this.outstanding.clear()
188
+ // Release anyone still waiting. A closed inbox would otherwise hold
189
+ // them to their own deadline for a completion that can no longer come.
190
+ for (const wake of [...this.arrivals]) wake()
191
+ this.arrivals.clear()
192
+ }
193
+ }
194
+
195
+ /** How much of a worker's output rides in the notification itself. */
196
+ const NOTIFICATION_OUTPUT_LIMIT = 4_000
197
+
198
+ /**
199
+ * The message a supervisor reads when a worker it stopped waiting for
200
+ * finishes.
201
+ *
202
+ * It carries the task id, because without one the model cannot say which of
203
+ * five workers this was, and it carries the output, because a notification
204
+ * that only says "done" forces exactly the follow-up call this mechanism
205
+ * exists to remove. Long output is truncated with the task id repeated in
206
+ * the truncation notice, so the full text stays one `wait_for_task` away and
207
+ * the model knows which id to ask for — that tool takes a `task_id` and
208
+ * returns immediately for a task that has already finished, where the
209
+ * listing takes only a state filter and could not have been followed.
210
+ */
211
+ export function formatCompletionNotification(handles: readonly TaskHandle[]): string {
212
+ const blocks = handles.map((handle) => {
213
+ const durationMs = handle.completedAt ? handle.completedAt - handle.createdAt : undefined
214
+ const output = handle.result?.result ?? handle.result?.lastError ?? ''
215
+ const truncated =
216
+ output.length > NOTIFICATION_OUTPUT_LIMIT
217
+ ? // `wait_for_task`, not `agent_task_list` — the listing takes only a
218
+ // state filter, so an instruction to call it "with task_id" named
219
+ // a parameter that does not exist and could not be followed. On an
220
+ // already-finished task the wait returns immediately.
221
+ `${output.slice(0, NOTIFICATION_OUTPUT_LIMIT)}\n… truncated. Call wait_for_task with task_id "${handle.taskId}" for the full output.`
222
+ : output
223
+
224
+ const lines = [
225
+ `task_id: ${handle.taskId}`,
226
+ `agent: ${handle.agentId}`,
227
+ `state: ${handle.state}`,
228
+ ...(durationMs !== undefined ? [`duration_ms: ${durationMs}`] : []),
229
+ '',
230
+ truncated.length > 0 ? truncated : '(the task produced no output)',
231
+ ]
232
+ return `<task-notification>\n${lines.join('\n')}\n</task-notification>`
233
+ })
234
+
235
+ const preamble =
236
+ handles.length === 1
237
+ ? 'A task you launched has finished. This is its result — you were not waiting on it, so it arrives here rather than as a tool result.'
238
+ : `${handles.length} tasks you launched have finished. These are their results — you were not waiting on them, so they arrive here rather than as tool results.`
239
+
240
+ return `${preamble}\n\n${blocks.join('\n\n')}`
241
+ }
@@ -232,6 +232,10 @@ export {
232
232
  export { InMemoryThreadStore } from './store/thread/memory.js'
233
233
 
234
234
  export { LocalTaskGateway } from './gateway/local.js'
235
+ // Exported because `buildCoordinatorTools` is: a host that builds the
236
+ // coordinator surface itself needs the same inbox the loop drains, or its
237
+ // abandoned completions go unheard exactly as they did before.
238
+ export { CompletionInbox, formatCompletionNotification } from './gateway/completion-inbox.js'
235
239
 
236
240
  // ─── providers, sandbox, vault ───────────────────────────────────────────
237
241
 
@@ -69,16 +69,19 @@ describe('saying a schema in the dialect a wire parses', () => {
69
69
  })
70
70
  })
71
71
 
72
- it('drops `additionalItems: false`, which both dialects already imply', () => {
73
- // Not a lossy shortcut: once `prefixItems` is set, a closed tuple is the
74
- // default in 2020-12, so emitting `items: false` would add a byte to
75
- // every request to say what was already true.
72
+ it('keeps a closed tuple closed', () => {
73
+ // This assertion used to be its own opposite, and the comment under it
74
+ // was wrong about the dialect: it claimed a closed tuple is 2020-12's
75
+ // default once `prefixItems` is set. It is not — with no `items`,
76
+ // elements past the tuple are UNCONSTRAINED. Dropping the `false`
77
+ // turned a schema written to forbid a third element into one that
78
+ // allows any, which is a silent widening rather than a saved byte.
76
79
  expect(
77
80
  toSchemaDialect(
78
81
  { type: 'array', items: [{ type: 'integer' }], additionalItems: false },
79
82
  '2020-12',
80
83
  ),
81
- ).toEqual({ type: 'array', prefixItems: [{ type: 'integer' }] })
84
+ ).toEqual({ type: 'array', prefixItems: [{ type: 'integer' }], items: false })
82
85
  })
83
86
 
84
87
  it('ignores `additionalItems` with no tuple to qualify', () => {