dsh-taskbridge 0.0.0-stage → 1.3.1

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 (74) hide show
  1. package/CHANGELOG.md +754 -0
  2. package/LICENSE +21 -0
  3. package/README.md +624 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-delegate.toml +245 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +32 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +922 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +293 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +220 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +135 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3260 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +454 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3609 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/mcp/server.js +1820 -0
  55. package/src/mcp/wait.js +536 -0
  56. package/src/model/connectivity.js +371 -0
  57. package/src/model/discovery.js +582 -0
  58. package/src/model/native-catalog.js +68 -0
  59. package/src/model/openai-adapter.js +671 -0
  60. package/src/model/probe.js +264 -0
  61. package/src/model/providers.js +756 -0
  62. package/src/model/routing.js +321 -0
  63. package/src/review/preset.js +868 -0
  64. package/src/review/prompts.js +126 -0
  65. package/src/review/reviewer.js +933 -0
  66. package/src/runtime/agent-runner.js +1738 -0
  67. package/src/runtime/endpoint-discovery.js +118 -0
  68. package/src/runtime/permissions.js +1429 -0
  69. package/src/runtime/sandbox.js +358 -0
  70. package/src/runtime/session-placement.js +1103 -0
  71. package/src/workspace/audit.js +775 -0
  72. package/src/workspace/locks.js +167 -0
  73. package/src/workspace/preflight.js +424 -0
  74. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,536 @@
1
+ // The bounded wait loop behind `delegate_wait`.
2
+ //
3
+ // The shape of the problem: a host must be told when a delegated task needs it — a
4
+ // permission request, a finished run, a failure, a cancellation — and it must be
5
+ // told ONCE, compactly, instead of polling. A single HTTP request cannot stay open
6
+ // for an hour, so one `delegate_wait` call is composed of several BOUNDED
7
+ // observation requests, each answered by the harness before it times out.
8
+ //
9
+ // Three rules make that composition safe:
10
+ //
11
+ // 1. **Each internal request is bounded.** `waitMs` per request is below the
12
+ // execution plane's own cap, so no request can be the thing that hangs.
13
+ // 2. **Only ACTIONABLE answers end the call.** The engine's `heartbeat` reason
14
+ // means "nothing changed yet"; it is consumed here and never surfaced, because a
15
+ // host that saw heartbeats would have a polling loop with extra steps.
16
+ // 3. **A deadline is not a result.** When the caller's own time is up the answer
17
+ // says `wait-limit` and keeps the task identity, so the host can immediately
18
+ // wait again on the SAME task. It never means "review it", "resubmit it" or
19
+ // "it failed".
20
+ //
21
+ // Metrics are counted HERE and nowhere else: `observationRequests` is the number of
22
+ // internal HTTP observations, while `waitReturns` is 1 — the number of answers the
23
+ // host actually receives. That distinction is the whole point of the metric, so it
24
+ // is a value in the answer rather than something a reader must infer.
25
+ //
26
+ // A fourth rule was added after a real acceptance run, and it is subtle enough to
27
+ // state at the top: **an interrupted OBSERVATION is not an interrupted RUN.**
28
+ //
29
+ // The engine reports `interrupted` for two completely different situations — this
30
+ // observer's own request ended (the caller's signal aborted, the connection dropped,
31
+ // the engine released the waiter during teardown), or a task record that was already
32
+ // `interrupted` came back from a restart. The first says nothing about the task: its
33
+ // worker is still running and the host must keep waiting on the SAME task. The second
34
+ // is a real terminal fact. Treating them alike either told a host that a healthy run
35
+ // had ended, or made it re-issue observations against a task that can never progress
36
+ // again. So the answer is derived from the TASK, not from the reason label alone.
37
+
38
+ import {
39
+ ACTIONABLE_REASONS,
40
+ OBSERVE_WAIT_MS,
41
+ WAIT_LIMIT_REASON,
42
+ isPermissionDecidable,
43
+ } from './server.js';
44
+
45
+ /**
46
+ * Reasons on which the wait loop keeps waiting instead of answering.
47
+ *
48
+ * Stated as a set rather than "not in ACTIONABLE_REASONS" so an unknown reason
49
+ * produced by a newer harness is treated as `attention` (a real, actionable
50
+ * answer) instead of silently spinning or being reported as `wait-limit`.
51
+ *
52
+ * `interrupted` is here because the reason alone cannot tell an observer-local
53
+ * interruption from a real terminal history — {@link resolveInterruption} decides
54
+ * from the task record, and that decision is either "keep waiting on this task" or
55
+ * an answer. A reason that arrives with NO task record joins this set only through
56
+ * that resolver's "unknown" branch, which never asserts that the run ended.
57
+ */
58
+ const CONTINUING_REASONS = new Set(['heartbeat', 'interrupted']);
59
+
60
+ /**
61
+ * How long an EARLY heartbeat is spaced out, in ms.
62
+ *
63
+ * A normal heartbeat has already waited out its own `waitMs`; this interval only
64
+ * applies when one arrives sooner than that (a fake engine, or an engine that
65
+ * answers at once), and it exists so such a stream cannot become a request storm.
66
+ * One second per observation is the floor: a one-hour wait against such an engine
67
+ * issues at most 3,600 observations, and a realistic engine issues far fewer.
68
+ */
69
+ const EARLY_HEARTBEAT_INTERVAL_MS = 1_000;
70
+
71
+ /**
72
+ * The task fields a wait answer carries.
73
+ *
74
+ * A wait answer must let a host act, so it carries identity, state, phase, timing
75
+ * and routing — and it must NOT carry the evidence a `delegate_result` answers
76
+ * with: no diff, no execution text, no review prose. That is a size decision and,
77
+ * more importantly, a decision about what a "ping" is allowed to hand to a model.
78
+ */
79
+ const TASK_FIELDS = Object.freeze([
80
+ 'taskId',
81
+ 'state',
82
+ 'phase',
83
+ 'elapsedMs',
84
+ 'lastActivityAt',
85
+ 'currentTool',
86
+ 'idleForMs',
87
+ 'route',
88
+ 'createdAt',
89
+ 'startedAt',
90
+ 'endedAt',
91
+ 'conversation',
92
+ 'selfApproved',
93
+ 'hostAcceptance',
94
+ 'cancelledBy',
95
+ ]);
96
+
97
+ /**
98
+ * Reasons that are a TERMINAL state of the task, not a request for attention.
99
+ * @type {ReadonlySet<string>}
100
+ */
101
+ const TERMINAL_REASONS = new Set(['ready', 'failed', 'cancelled', 'interrupted']);
102
+
103
+ /**
104
+ * Task states a live run can be in.
105
+ *
106
+ * `pending` and `running` mean the task has not settled: an `interrupted` observation
107
+ * about them is an interruption of the OBSERVER only, and waiting must go on.
108
+ */
109
+ const LIVE_TASK_STATES = new Set(['pending', 'running']);
110
+
111
+ /**
112
+ * Reasons whose name IS a settled task state, used only when an observation carried no
113
+ * task state at all. `ready`/`failed`/`cancelled` are finishes this tool can report
114
+ * from the reason alone; `interrupted` is deliberately absent, because that label also
115
+ * describes an interrupted OBSERVER and asserting an end from it is the defect this
116
+ * file exists to prevent.
117
+ */
118
+ const TERMINAL_STATE_REASONS = new Set(['ready', 'failed', 'cancelled']);
119
+
120
+ /**
121
+ * Task states that are a FINISHED run, mapped to the reason a wait reports for them.
122
+ *
123
+ * `awaiting-host-review` is a completion, not a failure: it belongs to `ready`, and a
124
+ * host that was told otherwise would never review the result. This map is what keeps an
125
+ * `interrupted` observation carrying a settled state from being reported as an
126
+ * unrecoverable interruption.
127
+ */
128
+ const SETTLED_STATE_REASONS = Object.freeze({
129
+ 'awaiting-host-review': 'ready',
130
+ failed: 'failed',
131
+ cancelled: 'cancelled',
132
+ interrupted: 'interrupted',
133
+ });
134
+
135
+ /**
136
+ * Compact one observation's task view into what a wait answer carries.
137
+ *
138
+ * Anything not named in {@link TASK_FIELDS} is dropped, which is what keeps a wait
139
+ * answer small and keeps a diff from reaching a host through the one tool that is
140
+ * supposed to be cheap.
141
+ * @param {object | null | undefined} task - observation `task`.
142
+ * @returns {object} the compact task.
143
+ */
144
+ export function compactTask(task) {
145
+ if (task === null || typeof task !== 'object' || Array.isArray(task)) return {};
146
+ const out = {};
147
+ for (const key of TASK_FIELDS) {
148
+ if (task[key] !== undefined) out[key] = task[key];
149
+ }
150
+ // Activity and self-check are small, bounded summaries the engine produced for
151
+ // exactly this purpose; they are carried whole rather than re-projected here.
152
+ if (task.activity !== undefined) out.activity = task.activity;
153
+ if (task.selfCheck !== undefined) out.selfCheck = task.selfCheck;
154
+ return out;
155
+ }
156
+
157
+ /**
158
+ * The task state a wait answer reports.
159
+ *
160
+ * The observation's own state is used when the engine published one. When it did not,
161
+ * the state is taken from the REASON only where that reason is a task state by
162
+ * definition (`failed`/`cancelled`); `ready` is a review outcome whose state is
163
+ * `awaiting-host-review`, and inventing `state: "ready"` would publish a state the
164
+ * engine never has. Everything else reports `null`: the wait's own outcomes
165
+ * (`wait-limit`, `attention`, `permission`) describe a live or unreadable task, and
166
+ * inventing "running" for an unreadable record would be a claim this tool cannot make.
167
+ * @param {object} task - compact task.
168
+ * @param {string} reason - reported reason.
169
+ * @returns {string | null} task state.
170
+ */
171
+ function resolvedTaskState(task, reason) {
172
+ if (typeof task?.state === 'string' && task.state !== '') return task.state;
173
+ if (SETTLED_STATE_REASONS[reason] !== undefined && reason !== 'ready' && reason !== 'interrupted') return reason;
174
+ return null;
175
+ }
176
+
177
+ /**
178
+ * The instructions a host reads in a wait answer.
179
+ * @param {string} reason - the reported reason.
180
+ * @param {{ resolved?: boolean, taskState?: string | null, kind?: string }} [facts] - `resolved`: the
181
+ * reason was settled by {@link resolveInterruption} rather than read verbatim;
182
+ * `taskState`: the state the answer reports, for the `interrupted` wording.
183
+ * @returns {string} one actionable sentence.
184
+ */
185
+ function instructionFor(reason, facts = {}) {
186
+ switch (reason) {
187
+ case WAIT_LIMIT_REASON:
188
+ return 'Nothing changed before this deadline. Call delegate_wait again with the same taskId; '
189
+ + 'do not review, resubmit, restart or cancel the task on account of this answer.';
190
+ case 'permission':
191
+ return 'A per-call permission request is pending. Decide it with delegate_permission_decide using '
192
+ + 'permission.requestId (and permission.fingerprint for allow-once), or reject it. The task is still '
193
+ + 'running and waiting.';
194
+ case 'attention':
195
+ return 'No activity has been observed for about ten minutes while the task is still running. The run may '
196
+ + 'be stuck. Check the current tool and idle time; cancel or follow up deliberately rather than '
197
+ + 'assuming completion.';
198
+ case 'ready':
199
+ return 'The run ended and is awaiting host review. Read delegate_result for the diff and evidence; '
200
+ + 'completion is not host acceptance.';
201
+ case 'failed':
202
+ return 'The run failed. Read delegate_result for the bounded error; the task is not awaiting review.';
203
+ case 'cancelled':
204
+ return 'The task is cancelled. Nothing further will run for it.';
205
+ case 'interrupted':
206
+ if (facts.kind === INTERRUPTION_KINDS.unknown || facts.resolved !== true) {
207
+ // The record could not be read as settled. The honest instruction keeps the task
208
+ // identity and forbids asserting an end that was never observed.
209
+ return 'The reported state could not be confirmed as settled. Do not assume the execution ended, and do '
210
+ + 'not assume it is still running: check with delegate_result, or call delegate_wait again with the same '
211
+ + 'taskId, before deciding anything.';
212
+ }
213
+ if (facts.kind === INTERRUPTION_KINDS.history) {
214
+ return 'The task record is itself interrupted (for example by a process restart) and will not resume, so '
215
+ + 'waiting for it cannot help. Read delegate_result for what is recorded, then decide whether a new task '
216
+ + 'is needed; do not keep calling delegate_wait on this taskId.';
217
+ }
218
+ // A LIVE task whose observation was cut off. NOT an error and NOT a result.
219
+ return 'The wait was interrupted while the task was still running; the execution was NOT stopped and this '
220
+ + 'is not a result. Call delegate_wait again with the same taskId; do not review, resubmit, restart or '
221
+ + 'cancel the task on account of this answer.';
222
+ default:
223
+ return 'The task reported a state this host should act on. Read delegate_result for detail.';
224
+ }
225
+ }
226
+
227
+ /** How the wait loop treats one `interrupted` observation. */
228
+ export const INTERRUPTION_KINDS = Object.freeze({
229
+ /** This observer's request ended; the task record is still live. Answer and wait again. */
230
+ observation: 'observation',
231
+ /** The task record is itself `interrupted` (a restart left it that way). Terminate. */
232
+ history: 'history',
233
+ /** No usable task state was reported; neither an end nor a live run may be asserted. */
234
+ unknown: 'unknown',
235
+ });
236
+
237
+ /**
238
+ * Decide what an `interrupted` observation actually says about the TASK.
239
+ *
240
+ * The engine emits `interrupted` both when an observer's own request ends and when a
241
+ * persisted, already-`interrupted` record is read back after a restart. The TASK RECORD
242
+ * is the evidence, and only one of its states is an unrecoverable interruption:
243
+ *
244
+ * * `pending`/`running` with no `endedAt` → {@link INTERRUPTION_KINDS.observation}:
245
+ * the run is live and the observer's request ended;
246
+ * * `interrupted` → {@link INTERRUPTION_KINDS.history}: a restart history, which this
247
+ * build's engine never sets for a live run;
248
+ * * a KNOWN settled state (`awaiting-host-review`, `failed`, `cancelled`) →
249
+ * `history`, and {@link resolveInterruption} reports that REAL outcome so a completed
250
+ * run still reaches host review;
251
+ * * `pending`/`running` WITH an `endedAt`, and anything else — a missing state, or a
252
+ * state string this build does not know → {@link INTERRUPTION_KINDS.unknown}. A live
253
+ * state carrying an end time is a contradictory record: it is neither "running" nor a
254
+ * known finish, so no terminal claim is made and the host is told to check. An
255
+ * unknown state is NEVER assumed to be a restart history either.
256
+ *
257
+ * @param {object | null | undefined} task - the observation's compact task.
258
+ * @returns {'observation' | 'history' | 'unknown'} what the interruption says.
259
+ */
260
+ export function classifyInterruption(task) {
261
+ const record = task !== null && typeof task === 'object' && !Array.isArray(task) ? task : null;
262
+ const state = record === null ? null : record.state;
263
+ if (typeof state !== 'string' || state === '') return INTERRUPTION_KINDS.unknown;
264
+ const ended = record.endedAt !== null && record.endedAt !== undefined;
265
+ // A live state with an end time contradicts itself: refuse to guess either way.
266
+ if (LIVE_TASK_STATES.has(state)) return ended ? INTERRUPTION_KINDS.unknown : INTERRUPTION_KINDS.observation;
267
+ // Only a state this build recognizes can be called a finish. A newer harness may have
268
+ // states this build has never seen, and guessing "finished" for one of them is how a
269
+ // running task would be silently abandoned.
270
+ if (Object.hasOwn(SETTLED_STATE_REASONS, state)) return INTERRUPTION_KINDS.history;
271
+ return INTERRUPTION_KINDS.unknown;
272
+ }
273
+
274
+ /**
275
+ * The reason and terminal flag a wait answer reports for an `interrupted`
276
+ * observation, after the task record has been read.
277
+ *
278
+ * This is a single point of return: it never loops. For a live task the answer is
279
+ * `interrupted` and NOT terminal (the host waits again on the same task); for a restart
280
+ * history it is `interrupted` and terminal; for a settled record the answer is the REAL
281
+ * outcome (`ready`/`failed`/`cancelled`), so a completed run is never described as an
282
+ * unrecoverable interruption and its review is never blocked.
283
+ * @param {object | null | undefined} observation - the observation.
284
+ * @returns {{ reason: string, terminal: boolean, state: string | null, kind: string }} resolved answer facts.
285
+ */
286
+ export function resolveInterruption(observation) {
287
+ const task = compactTask(observation?.task);
288
+ const reported = typeof task.state === 'string' && task.state !== '' ? task.state : null;
289
+ const kind = classifyInterruption(task);
290
+ if (kind === INTERRUPTION_KINDS.unknown) {
291
+ // Neither end nor "still running" is claimed; `state` stays whatever was reported
292
+ // (usually null) and nothing is invented.
293
+ return { reason: 'interrupted', terminal: false, state: reported, kind };
294
+ }
295
+ if (kind === INTERRUPTION_KINDS.history && reported !== null && SETTLED_STATE_REASONS[reported] !== undefined) {
296
+ // The REAL outcome, not the interruption: `awaiting-host-review` is `ready`, so a
297
+ // completed run still reaches host review. Its own review reason wins over the word
298
+ // `interrupted`, which describes only the ended observation.
299
+ return { reason: SETTLED_STATE_REASONS[reported], terminal: true, state: reported, kind };
300
+ }
301
+ // `observation`: a live record whose observer ended. `unknown`: a missing state, an
302
+ // unrecognized one, or a contradictory live-with-`endedAt` record — never claimed as
303
+ // either a finish or a live run.
304
+ return { reason: 'interrupted', terminal: false, state: reported, kind };
305
+ }
306
+
307
+ /**
308
+ * Wait for one task to reach a state the host must act on.
309
+ *
310
+ * The deadline is measured from the FIRST observation, not from "the clock when
311
+ * this function started", so an injected clock is the only thing that decides how
312
+ * much time a wait takes. A loop driven by a fake clock therefore measures its own
313
+ * elapsed time from the wait's real start, which is what a test asserts on.
314
+ * @param {object} options - `callExecution`, `taskId`, `waitMs` (deadline), `signal`,
315
+ * `observeWaitMs` (per-request bound), `now`, `sleep`.
316
+ * @returns {Promise<object>} the compact wait answer (without `ok`).
317
+ */
318
+ export async function waitForTask(options) {
319
+ const callExecution = options.callExecution;
320
+ const taskId = options.taskId;
321
+ const deadlineMs = options.waitMs;
322
+ const observeWaitMs = Math.min(options.observeWaitMs ?? OBSERVE_WAIT_MS, OBSERVE_WAIT_MS);
323
+ const signal = options.signal;
324
+ const now = options.now ?? (() => Date.now());
325
+ const sleep = options.sleep ?? ((ms) => new Promise((resolvePromise) => { setTimeout(resolvePromise, ms); }));
326
+
327
+ const startedAt = now();
328
+ let observationRequests = 0;
329
+ let heartbeats = 0;
330
+ let interruptions = 0;
331
+ let lastObservation = null;
332
+
333
+ /** Throw the local cancellation, so the caller sees a refusal and not an answer. */
334
+ const throwIfCancelled = () => {
335
+ if (signal?.aborted !== true) return;
336
+ const error = new Error('the wait was cancelled by the host');
337
+ error.name = 'AbortError';
338
+ error.code = 'MCP_REQUEST_CANCELLED';
339
+ throw error;
340
+ };
341
+
342
+ for (;;) {
343
+ throwIfCancelled();
344
+ const remaining = deadlineMs - (now() - startedAt);
345
+ if (remaining <= 0) return answer(WAIT_LIMIT_REASON, lastObservation, { resolved: false });
346
+ // One bounded observation. It never overruns the caller's deadline, so the wait
347
+ // cannot answer later than it said it would.
348
+ const perRequest = Math.min(observeWaitMs, remaining);
349
+ observationRequests += 1;
350
+ let observation;
351
+ try {
352
+ observation = await callExecution('observe', { taskId, waitMs: perRequest }, { signal });
353
+ } catch (error) {
354
+ if (error?.code === 'MCP_REQUEST_CANCELLED') throw error;
355
+ // A refusal is the harness's own answer and is returned as such: an unknown
356
+ // task must read as "no such task", never as an invented completion or as a
357
+ // retry loop against a task that does not exist here.
358
+ return {
359
+ ...failureAnswer(error),
360
+ wait: metrics(0),
361
+ };
362
+ }
363
+ lastObservation = observation;
364
+ const reason = reasonOf(observation);
365
+ if (reason === 'interrupted') {
366
+ // An interrupted OBSERVATION is not an interrupted RUN. This branch returns
367
+ // IMMEDIATELY in every case — it never re-issues an observation in the same call.
368
+ //
369
+ // Re-issuing was the defect: when the observer itself is disposed (the engine was
370
+ // torn down, the wait seam broke, the request's own signal aborted) every
371
+ // re-issued observation came back `interrupted` at once, so one `delegate_wait`
372
+ // call became an unbounded burst of HTTP requests. Returning lets the HOST decide
373
+ // to wait again, which is one observation per call at worst.
374
+ //
375
+ // `resolveInterruption` reads the task record, so the answer is the real state:
376
+ // a live task is reported as `interrupted` and NOT terminal, a restart history as
377
+ // terminal, and a settled record as its real outcome (`ready`/`failed`/`cancelled`)
378
+ // so a completed run still reaches review.
379
+ interruptions += 1;
380
+ const resolved = resolveInterruption(observation);
381
+ return answer(resolved.reason, observation, {
382
+ resolved: true,
383
+ resolvedState: resolved.state,
384
+ terminal: resolved.terminal,
385
+ kind: resolved.kind,
386
+ });
387
+ }
388
+ if (CONTINUING_REASONS.has(reason)) {
389
+ heartbeats += 1;
390
+ // A NORMAL heartbeat has already waited out its own `waitMs` inside the engine,
391
+ // so nothing is slept here. This branch only fires for a heartbeat that came
392
+ // back EARLY (a fake engine, or an engine that answers at once): a per-
393
+ // observation floor keeps such a stream from becoming a request storm. The
394
+ // pause is a slice of that floor, never the remaining deadline — sleeping the
395
+ // remaining budget on the first early heartbeat would turn one observation into
396
+ // the whole wait.
397
+ const elapsed = now() - startedAt;
398
+ // A duration, not an instant: `nextDueOffset` used to be an absolute clock value
399
+ // and subtracting an elapsed duration from it produced a pause of
400
+ // (startedAt + 1s), which swallowed the whole deadline on the first heartbeat.
401
+ const nextDueOffset = observationRequests * EARLY_HEARTBEAT_INTERVAL_MS;
402
+ if (elapsed < nextDueOffset) {
403
+ const pause = Math.min(nextDueOffset - elapsed, remaining);
404
+ if (pause > 0) await sleep(pause);
405
+ }
406
+ continue;
407
+ }
408
+ return answer(reason, observation, { resolved: false });
409
+ }
410
+
411
+ /**
412
+ * Build the host-facing answer for one observation.
413
+ * @param {string} reason - reported reason.
414
+ * @param {object | null} observation - the observation that produced it.
415
+ * @param {{ resolved?: boolean, resolvedState?: string | null, terminal?: boolean }} [facts] -
416
+ * `resolved`: the reason was settled by {@link resolveInterruption} rather than read
417
+ * verbatim; `resolvedState`/`terminal` are that resolution's own facts.
418
+ * @returns {object} compact answer.
419
+ */
420
+ function answer(reason, observation, facts = {}) {
421
+ const task = compactTask(observation?.task);
422
+ // A resolved interruption carries the state and terminal flag its resolution decided;
423
+ // every other answer derives them from the reason and the published task.
424
+ const state = facts.resolved === true
425
+ ? (facts.resolvedState ?? null)
426
+ : resolvedTaskState(task, reason);
427
+ const out = {
428
+ taskId: typeof task.taskId === 'string' ? task.taskId : taskId,
429
+ state,
430
+ phase: task.phase ?? null,
431
+ reason,
432
+ actionable: true,
433
+ // `terminal` is honest about the TASK: `wait-limit` and `attention` are
434
+ // reasons to act, but the run is still going, which a host must not confuse
435
+ // with a finished task. An interruption carries the flag its resolution decided.
436
+ terminal: facts.resolved === true ? facts.terminal === true : TERMINAL_REASONS.has(reason),
437
+ instruction: instructionFor(reason, { resolved: facts.resolved === true, taskState: state, kind: facts.kind }),
438
+ task,
439
+ metrics: metrics(1),
440
+ };
441
+ // The permission block is carried WHOLE — identity, fingerprint, completeness
442
+ // flags and the redacted operation — because a host that had to read
443
+ // `delegate_result` first would be doing two round trips to answer one question,
444
+ // and a host that reconstructed the operation from a summary would be deciding
445
+ // something the worker never asked for.
446
+ //
447
+ // The engine publishes this as the pending operation ITSELF (the contract:
448
+ // "permission is the full existing redacted pending-operation object including
449
+ // requestId/fingerprint/completeness/arguments"), so the operation is read from
450
+ // the observation directly, with the task-view wrapper honoured for a harness
451
+ // that nests it under `pending`.
452
+ if (reason === 'permission') {
453
+ const block = observation?.permission;
454
+ const pendingOperation = block !== null && typeof block === 'object' && block.pending !== undefined
455
+ ? block.pending
456
+ : block;
457
+ if (pendingOperation !== null && typeof pendingOperation === 'object') {
458
+ out.permission = pendingOperation;
459
+ // Stated so a host does not have to re-derive the rule, and — importantly —
460
+ // derived from the OPERATION AS PUBLISHED by this answer. `boundedJson` runs
461
+ // after this function and may shorten the operation, in which case its own
462
+ // flag-flipping (and the rescue path's forced `permissionDecidable: false`)
463
+ // makes the published answer say "not decidable"; the value here is the
464
+ // pre-bound one and is the truth when nothing has to be cut.
465
+ out.permissionDecidable = isPermissionDecidable(pendingOperation);
466
+ }
467
+ }
468
+ if (observation?.wait !== null && typeof observation?.wait === 'object') out.longPoll = observation.wait;
469
+ return out;
470
+ }
471
+
472
+ /**
473
+ * Build the metrics block of one return.
474
+ *
475
+ * `totalWaitMs` is the time this call has spent following the task, which includes
476
+ * the internal observations before the last one. It is separate from `elapsedMs`
477
+ * so a host can tell "the last observation waited 25 s" from "this call has been
478
+ * following the task for twenty minutes".
479
+ * @param {number} waitReturns - how many answers the host has received (0 or 1).
480
+ * @returns {object} metrics with no content and no credentials.
481
+ */
482
+ function metrics(waitReturns) {
483
+ return {
484
+ observationRequests,
485
+ heartbeatsConsumed: heartbeats,
486
+ // Observations that ended because THIS observer's request ended, not because the
487
+ // task reached a state. Counted separately from heartbeats so the two are never
488
+ // read as the same event.
489
+ interruptedObservations: interruptions,
490
+ waitReturns,
491
+ elapsedMs: Math.max(0, now() - startedAt),
492
+ deadlineMs,
493
+ perRequestWaitMs: observeWaitMs,
494
+ };
495
+ }
496
+ }
497
+
498
+ /**
499
+ * The reason an observation reported.
500
+ * @param {object} observation - observation answer.
501
+ * @returns {string} reason, defaulting to `attention` for an unknown one.
502
+ */
503
+ export function reasonOf(observation) {
504
+ const reason = observation?.reason;
505
+ if (typeof reason === 'string' && reason !== '') {
506
+ if (CONTINUING_REASONS.has(reason)) return reason;
507
+ if (ACTIONABLE_REASONS.includes(reason)) return reason;
508
+ // An unrecognized reason is a state this host should look at, not a reason to
509
+ // keep waiting: reporting it as `wait-limit` would hide it behind a retry.
510
+ return 'attention';
511
+ }
512
+ return 'attention';
513
+ }
514
+
515
+ /**
516
+ * Turn a thrown refusal into a compact, non-answer result.
517
+ *
518
+ * This is deliberately NOT shaped like a wait answer: `reason` is `null` and the
519
+ * error is named, so a host cannot mistake "the harness could not be asked" for
520
+ * "the task is in this state".
521
+ * @param {unknown} error - thrown value.
522
+ * @returns {object} refusal-shaped result.
523
+ */
524
+ function failureAnswer(error) {
525
+ return {
526
+ taskId: null,
527
+ reason: null,
528
+ error: {
529
+ code: typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED',
530
+ message: typeof error?.message === 'string' ? error.message : 'the wait could not be completed',
531
+ },
532
+ };
533
+ }
534
+
535
+ /** Re-exported so callers can assert the closed vocabulary without importing the server. */
536
+ export { ACTIONABLE_REASONS, WAIT_LIMIT_REASON };