@namzu/sdk 5.2.0 → 6.1.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 (111) hide show
  1. package/CHANGELOG.md +237 -0
  2. package/dist/agents/SupervisorAgent.d.ts.map +1 -1
  3. package/dist/agents/SupervisorAgent.js +13 -0
  4. package/dist/agents/SupervisorAgent.js.map +1 -1
  5. package/dist/gateway/__tests__/completion-inbox.test.d.ts +2 -0
  6. package/dist/gateway/__tests__/completion-inbox.test.d.ts.map +1 -0
  7. package/dist/gateway/__tests__/completion-inbox.test.js +258 -0
  8. package/dist/gateway/__tests__/completion-inbox.test.js.map +1 -0
  9. package/dist/gateway/completion-inbox.d.ts +113 -0
  10. package/dist/gateway/completion-inbox.d.ts.map +1 -0
  11. package/dist/gateway/completion-inbox.js +211 -0
  12. package/dist/gateway/completion-inbox.js.map +1 -0
  13. package/dist/provider/__tests__/strict-schema.test.js +50 -2
  14. package/dist/provider/__tests__/strict-schema.test.js.map +1 -1
  15. package/dist/provider/__tests__/vendor-detail.test.d.ts +2 -0
  16. package/dist/provider/__tests__/vendor-detail.test.d.ts.map +1 -0
  17. package/dist/provider/__tests__/vendor-detail.test.js +89 -0
  18. package/dist/provider/__tests__/vendor-detail.test.js.map +1 -0
  19. package/dist/provider/errors.d.ts +38 -5
  20. package/dist/provider/errors.d.ts.map +1 -1
  21. package/dist/provider/errors.js +107 -5
  22. package/dist/provider/errors.js.map +1 -1
  23. package/dist/provider/strict-schema.d.ts.map +1 -1
  24. package/dist/provider/strict-schema.js +64 -8
  25. package/dist/provider/strict-schema.js.map +1 -1
  26. package/dist/public-runtime.d.ts +4 -0
  27. package/dist/public-runtime.d.ts.map +1 -1
  28. package/dist/public-runtime.js +10 -0
  29. package/dist/public-runtime.js.map +1 -1
  30. package/dist/registry/tool/__tests__/dialect.test.d.ts +2 -0
  31. package/dist/registry/tool/__tests__/dialect.test.d.ts.map +1 -0
  32. package/dist/registry/tool/__tests__/dialect.test.js +146 -0
  33. package/dist/registry/tool/__tests__/dialect.test.js.map +1 -0
  34. package/dist/registry/tool/dialect.d.ts +50 -0
  35. package/dist/registry/tool/dialect.d.ts.map +1 -0
  36. package/dist/registry/tool/dialect.js +138 -0
  37. package/dist/registry/tool/dialect.js.map +1 -0
  38. package/dist/registry/tool/execute.d.ts.map +1 -1
  39. package/dist/registry/tool/execute.js +34 -0
  40. package/dist/registry/tool/execute.js.map +1 -1
  41. package/dist/registry/toolset/catalog.d.ts.map +1 -1
  42. package/dist/registry/toolset/catalog.js +10 -5
  43. package/dist/registry/toolset/catalog.js.map +1 -1
  44. package/dist/runtime/query/__tests__/completion-notification.test.d.ts +2 -0
  45. package/dist/runtime/query/__tests__/completion-notification.test.d.ts.map +1 -0
  46. package/dist/runtime/query/__tests__/completion-notification.test.js +168 -0
  47. package/dist/runtime/query/__tests__/completion-notification.test.js.map +1 -0
  48. package/dist/runtime/query/__tests__/step-allow-list.test.d.ts +2 -0
  49. package/dist/runtime/query/__tests__/step-allow-list.test.d.ts.map +1 -0
  50. package/dist/runtime/query/__tests__/step-allow-list.test.js +171 -0
  51. package/dist/runtime/query/__tests__/step-allow-list.test.js.map +1 -0
  52. package/dist/runtime/query/__tests__/stream-recovery.test.js +6 -0
  53. package/dist/runtime/query/__tests__/stream-recovery.test.js.map +1 -1
  54. package/dist/runtime/query/executor.d.ts +14 -0
  55. package/dist/runtime/query/executor.d.ts.map +1 -1
  56. package/dist/runtime/query/executor.js +20 -1
  57. package/dist/runtime/query/executor.js.map +1 -1
  58. package/dist/runtime/query/index.d.ts +9 -0
  59. package/dist/runtime/query/index.d.ts.map +1 -1
  60. package/dist/runtime/query/index.js +1 -0
  61. package/dist/runtime/query/index.js.map +1 -1
  62. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  63. package/dist/runtime/query/iteration/index.js +74 -1
  64. package/dist/runtime/query/iteration/index.js.map +1 -1
  65. package/dist/runtime/query/iteration/phases/context.d.ts +9 -0
  66. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  67. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  68. package/dist/runtime/query/result.d.ts.map +1 -1
  69. package/dist/runtime/query/result.js +6 -0
  70. package/dist/runtime/query/result.js.map +1 -1
  71. package/dist/tools/coordinator/__tests__/completion-delivery.test.d.ts +2 -0
  72. package/dist/tools/coordinator/__tests__/completion-delivery.test.d.ts.map +1 -0
  73. package/dist/tools/coordinator/__tests__/completion-delivery.test.js +255 -0
  74. package/dist/tools/coordinator/__tests__/completion-delivery.test.js.map +1 -0
  75. package/dist/tools/coordinator/__tests__/task-list.test.js +13 -7
  76. package/dist/tools/coordinator/__tests__/task-list.test.js.map +1 -1
  77. package/dist/tools/coordinator/index.d.ts +35 -0
  78. package/dist/tools/coordinator/index.d.ts.map +1 -1
  79. package/dist/tools/coordinator/index.js +222 -16
  80. package/dist/tools/coordinator/index.js.map +1 -1
  81. package/dist/types/provider/error.d.ts +20 -4
  82. package/dist/types/provider/error.d.ts.map +1 -1
  83. package/dist/types/tool/index.d.ts +13 -0
  84. package/dist/types/tool/index.d.ts.map +1 -1
  85. package/dist/types/tool/index.js.map +1 -1
  86. package/package.json +1 -1
  87. package/src/agents/SupervisorAgent.ts +14 -0
  88. package/src/gateway/__tests__/completion-inbox.test.ts +320 -0
  89. package/src/gateway/completion-inbox.ts +227 -0
  90. package/src/provider/__tests__/strict-schema.test.ts +58 -2
  91. package/src/provider/__tests__/vendor-detail.test.ts +107 -0
  92. package/src/provider/errors.ts +106 -5
  93. package/src/provider/strict-schema.ts +65 -8
  94. package/src/public-runtime.ts +11 -0
  95. package/src/registry/tool/__tests__/dialect.test.ts +200 -0
  96. package/src/registry/tool/dialect.ts +143 -0
  97. package/src/registry/tool/execute.ts +35 -0
  98. package/src/registry/toolset/catalog.ts +10 -5
  99. package/src/runtime/query/__tests__/completion-notification.test.ts +196 -0
  100. package/src/runtime/query/__tests__/step-allow-list.test.ts +205 -0
  101. package/src/runtime/query/__tests__/stream-recovery.test.ts +6 -0
  102. package/src/runtime/query/executor.ts +21 -1
  103. package/src/runtime/query/index.ts +11 -0
  104. package/src/runtime/query/iteration/index.ts +77 -1
  105. package/src/runtime/query/iteration/phases/context.ts +10 -0
  106. package/src/runtime/query/result.ts +6 -0
  107. package/src/tools/coordinator/__tests__/completion-delivery.test.ts +347 -0
  108. package/src/tools/coordinator/__tests__/task-list.test.ts +13 -7
  109. package/src/tools/coordinator/index.ts +250 -20
  110. package/src/types/provider/error.ts +20 -4
  111. package/src/types/tool/index.ts +13 -0
@@ -0,0 +1,320 @@
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('stops expecting a task that was cancelled', () => {
196
+ // `expect` is only cleared by a COMPLETION, so a cancelled worker used
197
+ // to keep the run open for the whole grace period, every time it tried
198
+ // to settle, waiting for a result that had been called off.
199
+ const { gateway } = fakeGateway()
200
+ const inbox = new CompletionInbox()
201
+ inbox.attach(gateway)
202
+ inbox.expect('tsk_1' as TaskId)
203
+
204
+ inbox.forget('tsk_1' as TaskId)
205
+
206
+ expect(inbox.hasPendingWork).toBe(false)
207
+ })
208
+
209
+ it('waits for an arrival and returns as soon as one lands', async () => {
210
+ const { gateway, settle } = fakeGateway()
211
+ const inbox = new CompletionInbox()
212
+ inbox.attach(gateway)
213
+ inbox.expect('tsk_1' as TaskId)
214
+
215
+ const waited = inbox.waitForArrival(5_000)
216
+ settle(handleFor('tsk_1', 'done'))
217
+ await waited
218
+
219
+ expect(inbox.drain().map((h) => h.taskId)).toEqual(['tsk_1'])
220
+ })
221
+
222
+ it('does not wait at all when there is nothing outstanding', async () => {
223
+ const { gateway } = fakeGateway()
224
+ const inbox = new CompletionInbox()
225
+ inbox.attach(gateway)
226
+
227
+ // A deadline this long would hang the suite if it were honoured.
228
+ await inbox.waitForArrival(600_000)
229
+ })
230
+
231
+ it('gives up at the deadline rather than holding a run forever', async () => {
232
+ // The bound is the point: a worker that never finishes must not keep
233
+ // the run open indefinitely.
234
+ const { gateway } = fakeGateway()
235
+ const inbox = new CompletionInbox()
236
+ inbox.attach(gateway)
237
+ inbox.expect('tsk_never' as TaskId)
238
+
239
+ await inbox.waitForArrival(10)
240
+
241
+ expect(inbox.hasPendingWork).toBe(true)
242
+ })
243
+
244
+ it('releases a waiter when the inbox closes', async () => {
245
+ const { gateway } = fakeGateway()
246
+ const inbox = new CompletionInbox()
247
+ inbox.attach(gateway)
248
+ inbox.expect('tsk_1' as TaskId)
249
+
250
+ const waited = inbox.waitForArrival(600_000)
251
+ inbox.close()
252
+ await waited
253
+ })
254
+ })
255
+
256
+ describe('the notification says which task and what it produced', () => {
257
+ it('carries the id, the agent, the state and the output', () => {
258
+ // All four matter. Without the id the supervisor cannot say which of
259
+ // five workers this was; without the output it has to make the extra
260
+ // call this mechanism exists to remove.
261
+ const text = formatCompletionNotification([handleFor('tsk_42', 'the findings')])
262
+
263
+ expect(text).toContain('task_id: tsk_42')
264
+ expect(text).toContain('agent: reviewer')
265
+ expect(text).toContain('state: completed')
266
+ expect(text).toContain('duration_ms: 2500')
267
+ expect(text).toContain('the findings')
268
+ })
269
+
270
+ it('names the tool that fetches the rest when it truncates', () => {
271
+ const text = formatCompletionNotification([handleFor('tsk_42', 'x'.repeat(10_000))])
272
+
273
+ expect(text).toContain('truncated')
274
+ // The id is repeated in the truncation notice, so the follow-up call
275
+ // does not require scrolling back up through 4 kB of output.
276
+ expect(text).toContain('wait_for_task with task_id "tsk_42"')
277
+ expect(text.length).toBeLessThan(4_500)
278
+ })
279
+
280
+ it('says so rather than going blank when a task produced nothing', () => {
281
+ const text = formatCompletionNotification([handleFor('tsk_42')])
282
+
283
+ expect(text).toContain('task_id: tsk_42')
284
+ expect(text).toContain('produced no output')
285
+ })
286
+
287
+ it('groups a batch into one message', () => {
288
+ const text = formatCompletionNotification([
289
+ handleFor('tsk_1', 'first'),
290
+ handleFor('tsk_2', 'second'),
291
+ ])
292
+
293
+ expect(text).toContain('2 tasks')
294
+ expect(text).toContain('tsk_1')
295
+ expect(text).toContain('tsk_2')
296
+ })
297
+
298
+ it('explains why it is arriving here and not as a tool result', () => {
299
+ // Otherwise the model has to guess whether it missed a call, and the
300
+ // guess it makes is to go looking — which is the polling loop again.
301
+ const text = formatCompletionNotification([handleFor('tsk_1', 'done')])
302
+
303
+ expect(text).toContain('not waiting on it')
304
+ })
305
+ })
306
+
307
+ describe('the inbox does not require anything of a host gateway', () => {
308
+ it('uses only onTaskCompleted', () => {
309
+ // The whole point of attaching through the existing subscription: a
310
+ // host that implements TaskGateway keeps working untouched, and one
311
+ // that was already firing completions into an empty listener set now
312
+ // has a listener.
313
+ const onTaskCompleted = vi.fn(() => () => {})
314
+ const inbox = new CompletionInbox()
315
+
316
+ inbox.attach({ onTaskCompleted } as unknown as TaskGateway)
317
+
318
+ expect(onTaskCompleted).toHaveBeenCalledTimes(1)
319
+ })
320
+ })
@@ -0,0 +1,227 @@
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
+ this.unheard.delete(taskId)
163
+ // Anyone waiting should re-check rather than sit out their deadline
164
+ // for a task that is no longer coming.
165
+ for (const wake of [...this.arrivals]) wake()
166
+ }
167
+
168
+ /** Stop listening. Safe to call more than once. */
169
+ close(): void {
170
+ this.detach?.()
171
+ this.detach = undefined
172
+ this.unheard.clear()
173
+ this.outstanding.clear()
174
+ // Release anyone still waiting. A closed inbox would otherwise hold
175
+ // them to their own deadline for a completion that can no longer come.
176
+ for (const wake of [...this.arrivals]) wake()
177
+ this.arrivals.clear()
178
+ }
179
+ }
180
+
181
+ /** How much of a worker's output rides in the notification itself. */
182
+ const NOTIFICATION_OUTPUT_LIMIT = 4_000
183
+
184
+ /**
185
+ * The message a supervisor reads when a worker it stopped waiting for
186
+ * finishes.
187
+ *
188
+ * It carries the task id, because without one the model cannot say which of
189
+ * five workers this was, and it carries the output, because a notification
190
+ * that only says "done" forces exactly the follow-up call this mechanism
191
+ * exists to remove. Long output is truncated with the task id repeated in
192
+ * the truncation notice, so the full text stays one `wait_for_task` away and
193
+ * the model knows which id to ask for — that tool takes a `task_id` and
194
+ * returns immediately for a task that has already finished, where the
195
+ * listing takes only a state filter and could not have been followed.
196
+ */
197
+ export function formatCompletionNotification(handles: readonly TaskHandle[]): string {
198
+ const blocks = handles.map((handle) => {
199
+ const durationMs = handle.completedAt ? handle.completedAt - handle.createdAt : undefined
200
+ const output = handle.result?.result ?? handle.result?.lastError ?? ''
201
+ const truncated =
202
+ output.length > NOTIFICATION_OUTPUT_LIMIT
203
+ ? // `wait_for_task`, not `agent_task_list` — the listing takes only a
204
+ // state filter, so an instruction to call it "with task_id" named
205
+ // a parameter that does not exist and could not be followed. On an
206
+ // already-finished task the wait returns immediately.
207
+ `${output.slice(0, NOTIFICATION_OUTPUT_LIMIT)}\n… truncated. Call wait_for_task with task_id "${handle.taskId}" for the full output.`
208
+ : output
209
+
210
+ const lines = [
211
+ `task_id: ${handle.taskId}`,
212
+ `agent: ${handle.agentId}`,
213
+ `state: ${handle.state}`,
214
+ ...(durationMs !== undefined ? [`duration_ms: ${durationMs}`] : []),
215
+ '',
216
+ truncated.length > 0 ? truncated : '(the task produced no output)',
217
+ ]
218
+ return `<task-notification>\n${lines.join('\n')}\n</task-notification>`
219
+ })
220
+
221
+ const preamble =
222
+ handles.length === 1
223
+ ? '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.'
224
+ : `${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.`
225
+
226
+ return `${preamble}\n\n${blocks.join('\n\n')}`
227
+ }
@@ -80,12 +80,17 @@ describe('the violation report names the exact path', () => {
80
80
  expect(findStrictSchemaViolations(schema)).toEqual([])
81
81
  })
82
82
 
83
- it('reports numeric and string bounds, which are also outside the subset', () => {
83
+ it('reports the bounds the wire refuses, and only those', () => {
84
+ // Measured against the live API rather than read off a page. The first
85
+ // version of this list was derived from documentation and was wrong in
86
+ // both directions: it refused `maxLength`, which the wire accepts, and
87
+ // permitted `prefixItems`, which it rejects.
84
88
  const schema = {
85
89
  type: 'object',
86
90
  properties: {
87
91
  n: { type: 'integer', minimum: 0 },
88
92
  s: { type: 'string', maxLength: 10 },
93
+ a: { type: 'array', items: { type: 'string' }, maxItems: 3, minItems: 1 },
89
94
  },
90
95
  }
91
96
 
@@ -93,7 +98,58 @@ describe('the violation report names the exact path', () => {
93
98
  findStrictSchemaViolations(schema)
94
99
  .map((v) => v.keyword)
95
100
  .sort(),
96
- ).toEqual(['maxLength', 'minimum'])
101
+ ).toEqual(['maxItems', 'minimum'])
102
+ })
103
+
104
+ it('leaves string length alone, because strict accepts it', () => {
105
+ // The false positive that would have refused tools which work.
106
+ expect(
107
+ findStrictSchemaViolations({ s: { type: 'string', minLength: 1, maxLength: 9 } }),
108
+ ).toEqual([])
109
+ })
110
+
111
+ it('catches a tuple in either spelling, because strict admits neither', () => {
112
+ // The interaction worth pinning, and the one a `prefixItems` entry alone
113
+ // got wrong. This check runs at REGISTRATION, on the schema as rendered
114
+ // — draft-07, where a tuple is `items: [a, b]` — while the wire sees the
115
+ // `prefixItems` the driver converts it to. So denying only `prefixItems`
116
+ // was a guard that could not fire on the path that produces tuples.
117
+ //
118
+ // Measured, strict rejects both, which is why a tool that is both strict
119
+ // and tuple-shaped cannot be expressed at all. Converting it only
120
+ // changes which error comes back.
121
+ for (const items of [
122
+ { prefixItems: [{ type: 'integer' }, { type: 'integer' }] },
123
+ { items: [{ type: 'integer' }, { type: 'integer' }] },
124
+ ]) {
125
+ const violations = findStrictSchemaViolations({
126
+ properties: { range: { type: 'array', ...items } },
127
+ })
128
+
129
+ expect(violations, JSON.stringify(items)).toHaveLength(1)
130
+ expect(violations[0]?.remedy).toContain('tuple cannot be expressed')
131
+ }
132
+ })
133
+
134
+ it('leaves an ordinary array alone, where `items` is one schema', () => {
135
+ // The false positive the tuple rule must not become: `items` is the
136
+ // normal spelling for a homogeneous array and strict accepts it. Only
137
+ // the array-of-schemas form is a tuple.
138
+ expect(findStrictSchemaViolations({ type: 'array', items: { type: 'string' } })).toEqual([])
139
+ })
140
+
141
+ it('admits minItems at 0 or 1 and refuses it above, as the wire does', () => {
142
+ // A blanket denial here was a false positive with a real cost: it
143
+ // refuses `z.array(...).nonempty()`, which renders `minItems: 1` and
144
+ // which the wire accepts. The constraint is on the VALUE, and the
145
+ // vendor's error says so — "'minItems' values other than 0 or 1 are not
146
+ // supported".
147
+ expect(findStrictSchemaViolations({ type: 'array', minItems: 0 })).toEqual([])
148
+ expect(findStrictSchemaViolations({ type: 'array', minItems: 1 })).toEqual([])
149
+
150
+ const violations = findStrictSchemaViolations({ type: 'array', minItems: 2 })
151
+ expect(violations).toHaveLength(1)
152
+ expect(violations[0]?.keyword).toBe('minItems')
97
153
  })
98
154
 
99
155
  it('admits additionalProperties only as false', () => {