dsh-taskbridge 0.0.0-stage → 1.3.2

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 (75) hide show
  1. package/CHANGELOG.md +763 -0
  2. package/LICENSE +21 -0
  3. package/README.md +622 -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-taskbridge.toml +247 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +34 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +937 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +304 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +223 -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 +138 -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 +3299 -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 +456 -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 +3614 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/jobs/title.js +17 -0
  55. package/src/mcp/server.js +1821 -0
  56. package/src/mcp/wait.js +536 -0
  57. package/src/model/connectivity.js +371 -0
  58. package/src/model/discovery.js +582 -0
  59. package/src/model/native-catalog.js +68 -0
  60. package/src/model/openai-adapter.js +671 -0
  61. package/src/model/probe.js +264 -0
  62. package/src/model/providers.js +756 -0
  63. package/src/model/routing.js +321 -0
  64. package/src/review/preset.js +868 -0
  65. package/src/review/prompts.js +126 -0
  66. package/src/review/reviewer.js +933 -0
  67. package/src/runtime/agent-runner.js +1740 -0
  68. package/src/runtime/endpoint-discovery.js +118 -0
  69. package/src/runtime/permissions.js +1429 -0
  70. package/src/runtime/sandbox.js +358 -0
  71. package/src/runtime/session-placement.js +1121 -0
  72. package/src/workspace/audit.js +775 -0
  73. package/src/workspace/locks.js +167 -0
  74. package/src/workspace/preflight.js +424 -0
  75. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,1740 @@
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
+ title: request?.title,
525
+ // The only thing that can continue an existing conversation, and it is the
526
+ // caller's explicit statement that this submission is a follow-up to THAT task.
527
+ // Omitted means a new conversation, always.
528
+ continueFromTaskId: request?.continueFromTaskId,
529
+ // Task/connection facts the continuation identity must match. The engine passes
530
+ // them because it is the only component that knows which task and connection
531
+ // this run belongs to.
532
+ taskId: request?.taskId,
533
+ connectionId: request?.connectionId,
534
+ sourcePath: request?.sourcePath,
535
+ presetId: request?.placementPresetId,
536
+ });
537
+ return placement;
538
+ }
539
+
540
+ /**
541
+ * Drive one native agent to completion under a timeout and a cancellation latch.
542
+ *
543
+ * @param {object} deps - `agents`, optional `sessions` (flush) and `logger`.
544
+ * @param {object} request - `prompt`, `cwd`, `selection`, `timeoutMs`, `signal`,
545
+ * `onEvent`, `presetId`, `placement`, `disposeOwned`.
546
+ * @returns {Promise<object>} run result with text, usage facts and lifecycle evidence.
547
+ */
548
+ export async function driveAgent(deps, request) {
549
+ const agents = deps?.agents;
550
+ if (agents === undefined || agents === null || typeof agents.create !== 'function') {
551
+ throw new RunError(RUN_CODES.agentsUnavailable, 'the native agent registry is not available', {});
552
+ }
553
+ const presets = presetRegistryOf(deps);
554
+ if (presets === null) {
555
+ throw new RunError(
556
+ RUN_CODES.agentPresetsUnavailable,
557
+ 'the native agent preset registry is not available, so no default tool composition can be installed',
558
+ {},
559
+ );
560
+ }
561
+ const prompt = typeof request?.prompt === 'string' ? request.prompt : '';
562
+ if (prompt === '') {
563
+ throw new RunError(RUN_CODES.turnFailed, 'the delegation prompt is empty', {});
564
+ }
565
+ if (prompt.length > LIMITS.promptChars) {
566
+ throw new RunError(RUN_CODES.promptTooLarge, `the delegation prompt exceeds ${LIMITS.promptChars} characters`, {
567
+ length: prompt.length,
568
+ limit: LIMITS.promptChars,
569
+ });
570
+ }
571
+ const selection = request.selection ?? {};
572
+ const timeoutMs = Number.isInteger(request.timeoutMs) && request.timeoutMs > 0 ? request.timeoutMs : null;
573
+ const placement = request?.placement ?? null;
574
+ const resolvedAgent = placement?.agent ?? null;
575
+ // A resolved agent carries its own session and preset composition; the run must
576
+ // not mount a second composition onto it. An agent created here still does.
577
+ //
578
+ // This holds on BOTH placement paths: a freshly created Session is also driven
579
+ // through the Agent the session controller resolved for it, because the Session
580
+ // already exists in the Workspace and `agents.create` would create a second one.
581
+ // The preset is installed by whoever created that Agent (the session controller's
582
+ // own composition, or — on the unplaced review path — this run's setup).
583
+ const mountsPreset = resolvedAgent === null;
584
+ const disposeOwned = request?.disposeOwned !== false;
585
+
586
+ // Preset selection. `undefined` means "whatever the registry configures as its
587
+ // default", which is what every worker run asks for. A named id is only
588
+ // mounted when the caller declares ownership of it: without that check any
589
+ // caller could re-point a run at a composition it does not own (including a
590
+ // user preset with a shell), and the run would silently lose the tool surface
591
+ // the caller intended to restrict.
592
+ const presetId = request.presetId;
593
+ if (mountsPreset && presetId !== undefined && presetId !== null) {
594
+ const ownership = request.presetOwnership;
595
+ const owned = typeof ownership?.owns === 'function' && ownership.owns(presetId) === true;
596
+ if (!owned) {
597
+ throw new RunError(
598
+ RUN_CODES.presetNotOwned,
599
+ 'the requested agent preset is not owned by the caller, so it will not be mounted',
600
+ {},
601
+ );
602
+ }
603
+ }
604
+
605
+ // The native create contract takes the identity from the CALLER: `sessionId`
606
+ // is required and the factory creates the session and the agent under it.
607
+ // Nothing in the default creation path mints one, and `AgentRegistry.enter()`
608
+ // refuses an agent whose `id` does not equal its session's — which is exactly
609
+ // how a call that omitted the id used to fail. So an absent identity is
610
+ // generated here, once per run, and travels on the create call.
611
+ //
612
+ // A placed run does not mint anything: its identity is the Session the
613
+ // Workspace controller created or the one a previous run recorded.
614
+ const sessionId = resolveSessionIdentity(placement?.sessionId ?? request?.sessionId);
615
+ // A caller-supplied identity that the native registry would reject (blank, not
616
+ // a string, or already live in this process) is refused before an agent
617
+ // exists, instead of surfacing later as an opaque creation failure. A resolved
618
+ // agent is already live under exactly this identity, so the check is skipped.
619
+ if (sessionId.generated === false && resolvedAgent === null) {
620
+ const unusable = sessionIdUnusable(agents, sessionId.value);
621
+ if (unusable !== null) {
622
+ throw new RunError(RUN_CODES.sessionIdUnusable, 'the requested session identity cannot be created', {
623
+ // Fixed text chosen by this module, never the caller's value.
624
+ reason: unusable,
625
+ // Never the raw identity: a caller-supplied value may carry anything.
626
+ requestedType: typeof sessionId.value,
627
+ });
628
+ }
629
+ }
630
+
631
+ const state = {
632
+ abortRequested: false,
633
+ abortCause: null,
634
+ handle: null,
635
+ handleDisposed: false,
636
+ // A resolved Agent is driven through the same handle shape a created one
637
+ // arrives in, so every step below (idle wait, prompt delivery, flush,
638
+ // cancellation) has exactly one implementation.
639
+ //
640
+ // `createdOwnAgent` is the lifecycle fact that decides disposal: only an Agent
641
+ // this run created may be disposed by it. Disposing a resolved Agent would end
642
+ // the Session it belongs to and make a later follow-up unable to continue it.
643
+ createdOwnAgent: resolvedAgent === null,
644
+ disposeOwned,
645
+ // Bounded and deduplicating: the native loop streams `text-delta` events and
646
+ // then emits the finished assistant message carrying the same text, so a
647
+ // naive append would report every answer twice and hold an unbounded string.
648
+ text: createTextCollector(OUTPUT_TEXT_CHARS),
649
+ reasoningSeen: false,
650
+ // The model request this run will actually make, known before creation so a
651
+ // refusal happens before an agent exists.
652
+ maxTokens: maxTokensFor(request.maxTokens),
653
+ usage: null,
654
+ turnEnd: null,
655
+ error: null,
656
+ agentId: null,
657
+ // The model selection this run actually installed on the Agent it drove, and
658
+ // the request budget it asked for. Reported so a placed run — which never goes
659
+ // through `agents.create` — can still be audited for "ran on the selected
660
+ // provider/model/effort with a usable budget".
661
+ selection: null,
662
+ // The identity this run will own, known before creation settles so a run
663
+ // that never produces a handle still reports the id it asked for instead of
664
+ // `null`.
665
+ sessionId: sessionId.value,
666
+ // The approval stance this run actually installed and read back, and whether
667
+ // an armed permission bridge is why the Session asks instead of rejecting.
668
+ // Reported as a verified fact, never as a configuration value.
669
+ approval: null,
670
+ // Removes the `approval/request` answerer when the run ends. Null when the run
671
+ // had no bridge, which is the ordinary worker run.
672
+ permissionAnswerer: null,
673
+ // The execution deadline this run owns. It is PAUSED around every permission
674
+ // wait, so the wait is not charged to the operator's execution budget.
675
+ deadline: null,
676
+ };
677
+ if (state.maxTokens.refused !== null) {
678
+ throw new RunError(
679
+ RUN_CODES.maxTokensUnusable,
680
+ 'the requested output token budget is not a bounded positive integer',
681
+ state.maxTokens.refused,
682
+ );
683
+ }
684
+ const requestBudget = state.maxTokens.value;
685
+
686
+ let resolveAbort;
687
+ const aborted = new Promise((resolvePromise) => { resolveAbort = resolvePromise; });
688
+
689
+ const latch = (cause) => {
690
+ if (state.abortRequested) return;
691
+ state.abortRequested = true;
692
+ state.abortCause = cause;
693
+ resolveAbort(cause);
694
+ // A live agent is cancelled immediately; a handle that arrives later is
695
+ // disposed by the creation path below.
696
+ if (state.handle !== null) {
697
+ try {
698
+ state.handle.agent.cancel({ kind: 'user' }, { keepInbox: false });
699
+ } catch {
700
+ // Cancellation of an already-idle agent is not an error we can act on.
701
+ }
702
+ }
703
+ };
704
+
705
+ const onAbortSignal = () => latch('cancelled');
706
+ if (request.signal !== undefined && request.signal !== null) {
707
+ if (request.signal.aborted === true) latch('cancelled');
708
+ else request.signal.addEventListener('abort', onAbortSignal, { once: true });
709
+ }
710
+
711
+ // Native dispatch is `('session/event', session, event)`; the second argument
712
+ // is the event. A second positional handler shape (`agent/error`) carries a
713
+ // payload object instead, and is registered separately below.
714
+ const onEvent = (sessionOrEvent, maybeEvent) => {
715
+ const event = maybeEvent === undefined ? sessionOrEvent : maybeEvent;
716
+ if (event === null || typeof event !== 'object') return;
717
+ if (state.abortRequested && event.type !== 'turn/end') return;
718
+ collectEvent(event, state);
719
+ request.onEvent?.(event);
720
+ };
721
+
722
+ try {
723
+ // A cancellation that arrived before the factory was ever called must not
724
+ // create an agent at all — creating one only to dispose it would still run
725
+ // setup, install a composition and pay for a session that nobody asked for.
726
+ if (state.abortRequested) {
727
+ return finish(state, state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
728
+ }
729
+
730
+ const handlePromise = resolvedAgent === null
731
+ ? agents.create({
732
+ // Always a string: the native contract requires it, and the factory mints
733
+ // both the session and (through `enter()`) the agent id from it.
734
+ sessionId: state.sessionId,
735
+ meta: { cwd: request.cwd },
736
+ agentOptions: agentOptionsFor(selection, requestBudget),
737
+ setup: async (agentCtx, agent) => {
738
+ // Join the default native preset *before* the model selection is
739
+ // installed. The preset is what mounts the Agent's tool composition and
740
+ // its scoped services; a run that skipped it would report a model the
741
+ // agent cannot actually exercise because it has no tools at all. Failing
742
+ // here fails the run closed, inside `agents.create`, which the caller
743
+ // already observes as a refusal.
744
+ try {
745
+ await (presetId === undefined || presetId === null
746
+ ? presets.mount(agentCtx)
747
+ : presets.mount(agentCtx, presetId));
748
+ } catch (error) {
749
+ throw new RunError(RUN_CODES.presetMountFailed, 'the native agent preset could not be mounted', {
750
+ cause: diagnostic(error?.message ?? error),
751
+ });
752
+ }
753
+ // Optional caller policy, installed after the composition exists (so the
754
+ // inventory it may inspect is the real one) and before the prompt is
755
+ // delivered (so no turn can run without it). A hook that throws fails
756
+ // creation closed, which is what a caller that needs a tool restriction
757
+ // wants: a refused restriction must never degrade into an unrestricted
758
+ // run. The agent is passed as the second argument because an agent's
759
+ // tools live on its own scope plane, and `tools.schemas()`/`restrict()`
760
+ // are scoped calls.
761
+ if (typeof request.setup === 'function') {
762
+ await request.setup(agentCtx, agent);
763
+ }
764
+ if (request.delegated === true) {
765
+ applyDelegatedPolicy(agent, deps, request);
766
+ }
767
+ // The created path takes the same capability-based adapter as the
768
+ // resolved one: on a modern harness the route is selected through the
769
+ // conversation's own model API and read back BEFORE the prompt, and on a
770
+ // legacy harness it travels through `installModelSelection`. Nothing is
771
+ // reported as applied that was not read back.
772
+ state.selection = applySelection(agentCtx, agent, selection);
773
+ agentCtx.on('session/event', onEvent);
774
+ agentCtx.on('agent/error', (payload) => {
775
+ state.error = errorText(payload?.error);
776
+ });
777
+ },
778
+ })
779
+ // A resolved Agent already carries its session, its preset composition and
780
+ // its listeners. What it must still receive is THIS run's model selection:
781
+ // the operator's provider/model/effort is per task, while the conversation
782
+ // it continues is shared, so re-applying the selection here is the whole
783
+ // point of driving the resolved agent instead of its logged header.
784
+ : adoptResolvedAgent(resolvedAgent, request, selection);
785
+
786
+ // The execution deadline is not a single `setTimeout`. A worker that is waiting
787
+ // for a permission decision is paused, not running, so the wait must not consume
788
+ // the operator's execution budget. {@link ExecutionDeadline} holds the remaining
789
+ // budget and re-arms only what is left, for any number of waits.
790
+ const deadline = timeoutMs === null ? null : new ExecutionDeadline(timeoutMs, () => latch('timeout'));
791
+ if (deadline !== null) deadline.arm();
792
+ state.deadline = deadline;
793
+
794
+ const raced = await Promise.race([
795
+ handlePromise.then((handle) => ({ kind: 'handle', handle })),
796
+ aborted.then((cause) => ({ kind: 'aborted', cause })),
797
+ ]);
798
+
799
+ if (raced.kind === 'aborted') {
800
+ // The handle may still arrive after the latch. Disposing it as soon as it
801
+ // does is the only way no agent outlives a run that is already terminal;
802
+ // the prompt is never delivered on this path.
803
+ handlePromise.then(
804
+ (handle) => { void releaseHandle(state, handle); },
805
+ () => {},
806
+ );
807
+ return finish(state, raced.cause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
808
+ }
809
+
810
+ const handle = raced.handle;
811
+ state.handle = handle;
812
+ // Both ids are read from the ONE live agent the factory returned, so the
813
+ // reported identity is what was actually created rather than what was asked
814
+ // for. A factory that honoured the identity request reports the same ids the
815
+ // run requested; `sessionId` falls back to the requested identity only for a
816
+ // handle that exposes no session object at all.
817
+ state.agentId = handle?.agent?.id ?? null;
818
+ state.sessionId = handle?.agent?.session?.id ?? state.sessionId;
819
+
820
+ if (state.abortRequested) {
821
+ await releaseHandle(state, handle);
822
+ return finish(state, state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
823
+ }
824
+
825
+ // Wait for the agent's own initial quiescence before prompting, so the
826
+ // prompt is not queued behind setup work that is still composing.
827
+ await Promise.race([handle.agent.whenIdle(), aborted]);
828
+ if (state.abortRequested) {
829
+ await releaseHandle(state, handle);
830
+ return finish(state, state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
831
+ }
832
+
833
+ handle.agent.followup(userMessage(prompt));
834
+ await Promise.race([handle.agent.whenIdle(), aborted]);
835
+
836
+ const outcome = state.abortRequested
837
+ ? (state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled)
838
+ : deriveOutcome(state);
839
+
840
+ // Flush the session so the transcript is durable before the caller reads it.
841
+ if (deps?.sessions !== undefined && typeof deps.sessions.flush === 'function' && handle?.agent?.session !== undefined) {
842
+ try {
843
+ await deps.sessions.flush(handle.agent.session);
844
+ } catch (error) {
845
+ deps?.logger?.warn?.('dsh-delegate: session flush failed', diagnostic(error?.message ?? error, 200));
846
+ }
847
+ }
848
+
849
+ await releaseHandle(state, handle);
850
+ return finish(state, outcome);
851
+ } catch (error) {
852
+ if (state.handle !== null) await releaseHandle(state, state.handle);
853
+ if (error instanceof RunError) throw error;
854
+ throw new RunError(RUN_CODES.createFailed, 'the delegated agent could not be created or driven', {
855
+ cause: diagnostic(error?.message ?? error),
856
+ });
857
+ } finally {
858
+ // The deadline is disarmed on every exit path, which also clears a paused span
859
+ // so a run that ends during a wait leaves no armed timer behind.
860
+ if (state.deadline !== null) state.deadline.dispose();
861
+ if (request.signal !== undefined && request.signal !== null) {
862
+ request.signal.removeEventListener?.('abort', onAbortSignal);
863
+ }
864
+ // The answerer is removed on every exit path. A run that is over must not keep
865
+ // a listener that could answer a request for an Agent it no longer drives, and
866
+ // a disposed bridge refuses everything anyway — this removes the listener that
867
+ // would otherwise stay registered on the conversation's context.
868
+ if (state.permissionAnswerer !== null) {
869
+ const remove = state.permissionAnswerer;
870
+ state.permissionAnswerer = null;
871
+ try {
872
+ remove();
873
+ } catch {
874
+ // The owning fiber disposes the listener on unload; this is best effort.
875
+ }
876
+ }
877
+ }
878
+
879
+ /**
880
+ * Attach one resolved Agent to this run: listeners, this run's model selection,
881
+ * and the handle shape the drive path expects.
882
+ *
883
+ * The selection is installed on the agent's own context — the same coupling
884
+ * `agents.create`'s setup callback uses — so a continued conversation still runs
885
+ * on the provider/model/effort the operator selected for THIS task instead of
886
+ * whatever the previous turn happened to use. A failure here is a create
887
+ * failure like any other, and it happens before the prompt is delivered.
888
+ * @param {object} agent - live native Agent returned by the session controller.
889
+ * @param {object} runRequest - the run request (for the optional setup hook).
890
+ * @param {object} runSelection - provider route, model and effort for this run.
891
+ * @returns {Promise<object>} handle for the drive path.
892
+ */
893
+ async function adoptResolvedAgent(agent, runRequest, runSelection) {
894
+ const agentCtx = agent?.ctx ?? null;
895
+ if (agentCtx === null || typeof agentCtx?.on !== 'function') {
896
+ throw new RunError(
897
+ RUN_CODES.createFailed,
898
+ 'the resolved session exposes no agent context, so its events cannot be observed',
899
+ { cause: 'SESSION_AGENT_CONTEXT_UNAVAILABLE' },
900
+ );
901
+ }
902
+ if (typeof runRequest.setup === 'function') {
903
+ await runRequest.setup(agentCtx, agent);
904
+ }
905
+ if (runRequest.delegated === true) {
906
+ applyDelegatedPolicy(agent, deps, runRequest);
907
+ }
908
+ // Recorded as a fact of the run, not inferred from the request: an operator
909
+ // asking "which model did this continued conversation actually run on" gets
910
+ // the triple that was applied AND read back from the conversation itself. On a
911
+ // modern harness a mismatch or a throwing readback refuses the run here —
912
+ // before the prompt — instead of driving the previous turn's route under this
913
+ // task's name. `maxTokens` is not part of the selection: the native selection
914
+ // carries only the provider route, model and effort.
915
+ state.selection = applySelection(agentCtx, agent, runSelection);
916
+ agentCtx.on('session/event', onEvent);
917
+ agentCtx.on('agent/error', (payload) => {
918
+ state.error = errorText(payload?.error);
919
+ });
920
+ return {
921
+ agent,
922
+ // Stated, not inferred: this handle owns nothing a dispose could legally end.
923
+ owned: false,
924
+ async dispose() {},
925
+ };
926
+ }
927
+
928
+ /**
929
+ * Apply the worker-only DSH policy before any prompt is delivered.
930
+ *
931
+ * The policy is not "set" by writing two events: it is set when the services
932
+ * that own them resolve the values back. `deps.policyServices` is the live
933
+ * accessor (`ctx.sandboxPolicy` / `ctx.approval`, read per call); a run that
934
+ * carries no accessor is refused rather than trusted, because an unverifiable
935
+ * policy is indistinguishable from no policy at all.
936
+ *
937
+ * Both arguments are explicit: the agent is the policy SUBJECT (its Session is
938
+ * what the events are appended to), the deps object is where the accessor and
939
+ * the installer live, and the request is what {@link driveAgent} was called
940
+ * with. Conflating them is how a caller-supplied seam silently stops applying.
941
+ * @param {object} agent - native Agent whose Session receives the policy.
942
+ * @param {object} deps - dependency object carrying `policyServices`.
943
+ * @param {object} runRequest - the run request carrying the optional seams.
944
+ * @returns {void}
945
+ * @throws {RunError} when policy cannot be installed AND verified.
946
+ */
947
+ function applyDelegatedPolicy(agent, deps, runRequest) {
948
+ try {
949
+ const bridge = bindPermissionBridge(agent, runRequest);
950
+ const services = typeof deps?.policyServices === 'function'
951
+ ? deps.policyServices()
952
+ : policyServicesOf(null);
953
+ const configure = typeof runRequest?.configureDelegatedSession === 'function'
954
+ ? runRequest.configureDelegatedSession
955
+ : configureDelegatedSession;
956
+ // The bridge is armed FIRST and the policy is decided from its own
957
+ // capability: an ARMED bridge bound to THIS Agent means `ask`, anything else
958
+ // means `never`. The answerer is registered after the stance, so a request
959
+ // can never arrive under `ask` with nothing listening.
960
+ const bridged = configure(agent, services, { bridge });
961
+ if (bridged?.bridged === true) {
962
+ installPermissionAnswerer(agent?.ctx ?? null, bridge);
963
+ }
964
+ state.approval = {
965
+ policy: bridged?.approvalPolicy ?? null,
966
+ bridged: bridged?.bridged === true,
967
+ };
968
+ } catch (error) {
969
+ // A bridge refusal keeps its own code: it is a different operator problem from
970
+ // a policy that could not be installed, and reporting it as one would send an
971
+ // operator to inspect the sandbox services instead of the bridge.
972
+ if (error instanceof RunError) throw error;
973
+ if (error instanceof SandboxPolicyError) {
974
+ throw new RunError(error.code, error.message, error.details);
975
+ }
976
+ if (error instanceof PermissionError) {
977
+ throw new RunError(
978
+ RUN_CODES.permissionBridgeUnavailable,
979
+ 'the permission bridge could not be bound to the delegated session, so the worker was not started',
980
+ { reason: PERMISSION_REASONS.unbound },
981
+ );
982
+ }
983
+ throw new RunError(
984
+ RUN_CODES.sandboxPolicyUnavailable,
985
+ 'the delegated DSH session policy could not be installed, so the worker was not started',
986
+ { reason: 'policy setup failed' },
987
+ );
988
+ }
989
+ }
990
+
991
+ /**
992
+ * Arm the run's permission bridge for the Agent this run will drive.
993
+ *
994
+ * Arming happens HERE — after the preset composition exists (so the worker's
995
+ * tool surface is the real one) and BEFORE the policy is installed and any prompt
996
+ * is delivered (so no turn can ask under an unarmed bridge). A bridge that
997
+ * cannot be armed for this Agent is a refusal, not a silent downgrade: without
998
+ * it the run would be reported as riding a bridge while `never` was installed.
999
+ *
1000
+ * A run with NO bridge is the ordinary worker run: the caller simply did not ask
1001
+ * for one, the policy stays `never`, and nothing here invents an answerer.
1002
+ * @param {object} agent - the live native Agent the run will drive.
1003
+ * @param {object} runRequest - the run request carrying the optional bridge.
1004
+ * @returns {object | null} the armed bridge, or null when the run has none.
1005
+ * @throws {RunError} when a supplied bridge cannot be armed for this Agent.
1006
+ */
1007
+ function bindPermissionBridge(agent, runRequest) {
1008
+ const bridge = runRequest?.permissionBridge ?? null;
1009
+ if (bridge === null || bridge === undefined) return null;
1010
+ if (typeof bridge.arm !== 'function') {
1011
+ // A non-bridge value is a caller bug. It is refused instead of being treated
1012
+ // as "no bridge", because the caller believes approvals are bridged.
1013
+ throw new RunError(
1014
+ RUN_CODES.permissionBridgeUnavailable,
1015
+ 'the requested permission bridge cannot be armed for this run, so the worker was not started',
1016
+ { reason: 'the bridge exposes no arm()' },
1017
+ );
1018
+ }
1019
+ try {
1020
+ bridge.arm(agent);
1021
+ } catch (error) {
1022
+ throw new RunError(
1023
+ RUN_CODES.permissionBridgeUnavailable,
1024
+ 'the permission bridge could not be bound to the delegated session, so the worker was not started',
1025
+ {
1026
+ reason: typeof error?.details?.reason === 'string' ? error.details.reason : 'the bridge refused this agent',
1027
+ },
1028
+ );
1029
+ }
1030
+ return bridge;
1031
+ }
1032
+
1033
+ /**
1034
+ * Register this run's permission bridge as the answerer for its own Agent.
1035
+ *
1036
+ * The seam is the native, agent-scoped waterfall `'approval/request'` (recorded
1037
+ * evidence: `ApprovalService.decide()` dispatches
1038
+ * `this.ctx.waterfall(scopeTarget(req.agent, req.agent), 'approval/request', req, …)`,
1039
+ * and `approveEscalation` is the one caller that raises it for a widened sandbox
1040
+ * request). A listener registered on the AGENT's own context therefore sees only
1041
+ * that Agent's requests — an ordinary session, another task's worker and the
1042
+ * optional read-only reviewer are all outside this scope and are never answered
1043
+ * by this bridge.
1044
+ *
1045
+ * The listener answers with the bridge's closed outcome. It never throws: the
1046
+ * seam already contains a thrown answerer into `'unavailable'`, and a bridge that
1047
+ * throws for a request it does not own would interfere with a scope it should
1048
+ * not be judging, so it falls through to `next()` for those.
1049
+ * @param {object} agentCtx - the agent's scoped context (listener target).
1050
+ * @param {object} bridge - the armed bridge.
1051
+ * @returns {() => void} disposer removing the listener.
1052
+ * @throws {RunError} when the context cannot register an approval answerer.
1053
+ */
1054
+ function installPermissionAnswerer(agentCtx, bridge) {
1055
+ if (agentCtx === null || agentCtx === undefined || typeof agentCtx.on !== 'function') {
1056
+ throw new RunError(
1057
+ RUN_CODES.permissionBridgeUnavailable,
1058
+ 'the delegated agent exposes no context an approval answerer could be registered on, so the worker was not started',
1059
+ { reason: 'agent context unavailable' },
1060
+ );
1061
+ }
1062
+ let disposer;
1063
+ try {
1064
+ // `prepend: true` is REQUIRED, and this is why: the native seam dispatches
1065
+ // `approval/request` as a cordis WATERFALL, where listener order is dispatch
1066
+ // order and the FIRST listener to return a value claims the question. An
1067
+ // ordinary `on()` appends, so a UI/operator answerer registered before this
1068
+ // run would answer first and this bridge would never see the request — which
1069
+ // is exactly the "the commander must intercept before the UI prompt" property
1070
+ // this feature exists for. Prepending puts this run's bridge ahead of any
1071
+ // pre-existing answerer for ITS OWN agent's scope (the listener still falls
1072
+ // through for every other agent, so an ordinary session keeps the prompt it
1073
+ // actually has).
1074
+ disposer = agentCtx.on('approval/request', async (request, next) => {
1075
+ if (bridge.owns(request) !== true) {
1076
+ // Not this Agent's request: leave the chain untouched. Reporting a foreign
1077
+ // request as `unavailable` would deny an ordinary session the answerer it
1078
+ // actually has.
1079
+ return await next();
1080
+ }
1081
+ // PAUSE the run's execution deadline for the duration of the wait. This is a
1082
+ // real timer pause (the budget is charged and the timer disarmed), not a
1083
+ // reported counter: a wait longer than the remaining budget therefore does
1084
+ // NOT time the run out, while the budget still expires afterwards if the run
1085
+ // really does keep executing.
1086
+ const deadline = state.deadline;
1087
+ const pausedAt = Date.now();
1088
+ deadline?.pause();
1089
+ let outcome;
1090
+ try {
1091
+ outcome = await bridge.answer(request);
1092
+ } finally {
1093
+ // Resume on EVERY exit — answered, cancelled, disposed, thrown — so no path
1094
+ // can leave the run paused and therefore unable to time out at all.
1095
+ if (deadline !== null) {
1096
+ deadline.notePaused(Date.now() - pausedAt);
1097
+ deadline.resume();
1098
+ }
1099
+ }
1100
+ return isApprovalOutcome(outcome) ? outcome : 'unavailable';
1101
+ }, { prepend: true });
1102
+ } catch (error) {
1103
+ throw new RunError(
1104
+ RUN_CODES.permissionBridgeUnavailable,
1105
+ 'the approval answerer could not be registered for the delegated session, so the worker was not started',
1106
+ { reason: typeof error?.code === 'string' ? error.code : 'agent context refused the answerer' },
1107
+ );
1108
+ }
1109
+ state.permissionAnswerer = typeof disposer === 'function' ? disposer : null;
1110
+ return () => {
1111
+ const remove = state.permissionAnswerer;
1112
+ state.permissionAnswerer = null;
1113
+ try {
1114
+ remove?.();
1115
+ } catch {
1116
+ // The owning fiber disposes the listener on unload; this is best effort.
1117
+ }
1118
+ };
1119
+ }
1120
+
1121
+ /**
1122
+ * Release one handle at the end of a run.
1123
+ *
1124
+ * Disposal is skipped for an Agent this run did not create, and for any handle
1125
+ * the caller marked as not owned. A Session that is disposed cannot be
1126
+ * continued, so disposing a resolved Agent would silently break a later
1127
+ * `continueFromTaskId` follow-up — exactly the failure this feature must not
1128
+ * have.
1129
+ * @param {object} target - run state.
1130
+ * @param {object} handle - handle to release.
1131
+ * @returns {Promise<void>} resolves after the attempt.
1132
+ */
1133
+ async function releaseHandle(target, handle) {
1134
+ if (handle === null || handle === undefined) return;
1135
+ if (target.handle === handle) {
1136
+ if (target.handleDisposed) return;
1137
+ target.handleDisposed = true;
1138
+ }
1139
+ if (target.createdOwnAgent !== true || target.disposeOwned !== true) return;
1140
+ await disposeQuietly(handle);
1141
+ }
1142
+
1143
+ // Native session events carry their payload under `data`, e.g.
1144
+ // `{ type: 'assistant/message', data: { message, usage } }` and
1145
+ // `{ type: 'turn/end', data: { reason: { kind } } }`. Streaming chunk types
1146
+ // (`text-delta`, `reasoning-delta`) appear both inside a message part event and
1147
+ // as top-level events, so both spellings are accepted.
1148
+ //
1149
+ // The loop streams deltas and *then* emits the finished message with the same
1150
+ // text, so the collector has to reconcile the two: deltas are appended, and the
1151
+ // final message replaces them only when it carries the answer the deltas were
1152
+ // streaming. Appending both would report every answer twice.
1153
+ function collectEvent(event, target) {
1154
+ if (event === null || typeof event !== 'object') return;
1155
+ const type = event.type;
1156
+ if (type === 'turn/end') {
1157
+ const reason = event.data?.reason ?? event.reason ?? null;
1158
+ target.turnEnd = { reason: typeof reason === 'string' ? reason : (reason?.kind ?? 'unknown') };
1159
+ return;
1160
+ }
1161
+ if (type === 'assistant/message' || type === 'message') {
1162
+ const message = event.data?.message ?? event.message ?? null;
1163
+ const usage = event.data?.usage ?? event.usage ?? null;
1164
+ const content = Array.isArray(message?.content) ? message.content : [];
1165
+ let finalText = '';
1166
+ for (const block of content) {
1167
+ if (block?.type === 'text' && typeof block.text === 'string') finalText += block.text;
1168
+ if (block?.type === 'reasoning' && typeof block.text === 'string' && block.text !== '') {
1169
+ target.reasoningSeen = true;
1170
+ }
1171
+ }
1172
+ if (finalText !== '') target.text.mergeFinal(finalText);
1173
+ if (usage !== null && typeof usage === 'object') target.usage = normalizeUsage(usage);
1174
+ return;
1175
+ }
1176
+ if (type === 'usage') {
1177
+ const usage = event.data?.usage ?? event.usage ?? event.data ?? null;
1178
+ if (usage !== null && typeof usage === 'object') target.usage = normalizeUsage(usage);
1179
+ return;
1180
+ }
1181
+ if (type === 'text-delta') {
1182
+ const text = event.data?.text ?? event.text;
1183
+ if (typeof text === 'string' && text !== '') target.text.appendDelta(text);
1184
+ return;
1185
+ }
1186
+ if (type === 'reasoning-delta') {
1187
+ const text = event.data?.text ?? event.text;
1188
+ // A reasoning delta is activity even when it carries no display text yet.
1189
+ if (typeof text !== 'string' || text !== '') target.reasoningSeen = true;
1190
+ return;
1191
+ }
1192
+ if (type === 'message/part' || type === 'assistant/delta') {
1193
+ const delta = event.data?.delta ?? event.delta ?? event.data ?? null;
1194
+ if (delta?.type === 'text-delta' && typeof delta.text === 'string' && delta.text !== '') {
1195
+ target.text.appendDelta(delta.text);
1196
+ }
1197
+ if (delta?.type === 'reasoning-delta') target.reasoningSeen = true;
1198
+ }
1199
+ }
1200
+
1201
+ function finish(target, outcome) {
1202
+ const text = target.text.value();
1203
+ // The native registry publishes an agent only under its session's id
1204
+ // (`AgentRegistry.enter()` refuses a mismatch), so an agent that exists has
1205
+ // exactly one identity. Reporting the session id as the agent id when no
1206
+ // handle was ever published keeps the pair honest for terminal runs
1207
+ // (cancel/timeout during creation) instead of emitting `agentId: null`
1208
+ // beside a real session id that names nothing.
1209
+ const agentId = target.agentId ?? target.sessionId ?? null;
1210
+ return {
1211
+ outcome,
1212
+ text: redactText(text).trim(),
1213
+ // "Reasoning only" is about what the *agent* produced, decided before
1214
+ // redaction: a redacted-out answer is still an answer.
1215
+ reasoningOnly: target.reasoningSeen && text.trim() === '',
1216
+ textTruncated: target.text.truncated(),
1217
+ usage: target.usage,
1218
+ turnEnd: target.turnEnd,
1219
+ agentId,
1220
+ sessionId: target.sessionId,
1221
+ // The provider/model/effort applied on the Agent this run drove, and the
1222
+ // output budget it requested. Present on both the created and the resolved
1223
+ // path. On a harness with the conversation's own model API this is the route
1224
+ // READ BACK from the conversation, so `applied: true` is a verified fact; on
1225
+ // the legacy shape it is the route the request-rewriting coupling was given.
1226
+ // `applied: false` means no route was requested at all (the review, which
1227
+ // inherits its composition's configured model) — never a failed selection,
1228
+ // which refuses the run instead.
1229
+ selection: target.selection,
1230
+ maxTokens: target.maxTokens?.value ?? null,
1231
+ // Where this run's conversation landed, or `null` for the unplaced path
1232
+ // (the review). Stated as its own fact so a caller can report the Workspace
1233
+ // group, whether the run started a new conversation or continued the task
1234
+ // thread it named, without re-deriving any of it from the ids.
1235
+ conversation: placement === null ? null : {
1236
+ kind: placement.kind ?? null,
1237
+ continuedFromTaskId: placement.continuedFromTaskId ?? null,
1238
+ reused: placement.reused === true,
1239
+ workspaceId: placement.workspaceId ?? null,
1240
+ workspacePath: placement.workspacePath ?? null,
1241
+ workspaceTitle: placement.workspaceTitle ?? null,
1242
+ sessionId: target.sessionId ?? placement.sessionId ?? null,
1243
+ },
1244
+ cancelCause: target.abortCause,
1245
+ error: target.error,
1246
+ aborted: target.abortRequested,
1247
+ // The approval stance this run installed and read back, plus whether an
1248
+ // armed bridge is the answerer behind it. `null` for a run that never had a
1249
+ // delegated policy installed (the review, an ordinary session).
1250
+ approval: target.approval ?? null,
1251
+ };
1252
+ }
1253
+
1254
+ /**
1255
+ * Classify the turn the agent loop actually finished.
1256
+ *
1257
+ * The loop ends a turn with `max-tokens` — a response that ran out of its output
1258
+ * budget — *after* the same `assistant/message` append a `completed` turn
1259
+ * performs, so that reason is an ending, not a failure. Reading everything
1260
+ * except `completed` as a failure therefore reported a working run whose model
1261
+ * spent its budget thinking as "the delegated run produced no output" — the
1262
+ * reasoning-only false negative this plugin exists to avoid.
1263
+ *
1264
+ * Order, and why:
1265
+ * 1. an aborted or timed-out turn is cancelled, whatever it had collected;
1266
+ * 2. a recorded agent error is an execution failure, whatever the turn produced;
1267
+ * 3. a turn with text, or with reasoning, ended productively. Text stays text —
1268
+ * a long answer is never trimmed into a reasoning-only one — and a
1269
+ * reasoning-only turn reports its (empty) text as observed instead of being
1270
+ * turned into an error or into a synthetic summary;
1271
+ * 4. nothing at all is a failure with its own message, split by reason: a
1272
+ * `max-tokens` ending means the model filled its budget before answering
1273
+ * (raise the budget), anything else means the turn was genuinely empty.
1274
+ * @param {object} target - run state.
1275
+ * @returns {string} one of {@link RUN_OUTCOMES}.
1276
+ */
1277
+ function deriveOutcome(target) {
1278
+ const reason = target.turnEnd?.reason;
1279
+ if (reason === 'aborted') return RUN_OUTCOMES.cancelled;
1280
+ if (target.error !== null) return RUN_OUTCOMES.failed;
1281
+ if (target.text.length() > 0 || target.reasoningSeen) return RUN_OUTCOMES.completed;
1282
+ // No content and no error. The reason decides which kind of nothing this was;
1283
+ // both are failures with distinguishable text, and neither is a reasoning-only
1284
+ // run (those returned as completed above).
1285
+ target.error = reason === 'max-tokens' ? RUN_ERRORS.budgetExhausted : RUN_ERRORS.emptyOutput;
1286
+ return RUN_OUTCOMES.failed;
1287
+ }
1288
+ }
1289
+
1290
+ /**
1291
+ * Build the native agent options for one run's model request.
1292
+ *
1293
+ * `maxTokens` is always explicit: large enough that a reasoning model is not
1294
+ * starved into an apparent timeout, bounded so one request cannot ask for more
1295
+ * than a model serves. The caller's budget was validated before this point and is
1296
+ * forwarded unchanged.
1297
+ * @param {object} selection - provider route, model, optional effort.
1298
+ * @param {number} budget - validated output-token budget.
1299
+ * @returns {object} agent options for `agents.create`.
1300
+ */
1301
+ function agentOptionsFor(selection, budget) {
1302
+ return {
1303
+ provider: selection.providerRoute,
1304
+ model: selection.model,
1305
+ ...(selection.reasoningEffort === null || selection.reasoningEffort === undefined
1306
+ ? {}
1307
+ : { reasoningEffort: selection.reasoningEffort }),
1308
+ maxTokens: budget,
1309
+ };
1310
+ }
1311
+
1312
+ /**
1313
+ * Make one run's provider/model/effort the route the conversation will actually
1314
+ * run on, and prove it was applied before the prompt can be delivered.
1315
+ *
1316
+ * This is the capability-based adapter between the two supported native shapes
1317
+ * (see {@link SELECTION_MODES}), and it is used by BOTH paths — a freshly created
1318
+ * Agent and a resolved/continued one — so a follow-up cannot be reported on a
1319
+ * route that only the previous turn used.
1320
+ *
1321
+ * Rules, and why each one exists:
1322
+ * * when the Agent exposes `model.select`/`model.current`, ONLY that API is used:
1323
+ * the route is recorded through `select()`, read back through `current()`, and
1324
+ * compared — provider, model, and the optional effort — before the caller may
1325
+ * prompt. A throw, an empty answer, or any disagreement is a
1326
+ * {@link RunError} refusal. There is deliberately no legacy fallback after a
1327
+ * present modern API fails: on such a release the legacy installer carries no
1328
+ * selection at all (it installs the model-switch notice), so falling back would
1329
+ * "succeed" without selecting anything, which is the defect this adapter
1330
+ * removes;
1331
+ * * when the Agent exposes no model surface at all (`agent.model` null/undefined
1332
+ * — an old release), the legacy `installModelSelection` coupling is used
1333
+ * exactly as before — it is the only way a route reaches a turn there (its
1334
+ * `agent/request` listener rewrites the request);
1335
+ * * when the Agent's model surface is PRESENT but incomplete/malformed, the run
1336
+ * is refused with {@link SELECTION_REASONS.modelSurfaceIncomplete}. Such a
1337
+ * surface is not an old release, so the legacy coupling is not a substitute:
1338
+ * on a modern harness it installs only the notice listener and would let the
1339
+ * run claim a route nothing applied;
1340
+ * * when no surface exists and the legacy installer is unavailable too, the run
1341
+ * is refused UNLESS it named no route at all (the review composition, which
1342
+ * inherits the conversation's configured route). A run that named a route and
1343
+ * cannot apply it is never driven.
1344
+ *
1345
+ * Nothing is reported as `applied` that was not applied: the modern path reports
1346
+ * the READ-BACK route, and the legacy path is only reachable where no readback API
1347
+ * exists.
1348
+ * @param {object} agentCtx - the agent's scoped context (legacy listener target).
1349
+ * @param {object} agent - the live Agent the run will drive.
1350
+ * @param {object} selection - provider route, model, optional effort.
1351
+ * @returns {{ provider: string|null, model: string|null, reasoningEffort: string|null, applied: boolean }} reported fact.
1352
+ * @throws {RunError} when the selection cannot be applied and verified.
1353
+ */
1354
+ function applySelection(agentCtx, agent, selection) {
1355
+ const wanted = {
1356
+ provider: selection?.providerRoute ?? null,
1357
+ model: selection?.model ?? null,
1358
+ // An unsupported/omitted effort must stay ABSENT rather than travel as `null`:
1359
+ // the native selection types it as optional, and "absent" is a value of its
1360
+ // own when the readback is compared.
1361
+ reasoningEffort: selection?.reasoningEffort ?? undefined,
1362
+ };
1363
+ const mode = selectionModeOf(agent);
1364
+ if (mode === SELECTION_MODES.modern) {
1365
+ return selectThroughAgentModel(agent, wanted);
1366
+ }
1367
+ if (mode === SELECTION_MODES.unavailable) {
1368
+ // Present but not selectable-and-readable. Refused before the prompt on both
1369
+ // the created and the resolved path, and no legacy listener is installed.
1370
+ throw new RunError(
1371
+ RUN_CODES.selectionUnavailable,
1372
+ 'the conversation exposes a model API this run cannot select and verify through, so the worker was not started',
1373
+ {
1374
+ reason: SELECTION_REASONS.modelSurfaceIncomplete,
1375
+ // Only the capability facts: never the surface object itself.
1376
+ surface: describeModelSurface(agent?.model),
1377
+ },
1378
+ );
1379
+ }
1380
+ if (wanted.provider !== null && wanted.model !== null && typeof installModelSelection === 'function') {
1381
+ // The legacy coupling: the mutable `current` ref is what its `agent/request`
1382
+ // listener reads to rewrite the request, and its `system-prompt/assemble`
1383
+ // listener to publish the route to the prompt. No notice listener is installed
1384
+ // separately on this path, because this installer already owns one.
1385
+ installModelSelection(agentCtx, {
1386
+ current: {
1387
+ provider: wanted.provider,
1388
+ model: wanted.model,
1389
+ reasoningEffort: wanted.reasoningEffort,
1390
+ },
1391
+ assembled: undefined,
1392
+ });
1393
+ return {
1394
+ provider: wanted.provider,
1395
+ model: wanted.model,
1396
+ reasoningEffort: wanted.reasoningEffort ?? null,
1397
+ applied: true,
1398
+ };
1399
+ }
1400
+ if (wanted.provider !== null || wanted.model !== null) {
1401
+ throw new RunError(
1402
+ RUN_CODES.selectionUnavailable,
1403
+ 'this harness exposes no way to select a model route, so the worker was not started on an unverified route',
1404
+ { reason: SELECTION_REASONS.noCapability },
1405
+ );
1406
+ }
1407
+ // No route was requested and the Agent exposes no model surface to verify: the
1408
+ // conversation runs on whatever its composition configured. Reported as an
1409
+ // omission, not as an applied route.
1410
+ return { provider: null, model: null, reasoningEffort: null, applied: false };
1411
+ }
1412
+
1413
+ /**
1414
+ * Select one run's route through the conversation's own model API and verify it.
1415
+ *
1416
+ * `select()` records the choice in the Session's durable `modelSelection`
1417
+ * projection (the next step's `pre-step` reads it, which is what makes the route
1418
+ * this run's rather than the previous turn's), and `current()` reads it back. The
1419
+ * readback is what the run reports: a `select()` that silently did nothing, or a
1420
+ * conversation whose recorded choice is another route, is refused here instead of
1421
+ * being reported as applied.
1422
+ * @param {object} agent - native Agent with `model.select`/`model.current`.
1423
+ * @param {{ provider: string|null, model: string|null, reasoningEffort: string|undefined }} wanted - the route.
1424
+ * @returns {{ provider: string|null, model: string|null, reasoningEffort: string|null, applied: boolean }} readback fact.
1425
+ * @throws {RunError} when the route is incomplete, rejected, unreadable or different.
1426
+ */
1427
+ function selectThroughAgentModel(agent, wanted) {
1428
+ // The modern API records a complete route, so an incomplete request has no
1429
+ // meaning it could apply: half a selection is a refusal, not a default.
1430
+ if (wanted.provider === null || wanted.model === null) {
1431
+ throw new RunError(
1432
+ RUN_CODES.selectionUnavailable,
1433
+ 'the run names no provider/model route, so a model selection cannot be recorded for it',
1434
+ { reason: SELECTION_REASONS.noCapability },
1435
+ );
1436
+ }
1437
+ try {
1438
+ agent.model.select({
1439
+ provider: wanted.provider,
1440
+ model: wanted.model,
1441
+ ...(wanted.reasoningEffort === undefined ? {} : { reasoningEffort: wanted.reasoningEffort }),
1442
+ });
1443
+ } catch (error) {
1444
+ throw new RunError(
1445
+ RUN_CODES.selectionUnavailable,
1446
+ 'the conversation rejected its model selection, so the worker was not started',
1447
+ {
1448
+ reason: SELECTION_REASONS.writeFailed,
1449
+ // The native code, never the upstream message: a message may carry a
1450
+ // provider response that this plugin must not copy into a job record.
1451
+ cause: typeof error?.code === 'string' ? diagnostic(error.code, 120) : null,
1452
+ },
1453
+ );
1454
+ }
1455
+
1456
+ let observed;
1457
+ try {
1458
+ observed = agent.model.current();
1459
+ } catch (error) {
1460
+ throw new RunError(
1461
+ RUN_CODES.selectionUnavailable,
1462
+ 'the conversation could not report the model selection it recorded, so the worker was not started',
1463
+ {
1464
+ reason: SELECTION_REASONS.readbackFailed,
1465
+ cause: typeof error?.code === 'string' ? diagnostic(error.code, 120) : null,
1466
+ },
1467
+ );
1468
+ }
1469
+ if (observed === null || observed === undefined || typeof observed !== 'object'
1470
+ || typeof observed.provider !== 'string' || typeof observed.model !== 'string') {
1471
+ throw new RunError(
1472
+ RUN_CODES.selectionUnavailable,
1473
+ 'the conversation reports no model selection after one was recorded, so the worker was not started',
1474
+ { reason: SELECTION_REASONS.readbackUnusable },
1475
+ );
1476
+ }
1477
+ // The readback is the fact: when it disagrees with what was asked for, the
1478
+ // prompt is never delivered. The observed route is operator-selected metadata
1479
+ // (never a credential), so it is comparable and reportable.
1480
+ if (observed.provider !== wanted.provider || observed.model !== wanted.model) {
1481
+ throw new RunError(
1482
+ RUN_CODES.selectionUnavailable,
1483
+ 'the conversation would run on a different model route than the one selected, so the worker was not started',
1484
+ {
1485
+ reason: SELECTION_REASONS.routeMismatch,
1486
+ expected: { provider: wanted.provider, model: wanted.model, reasoningEffort: wanted.reasoningEffort ?? null },
1487
+ observed: {
1488
+ provider: observed.provider,
1489
+ model: observed.model,
1490
+ reasoningEffort: typeof observed.reasoningEffort === 'string' ? observed.reasoningEffort : null,
1491
+ },
1492
+ },
1493
+ );
1494
+ }
1495
+ const observedEffort = typeof observed.reasoningEffort === 'string' && observed.reasoningEffort !== ''
1496
+ ? observed.reasoningEffort
1497
+ : undefined;
1498
+ if (wanted.reasoningEffort !== undefined && observedEffort !== wanted.reasoningEffort) {
1499
+ throw new RunError(
1500
+ RUN_CODES.selectionUnavailable,
1501
+ 'the conversation would run at a different reasoning effort than the one selected, so the worker was not started',
1502
+ {
1503
+ reason: SELECTION_REASONS.effortMismatch,
1504
+ expected: { reasoningEffort: wanted.reasoningEffort },
1505
+ observed: { reasoningEffort: observedEffort ?? null },
1506
+ },
1507
+ );
1508
+ }
1509
+ // Nothing asked for an effort, yet the conversation carries one: this run cannot
1510
+ // prove the operator's "no effort" choice is what the turn will use, so the
1511
+ // route is not reported as applied.
1512
+ if (wanted.reasoningEffort === undefined && observedEffort !== undefined) {
1513
+ throw new RunError(
1514
+ RUN_CODES.selectionUnavailable,
1515
+ 'the conversation carries a reasoning effort this run did not select, so the worker was not started',
1516
+ {
1517
+ reason: SELECTION_REASONS.unrequestedEffort,
1518
+ observed: { reasoningEffort: observedEffort },
1519
+ },
1520
+ );
1521
+ }
1522
+ return {
1523
+ provider: observed.provider,
1524
+ model: observed.model,
1525
+ reasoningEffort: observedEffort ?? null,
1526
+ applied: true,
1527
+ };
1528
+ }
1529
+
1530
+ function numeric(value) {
1531
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
1532
+ }
1533
+
1534
+ /**
1535
+ * Resolve the output-token budget one model request is made with.
1536
+ *
1537
+ * The rule, and why each clause exists:
1538
+ * - an ABSENT budget (`undefined`/`null`) is not "no budget": it resolves to
1539
+ * {@link DEFAULT_MAX_TOKENS}, because a native request with no explicit
1540
+ * allowance is what made an installed worker stop mid-answer;
1541
+ * - a supplied budget is PRESERVED verbatim, so an explicit caller decision is
1542
+ * never silently replaced by the default;
1543
+ * - a supplied budget that is not an integer inside
1544
+ * {@link MAX_TOKENS_BOUNDS} is REFUSED (`refused` non-null) rather than
1545
+ * clamped or dropped, so a request can never travel as unbounded.
1546
+ *
1547
+ * Note the bounds are checked by value, not reparsed: `0`, `NaN`, `1.5`, `'8192'`
1548
+ * and an out-of-range integer are all refusals.
1549
+ * @param {unknown} requested - the caller's `maxTokens`.
1550
+ * @returns {{ value: number, refused: { reason: string, min: number, max: number } | null }} resolution.
1551
+ */
1552
+ function maxTokensFor(requested) {
1553
+ const bounds = { min: MAX_TOKENS_BOUNDS.min, max: MAX_TOKENS_BOUNDS.max };
1554
+ if (requested === undefined || requested === null) return { value: DEFAULT_MAX_TOKENS, refused: null };
1555
+ if (typeof requested !== 'number' || !Number.isInteger(requested)) {
1556
+ // The type is reported, never the raw value: a bad budget may carry anything.
1557
+ return { value: DEFAULT_MAX_TOKENS, refused: { ...bounds, reason: 'maxTokens must be an integer', requestedType: typeof requested } };
1558
+ }
1559
+ if (requested < bounds.min || requested > bounds.max) {
1560
+ return { value: DEFAULT_MAX_TOKENS, refused: { ...bounds, reason: 'maxTokens is outside the supported range' } };
1561
+ }
1562
+ return { value: requested, refused: null };
1563
+ }
1564
+
1565
+ /**
1566
+ * Narrow a dependency object to the preset registry, or `null` when it cannot
1567
+ * install a composition.
1568
+ *
1569
+ * `agentPresets.mount(ctx, id?)` is the native entry point that joins an Agent
1570
+ * to a preset revision and mounts its plugin subtree (tools, scoped services).
1571
+ * Its absence is not a degraded mode to paper over: an Agent with no preset has
1572
+ * no tools, so the run is refused before any agent is created.
1573
+ * @param {object} deps - dependency object.
1574
+ * @returns {{ mount: (agentCtx: object, id?: string) => Promise<unknown> } | null} registry facade or null.
1575
+ */
1576
+ function presetRegistryOf(deps) {
1577
+ const presets = deps?.agentPresets;
1578
+ if (presets === undefined || presets === null || typeof presets.mount !== 'function') return null;
1579
+ return {
1580
+ // The id is forwarded verbatim: `undefined` makes the registry apply its
1581
+ // configured default rather than this plugin inventing one, and a named id is
1582
+ // one the run already proved its caller owns.
1583
+ mount: (agentCtx, id) => (id === undefined ? presets.mount(agentCtx) : presets.mount(agentCtx, id)),
1584
+ };
1585
+ }
1586
+
1587
+ /**
1588
+ * Resolve the agent/session identity a run will own.
1589
+ *
1590
+ * `CreateAgentOptions.sessionId` is required and the native factory creates the
1591
+ * session — and, through `AgentRegistry.enter()`, the agent — under exactly that
1592
+ * id. The default creation path mints nothing, so a caller that omits the id
1593
+ * used to pass `undefined` and the registry refused the freshly built agent with
1594
+ * `agent id "undefined" does not match session id "session-N"`.
1595
+ *
1596
+ * Rule: an identity the caller supplied is preserved verbatim (it is the
1597
+ * caller's ownership decision: a fork, an ACP id, a resumed session); only an
1598
+ * ABSENT one (`undefined`/`null`) is generated, once per run. The shape mirrors
1599
+ * the sibling one-shot runner in `dsh-headless`, which does
1600
+ * `config.sessionId ?? \`session-${randomUUID()}\`` before `agents.create`, so
1601
+ * ids stay recognisable and unrelated to this plugin's own naming.
1602
+ * @param {unknown} requested - the caller's `sessionId`, possibly absent.
1603
+ * @returns {{ value: string, generated: boolean }} the identity to create under.
1604
+ */
1605
+ export function resolveSessionIdentity(requested) {
1606
+ if (typeof requested === 'string') return { value: requested, generated: false };
1607
+ // `undefined`/`null` mean "the caller has no identity to impose". Any other
1608
+ // type is a caller bug, not an omission: it is passed through so the
1609
+ // pre-create admission check below refuses it with a stated reason instead of
1610
+ // this helper silently inventing a different identity.
1611
+ if (requested === undefined || requested === null) {
1612
+ return { value: `session-${randomUUID()}`, generated: true };
1613
+ }
1614
+ return { value: requested, generated: false };
1615
+ }
1616
+
1617
+ /**
1618
+ * Why the native registry would refuse a caller-supplied identity, or `null`.
1619
+ *
1620
+ * These are the checks `AgentRegistry`/`SessionStore.prepare` apply to an id, so
1621
+ * a run that would fail them is refused here — before an agent or a session
1622
+ * exists — instead of failing later as an opaque `RUN_CREATE_FAILED` whose cause
1623
+ * an operator cannot separate from a provider problem.
1624
+ * @param {object} agents - native agent registry (only `get` is used).
1625
+ * @param {string|unknown} id - identity the caller asked for.
1626
+ * @returns {string|null} reason text, or `null` when the id is admissible.
1627
+ */
1628
+ function sessionIdUnusable(agents, id) {
1629
+ if (typeof id !== 'string') return 'sessionId must be a string';
1630
+ // `SessionStore.prepare` brands whatever string it is handed as a session id,
1631
+ // so an empty one would become a real (and unusable) session identity.
1632
+ if (id.trim() === '') return 'sessionId must not be blank';
1633
+ // `SessionStore.prepare` throws when the id already has a session; a live
1634
+ // agent is the process-local form of that collision.
1635
+ if (typeof agents.get === 'function') {
1636
+ try {
1637
+ if (agents.get(id) !== undefined) return 'a live agent already owns this session id in this process';
1638
+ } catch {
1639
+ // An unreadable registry cannot answer the question; creation itself is
1640
+ // the next authority and will refuse an id it cannot admit.
1641
+ }
1642
+ }
1643
+ return null;
1644
+ }
1645
+
1646
+ /**
1647
+ * Normalize an agent error payload into redacted diagnostic text.
1648
+ *
1649
+ * Native `agent/error` payloads carry either an `Error` or a bare message, and
1650
+ * the provider code (e.g. `401`, `context_length_exceeded`) is the part an
1651
+ * operator needs to act on, so it is preserved alongside the message instead of
1652
+ * being flattened away.
1653
+ * @param {unknown} value - error payload.
1654
+ * @returns {string} redacted diagnostic.
1655
+ */
1656
+ function errorText(value) {
1657
+ if (value === null || value === undefined) return 'agent error';
1658
+ const code = typeof value?.code === 'string' && value.code !== '' ? value.code : null;
1659
+ const message = value?.message ?? (typeof value === 'string' ? value : null);
1660
+ const text = message === null ? 'agent error' : String(message);
1661
+ return diagnostic(code === null ? text : `${code}: ${text}`);
1662
+ }
1663
+
1664
+ /**
1665
+ * Build the bounded, duplicate-aware collector for assistant text.
1666
+ *
1667
+ * Two native behaviors make a plain array of chunks wrong:
1668
+ * - `text-delta` events stream an answer and are followed by an
1669
+ * `assistant/message` carrying the same text, so appending both would double
1670
+ * it in job history;
1671
+ * - neither source is bounded, so a runaway stream could make the process hold
1672
+ * an unbounded string before any post-hoc slice applied.
1673
+ *
1674
+ * Both are handled here: every append is clamped to the limit as it happens, and
1675
+ * a completed message supersedes the deltas it was streaming instead of
1676
+ * following them. A later message starts a fresh pending buffer, so a multi-turn
1677
+ * run still accumulates each turn exactly once.
1678
+ * @param {number} limit - maximum retained characters.
1679
+ * @returns {object} collector with `appendDelta`, `mergeFinal`, `value`, `length`, `truncated`.
1680
+ */
1681
+ function createTextCollector(limit) {
1682
+ let completed = '';
1683
+ let pending = '';
1684
+ let truncated = false;
1685
+
1686
+ const clampAppend = (current, addition) => {
1687
+ if (addition === '') return current;
1688
+ if (current.length >= limit) {
1689
+ truncated = true;
1690
+ return current;
1691
+ }
1692
+ const joined = current + addition;
1693
+ if (joined.length <= limit) return joined;
1694
+ truncated = true;
1695
+ return joined.slice(0, limit);
1696
+ };
1697
+
1698
+ return {
1699
+ appendDelta(text) {
1700
+ if (typeof text !== 'string' || text === '') return;
1701
+ pending = clampAppend(pending, text);
1702
+ },
1703
+ mergeFinal(text) {
1704
+ if (typeof text !== 'string' || text === '') return;
1705
+ // The completed message is authoritative for the turn it closes: when the
1706
+ // streamed deltas were its prefix, the message replaces them rather than
1707
+ // repeating them. Deltas that the message does not cover are kept.
1708
+ const merged = pending !== '' && !text.startsWith(pending) ? `${pending}${text}` : text;
1709
+ completed = clampAppend(completed, merged);
1710
+ pending = '';
1711
+ },
1712
+ value() {
1713
+ return completed + pending;
1714
+ },
1715
+ length() {
1716
+ return (completed + pending).length;
1717
+ },
1718
+ truncated() {
1719
+ return truncated;
1720
+ },
1721
+ };
1722
+ }
1723
+
1724
+ function normalizeUsage(usage) {
1725
+ return {
1726
+ inputTokens: numeric(usage.inputTokens),
1727
+ outputTokens: numeric(usage.outputTokens),
1728
+ totalTokens: numeric(usage.totalTokens),
1729
+ reasoningTokens: numeric(usage.reasoningTokens),
1730
+ };
1731
+ }
1732
+
1733
+ async function disposeQuietly(handle) {
1734
+ try {
1735
+ await handle.dispose();
1736
+ } catch {
1737
+ // Disposal failure must not mask the run outcome; the handle is unowned
1738
+ // either way and the native layer performs its own cleanup.
1739
+ }
1740
+ }