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,1738 @@
1
+ // Native agent execution: one job, one agent, one session, no ambience.
2
+ //
3
+ // The runner is deliberately a thin, observable wrapper around the native
4
+ // lifecycle rather than a reimplementation of it. It adds exactly six things
5
+ // the native layer does not provide on its own:
6
+ // 1. an abort latch, so cancel/timeout that lands while creation is still in
7
+ // flight still prevents the prompt from being delivered, and any handle
8
+ // acquired afterwards is disposed instead of driven;
9
+ // 2. the agent-preset mount, because an Agent that joins no preset has no tools
10
+ // at all and would report a model it cannot exercise. The identity is the
11
+ // caller's choice: omitted means "the registry's configured default" (every
12
+ // worker run), and an explicit `presetId` names a composition the caller
13
+ // owns and has already verified (the additional review);
14
+ // 3. bounded prompt sizes, so a huge request cannot be smuggled into a turn;
15
+ // 4. an explicit, bounded request budget for the model call (never
16
+ // `maxTokens: 1`, which makes a working provider look broken, and never an
17
+ // unbounded request: a native worker needs room for a reasoning effort and
18
+ // a real answer, so the default is the model-level allowance);
19
+ // 5. a bounded, duplicate-aware text collector and redacted diagnostics, so a
20
+ // streamed-then-final answer is reported once and a provider error cannot
21
+ // leak a credential into job history;
22
+ // 6. a caller-generated session identity when the request omits one, because
23
+ // `CreateAgentOptions.sessionId` is REQUIRED and the native factory mints
24
+ // the session under exactly that id. It does not mint an agent identity:
25
+ // `AgentRegistry.enter()` refuses any agent whose `id` differs from its
26
+ // session's, so a default create that omits the id fails with
27
+ // `agent id "undefined" does not match session id "session-N"`.
28
+ //
29
+ // Model selection is the seventh concern and the one with two native shapes: a
30
+ // harness that exposes the conversation's own `agent.model.select`/`.current`
31
+ // records the route durably and can read it back, while an older one has only the
32
+ // legacy `installModelSelection(agentCtx, { current })` coupling. The runner picks
33
+ // by CAPABILITY ({@link SELECTION_MODES}) and, on the modern shape, refuses the run
34
+ // unless the route it asked for is the route the conversation reports — before any
35
+ // prompt is delivered. A model surface that is PRESENT but not fully selectable and
36
+ // readable is refused rather than treated as the old shape: only an absent
37
+ // `agent.model` means "old release", and the legacy coupling on a modern harness
38
+ // carries no selection at all.
39
+
40
+ import { randomUUID } from 'node:crypto';
41
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
42
+ import { installModelSelection } from '@deepseek-ai/dsh-agent';
43
+ import { diagnostic, redactText } from '../config/redact.js';
44
+ import { LIMITS } from '../config/defaults.js';
45
+ import { placeSession, SessionPlacementError as SessionPlacementRefusal } from './session-placement.js';
46
+ import { configureDelegatedSession, policyServicesOf, SandboxPolicyError, SANDBOX_CODES } from './sandbox.js';
47
+ import { PermissionError, PERMISSION_REASONS, isApprovalOutcome } from './permissions.js';
48
+
49
+ // Re-exported for the callers that already reach it through this module. The
50
+ // implementation lives in `config/redact.js` so a harness-independent consumer
51
+ // (the stdio MCP executable) can use it without importing the DSH peers above.
52
+ export { diagnostic };
53
+
54
+ /**
55
+ * Pass-through re-export so the engine can map every placement refusal without
56
+ * importing the placement module as well.
57
+ */
58
+ export { SessionPlacementRefusal };
59
+
60
+ /** Execution outcome kinds. A job never reports "approved"; that is the host's call. */
61
+ export const RUN_OUTCOMES = Object.freeze({
62
+ completed: 'completed',
63
+ failed: 'failed',
64
+ cancelled: 'cancelled',
65
+ timedOut: 'timed_out',
66
+ });
67
+
68
+ /** Errors specific to driving an agent. */
69
+ export const RUN_CODES = Object.freeze({
70
+ cancelled: 'RUN_CANCELLED',
71
+ timeout: 'RUN_TIMEOUT',
72
+ promptTooLarge: 'RUN_PROMPT_TOO_LARGE',
73
+ agentsUnavailable: 'RUN_AGENTS_UNAVAILABLE',
74
+ // A native agent that joins no preset composition has no default tool set;
75
+ // driving it would report a model the run cannot actually exercise.
76
+ agentPresetsUnavailable: 'RUN_AGENT_PRESETS_UNAVAILABLE',
77
+ presetMountFailed: 'RUN_PRESET_MOUNT_FAILED',
78
+ // A caller named a preset id that this dependency set refuses to mount. The
79
+ // runner only mounts ids its caller marked as owned (`presetOwnership.owns`),
80
+ // so an arbitrary id can never re-point a run at a composition the caller does
81
+ // not control.
82
+ presetNotOwned: 'RUN_PRESET_NOT_OWNED',
83
+ // A caller-supplied session identity the native registry would refuse before
84
+ // any agent existed (not a string, blank, or already live in this process).
85
+ sessionIdUnusable: 'RUN_SESSION_ID_UNUSABLE',
86
+ createFailed: 'RUN_CREATE_FAILED',
87
+ turnFailed: 'RUN_TURN_FAILED',
88
+ noText: 'RUN_NO_TEXT',
89
+ // A caller-supplied output budget that is not a bounded positive integer. It is
90
+ // refused before an agent exists: silently substituting a value would report a
91
+ // budget the request did not ask for, and forwarding it unbounded is exactly the
92
+ // "practical allowance" this contract exists to guarantee.
93
+ maxTokensUnusable: 'RUN_MAX_TOKENS_UNUSABLE',
94
+ sandboxPolicyUnavailable: SANDBOX_CODES.unavailable,
95
+ // A permission bridge was handed to the run but could not be armed for the Agent
96
+ // it would have to answer for. Refused before the prompt: a run that reported a
97
+ // bridge while installing `never` would look like the commander could decide,
98
+ // and nothing would ever reach it.
99
+ permissionBridgeUnavailable: 'RUN_PERMISSION_BRIDGE_UNAVAILABLE',
100
+ // The conversation's own model API (`agent.model`)
101
+ // is present but unusable: it threw, answered nothing, answered a route
102
+ // this run did not select, or exposed a surface that cannot be selected through
103
+ // and read back (a half-installed/malformed model API). The run is refused
104
+ // BEFORE its prompt in every one of those cases, because a conversation driven
105
+ // on an unverified route would report the operator's selection while running on
106
+ // another one — and there is no legacy fallback after a present model surface
107
+ // fails: on a modern helper that installer carries no selection at all.
108
+ selectionUnavailable: 'RUN_MODEL_SELECTION_UNAVAILABLE',
109
+ });
110
+
111
+ /**
112
+ * Stable reasons carried in `RunError.details.reason` for a model selection that
113
+ * could not be applied and read back.
114
+ *
115
+ * Fixed strings chosen by this module, never an upstream message, so an operator
116
+ * can tell WHICH capability was missing or disagreed without reading a provider
117
+ * error into a job record.
118
+ */
119
+ export const SELECTION_REASONS = Object.freeze({
120
+ noAgent: 'agent model API unavailable',
121
+ writeFailed: 'model selection was rejected',
122
+ readbackFailed: 'model selection could not be read back',
123
+ readbackUnusable: 'model selection read back without a route',
124
+ routeMismatch: 'model selection read back disagrees',
125
+ effortMismatch: 'reasoning effort read back disagrees',
126
+ unrequestedEffort: 'model selection read back an effort this run did not select',
127
+ // No capability at all on this harness, on a run that left its route to the
128
+ // conversation: nothing named a provider/model, so there is nothing to apply,
129
+ // and a run must never invent one.
130
+ noCapability: 'no model selection capability',
131
+ // The Agent DOES expose a model surface, but not one this run can select
132
+ // through and read back (a half-installed or malformed API, e.g. `select()`
133
+ // without `current()`, or a non-callable member). Such a surface is neither the
134
+ // verifiable modern API nor evidence of an old release, so the legacy coupling
135
+ // is not a legitimate substitute: on a modern helper it carries no selection
136
+ // at all and would let the run claim a route it never applied.
137
+ modelSurfaceIncomplete: 'agent model API is present but incomplete',
138
+ });
139
+
140
+ /**
141
+ * What one conversation can do with its own model route.
142
+ *
143
+ * The native API moved between supported DSH releases, and the two shapes are not
144
+ * interchangeable:
145
+ *
146
+ * * `agent.model.select({ provider, model, reasoningEffort? })` with
147
+ * `agent.model.current()` (the modern shape) records the choice in the
148
+ * conversation's durable `modelSelection` projection, which every later step
149
+ * reads. `installModelSelection(agentCtx)` on such a release only installs the
150
+ * pre-step model-switch NOTICE listener: it carries no selection, so calling
151
+ * it with a selection changes nothing about the route a turn runs on.
152
+ * * `installModelSelection(agentCtx, { current, assembled })` (the legacy shape)
153
+ * is what applies a route on a release that has no `agent.model` at all: its
154
+ * `agent/request` listener rewrites the request, and its
155
+ * `system-prompt/assemble` listener publishes the route to the prompt.
156
+ *
157
+ * `mode` is therefore decided by CAPABILITY, per run, and never by a version
158
+ * string: a harness that exposes the modern API uses ONLY it (so a selection is
159
+ * verified instead of assumed), one with NO model surface keeps the legacy
160
+ * coupling it needs, and a present-but-incomplete surface is `unavailable` — a
161
+ * refusal, because neither route can prove what it applied.
162
+ */
163
+ export const SELECTION_MODES = Object.freeze({
164
+ modern: 'modern',
165
+ legacy: 'legacy',
166
+ unavailable: 'unavailable',
167
+ });
168
+
169
+ /**
170
+ * Which model-selection capability one agent exposes.
171
+ *
172
+ * Capability presence, not a version, decided in this order:
173
+ * * a completely callable `model.select`/`model.current` pair is
174
+ * {@link SELECTION_MODES.modern};
175
+ * * NO model surface at all (`agent.model` null/undefined) is the only state
176
+ * that may take the legacy coupling, because that is what a release without
177
+ * the conversation's own model API looks like;
178
+ * * anything else — a model surface that is present but malformed, or that
179
+ * lacks either callable member — is {@link SELECTION_MODES.unavailable}. It is
180
+ * deliberately NOT legacy: on a modern harness the legacy installer only
181
+ * installs the model-switch NOTICE, so falling back would report a selection
182
+ * that was never applied. Failing closed is the only honest answer.
183
+ * @param {object} agent - native (or fake) Agent.
184
+ * @returns {string} one of {@link SELECTION_MODES}.
185
+ */
186
+ export function selectionModeOf(agent) {
187
+ // Anything that is not an observable object offers no model surface at all.
188
+ if (agent === null || typeof agent !== 'object') return SELECTION_MODES.legacy;
189
+ const model = agent.model;
190
+ // `null`/`undefined` is the ONLY absence: an old release has no `agent.model`.
191
+ if (model === undefined || model === null) return SELECTION_MODES.legacy;
192
+ if (typeof model !== 'object') return SELECTION_MODES.unavailable;
193
+ const selectable = typeof model.select === 'function';
194
+ const readable = typeof model.current === 'function';
195
+ return selectable && readable ? SELECTION_MODES.modern : SELECTION_MODES.unavailable;
196
+ }
197
+
198
+ /**
199
+ * Describe a model surface by capability only.
200
+ *
201
+ * Reported in a refusal's details so an operator can tell WHICH half is missing
202
+ * without this module copying an arbitrary object into a job record: no member
203
+ * value and no object identity ever travels, only booleans.
204
+ * @param {unknown} model - the Agent's `model` value.
205
+ * @returns {{ kind: string, select: boolean, current: boolean }} capability facts.
206
+ */
207
+ function describeModelSurface(model) {
208
+ return {
209
+ // The JavaScript type of the surface, fixed vocabulary (`object`, `string`…).
210
+ kind: model === undefined ? 'undefined' : (model === null ? 'null' : typeof model),
211
+ select: typeof model?.select === 'function',
212
+ current: typeof model?.current === 'function',
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Default output-token budget for one native model request.
218
+ *
219
+ * 32768 is the model-level allowance this plugin already declares for a model the
220
+ * settings document does not size (`DEFAULT_MAX_TOKENS` in
221
+ * `src/model/openai-adapter.js`, mirroring the pi-ai defaults), so a worker whose
222
+ * route declares no per-request allowance is not silently starved to a fraction
223
+ * of what its model can emit. It is a REQUEST bound, not a model capability
224
+ * claim: the provider still refuses what it cannot serve.
225
+ */
226
+ export const DEFAULT_MAX_TOKENS = 32768;
227
+
228
+ /**
229
+ * Hard bounds on a caller-supplied request budget.
230
+ *
231
+ * Below the minimum a reasoning model is starved into an apparent timeout; above
232
+ * the maximum a single request can reserve more than any model serves. A value
233
+ * outside the range is a validation refusal, never a clamp: an operator who asked
234
+ * for an impossible budget must be told, not quietly given another one.
235
+ */
236
+ export const MAX_TOKENS_BOUNDS = Object.freeze({ min: 256, max: 262144 });
237
+
238
+ /**
239
+ * In-band run failures, stated on the run's own `error` field.
240
+ *
241
+ * These are not members of `RUN_CODES`, which is the set of *refusals* this module
242
+ * throws before or instead of driving an agent. They describe an agent that ran and
243
+ * produced nothing usable, and the engine maps them onto job codes by matching the
244
+ * text; keeping the vocabulary apart is what lets a caller tell "no agent was ever
245
+ * created" from "the agent answered nothing".
246
+ */
247
+ const RUN_ERRORS = Object.freeze({
248
+ emptyOutput: 'the agent produced no assistant text',
249
+ budgetExhausted: 'the agent exhausted its output token budget without producing an answer',
250
+ });
251
+
252
+ /**
253
+ * Hard bound on the assistant text one run retains.
254
+ *
255
+ * The collector clamps *while* it collects rather than at the end, so a runaway
256
+ * or hostile stream cannot make the process hold an unbounded string before the
257
+ * final slice. `LIMITS.outputChars` is honoured when the configuration layer
258
+ * defines it; 64k is the plugin's own bound otherwise.
259
+ */
260
+ const OUTPUT_TEXT_CHARS = (() => {
261
+ const configured = Number(LIMITS?.outputChars);
262
+ return Number.isInteger(configured) && configured > 0 ? configured : 64_000;
263
+ })();
264
+
265
+ /** Raised when a run cannot proceed. */
266
+ export class RunError extends Error {
267
+ /**
268
+ * @param {string} code - stable machine code.
269
+ * @param {string} message - human-readable explanation.
270
+ * @param {object} [details] - bounded, redacted details.
271
+ */
272
+ constructor(code, message, details = {}) {
273
+ super(message);
274
+ this.name = 'RunError';
275
+ this.code = code;
276
+ this.details = details;
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Build a native user message through the harness's own constructor, so the
282
+ * identity, `role` tag, deep freeze and source validation come from
283
+ * `@deepseek-ai/dsh-llm` rather than a locally re-derived shape the loop could
284
+ * drift away from. `source: { kind: 'user' }` is required by the native
285
+ * `UserMessage` type and is what every native caller passes; omitting it
286
+ * produces a message with no declared producer.
287
+ * @param {string} text - prompt text.
288
+ * @returns {object} frozen user message.
289
+ */
290
+ export function userMessage(text) {
291
+ return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } });
292
+ }
293
+
294
+ /**
295
+ * One run's execution deadline, with a real pause and resume.
296
+ *
297
+ * The previous design armed a single `setTimeout(timeoutMs)` and never touched it
298
+ * again. A worker that paused on a permission request therefore kept burning its
299
+ * execution budget while it was doing nothing, and a wait longer than the budget
300
+ * timed the run out for a decision the run was not making.
301
+ *
302
+ * This class owns the budget instead of only reporting on it:
303
+ *
304
+ * * `arm()` starts the remaining budget;
305
+ * * `pause()` clears the timer AND charges the elapsed span against the budget, so
306
+ * a paused run holds a smaller remaining budget and NO armed timer at all;
307
+ * * `resume()` re-arms exactly the remaining budget;
308
+ * * repeated pauses accumulate correctly, because each one debits what it used;
309
+ * * `dispose()` disarms and drops any un-charged paused span, so a run that ends
310
+ * during a wait leaves nothing armed.
311
+ *
312
+ * The clock is injectable so a test can drive a wait longer than the budget without
313
+ * spending real wall-clock time.
314
+ */
315
+ export class ExecutionDeadline {
316
+ /**
317
+ * @param {number} totalMs - the run's execution budget.
318
+ * @param {() => void} onExpire - called once, when the remaining budget is gone.
319
+ * @param {object} [options] - `now` (ms clock); a test seam only.
320
+ */
321
+ constructor(totalMs, onExpire, options = {}) {
322
+ this.totalMs = totalMs;
323
+ this.remainingMs = totalMs;
324
+ this.onExpire = onExpire;
325
+ this.now = typeof options?.now === 'function' ? options.now : () => Date.now();
326
+ this.timer = null;
327
+ /** When the current running span started, or null while paused/disarmed. */
328
+ this.runningSince = null;
329
+ /** Total time spent paused, reported as evidence. */
330
+ this.pausedMs = 0;
331
+ this.expired = false;
332
+ this.disposed = false;
333
+ }
334
+
335
+ /** Whether a timer is currently armed (i.e. the run is not paused). */
336
+ get armed() {
337
+ return this.timer !== null;
338
+ }
339
+
340
+ /**
341
+ * Arm the remaining budget, unless the run is disposed or already expired.
342
+ * @returns {void}
343
+ */
344
+ arm() {
345
+ if (this.disposed || this.expired || this.timer !== null) return;
346
+ this.runningSince = this.now();
347
+ const delay = Math.max(0, Math.floor(this.remainingMs));
348
+ this.timer = setTimeout(() => {
349
+ this.timer = null;
350
+ this.runningSince = null;
351
+ this.remainingMs = 0;
352
+ this.expired = true;
353
+ try {
354
+ this.onExpire();
355
+ } catch {
356
+ // The expiry callback latches the run; a throw here cannot be acted on.
357
+ }
358
+ }, delay);
359
+ this.timer.unref?.();
360
+ }
361
+
362
+ /**
363
+ * Charge the elapsed running span against the remaining budget and disarm.
364
+ *
365
+ * This is the half the old design was missing: pausing does not merely record a
366
+ * timestamp, it reduces the budget and removes the timer, so nothing can expire
367
+ * while the run waits.
368
+ * @returns {number} the budget remaining after the charge.
369
+ */
370
+ pause() {
371
+ if (this.disposed) return this.remainingMs;
372
+ if (this.timer !== null) {
373
+ clearTimeout(this.timer);
374
+ this.timer = null;
375
+ }
376
+ if (this.runningSince !== null) {
377
+ const spent = Math.max(0, this.now() - this.runningSince);
378
+ this.remainingMs = Math.max(0, this.remainingMs - spent);
379
+ this.runningSince = null;
380
+ }
381
+ return this.remainingMs;
382
+ }
383
+
384
+ /**
385
+ * Re-arm exactly the remaining budget after a wait ended.
386
+ *
387
+ * A wait that has already consumed the whole budget expires the run on resume —
388
+ * that is the honest outcome, because the budget really is gone. The verdict is
389
+ * reached SYNCHRONOUSLY here rather than by arming a 0 ms timer, so a caller (and
390
+ * a test) observes the expiry as part of the resume, not one tick later.
391
+ * @returns {void}
392
+ */
393
+ resume() {
394
+ if (this.disposed || this.expired) return;
395
+ if (this.remainingMs <= 0) {
396
+ this.expired = true;
397
+ try {
398
+ this.onExpire();
399
+ } catch {
400
+ // The expiry callback latches the run; a throw here cannot be acted on.
401
+ }
402
+ return;
403
+ }
404
+ this.arm();
405
+ }
406
+
407
+ /**
408
+ * Record a paused span for evidence (the wait itself is accounted by `pause`).
409
+ * @param {number} ms - the span to record as waited.
410
+ * @returns {void}
411
+ */
412
+ notePaused(ms) {
413
+ if (!Number.isFinite(ms) || ms <= 0) return;
414
+ this.pausedMs += ms;
415
+ }
416
+
417
+ /** Disarm and release the timer. Safe to call more than once. */
418
+ dispose() {
419
+ if (this.timer !== null) {
420
+ clearTimeout(this.timer);
421
+ this.timer = null;
422
+ }
423
+ this.runningSince = null;
424
+ this.disposed = true;
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Drive one native agent to completion under a timeout and a cancellation latch.
430
+ *
431
+ * Two ways a run can obtain its agent, and both produce the same evidence:
432
+ *
433
+ * * a Workspace PLACEMENT (`request.placement`, or one resolved from the native
434
+ * controllers when the caller did not supply it): the DSH Session already exists
435
+ * in its Workspace, so the run drives the live Agent resolved for it. A continued
436
+ * task thread arrives this way, and so does a freshly created Session —
437
+ * resolving it is what attaches the native Agent to the Workspace the Session
438
+ * was created in.
439
+ * * no placement: the historical path, which creates a Session (and Agent) through
440
+ * `agents.create` under a caller-supplied or generated identity. Retained for a
441
+ * caller that owns its own conversation identity — the additional review, which
442
+ * composes its own preset and must not join the operator's history.
443
+ *
444
+ * The runner never disposes an agent it resolved. Disposal would end a conversation
445
+ * a later follow-up must be able to continue, so {@link driveAgent} accepts an
446
+ * inherited `disposeOwned` and this entry point sets it only for agents it created.
447
+ *
448
+ * Cancellation is decided before anything is created: a run whose signal is
449
+ * already aborted takes the unplaced path and returns `cancelled` without creating
450
+ * a Workspace, a Session or an Agent, so an operator never finds an empty group
451
+ * left behind by a run that never started.
452
+ * @param {object} deps - `agents` (native agent registry), `agentPresets`, optional
453
+ * `workspaces`/`sessionController` for workspace-grouped placement, the native
454
+ * `sessions` persistence service (flush only), the optional `policyServices`
455
+ * accessor for the two native policy services, and `logger`.
456
+ * @param {object} request - `prompt`, `cwd`, `selection`, `timeoutMs`, `signal`,
457
+ * `onEvent`, the optional preset selection (`presetId`, `presetOwnership`), and the
458
+ * optional `placement` / `continueFromTaskId` / `allowUnplaced`, and
459
+ * `delegated` for a worker session that must receive the DSH sandbox policy.
460
+ * @returns {Promise<object>} run result with text, usage facts, the `conversation`
461
+ * placement fact and lifecycle evidence.
462
+ */
463
+ export async function runAgent(deps, request) {
464
+ const agents = deps?.agents;
465
+ if (agents === undefined || agents === null || typeof agents.create !== 'function') {
466
+ throw new RunError(RUN_CODES.agentsUnavailable, 'the native agent registry is not available', {});
467
+ }
468
+ // A run whose cancellation is already known must not place anything: creating a
469
+ // Workspace (and then a Session inside it) for a run that will never deliver a
470
+ // prompt leaves the operator an empty group and an empty conversation. The
471
+ // latch below re-checks at the exact step that creates anything; this check
472
+ // exists so the placement call is never even entered.
473
+ if (request?.signal?.aborted === true) {
474
+ return await driveAgent(deps, {
475
+ ...request,
476
+ placement: request?.placement ?? null,
477
+ // Nothing was created by this run, so there is nothing to dispose — and even
478
+ // a later-arriving resolved Agent is not ours to end.
479
+ disposeOwned: false,
480
+ });
481
+ }
482
+ // A caller that brings its own conversation identity decides its own placement.
483
+ // One that does not is placed through the native controllers, and an unavailable
484
+ // controller is a refusal — never an ungrouped run.
485
+ const placement = request?.placement !== undefined
486
+ ? request.placement
487
+ : await resolvePlacement(deps, request);
488
+ const owned = request?.placement !== undefined || request?.allowUnplaced === true;
489
+ return await driveAgent(deps, {
490
+ ...request,
491
+ placement,
492
+ // Only an Agent this run created is owned by it. Both placement paths drive a
493
+ // RESOLVED Agent (a new Session is resolved to its Agent too), and a resolved
494
+ // Agent belongs to its Session: disposing it would end a conversation that a
495
+ // later `continueFromTaskId` follow-up must be able to resume.
496
+ disposeOwned: owned ? (placement === null || placement.reused !== true) : false,
497
+ });
498
+ }
499
+
500
+ /**
501
+ * Resolve the Workspace and Session one run drives, or `null` for the
502
+ * unnamed-session path.
503
+ *
504
+ * `null` (the value `placeSession` never returns) happens only when the caller
505
+ * explicitly asked for an unnamed conversation, which the review does: it must not
506
+ * appear in the operator's Workspace history. Every worker run gets a placement
507
+ * or a refusal; there is no third outcome.
508
+ * @param {object} deps - dependency object.
509
+ * @param {object} request - run request.
510
+ * @returns {Promise<object | null>} placement fact, or null.
511
+ * @throws {SessionPlacementError} when the harness cannot place the run.
512
+ */
513
+ async function resolvePlacement(deps, request) {
514
+ // `allowUnplaced: true` is the review's own composition, which creates its
515
+ // agent under a caller-owned preset and identity and is not a conversation the
516
+ // operator navigates. It is never reachable from a job submission.
517
+ if (request?.allowUnplaced === true) return null;
518
+ // A caller-owned identity means the caller owns placement too. This is the
519
+ // review's session id and the historical unplaced path a lifecycle test drives;
520
+ // it is not reachable from `JobEngine.execute`, which never supplies one.
521
+ if (request?.sessionId !== undefined && request?.sessionId !== null) return null;
522
+ const placement = await placeSession(deps, {
523
+ path: request?.cwd,
524
+ // The only thing that can continue an existing conversation, and it is the
525
+ // caller's explicit statement that this submission is a follow-up to THAT task.
526
+ // Omitted means a new conversation, always.
527
+ continueFromTaskId: request?.continueFromTaskId,
528
+ // Task/connection facts the continuation identity must match. The engine passes
529
+ // them because it is the only component that knows which task and connection
530
+ // this run belongs to.
531
+ taskId: request?.taskId,
532
+ connectionId: request?.connectionId,
533
+ sourcePath: request?.sourcePath,
534
+ presetId: request?.placementPresetId,
535
+ });
536
+ return placement;
537
+ }
538
+
539
+ /**
540
+ * Drive one native agent to completion under a timeout and a cancellation latch.
541
+ *
542
+ * @param {object} deps - `agents`, optional `sessions` (flush) and `logger`.
543
+ * @param {object} request - `prompt`, `cwd`, `selection`, `timeoutMs`, `signal`,
544
+ * `onEvent`, `presetId`, `placement`, `disposeOwned`.
545
+ * @returns {Promise<object>} run result with text, usage facts and lifecycle evidence.
546
+ */
547
+ export async function driveAgent(deps, request) {
548
+ const agents = deps?.agents;
549
+ if (agents === undefined || agents === null || typeof agents.create !== 'function') {
550
+ throw new RunError(RUN_CODES.agentsUnavailable, 'the native agent registry is not available', {});
551
+ }
552
+ const presets = presetRegistryOf(deps);
553
+ if (presets === null) {
554
+ throw new RunError(
555
+ RUN_CODES.agentPresetsUnavailable,
556
+ 'the native agent preset registry is not available, so no default tool composition can be installed',
557
+ {},
558
+ );
559
+ }
560
+ const prompt = typeof request?.prompt === 'string' ? request.prompt : '';
561
+ if (prompt === '') {
562
+ throw new RunError(RUN_CODES.turnFailed, 'the delegation prompt is empty', {});
563
+ }
564
+ if (prompt.length > LIMITS.promptChars) {
565
+ throw new RunError(RUN_CODES.promptTooLarge, `the delegation prompt exceeds ${LIMITS.promptChars} characters`, {
566
+ length: prompt.length,
567
+ limit: LIMITS.promptChars,
568
+ });
569
+ }
570
+ const selection = request.selection ?? {};
571
+ const timeoutMs = Number.isInteger(request.timeoutMs) && request.timeoutMs > 0 ? request.timeoutMs : null;
572
+ const placement = request?.placement ?? null;
573
+ const resolvedAgent = placement?.agent ?? null;
574
+ // A resolved agent carries its own session and preset composition; the run must
575
+ // not mount a second composition onto it. An agent created here still does.
576
+ //
577
+ // This holds on BOTH placement paths: a freshly created Session is also driven
578
+ // through the Agent the session controller resolved for it, because the Session
579
+ // already exists in the Workspace and `agents.create` would create a second one.
580
+ // The preset is installed by whoever created that Agent (the session controller's
581
+ // own composition, or — on the unplaced review path — this run's setup).
582
+ const mountsPreset = resolvedAgent === null;
583
+ const disposeOwned = request?.disposeOwned !== false;
584
+
585
+ // Preset selection. `undefined` means "whatever the registry configures as its
586
+ // default", which is what every worker run asks for. A named id is only
587
+ // mounted when the caller declares ownership of it: without that check any
588
+ // caller could re-point a run at a composition it does not own (including a
589
+ // user preset with a shell), and the run would silently lose the tool surface
590
+ // the caller intended to restrict.
591
+ const presetId = request.presetId;
592
+ if (mountsPreset && presetId !== undefined && presetId !== null) {
593
+ const ownership = request.presetOwnership;
594
+ const owned = typeof ownership?.owns === 'function' && ownership.owns(presetId) === true;
595
+ if (!owned) {
596
+ throw new RunError(
597
+ RUN_CODES.presetNotOwned,
598
+ 'the requested agent preset is not owned by the caller, so it will not be mounted',
599
+ {},
600
+ );
601
+ }
602
+ }
603
+
604
+ // The native create contract takes the identity from the CALLER: `sessionId`
605
+ // is required and the factory creates the session and the agent under it.
606
+ // Nothing in the default creation path mints one, and `AgentRegistry.enter()`
607
+ // refuses an agent whose `id` does not equal its session's — which is exactly
608
+ // how a call that omitted the id used to fail. So an absent identity is
609
+ // generated here, once per run, and travels on the create call.
610
+ //
611
+ // A placed run does not mint anything: its identity is the Session the
612
+ // Workspace controller created or the one a previous run recorded.
613
+ const sessionId = resolveSessionIdentity(placement?.sessionId ?? request?.sessionId);
614
+ // A caller-supplied identity that the native registry would reject (blank, not
615
+ // a string, or already live in this process) is refused before an agent
616
+ // exists, instead of surfacing later as an opaque creation failure. A resolved
617
+ // agent is already live under exactly this identity, so the check is skipped.
618
+ if (sessionId.generated === false && resolvedAgent === null) {
619
+ const unusable = sessionIdUnusable(agents, sessionId.value);
620
+ if (unusable !== null) {
621
+ throw new RunError(RUN_CODES.sessionIdUnusable, 'the requested session identity cannot be created', {
622
+ // Fixed text chosen by this module, never the caller's value.
623
+ reason: unusable,
624
+ // Never the raw identity: a caller-supplied value may carry anything.
625
+ requestedType: typeof sessionId.value,
626
+ });
627
+ }
628
+ }
629
+
630
+ const state = {
631
+ abortRequested: false,
632
+ abortCause: null,
633
+ handle: null,
634
+ handleDisposed: false,
635
+ // A resolved Agent is driven through the same handle shape a created one
636
+ // arrives in, so every step below (idle wait, prompt delivery, flush,
637
+ // cancellation) has exactly one implementation.
638
+ //
639
+ // `createdOwnAgent` is the lifecycle fact that decides disposal: only an Agent
640
+ // this run created may be disposed by it. Disposing a resolved Agent would end
641
+ // the Session it belongs to and make a later follow-up unable to continue it.
642
+ createdOwnAgent: resolvedAgent === null,
643
+ disposeOwned,
644
+ // Bounded and deduplicating: the native loop streams `text-delta` events and
645
+ // then emits the finished assistant message carrying the same text, so a
646
+ // naive append would report every answer twice and hold an unbounded string.
647
+ text: createTextCollector(OUTPUT_TEXT_CHARS),
648
+ reasoningSeen: false,
649
+ // The model request this run will actually make, known before creation so a
650
+ // refusal happens before an agent exists.
651
+ maxTokens: maxTokensFor(request.maxTokens),
652
+ usage: null,
653
+ turnEnd: null,
654
+ error: null,
655
+ agentId: null,
656
+ // The model selection this run actually installed on the Agent it drove, and
657
+ // the request budget it asked for. Reported so a placed run — which never goes
658
+ // through `agents.create` — can still be audited for "ran on the selected
659
+ // provider/model/effort with a usable budget".
660
+ selection: null,
661
+ // The identity this run will own, known before creation settles so a run
662
+ // that never produces a handle still reports the id it asked for instead of
663
+ // `null`.
664
+ sessionId: sessionId.value,
665
+ // The approval stance this run actually installed and read back, and whether
666
+ // an armed permission bridge is why the Session asks instead of rejecting.
667
+ // Reported as a verified fact, never as a configuration value.
668
+ approval: null,
669
+ // Removes the `approval/request` answerer when the run ends. Null when the run
670
+ // had no bridge, which is the ordinary worker run.
671
+ permissionAnswerer: null,
672
+ // The execution deadline this run owns. It is PAUSED around every permission
673
+ // wait, so the wait is not charged to the operator's execution budget.
674
+ deadline: null,
675
+ };
676
+ if (state.maxTokens.refused !== null) {
677
+ throw new RunError(
678
+ RUN_CODES.maxTokensUnusable,
679
+ 'the requested output token budget is not a bounded positive integer',
680
+ state.maxTokens.refused,
681
+ );
682
+ }
683
+ const requestBudget = state.maxTokens.value;
684
+
685
+ let resolveAbort;
686
+ const aborted = new Promise((resolvePromise) => { resolveAbort = resolvePromise; });
687
+
688
+ const latch = (cause) => {
689
+ if (state.abortRequested) return;
690
+ state.abortRequested = true;
691
+ state.abortCause = cause;
692
+ resolveAbort(cause);
693
+ // A live agent is cancelled immediately; a handle that arrives later is
694
+ // disposed by the creation path below.
695
+ if (state.handle !== null) {
696
+ try {
697
+ state.handle.agent.cancel({ kind: 'user' }, { keepInbox: false });
698
+ } catch {
699
+ // Cancellation of an already-idle agent is not an error we can act on.
700
+ }
701
+ }
702
+ };
703
+
704
+ const onAbortSignal = () => latch('cancelled');
705
+ if (request.signal !== undefined && request.signal !== null) {
706
+ if (request.signal.aborted === true) latch('cancelled');
707
+ else request.signal.addEventListener('abort', onAbortSignal, { once: true });
708
+ }
709
+
710
+ // Native dispatch is `('session/event', session, event)`; the second argument
711
+ // is the event. A second positional handler shape (`agent/error`) carries a
712
+ // payload object instead, and is registered separately below.
713
+ const onEvent = (sessionOrEvent, maybeEvent) => {
714
+ const event = maybeEvent === undefined ? sessionOrEvent : maybeEvent;
715
+ if (event === null || typeof event !== 'object') return;
716
+ if (state.abortRequested && event.type !== 'turn/end') return;
717
+ collectEvent(event, state);
718
+ request.onEvent?.(event);
719
+ };
720
+
721
+ try {
722
+ // A cancellation that arrived before the factory was ever called must not
723
+ // create an agent at all — creating one only to dispose it would still run
724
+ // setup, install a composition and pay for a session that nobody asked for.
725
+ if (state.abortRequested) {
726
+ return finish(state, state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
727
+ }
728
+
729
+ const handlePromise = resolvedAgent === null
730
+ ? agents.create({
731
+ // Always a string: the native contract requires it, and the factory mints
732
+ // both the session and (through `enter()`) the agent id from it.
733
+ sessionId: state.sessionId,
734
+ meta: { cwd: request.cwd },
735
+ agentOptions: agentOptionsFor(selection, requestBudget),
736
+ setup: async (agentCtx, agent) => {
737
+ // Join the default native preset *before* the model selection is
738
+ // installed. The preset is what mounts the Agent's tool composition and
739
+ // its scoped services; a run that skipped it would report a model the
740
+ // agent cannot actually exercise because it has no tools at all. Failing
741
+ // here fails the run closed, inside `agents.create`, which the caller
742
+ // already observes as a refusal.
743
+ try {
744
+ await (presetId === undefined || presetId === null
745
+ ? presets.mount(agentCtx)
746
+ : presets.mount(agentCtx, presetId));
747
+ } catch (error) {
748
+ throw new RunError(RUN_CODES.presetMountFailed, 'the native agent preset could not be mounted', {
749
+ cause: diagnostic(error?.message ?? error),
750
+ });
751
+ }
752
+ // Optional caller policy, installed after the composition exists (so the
753
+ // inventory it may inspect is the real one) and before the prompt is
754
+ // delivered (so no turn can run without it). A hook that throws fails
755
+ // creation closed, which is what a caller that needs a tool restriction
756
+ // wants: a refused restriction must never degrade into an unrestricted
757
+ // run. The agent is passed as the second argument because an agent's
758
+ // tools live on its own scope plane, and `tools.schemas()`/`restrict()`
759
+ // are scoped calls.
760
+ if (typeof request.setup === 'function') {
761
+ await request.setup(agentCtx, agent);
762
+ }
763
+ if (request.delegated === true) {
764
+ applyDelegatedPolicy(agent, deps, request);
765
+ }
766
+ // The created path takes the same capability-based adapter as the
767
+ // resolved one: on a modern harness the route is selected through the
768
+ // conversation's own model API and read back BEFORE the prompt, and on a
769
+ // legacy harness it travels through `installModelSelection`. Nothing is
770
+ // reported as applied that was not read back.
771
+ state.selection = applySelection(agentCtx, agent, selection);
772
+ agentCtx.on('session/event', onEvent);
773
+ agentCtx.on('agent/error', (payload) => {
774
+ state.error = errorText(payload?.error);
775
+ });
776
+ },
777
+ })
778
+ // A resolved Agent already carries its session, its preset composition and
779
+ // its listeners. What it must still receive is THIS run's model selection:
780
+ // the operator's provider/model/effort is per task, while the conversation
781
+ // it continues is shared, so re-applying the selection here is the whole
782
+ // point of driving the resolved agent instead of its logged header.
783
+ : adoptResolvedAgent(resolvedAgent, request, selection);
784
+
785
+ // The execution deadline is not a single `setTimeout`. A worker that is waiting
786
+ // for a permission decision is paused, not running, so the wait must not consume
787
+ // the operator's execution budget. {@link ExecutionDeadline} holds the remaining
788
+ // budget and re-arms only what is left, for any number of waits.
789
+ const deadline = timeoutMs === null ? null : new ExecutionDeadline(timeoutMs, () => latch('timeout'));
790
+ if (deadline !== null) deadline.arm();
791
+ state.deadline = deadline;
792
+
793
+ const raced = await Promise.race([
794
+ handlePromise.then((handle) => ({ kind: 'handle', handle })),
795
+ aborted.then((cause) => ({ kind: 'aborted', cause })),
796
+ ]);
797
+
798
+ if (raced.kind === 'aborted') {
799
+ // The handle may still arrive after the latch. Disposing it as soon as it
800
+ // does is the only way no agent outlives a run that is already terminal;
801
+ // the prompt is never delivered on this path.
802
+ handlePromise.then(
803
+ (handle) => { void releaseHandle(state, handle); },
804
+ () => {},
805
+ );
806
+ return finish(state, raced.cause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
807
+ }
808
+
809
+ const handle = raced.handle;
810
+ state.handle = handle;
811
+ // Both ids are read from the ONE live agent the factory returned, so the
812
+ // reported identity is what was actually created rather than what was asked
813
+ // for. A factory that honoured the identity request reports the same ids the
814
+ // run requested; `sessionId` falls back to the requested identity only for a
815
+ // handle that exposes no session object at all.
816
+ state.agentId = handle?.agent?.id ?? null;
817
+ state.sessionId = handle?.agent?.session?.id ?? state.sessionId;
818
+
819
+ if (state.abortRequested) {
820
+ await releaseHandle(state, handle);
821
+ return finish(state, state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
822
+ }
823
+
824
+ // Wait for the agent's own initial quiescence before prompting, so the
825
+ // prompt is not queued behind setup work that is still composing.
826
+ await Promise.race([handle.agent.whenIdle(), aborted]);
827
+ if (state.abortRequested) {
828
+ await releaseHandle(state, handle);
829
+ return finish(state, state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
830
+ }
831
+
832
+ handle.agent.followup(userMessage(prompt));
833
+ await Promise.race([handle.agent.whenIdle(), aborted]);
834
+
835
+ const outcome = state.abortRequested
836
+ ? (state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled)
837
+ : deriveOutcome(state);
838
+
839
+ // Flush the session so the transcript is durable before the caller reads it.
840
+ if (deps?.sessions !== undefined && typeof deps.sessions.flush === 'function' && handle?.agent?.session !== undefined) {
841
+ try {
842
+ await deps.sessions.flush(handle.agent.session);
843
+ } catch (error) {
844
+ deps?.logger?.warn?.('dsh-delegate: session flush failed', diagnostic(error?.message ?? error, 200));
845
+ }
846
+ }
847
+
848
+ await releaseHandle(state, handle);
849
+ return finish(state, outcome);
850
+ } catch (error) {
851
+ if (state.handle !== null) await releaseHandle(state, state.handle);
852
+ if (error instanceof RunError) throw error;
853
+ throw new RunError(RUN_CODES.createFailed, 'the delegated agent could not be created or driven', {
854
+ cause: diagnostic(error?.message ?? error),
855
+ });
856
+ } finally {
857
+ // The deadline is disarmed on every exit path, which also clears a paused span
858
+ // so a run that ends during a wait leaves no armed timer behind.
859
+ if (state.deadline !== null) state.deadline.dispose();
860
+ if (request.signal !== undefined && request.signal !== null) {
861
+ request.signal.removeEventListener?.('abort', onAbortSignal);
862
+ }
863
+ // The answerer is removed on every exit path. A run that is over must not keep
864
+ // a listener that could answer a request for an Agent it no longer drives, and
865
+ // a disposed bridge refuses everything anyway — this removes the listener that
866
+ // would otherwise stay registered on the conversation's context.
867
+ if (state.permissionAnswerer !== null) {
868
+ const remove = state.permissionAnswerer;
869
+ state.permissionAnswerer = null;
870
+ try {
871
+ remove();
872
+ } catch {
873
+ // The owning fiber disposes the listener on unload; this is best effort.
874
+ }
875
+ }
876
+ }
877
+
878
+ /**
879
+ * Attach one resolved Agent to this run: listeners, this run's model selection,
880
+ * and the handle shape the drive path expects.
881
+ *
882
+ * The selection is installed on the agent's own context — the same coupling
883
+ * `agents.create`'s setup callback uses — so a continued conversation still runs
884
+ * on the provider/model/effort the operator selected for THIS task instead of
885
+ * whatever the previous turn happened to use. A failure here is a create
886
+ * failure like any other, and it happens before the prompt is delivered.
887
+ * @param {object} agent - live native Agent returned by the session controller.
888
+ * @param {object} runRequest - the run request (for the optional setup hook).
889
+ * @param {object} runSelection - provider route, model and effort for this run.
890
+ * @returns {Promise<object>} handle for the drive path.
891
+ */
892
+ async function adoptResolvedAgent(agent, runRequest, runSelection) {
893
+ const agentCtx = agent?.ctx ?? null;
894
+ if (agentCtx === null || typeof agentCtx?.on !== 'function') {
895
+ throw new RunError(
896
+ RUN_CODES.createFailed,
897
+ 'the resolved session exposes no agent context, so its events cannot be observed',
898
+ { cause: 'SESSION_AGENT_CONTEXT_UNAVAILABLE' },
899
+ );
900
+ }
901
+ if (typeof runRequest.setup === 'function') {
902
+ await runRequest.setup(agentCtx, agent);
903
+ }
904
+ if (runRequest.delegated === true) {
905
+ applyDelegatedPolicy(agent, deps, runRequest);
906
+ }
907
+ // Recorded as a fact of the run, not inferred from the request: an operator
908
+ // asking "which model did this continued conversation actually run on" gets
909
+ // the triple that was applied AND read back from the conversation itself. On a
910
+ // modern harness a mismatch or a throwing readback refuses the run here —
911
+ // before the prompt — instead of driving the previous turn's route under this
912
+ // task's name. `maxTokens` is not part of the selection: the native selection
913
+ // carries only the provider route, model and effort.
914
+ state.selection = applySelection(agentCtx, agent, runSelection);
915
+ agentCtx.on('session/event', onEvent);
916
+ agentCtx.on('agent/error', (payload) => {
917
+ state.error = errorText(payload?.error);
918
+ });
919
+ return {
920
+ agent,
921
+ // Stated, not inferred: this handle owns nothing a dispose could legally end.
922
+ owned: false,
923
+ async dispose() {},
924
+ };
925
+ }
926
+
927
+ /**
928
+ * Apply the worker-only DSH policy before any prompt is delivered.
929
+ *
930
+ * The policy is not "set" by writing two events: it is set when the services
931
+ * that own them resolve the values back. `deps.policyServices` is the live
932
+ * accessor (`ctx.sandboxPolicy` / `ctx.approval`, read per call); a run that
933
+ * carries no accessor is refused rather than trusted, because an unverifiable
934
+ * policy is indistinguishable from no policy at all.
935
+ *
936
+ * Both arguments are explicit: the agent is the policy SUBJECT (its Session is
937
+ * what the events are appended to), the deps object is where the accessor and
938
+ * the installer live, and the request is what {@link driveAgent} was called
939
+ * with. Conflating them is how a caller-supplied seam silently stops applying.
940
+ * @param {object} agent - native Agent whose Session receives the policy.
941
+ * @param {object} deps - dependency object carrying `policyServices`.
942
+ * @param {object} runRequest - the run request carrying the optional seams.
943
+ * @returns {void}
944
+ * @throws {RunError} when policy cannot be installed AND verified.
945
+ */
946
+ function applyDelegatedPolicy(agent, deps, runRequest) {
947
+ try {
948
+ const bridge = bindPermissionBridge(agent, runRequest);
949
+ const services = typeof deps?.policyServices === 'function'
950
+ ? deps.policyServices()
951
+ : policyServicesOf(null);
952
+ const configure = typeof runRequest?.configureDelegatedSession === 'function'
953
+ ? runRequest.configureDelegatedSession
954
+ : configureDelegatedSession;
955
+ // The bridge is armed FIRST and the policy is decided from its own
956
+ // capability: an ARMED bridge bound to THIS Agent means `ask`, anything else
957
+ // means `never`. The answerer is registered after the stance, so a request
958
+ // can never arrive under `ask` with nothing listening.
959
+ const bridged = configure(agent, services, { bridge });
960
+ if (bridged?.bridged === true) {
961
+ installPermissionAnswerer(agent?.ctx ?? null, bridge);
962
+ }
963
+ state.approval = {
964
+ policy: bridged?.approvalPolicy ?? null,
965
+ bridged: bridged?.bridged === true,
966
+ };
967
+ } catch (error) {
968
+ // A bridge refusal keeps its own code: it is a different operator problem from
969
+ // a policy that could not be installed, and reporting it as one would send an
970
+ // operator to inspect the sandbox services instead of the bridge.
971
+ if (error instanceof RunError) throw error;
972
+ if (error instanceof SandboxPolicyError) {
973
+ throw new RunError(error.code, error.message, error.details);
974
+ }
975
+ if (error instanceof PermissionError) {
976
+ throw new RunError(
977
+ RUN_CODES.permissionBridgeUnavailable,
978
+ 'the permission bridge could not be bound to the delegated session, so the worker was not started',
979
+ { reason: PERMISSION_REASONS.unbound },
980
+ );
981
+ }
982
+ throw new RunError(
983
+ RUN_CODES.sandboxPolicyUnavailable,
984
+ 'the delegated DSH session policy could not be installed, so the worker was not started',
985
+ { reason: 'policy setup failed' },
986
+ );
987
+ }
988
+ }
989
+
990
+ /**
991
+ * Arm the run's permission bridge for the Agent this run will drive.
992
+ *
993
+ * Arming happens HERE — after the preset composition exists (so the worker's
994
+ * tool surface is the real one) and BEFORE the policy is installed and any prompt
995
+ * is delivered (so no turn can ask under an unarmed bridge). A bridge that
996
+ * cannot be armed for this Agent is a refusal, not a silent downgrade: without
997
+ * it the run would be reported as riding a bridge while `never` was installed.
998
+ *
999
+ * A run with NO bridge is the ordinary worker run: the caller simply did not ask
1000
+ * for one, the policy stays `never`, and nothing here invents an answerer.
1001
+ * @param {object} agent - the live native Agent the run will drive.
1002
+ * @param {object} runRequest - the run request carrying the optional bridge.
1003
+ * @returns {object | null} the armed bridge, or null when the run has none.
1004
+ * @throws {RunError} when a supplied bridge cannot be armed for this Agent.
1005
+ */
1006
+ function bindPermissionBridge(agent, runRequest) {
1007
+ const bridge = runRequest?.permissionBridge ?? null;
1008
+ if (bridge === null || bridge === undefined) return null;
1009
+ if (typeof bridge.arm !== 'function') {
1010
+ // A non-bridge value is a caller bug. It is refused instead of being treated
1011
+ // as "no bridge", because the caller believes approvals are bridged.
1012
+ throw new RunError(
1013
+ RUN_CODES.permissionBridgeUnavailable,
1014
+ 'the requested permission bridge cannot be armed for this run, so the worker was not started',
1015
+ { reason: 'the bridge exposes no arm()' },
1016
+ );
1017
+ }
1018
+ try {
1019
+ bridge.arm(agent);
1020
+ } catch (error) {
1021
+ throw new RunError(
1022
+ RUN_CODES.permissionBridgeUnavailable,
1023
+ 'the permission bridge could not be bound to the delegated session, so the worker was not started',
1024
+ {
1025
+ reason: typeof error?.details?.reason === 'string' ? error.details.reason : 'the bridge refused this agent',
1026
+ },
1027
+ );
1028
+ }
1029
+ return bridge;
1030
+ }
1031
+
1032
+ /**
1033
+ * Register this run's permission bridge as the answerer for its own Agent.
1034
+ *
1035
+ * The seam is the native, agent-scoped waterfall `'approval/request'` (recorded
1036
+ * evidence: `ApprovalService.decide()` dispatches
1037
+ * `this.ctx.waterfall(scopeTarget(req.agent, req.agent), 'approval/request', req, …)`,
1038
+ * and `approveEscalation` is the one caller that raises it for a widened sandbox
1039
+ * request). A listener registered on the AGENT's own context therefore sees only
1040
+ * that Agent's requests — an ordinary session, another task's worker and the
1041
+ * optional read-only reviewer are all outside this scope and are never answered
1042
+ * by this bridge.
1043
+ *
1044
+ * The listener answers with the bridge's closed outcome. It never throws: the
1045
+ * seam already contains a thrown answerer into `'unavailable'`, and a bridge that
1046
+ * throws for a request it does not own would interfere with a scope it should
1047
+ * not be judging, so it falls through to `next()` for those.
1048
+ * @param {object} agentCtx - the agent's scoped context (listener target).
1049
+ * @param {object} bridge - the armed bridge.
1050
+ * @returns {() => void} disposer removing the listener.
1051
+ * @throws {RunError} when the context cannot register an approval answerer.
1052
+ */
1053
+ function installPermissionAnswerer(agentCtx, bridge) {
1054
+ if (agentCtx === null || agentCtx === undefined || typeof agentCtx.on !== 'function') {
1055
+ throw new RunError(
1056
+ RUN_CODES.permissionBridgeUnavailable,
1057
+ 'the delegated agent exposes no context an approval answerer could be registered on, so the worker was not started',
1058
+ { reason: 'agent context unavailable' },
1059
+ );
1060
+ }
1061
+ let disposer;
1062
+ try {
1063
+ // `prepend: true` is REQUIRED, and this is why: the native seam dispatches
1064
+ // `approval/request` as a cordis WATERFALL, where listener order is dispatch
1065
+ // order and the FIRST listener to return a value claims the question. An
1066
+ // ordinary `on()` appends, so a UI/operator answerer registered before this
1067
+ // run would answer first and this bridge would never see the request — which
1068
+ // is exactly the "the commander must intercept before the UI prompt" property
1069
+ // this feature exists for. Prepending puts this run's bridge ahead of any
1070
+ // pre-existing answerer for ITS OWN agent's scope (the listener still falls
1071
+ // through for every other agent, so an ordinary session keeps the prompt it
1072
+ // actually has).
1073
+ disposer = agentCtx.on('approval/request', async (request, next) => {
1074
+ if (bridge.owns(request) !== true) {
1075
+ // Not this Agent's request: leave the chain untouched. Reporting a foreign
1076
+ // request as `unavailable` would deny an ordinary session the answerer it
1077
+ // actually has.
1078
+ return await next();
1079
+ }
1080
+ // PAUSE the run's execution deadline for the duration of the wait. This is a
1081
+ // real timer pause (the budget is charged and the timer disarmed), not a
1082
+ // reported counter: a wait longer than the remaining budget therefore does
1083
+ // NOT time the run out, while the budget still expires afterwards if the run
1084
+ // really does keep executing.
1085
+ const deadline = state.deadline;
1086
+ const pausedAt = Date.now();
1087
+ deadline?.pause();
1088
+ let outcome;
1089
+ try {
1090
+ outcome = await bridge.answer(request);
1091
+ } finally {
1092
+ // Resume on EVERY exit — answered, cancelled, disposed, thrown — so no path
1093
+ // can leave the run paused and therefore unable to time out at all.
1094
+ if (deadline !== null) {
1095
+ deadline.notePaused(Date.now() - pausedAt);
1096
+ deadline.resume();
1097
+ }
1098
+ }
1099
+ return isApprovalOutcome(outcome) ? outcome : 'unavailable';
1100
+ }, { prepend: true });
1101
+ } catch (error) {
1102
+ throw new RunError(
1103
+ RUN_CODES.permissionBridgeUnavailable,
1104
+ 'the approval answerer could not be registered for the delegated session, so the worker was not started',
1105
+ { reason: typeof error?.code === 'string' ? error.code : 'agent context refused the answerer' },
1106
+ );
1107
+ }
1108
+ state.permissionAnswerer = typeof disposer === 'function' ? disposer : null;
1109
+ return () => {
1110
+ const remove = state.permissionAnswerer;
1111
+ state.permissionAnswerer = null;
1112
+ try {
1113
+ remove?.();
1114
+ } catch {
1115
+ // The owning fiber disposes the listener on unload; this is best effort.
1116
+ }
1117
+ };
1118
+ }
1119
+
1120
+ /**
1121
+ * Release one handle at the end of a run.
1122
+ *
1123
+ * Disposal is skipped for an Agent this run did not create, and for any handle
1124
+ * the caller marked as not owned. A Session that is disposed cannot be
1125
+ * continued, so disposing a resolved Agent would silently break a later
1126
+ * `continueFromTaskId` follow-up — exactly the failure this feature must not
1127
+ * have.
1128
+ * @param {object} target - run state.
1129
+ * @param {object} handle - handle to release.
1130
+ * @returns {Promise<void>} resolves after the attempt.
1131
+ */
1132
+ async function releaseHandle(target, handle) {
1133
+ if (handle === null || handle === undefined) return;
1134
+ if (target.handle === handle) {
1135
+ if (target.handleDisposed) return;
1136
+ target.handleDisposed = true;
1137
+ }
1138
+ if (target.createdOwnAgent !== true || target.disposeOwned !== true) return;
1139
+ await disposeQuietly(handle);
1140
+ }
1141
+
1142
+ // Native session events carry their payload under `data`, e.g.
1143
+ // `{ type: 'assistant/message', data: { message, usage } }` and
1144
+ // `{ type: 'turn/end', data: { reason: { kind } } }`. Streaming chunk types
1145
+ // (`text-delta`, `reasoning-delta`) appear both inside a message part event and
1146
+ // as top-level events, so both spellings are accepted.
1147
+ //
1148
+ // The loop streams deltas and *then* emits the finished message with the same
1149
+ // text, so the collector has to reconcile the two: deltas are appended, and the
1150
+ // final message replaces them only when it carries the answer the deltas were
1151
+ // streaming. Appending both would report every answer twice.
1152
+ function collectEvent(event, target) {
1153
+ if (event === null || typeof event !== 'object') return;
1154
+ const type = event.type;
1155
+ if (type === 'turn/end') {
1156
+ const reason = event.data?.reason ?? event.reason ?? null;
1157
+ target.turnEnd = { reason: typeof reason === 'string' ? reason : (reason?.kind ?? 'unknown') };
1158
+ return;
1159
+ }
1160
+ if (type === 'assistant/message' || type === 'message') {
1161
+ const message = event.data?.message ?? event.message ?? null;
1162
+ const usage = event.data?.usage ?? event.usage ?? null;
1163
+ const content = Array.isArray(message?.content) ? message.content : [];
1164
+ let finalText = '';
1165
+ for (const block of content) {
1166
+ if (block?.type === 'text' && typeof block.text === 'string') finalText += block.text;
1167
+ if (block?.type === 'reasoning' && typeof block.text === 'string' && block.text !== '') {
1168
+ target.reasoningSeen = true;
1169
+ }
1170
+ }
1171
+ if (finalText !== '') target.text.mergeFinal(finalText);
1172
+ if (usage !== null && typeof usage === 'object') target.usage = normalizeUsage(usage);
1173
+ return;
1174
+ }
1175
+ if (type === 'usage') {
1176
+ const usage = event.data?.usage ?? event.usage ?? event.data ?? null;
1177
+ if (usage !== null && typeof usage === 'object') target.usage = normalizeUsage(usage);
1178
+ return;
1179
+ }
1180
+ if (type === 'text-delta') {
1181
+ const text = event.data?.text ?? event.text;
1182
+ if (typeof text === 'string' && text !== '') target.text.appendDelta(text);
1183
+ return;
1184
+ }
1185
+ if (type === 'reasoning-delta') {
1186
+ const text = event.data?.text ?? event.text;
1187
+ // A reasoning delta is activity even when it carries no display text yet.
1188
+ if (typeof text !== 'string' || text !== '') target.reasoningSeen = true;
1189
+ return;
1190
+ }
1191
+ if (type === 'message/part' || type === 'assistant/delta') {
1192
+ const delta = event.data?.delta ?? event.delta ?? event.data ?? null;
1193
+ if (delta?.type === 'text-delta' && typeof delta.text === 'string' && delta.text !== '') {
1194
+ target.text.appendDelta(delta.text);
1195
+ }
1196
+ if (delta?.type === 'reasoning-delta') target.reasoningSeen = true;
1197
+ }
1198
+ }
1199
+
1200
+ function finish(target, outcome) {
1201
+ const text = target.text.value();
1202
+ // The native registry publishes an agent only under its session's id
1203
+ // (`AgentRegistry.enter()` refuses a mismatch), so an agent that exists has
1204
+ // exactly one identity. Reporting the session id as the agent id when no
1205
+ // handle was ever published keeps the pair honest for terminal runs
1206
+ // (cancel/timeout during creation) instead of emitting `agentId: null`
1207
+ // beside a real session id that names nothing.
1208
+ const agentId = target.agentId ?? target.sessionId ?? null;
1209
+ return {
1210
+ outcome,
1211
+ text: redactText(text).trim(),
1212
+ // "Reasoning only" is about what the *agent* produced, decided before
1213
+ // redaction: a redacted-out answer is still an answer.
1214
+ reasoningOnly: target.reasoningSeen && text.trim() === '',
1215
+ textTruncated: target.text.truncated(),
1216
+ usage: target.usage,
1217
+ turnEnd: target.turnEnd,
1218
+ agentId,
1219
+ sessionId: target.sessionId,
1220
+ // The provider/model/effort applied on the Agent this run drove, and the
1221
+ // output budget it requested. Present on both the created and the resolved
1222
+ // path. On a harness with the conversation's own model API this is the route
1223
+ // READ BACK from the conversation, so `applied: true` is a verified fact; on
1224
+ // the legacy shape it is the route the request-rewriting coupling was given.
1225
+ // `applied: false` means no route was requested at all (the review, which
1226
+ // inherits its composition's configured model) — never a failed selection,
1227
+ // which refuses the run instead.
1228
+ selection: target.selection,
1229
+ maxTokens: target.maxTokens?.value ?? null,
1230
+ // Where this run's conversation landed, or `null` for the unplaced path
1231
+ // (the review). Stated as its own fact so a caller can report the Workspace
1232
+ // group, whether the run started a new conversation or continued the task
1233
+ // thread it named, without re-deriving any of it from the ids.
1234
+ conversation: placement === null ? null : {
1235
+ kind: placement.kind ?? null,
1236
+ continuedFromTaskId: placement.continuedFromTaskId ?? null,
1237
+ reused: placement.reused === true,
1238
+ workspaceId: placement.workspaceId ?? null,
1239
+ workspacePath: placement.workspacePath ?? null,
1240
+ sessionId: target.sessionId ?? placement.sessionId ?? null,
1241
+ },
1242
+ cancelCause: target.abortCause,
1243
+ error: target.error,
1244
+ aborted: target.abortRequested,
1245
+ // The approval stance this run installed and read back, plus whether an
1246
+ // armed bridge is the answerer behind it. `null` for a run that never had a
1247
+ // delegated policy installed (the review, an ordinary session).
1248
+ approval: target.approval ?? null,
1249
+ };
1250
+ }
1251
+
1252
+ /**
1253
+ * Classify the turn the agent loop actually finished.
1254
+ *
1255
+ * The loop ends a turn with `max-tokens` — a response that ran out of its output
1256
+ * budget — *after* the same `assistant/message` append a `completed` turn
1257
+ * performs, so that reason is an ending, not a failure. Reading everything
1258
+ * except `completed` as a failure therefore reported a working run whose model
1259
+ * spent its budget thinking as "the delegated run produced no output" — the
1260
+ * reasoning-only false negative this plugin exists to avoid.
1261
+ *
1262
+ * Order, and why:
1263
+ * 1. an aborted or timed-out turn is cancelled, whatever it had collected;
1264
+ * 2. a recorded agent error is an execution failure, whatever the turn produced;
1265
+ * 3. a turn with text, or with reasoning, ended productively. Text stays text —
1266
+ * a long answer is never trimmed into a reasoning-only one — and a
1267
+ * reasoning-only turn reports its (empty) text as observed instead of being
1268
+ * turned into an error or into a synthetic summary;
1269
+ * 4. nothing at all is a failure with its own message, split by reason: a
1270
+ * `max-tokens` ending means the model filled its budget before answering
1271
+ * (raise the budget), anything else means the turn was genuinely empty.
1272
+ * @param {object} target - run state.
1273
+ * @returns {string} one of {@link RUN_OUTCOMES}.
1274
+ */
1275
+ function deriveOutcome(target) {
1276
+ const reason = target.turnEnd?.reason;
1277
+ if (reason === 'aborted') return RUN_OUTCOMES.cancelled;
1278
+ if (target.error !== null) return RUN_OUTCOMES.failed;
1279
+ if (target.text.length() > 0 || target.reasoningSeen) return RUN_OUTCOMES.completed;
1280
+ // No content and no error. The reason decides which kind of nothing this was;
1281
+ // both are failures with distinguishable text, and neither is a reasoning-only
1282
+ // run (those returned as completed above).
1283
+ target.error = reason === 'max-tokens' ? RUN_ERRORS.budgetExhausted : RUN_ERRORS.emptyOutput;
1284
+ return RUN_OUTCOMES.failed;
1285
+ }
1286
+ }
1287
+
1288
+ /**
1289
+ * Build the native agent options for one run's model request.
1290
+ *
1291
+ * `maxTokens` is always explicit: large enough that a reasoning model is not
1292
+ * starved into an apparent timeout, bounded so one request cannot ask for more
1293
+ * than a model serves. The caller's budget was validated before this point and is
1294
+ * forwarded unchanged.
1295
+ * @param {object} selection - provider route, model, optional effort.
1296
+ * @param {number} budget - validated output-token budget.
1297
+ * @returns {object} agent options for `agents.create`.
1298
+ */
1299
+ function agentOptionsFor(selection, budget) {
1300
+ return {
1301
+ provider: selection.providerRoute,
1302
+ model: selection.model,
1303
+ ...(selection.reasoningEffort === null || selection.reasoningEffort === undefined
1304
+ ? {}
1305
+ : { reasoningEffort: selection.reasoningEffort }),
1306
+ maxTokens: budget,
1307
+ };
1308
+ }
1309
+
1310
+ /**
1311
+ * Make one run's provider/model/effort the route the conversation will actually
1312
+ * run on, and prove it was applied before the prompt can be delivered.
1313
+ *
1314
+ * This is the capability-based adapter between the two supported native shapes
1315
+ * (see {@link SELECTION_MODES}), and it is used by BOTH paths — a freshly created
1316
+ * Agent and a resolved/continued one — so a follow-up cannot be reported on a
1317
+ * route that only the previous turn used.
1318
+ *
1319
+ * Rules, and why each one exists:
1320
+ * * when the Agent exposes `model.select`/`model.current`, ONLY that API is used:
1321
+ * the route is recorded through `select()`, read back through `current()`, and
1322
+ * compared — provider, model, and the optional effort — before the caller may
1323
+ * prompt. A throw, an empty answer, or any disagreement is a
1324
+ * {@link RunError} refusal. There is deliberately no legacy fallback after a
1325
+ * present modern API fails: on such a release the legacy installer carries no
1326
+ * selection at all (it installs the model-switch notice), so falling back would
1327
+ * "succeed" without selecting anything, which is the defect this adapter
1328
+ * removes;
1329
+ * * when the Agent exposes no model surface at all (`agent.model` null/undefined
1330
+ * — an old release), the legacy `installModelSelection` coupling is used
1331
+ * exactly as before — it is the only way a route reaches a turn there (its
1332
+ * `agent/request` listener rewrites the request);
1333
+ * * when the Agent's model surface is PRESENT but incomplete/malformed, the run
1334
+ * is refused with {@link SELECTION_REASONS.modelSurfaceIncomplete}. Such a
1335
+ * surface is not an old release, so the legacy coupling is not a substitute:
1336
+ * on a modern harness it installs only the notice listener and would let the
1337
+ * run claim a route nothing applied;
1338
+ * * when no surface exists and the legacy installer is unavailable too, the run
1339
+ * is refused UNLESS it named no route at all (the review composition, which
1340
+ * inherits the conversation's configured route). A run that named a route and
1341
+ * cannot apply it is never driven.
1342
+ *
1343
+ * Nothing is reported as `applied` that was not applied: the modern path reports
1344
+ * the READ-BACK route, and the legacy path is only reachable where no readback API
1345
+ * exists.
1346
+ * @param {object} agentCtx - the agent's scoped context (legacy listener target).
1347
+ * @param {object} agent - the live Agent the run will drive.
1348
+ * @param {object} selection - provider route, model, optional effort.
1349
+ * @returns {{ provider: string|null, model: string|null, reasoningEffort: string|null, applied: boolean }} reported fact.
1350
+ * @throws {RunError} when the selection cannot be applied and verified.
1351
+ */
1352
+ function applySelection(agentCtx, agent, selection) {
1353
+ const wanted = {
1354
+ provider: selection?.providerRoute ?? null,
1355
+ model: selection?.model ?? null,
1356
+ // An unsupported/omitted effort must stay ABSENT rather than travel as `null`:
1357
+ // the native selection types it as optional, and "absent" is a value of its
1358
+ // own when the readback is compared.
1359
+ reasoningEffort: selection?.reasoningEffort ?? undefined,
1360
+ };
1361
+ const mode = selectionModeOf(agent);
1362
+ if (mode === SELECTION_MODES.modern) {
1363
+ return selectThroughAgentModel(agent, wanted);
1364
+ }
1365
+ if (mode === SELECTION_MODES.unavailable) {
1366
+ // Present but not selectable-and-readable. Refused before the prompt on both
1367
+ // the created and the resolved path, and no legacy listener is installed.
1368
+ throw new RunError(
1369
+ RUN_CODES.selectionUnavailable,
1370
+ 'the conversation exposes a model API this run cannot select and verify through, so the worker was not started',
1371
+ {
1372
+ reason: SELECTION_REASONS.modelSurfaceIncomplete,
1373
+ // Only the capability facts: never the surface object itself.
1374
+ surface: describeModelSurface(agent?.model),
1375
+ },
1376
+ );
1377
+ }
1378
+ if (wanted.provider !== null && wanted.model !== null && typeof installModelSelection === 'function') {
1379
+ // The legacy coupling: the mutable `current` ref is what its `agent/request`
1380
+ // listener reads to rewrite the request, and its `system-prompt/assemble`
1381
+ // listener to publish the route to the prompt. No notice listener is installed
1382
+ // separately on this path, because this installer already owns one.
1383
+ installModelSelection(agentCtx, {
1384
+ current: {
1385
+ provider: wanted.provider,
1386
+ model: wanted.model,
1387
+ reasoningEffort: wanted.reasoningEffort,
1388
+ },
1389
+ assembled: undefined,
1390
+ });
1391
+ return {
1392
+ provider: wanted.provider,
1393
+ model: wanted.model,
1394
+ reasoningEffort: wanted.reasoningEffort ?? null,
1395
+ applied: true,
1396
+ };
1397
+ }
1398
+ if (wanted.provider !== null || wanted.model !== null) {
1399
+ throw new RunError(
1400
+ RUN_CODES.selectionUnavailable,
1401
+ 'this harness exposes no way to select a model route, so the worker was not started on an unverified route',
1402
+ { reason: SELECTION_REASONS.noCapability },
1403
+ );
1404
+ }
1405
+ // No route was requested and the Agent exposes no model surface to verify: the
1406
+ // conversation runs on whatever its composition configured. Reported as an
1407
+ // omission, not as an applied route.
1408
+ return { provider: null, model: null, reasoningEffort: null, applied: false };
1409
+ }
1410
+
1411
+ /**
1412
+ * Select one run's route through the conversation's own model API and verify it.
1413
+ *
1414
+ * `select()` records the choice in the Session's durable `modelSelection`
1415
+ * projection (the next step's `pre-step` reads it, which is what makes the route
1416
+ * this run's rather than the previous turn's), and `current()` reads it back. The
1417
+ * readback is what the run reports: a `select()` that silently did nothing, or a
1418
+ * conversation whose recorded choice is another route, is refused here instead of
1419
+ * being reported as applied.
1420
+ * @param {object} agent - native Agent with `model.select`/`model.current`.
1421
+ * @param {{ provider: string|null, model: string|null, reasoningEffort: string|undefined }} wanted - the route.
1422
+ * @returns {{ provider: string|null, model: string|null, reasoningEffort: string|null, applied: boolean }} readback fact.
1423
+ * @throws {RunError} when the route is incomplete, rejected, unreadable or different.
1424
+ */
1425
+ function selectThroughAgentModel(agent, wanted) {
1426
+ // The modern API records a complete route, so an incomplete request has no
1427
+ // meaning it could apply: half a selection is a refusal, not a default.
1428
+ if (wanted.provider === null || wanted.model === null) {
1429
+ throw new RunError(
1430
+ RUN_CODES.selectionUnavailable,
1431
+ 'the run names no provider/model route, so a model selection cannot be recorded for it',
1432
+ { reason: SELECTION_REASONS.noCapability },
1433
+ );
1434
+ }
1435
+ try {
1436
+ agent.model.select({
1437
+ provider: wanted.provider,
1438
+ model: wanted.model,
1439
+ ...(wanted.reasoningEffort === undefined ? {} : { reasoningEffort: wanted.reasoningEffort }),
1440
+ });
1441
+ } catch (error) {
1442
+ throw new RunError(
1443
+ RUN_CODES.selectionUnavailable,
1444
+ 'the conversation rejected its model selection, so the worker was not started',
1445
+ {
1446
+ reason: SELECTION_REASONS.writeFailed,
1447
+ // The native code, never the upstream message: a message may carry a
1448
+ // provider response that this plugin must not copy into a job record.
1449
+ cause: typeof error?.code === 'string' ? diagnostic(error.code, 120) : null,
1450
+ },
1451
+ );
1452
+ }
1453
+
1454
+ let observed;
1455
+ try {
1456
+ observed = agent.model.current();
1457
+ } catch (error) {
1458
+ throw new RunError(
1459
+ RUN_CODES.selectionUnavailable,
1460
+ 'the conversation could not report the model selection it recorded, so the worker was not started',
1461
+ {
1462
+ reason: SELECTION_REASONS.readbackFailed,
1463
+ cause: typeof error?.code === 'string' ? diagnostic(error.code, 120) : null,
1464
+ },
1465
+ );
1466
+ }
1467
+ if (observed === null || observed === undefined || typeof observed !== 'object'
1468
+ || typeof observed.provider !== 'string' || typeof observed.model !== 'string') {
1469
+ throw new RunError(
1470
+ RUN_CODES.selectionUnavailable,
1471
+ 'the conversation reports no model selection after one was recorded, so the worker was not started',
1472
+ { reason: SELECTION_REASONS.readbackUnusable },
1473
+ );
1474
+ }
1475
+ // The readback is the fact: when it disagrees with what was asked for, the
1476
+ // prompt is never delivered. The observed route is operator-selected metadata
1477
+ // (never a credential), so it is comparable and reportable.
1478
+ if (observed.provider !== wanted.provider || observed.model !== wanted.model) {
1479
+ throw new RunError(
1480
+ RUN_CODES.selectionUnavailable,
1481
+ 'the conversation would run on a different model route than the one selected, so the worker was not started',
1482
+ {
1483
+ reason: SELECTION_REASONS.routeMismatch,
1484
+ expected: { provider: wanted.provider, model: wanted.model, reasoningEffort: wanted.reasoningEffort ?? null },
1485
+ observed: {
1486
+ provider: observed.provider,
1487
+ model: observed.model,
1488
+ reasoningEffort: typeof observed.reasoningEffort === 'string' ? observed.reasoningEffort : null,
1489
+ },
1490
+ },
1491
+ );
1492
+ }
1493
+ const observedEffort = typeof observed.reasoningEffort === 'string' && observed.reasoningEffort !== ''
1494
+ ? observed.reasoningEffort
1495
+ : undefined;
1496
+ if (wanted.reasoningEffort !== undefined && observedEffort !== wanted.reasoningEffort) {
1497
+ throw new RunError(
1498
+ RUN_CODES.selectionUnavailable,
1499
+ 'the conversation would run at a different reasoning effort than the one selected, so the worker was not started',
1500
+ {
1501
+ reason: SELECTION_REASONS.effortMismatch,
1502
+ expected: { reasoningEffort: wanted.reasoningEffort },
1503
+ observed: { reasoningEffort: observedEffort ?? null },
1504
+ },
1505
+ );
1506
+ }
1507
+ // Nothing asked for an effort, yet the conversation carries one: this run cannot
1508
+ // prove the operator's "no effort" choice is what the turn will use, so the
1509
+ // route is not reported as applied.
1510
+ if (wanted.reasoningEffort === undefined && observedEffort !== undefined) {
1511
+ throw new RunError(
1512
+ RUN_CODES.selectionUnavailable,
1513
+ 'the conversation carries a reasoning effort this run did not select, so the worker was not started',
1514
+ {
1515
+ reason: SELECTION_REASONS.unrequestedEffort,
1516
+ observed: { reasoningEffort: observedEffort },
1517
+ },
1518
+ );
1519
+ }
1520
+ return {
1521
+ provider: observed.provider,
1522
+ model: observed.model,
1523
+ reasoningEffort: observedEffort ?? null,
1524
+ applied: true,
1525
+ };
1526
+ }
1527
+
1528
+ function numeric(value) {
1529
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
1530
+ }
1531
+
1532
+ /**
1533
+ * Resolve the output-token budget one model request is made with.
1534
+ *
1535
+ * The rule, and why each clause exists:
1536
+ * - an ABSENT budget (`undefined`/`null`) is not "no budget": it resolves to
1537
+ * {@link DEFAULT_MAX_TOKENS}, because a native request with no explicit
1538
+ * allowance is what made an installed worker stop mid-answer;
1539
+ * - a supplied budget is PRESERVED verbatim, so an explicit caller decision is
1540
+ * never silently replaced by the default;
1541
+ * - a supplied budget that is not an integer inside
1542
+ * {@link MAX_TOKENS_BOUNDS} is REFUSED (`refused` non-null) rather than
1543
+ * clamped or dropped, so a request can never travel as unbounded.
1544
+ *
1545
+ * Note the bounds are checked by value, not reparsed: `0`, `NaN`, `1.5`, `'8192'`
1546
+ * and an out-of-range integer are all refusals.
1547
+ * @param {unknown} requested - the caller's `maxTokens`.
1548
+ * @returns {{ value: number, refused: { reason: string, min: number, max: number } | null }} resolution.
1549
+ */
1550
+ function maxTokensFor(requested) {
1551
+ const bounds = { min: MAX_TOKENS_BOUNDS.min, max: MAX_TOKENS_BOUNDS.max };
1552
+ if (requested === undefined || requested === null) return { value: DEFAULT_MAX_TOKENS, refused: null };
1553
+ if (typeof requested !== 'number' || !Number.isInteger(requested)) {
1554
+ // The type is reported, never the raw value: a bad budget may carry anything.
1555
+ return { value: DEFAULT_MAX_TOKENS, refused: { ...bounds, reason: 'maxTokens must be an integer', requestedType: typeof requested } };
1556
+ }
1557
+ if (requested < bounds.min || requested > bounds.max) {
1558
+ return { value: DEFAULT_MAX_TOKENS, refused: { ...bounds, reason: 'maxTokens is outside the supported range' } };
1559
+ }
1560
+ return { value: requested, refused: null };
1561
+ }
1562
+
1563
+ /**
1564
+ * Narrow a dependency object to the preset registry, or `null` when it cannot
1565
+ * install a composition.
1566
+ *
1567
+ * `agentPresets.mount(ctx, id?)` is the native entry point that joins an Agent
1568
+ * to a preset revision and mounts its plugin subtree (tools, scoped services).
1569
+ * Its absence is not a degraded mode to paper over: an Agent with no preset has
1570
+ * no tools, so the run is refused before any agent is created.
1571
+ * @param {object} deps - dependency object.
1572
+ * @returns {{ mount: (agentCtx: object, id?: string) => Promise<unknown> } | null} registry facade or null.
1573
+ */
1574
+ function presetRegistryOf(deps) {
1575
+ const presets = deps?.agentPresets;
1576
+ if (presets === undefined || presets === null || typeof presets.mount !== 'function') return null;
1577
+ return {
1578
+ // The id is forwarded verbatim: `undefined` makes the registry apply its
1579
+ // configured default rather than this plugin inventing one, and a named id is
1580
+ // one the run already proved its caller owns.
1581
+ mount: (agentCtx, id) => (id === undefined ? presets.mount(agentCtx) : presets.mount(agentCtx, id)),
1582
+ };
1583
+ }
1584
+
1585
+ /**
1586
+ * Resolve the agent/session identity a run will own.
1587
+ *
1588
+ * `CreateAgentOptions.sessionId` is required and the native factory creates the
1589
+ * session — and, through `AgentRegistry.enter()`, the agent — under exactly that
1590
+ * id. The default creation path mints nothing, so a caller that omits the id
1591
+ * used to pass `undefined` and the registry refused the freshly built agent with
1592
+ * `agent id "undefined" does not match session id "session-N"`.
1593
+ *
1594
+ * Rule: an identity the caller supplied is preserved verbatim (it is the
1595
+ * caller's ownership decision: a fork, an ACP id, a resumed session); only an
1596
+ * ABSENT one (`undefined`/`null`) is generated, once per run. The shape mirrors
1597
+ * the sibling one-shot runner in `dsh-headless`, which does
1598
+ * `config.sessionId ?? \`session-${randomUUID()}\`` before `agents.create`, so
1599
+ * ids stay recognisable and unrelated to this plugin's own naming.
1600
+ * @param {unknown} requested - the caller's `sessionId`, possibly absent.
1601
+ * @returns {{ value: string, generated: boolean }} the identity to create under.
1602
+ */
1603
+ export function resolveSessionIdentity(requested) {
1604
+ if (typeof requested === 'string') return { value: requested, generated: false };
1605
+ // `undefined`/`null` mean "the caller has no identity to impose". Any other
1606
+ // type is a caller bug, not an omission: it is passed through so the
1607
+ // pre-create admission check below refuses it with a stated reason instead of
1608
+ // this helper silently inventing a different identity.
1609
+ if (requested === undefined || requested === null) {
1610
+ return { value: `session-${randomUUID()}`, generated: true };
1611
+ }
1612
+ return { value: requested, generated: false };
1613
+ }
1614
+
1615
+ /**
1616
+ * Why the native registry would refuse a caller-supplied identity, or `null`.
1617
+ *
1618
+ * These are the checks `AgentRegistry`/`SessionStore.prepare` apply to an id, so
1619
+ * a run that would fail them is refused here — before an agent or a session
1620
+ * exists — instead of failing later as an opaque `RUN_CREATE_FAILED` whose cause
1621
+ * an operator cannot separate from a provider problem.
1622
+ * @param {object} agents - native agent registry (only `get` is used).
1623
+ * @param {string|unknown} id - identity the caller asked for.
1624
+ * @returns {string|null} reason text, or `null` when the id is admissible.
1625
+ */
1626
+ function sessionIdUnusable(agents, id) {
1627
+ if (typeof id !== 'string') return 'sessionId must be a string';
1628
+ // `SessionStore.prepare` brands whatever string it is handed as a session id,
1629
+ // so an empty one would become a real (and unusable) session identity.
1630
+ if (id.trim() === '') return 'sessionId must not be blank';
1631
+ // `SessionStore.prepare` throws when the id already has a session; a live
1632
+ // agent is the process-local form of that collision.
1633
+ if (typeof agents.get === 'function') {
1634
+ try {
1635
+ if (agents.get(id) !== undefined) return 'a live agent already owns this session id in this process';
1636
+ } catch {
1637
+ // An unreadable registry cannot answer the question; creation itself is
1638
+ // the next authority and will refuse an id it cannot admit.
1639
+ }
1640
+ }
1641
+ return null;
1642
+ }
1643
+
1644
+ /**
1645
+ * Normalize an agent error payload into redacted diagnostic text.
1646
+ *
1647
+ * Native `agent/error` payloads carry either an `Error` or a bare message, and
1648
+ * the provider code (e.g. `401`, `context_length_exceeded`) is the part an
1649
+ * operator needs to act on, so it is preserved alongside the message instead of
1650
+ * being flattened away.
1651
+ * @param {unknown} value - error payload.
1652
+ * @returns {string} redacted diagnostic.
1653
+ */
1654
+ function errorText(value) {
1655
+ if (value === null || value === undefined) return 'agent error';
1656
+ const code = typeof value?.code === 'string' && value.code !== '' ? value.code : null;
1657
+ const message = value?.message ?? (typeof value === 'string' ? value : null);
1658
+ const text = message === null ? 'agent error' : String(message);
1659
+ return diagnostic(code === null ? text : `${code}: ${text}`);
1660
+ }
1661
+
1662
+ /**
1663
+ * Build the bounded, duplicate-aware collector for assistant text.
1664
+ *
1665
+ * Two native behaviors make a plain array of chunks wrong:
1666
+ * - `text-delta` events stream an answer and are followed by an
1667
+ * `assistant/message` carrying the same text, so appending both would double
1668
+ * it in job history;
1669
+ * - neither source is bounded, so a runaway stream could make the process hold
1670
+ * an unbounded string before any post-hoc slice applied.
1671
+ *
1672
+ * Both are handled here: every append is clamped to the limit as it happens, and
1673
+ * a completed message supersedes the deltas it was streaming instead of
1674
+ * following them. A later message starts a fresh pending buffer, so a multi-turn
1675
+ * run still accumulates each turn exactly once.
1676
+ * @param {number} limit - maximum retained characters.
1677
+ * @returns {object} collector with `appendDelta`, `mergeFinal`, `value`, `length`, `truncated`.
1678
+ */
1679
+ function createTextCollector(limit) {
1680
+ let completed = '';
1681
+ let pending = '';
1682
+ let truncated = false;
1683
+
1684
+ const clampAppend = (current, addition) => {
1685
+ if (addition === '') return current;
1686
+ if (current.length >= limit) {
1687
+ truncated = true;
1688
+ return current;
1689
+ }
1690
+ const joined = current + addition;
1691
+ if (joined.length <= limit) return joined;
1692
+ truncated = true;
1693
+ return joined.slice(0, limit);
1694
+ };
1695
+
1696
+ return {
1697
+ appendDelta(text) {
1698
+ if (typeof text !== 'string' || text === '') return;
1699
+ pending = clampAppend(pending, text);
1700
+ },
1701
+ mergeFinal(text) {
1702
+ if (typeof text !== 'string' || text === '') return;
1703
+ // The completed message is authoritative for the turn it closes: when the
1704
+ // streamed deltas were its prefix, the message replaces them rather than
1705
+ // repeating them. Deltas that the message does not cover are kept.
1706
+ const merged = pending !== '' && !text.startsWith(pending) ? `${pending}${text}` : text;
1707
+ completed = clampAppend(completed, merged);
1708
+ pending = '';
1709
+ },
1710
+ value() {
1711
+ return completed + pending;
1712
+ },
1713
+ length() {
1714
+ return (completed + pending).length;
1715
+ },
1716
+ truncated() {
1717
+ return truncated;
1718
+ },
1719
+ };
1720
+ }
1721
+
1722
+ function normalizeUsage(usage) {
1723
+ return {
1724
+ inputTokens: numeric(usage.inputTokens),
1725
+ outputTokens: numeric(usage.outputTokens),
1726
+ totalTokens: numeric(usage.totalTokens),
1727
+ reasoningTokens: numeric(usage.reasoningTokens),
1728
+ };
1729
+ }
1730
+
1731
+ async function disposeQuietly(handle) {
1732
+ try {
1733
+ await handle.dispose();
1734
+ } catch {
1735
+ // Disposal failure must not mask the run outcome; the handle is unowned
1736
+ // either way and the native layer performs its own cleanup.
1737
+ }
1738
+ }