dsh-taskbridge 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +16 -2
  2. package/README.md +8 -7
  3. package/bin/dsh-delegate-mcp.d.ts +20 -3
  4. package/bin/dsh-delegate-mcp.js +15 -0
  5. package/codex/dsh-taskbridge.toml +74 -5
  6. package/docs/INTRODUCTION.md +2 -2
  7. package/docs/INTRODUCTION.zh.md +2 -2
  8. package/docs/codex-integration.md +4 -2
  9. package/docs/conversation-placement.md +44 -7
  10. package/docs/plugin-market.md +1 -1
  11. package/docs/redaction-contract.md +47 -4
  12. package/docs/releases/1.5.0-token-benchmark.zh.md +73 -0
  13. package/docs/releases/1.5.0.zh.md +51 -0
  14. package/docs/runtime-compatibility.md +4 -4
  15. package/docs/silent-wait.md +84 -0
  16. package/docs/taskbridge-upgrade.md +1 -1
  17. package/docs/worker-permissions.md +154 -17
  18. package/lib/client.js +3 -0
  19. package/package.json +4 -2
  20. package/src/client/api.js +26 -0
  21. package/src/codex/installer.js +15 -0
  22. package/src/config/redact.js +72 -11
  23. package/src/http/execution-plane.js +76 -5
  24. package/src/index.d.ts +285 -0
  25. package/src/index.js +72 -2
  26. package/src/jobs/activity.js +10 -0
  27. package/src/jobs/continuation-identity.js +278 -0
  28. package/src/jobs/engine.js +326 -36
  29. package/src/jobs/history.js +53 -0
  30. package/src/mcp/continuation.js +317 -0
  31. package/src/mcp/metrics.js +343 -0
  32. package/src/mcp/server.js +1079 -47
  33. package/src/mcp/wait.js +266 -74
  34. package/src/review/prompts.js +145 -126
  35. package/src/runtime/agent-runner.js +165 -0
  36. package/src/runtime/permissions.js +192 -2
  37. package/src/runtime/question-call.js +162 -0
  38. package/src/runtime/questions.js +909 -0
  39. package/src/runtime/session-placement.js +78 -5
  40. package/src/version.js +99 -0
@@ -1,126 +1,145 @@
1
- // Prompt construction for delegated work and independent review.
2
- //
3
- // Prompt text is a contract, not decoration. It states what the worker must do,
4
- // what it must not do, and — critically — what it cannot do on its own: the
5
- // worker cannot approve its own work, and the reviewer cannot change the
6
- // workspace. Both prompts also carry an explicit evidence boundary so neither
7
- // party believes it may widen its own scope.
8
-
9
- /** Placeholder substituted for withheld patch content. */
10
- export const REDACTED_PLACEHOLDER = '[content withheld: sensitive path]';
11
-
12
- /** Bounds on interpolated evidence inside a prompt. */
13
- const EVIDENCE_LIMITS = Object.freeze({
14
- fileList: 200,
15
- patchChars: 24_000,
16
- });
17
-
18
- /**
19
- * Build the delegation prompt for one task.
20
- * @param {object} input - `taskId`, `prompt`, `workspacePath`, `isolation`, `diff`, `baseline`.
21
- * @returns {string} assembled prompt.
22
- */
23
- export function buildWorkerPrompt(input) {
24
- const lines = [];
25
- lines.push('You are a delegated implementation worker. Your work will be reviewed by the host and by an independent reviewer.');
26
- lines.push('');
27
- lines.push(`Task id: ${input.taskId}`);
28
- if (typeof input.workspacePath === 'string' && input.workspacePath !== '') {
29
- lines.push(`Workspace: ${input.workspacePath}`);
30
- }
31
- lines.push(`Isolation: ${input.isolation ?? 'shared'}`);
32
- lines.push('');
33
- lines.push('## Task');
34
- lines.push(String(input.prompt ?? '').trim());
35
- lines.push('');
36
- lines.push('## Working rules');
37
- lines.push('- You may modify files only inside the workspace above.');
38
- lines.push('- Do not commit, push, tag, or rewrite git history.');
39
- lines.push('- Do not read or print credentials, tokens, or .env contents.');
40
- lines.push('- Do not install packages from the network unless the task explicitly requires it.');
41
- lines.push('- Report what you changed and what you could not do. Do not claim checks you did not run.');
42
- lines.push('');
43
- lines.push('## Completion');
44
- lines.push('When the task is complete, reply with a short summary, the files you changed, and any checks you actually ran with their results.');
45
- lines.push('You cannot approve your own work; the host decides acceptance.');
46
- if (input.baseline !== undefined && input.baseline !== null) {
47
- lines.push('');
48
- lines.push(`## Starting state: ${input.baseline.dirtyBaseline === true ? 'the workspace already had uncommitted changes' : 'the workspace was clean'}`);
49
- }
50
- return lines.join('\n');
51
- }
52
-
53
- /**
54
- * Build the independent review prompt.
55
- *
56
- * The reviewer is asked for a machine-readable verdict line and is told
57
- * explicitly that it must not modify anything and cannot approve on the host's
58
- * behalf.
59
- * @param {object} input - `taskId`, `taskPrompt`, `workerSummary`, `evidence`.
60
- * @returns {string} assembled prompt.
61
- */
62
- export function buildReviewPrompt(input) {
63
- const lines = [];
64
- lines.push('You are an independent reviewer. You did not perform this work.');
65
- lines.push('');
66
- lines.push(`Task id: ${input.taskId}`);
67
- lines.push('');
68
- lines.push('## The task that was delegated');
69
- lines.push(String(input.taskPrompt ?? '').trim());
70
- lines.push('');
71
- lines.push('## The worker\'s report');
72
- lines.push(String(input.workerSummary ?? '(no summary produced)').trim());
73
- lines.push('');
74
- lines.push('## Measured changes');
75
- lines.push(renderEvidence(input.evidence));
76
- lines.push('');
77
- lines.push('## Your constraints');
78
- lines.push('- You are read-only. Any attempt to modify the workspace will be denied by the harness.');
79
- lines.push('- You cannot approve work on behalf of the host. Your verdict is evidence, not acceptance.');
80
- lines.push('- Judge only what the evidence above shows; if it is insufficient, say so.');
81
- lines.push('');
82
- lines.push('## Required output');
83
- lines.push('End your reply with exactly these two lines:');
84
- lines.push('VERDICT: approve (or) VERDICT: changes-requested');
85
- lines.push('REASON: one sentence');
86
- return lines.join('\n');
87
- }
88
-
89
- /**
90
- * Render measured change evidence into prompt-safe text.
91
- * @param {object | null} evidence - value returned by the workspace audit.
92
- * @returns {string} bounded evidence block.
93
- */
94
- export function renderEvidence(evidence) {
95
- if (evidence === null || evidence === undefined) return 'No change evidence was captured.';
96
- const lines = [];
97
- if (evidence.dirtyBaseline === true) {
98
- lines.push(`Note: the workspace had ${evidence.preexistingChanges ?? 'some'} pre-existing change(s) before this task ran.`);
99
- }
100
- const files = Array.isArray(evidence.files) ? evidence.files.slice(0, EVIDENCE_LIMITS.fileList) : [];
101
- if (files.length === 0) {
102
- lines.push('No files changed.');
103
- } else {
104
- lines.push(`Changed files (${evidence.fileCount ?? files.length}${evidence.truncatedFiles ? ', list truncated' : ''}):`);
105
- for (const file of files) {
106
- lines.push(` ${file.status} ${file.path}${file.sensitive === true ? ' [sensitive: content withheld]' : ''}`);
107
- }
108
- }
109
- if (Array.isArray(evidence.sensitivePaths) && evidence.sensitivePaths.length > 0) {
110
- lines.push('');
111
- lines.push('Sensitive paths were touched. Their content is withheld from this evidence:');
112
- for (const path of evidence.sensitivePaths.slice(0, EVIDENCE_LIMITS.fileList)) lines.push(` ${path}`);
113
- }
114
- lines.push('');
115
- lines.push('Diff:');
116
- const patch = typeof evidence.patchText === 'string' ? evidence.patchText : '';
117
- if (patch === '') {
118
- lines.push('(no textual diff captured)');
119
- } else {
120
- lines.push(patch.slice(0, EVIDENCE_LIMITS.patchChars));
121
- if (patch.length > EVIDENCE_LIMITS.patchChars || evidence.patchTruncated === true) {
122
- lines.push(`(diff truncated for review at ${EVIDENCE_LIMITS.patchChars} characters)`);
123
- }
124
- }
125
- return lines.join('\n');
126
- }
1
+ // Prompt construction for delegated work and independent review.
2
+ //
3
+ // Prompt text is a contract, not decoration. It states what the worker must do,
4
+ // what it must not do, and — critically — what it cannot do on its own: the
5
+ // worker cannot approve its own work, and the reviewer cannot change the
6
+ // workspace. Both prompts also carry an explicit evidence boundary so neither
7
+ // party believes it may widen its own scope.
8
+
9
+ /** Placeholder substituted for withheld patch content. */
10
+ export const REDACTED_PLACEHOLDER = '[content withheld: sensitive path]';
11
+
12
+ /** Bounds on interpolated evidence inside a prompt. */
13
+ const EVIDENCE_LIMITS = Object.freeze({
14
+ fileList: 200,
15
+ patchChars: 24_000,
16
+ });
17
+
18
+ /**
19
+ * Build the delegation prompt for one task.
20
+ * @param {object} input - `taskId`, `prompt`, `workspacePath`, `isolation`, `diff`, `baseline`.
21
+ * @returns {string} assembled prompt.
22
+ */
23
+ export function buildWorkerPrompt(input) {
24
+ const lines = [];
25
+ lines.push('You are a delegated implementation worker. Your work will be reviewed by the host and by an independent reviewer.');
26
+ lines.push('');
27
+ lines.push(`Task id: ${input.taskId}`);
28
+ if (typeof input.workspacePath === 'string' && input.workspacePath !== '') {
29
+ lines.push(`Workspace: ${input.workspacePath}`);
30
+ }
31
+ lines.push(`Isolation: ${input.isolation ?? 'shared'}`);
32
+ lines.push('');
33
+ lines.push('## Task');
34
+ lines.push(String(input.prompt ?? '').trim());
35
+ lines.push('');
36
+ lines.push('## Working rules');
37
+ lines.push('- You may modify files only inside the workspace above.');
38
+ lines.push('- Do not commit, push, tag, or rewrite git history.');
39
+ lines.push('- Do not read or print credentials, tokens, or .env contents.');
40
+ lines.push('- Do not install packages from the network unless the task explicitly requires it.');
41
+ lines.push('- Report what you changed and what you could not do. Do not claim checks you did not run.');
42
+ lines.push('');
43
+ lines.push('## Checks and extra permissions');
44
+ lines.push('- Read ordinary files and logs with the normal file tools and the ordinary workspace permission. '
45
+ + 'Do not ask for elevated access merely to read a log, and do not use a sandbox escape as a substitute for '
46
+ + 'a file tool.');
47
+ lines.push('- Run tests under the ordinary permission first. If a test fails for a CONCRETE environment reason '
48
+ + '(a missing module, a denied pipe, an absent binary), keep that error text and report it rather than retrying '
49
+ + 'the same command with more access.');
50
+ lines.push('- Ask for extra permission only for the one complete, bounded command that genuinely needs it, and say '
51
+ + 'which error it resolves. A permission granted for one call never covers a later call, and it never widens '
52
+ + 'the sandbox permanently.');
53
+ lines.push('- Run one combined test command, save its FULL stdout/stderr, its real exit code and a short summary '
54
+ + '(for example into `.cache/`), and read that saved log afterwards with the file tools. Do not re-run a test '
55
+ + 'merely to change a filter, a `Select-String` pattern or a `Select-Object -First N`: read the log instead.');
56
+ lines.push('- A missing dependency is a fact to verify, not a reason to re-run the suite: check whether the module '
57
+ + 'exists before concluding the test failed, and never use extra permission to paper over a module-not-found '
58
+ + 'error.');
59
+ lines.push('- Fix a failing test before running the suite again. Report the tests you actually ran, their exit '
60
+ + 'codes and their counts; if the worktree cannot provide a dependency, say so plainly instead of retrying.');
61
+ lines.push('');
62
+ lines.push('## Completion');
63
+ lines.push('When the task is complete, reply with a short summary, the files you changed, and any checks you actually ran with their results.');
64
+ lines.push('You cannot approve your own work; the host decides acceptance.');
65
+ if (input.baseline !== undefined && input.baseline !== null) {
66
+ lines.push('');
67
+ lines.push(`## Starting state: ${input.baseline.dirtyBaseline === true ? 'the workspace already had uncommitted changes' : 'the workspace was clean'}`);
68
+ }
69
+ return lines.join('\n');
70
+ }
71
+
72
+ /**
73
+ * Build the independent review prompt.
74
+ *
75
+ * The reviewer is asked for a machine-readable verdict line and is told
76
+ * explicitly that it must not modify anything and cannot approve on the host's
77
+ * behalf.
78
+ * @param {object} input - `taskId`, `taskPrompt`, `workerSummary`, `evidence`.
79
+ * @returns {string} assembled prompt.
80
+ */
81
+ export function buildReviewPrompt(input) {
82
+ const lines = [];
83
+ lines.push('You are an independent reviewer. You did not perform this work.');
84
+ lines.push('');
85
+ lines.push(`Task id: ${input.taskId}`);
86
+ lines.push('');
87
+ lines.push('## The task that was delegated');
88
+ lines.push(String(input.taskPrompt ?? '').trim());
89
+ lines.push('');
90
+ lines.push('## The worker\'s report');
91
+ lines.push(String(input.workerSummary ?? '(no summary produced)').trim());
92
+ lines.push('');
93
+ lines.push('## Measured changes');
94
+ lines.push(renderEvidence(input.evidence));
95
+ lines.push('');
96
+ lines.push('## Your constraints');
97
+ lines.push('- You are read-only. Any attempt to modify the workspace will be denied by the harness.');
98
+ lines.push('- You cannot approve work on behalf of the host. Your verdict is evidence, not acceptance.');
99
+ lines.push('- Judge only what the evidence above shows; if it is insufficient, say so.');
100
+ lines.push('');
101
+ lines.push('## Required output');
102
+ lines.push('End your reply with exactly these two lines:');
103
+ lines.push('VERDICT: approve (or) VERDICT: changes-requested');
104
+ lines.push('REASON: one sentence');
105
+ return lines.join('\n');
106
+ }
107
+
108
+ /**
109
+ * Render measured change evidence into prompt-safe text.
110
+ * @param {object | null} evidence - value returned by the workspace audit.
111
+ * @returns {string} bounded evidence block.
112
+ */
113
+ export function renderEvidence(evidence) {
114
+ if (evidence === null || evidence === undefined) return 'No change evidence was captured.';
115
+ const lines = [];
116
+ if (evidence.dirtyBaseline === true) {
117
+ lines.push(`Note: the workspace had ${evidence.preexistingChanges ?? 'some'} pre-existing change(s) before this task ran.`);
118
+ }
119
+ const files = Array.isArray(evidence.files) ? evidence.files.slice(0, EVIDENCE_LIMITS.fileList) : [];
120
+ if (files.length === 0) {
121
+ lines.push('No files changed.');
122
+ } else {
123
+ lines.push(`Changed files (${evidence.fileCount ?? files.length}${evidence.truncatedFiles ? ', list truncated' : ''}):`);
124
+ for (const file of files) {
125
+ lines.push(` ${file.status} ${file.path}${file.sensitive === true ? ' [sensitive: content withheld]' : ''}`);
126
+ }
127
+ }
128
+ if (Array.isArray(evidence.sensitivePaths) && evidence.sensitivePaths.length > 0) {
129
+ lines.push('');
130
+ lines.push('Sensitive paths were touched. Their content is withheld from this evidence:');
131
+ for (const path of evidence.sensitivePaths.slice(0, EVIDENCE_LIMITS.fileList)) lines.push(` ${path}`);
132
+ }
133
+ lines.push('');
134
+ lines.push('Diff:');
135
+ const patch = typeof evidence.patchText === 'string' ? evidence.patchText : '';
136
+ if (patch === '') {
137
+ lines.push('(no textual diff captured)');
138
+ } else {
139
+ lines.push(patch.slice(0, EVIDENCE_LIMITS.patchChars));
140
+ if (patch.length > EVIDENCE_LIMITS.patchChars || evidence.patchTruncated === true) {
141
+ lines.push(`(diff truncated for review at ${EVIDENCE_LIMITS.patchChars} characters)`);
142
+ }
143
+ }
144
+ return lines.join('\n');
145
+ }
@@ -97,6 +97,11 @@ export const RUN_CODES = Object.freeze({
97
97
  // bridge while installing `never` would look like the commander could decide,
98
98
  // and nothing would ever reach it.
99
99
  permissionBridgeUnavailable: 'RUN_PERMISSION_BRIDGE_UNAVAILABLE',
100
+ // A question bridge was handed to the run but the answerer could not be registered on
101
+ // its Agent. The run still starts: unlike an approval bridge, an uninstalled question
102
+ // answerer cannot misrepresent a grant — it only means questions cannot be surfaced,
103
+ // which the tool surface already governs.
104
+ questionBridgeUnavailable: 'RUN_QUESTION_BRIDGE_UNAVAILABLE',
100
105
  // The conversation's own model API (`agent.model`)
101
106
  // is present but unusable: it threw, answered nothing, answered a route
102
107
  // this run did not select, or exposed a surface that cannot be selected through
@@ -291,6 +296,23 @@ export function userMessage(text) {
291
296
  return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } });
292
297
  }
293
298
 
299
+ /**
300
+ * The production message factory a bridge should be handed.
301
+ *
302
+ * Exported so the plugin's own composition can pass the REAL `createUserMessage` to a
303
+ * bridge instead of relying on that bridge's local fallback: the native helper normalises
304
+ * ids, roles and content, and a hand-built object is only ever a stand-in. The source kind
305
+ * (`'user-approval'`) is the one the native approval service already uses for its policy
306
+ * notices, so the message is a recognised, natively-supported shape rather than an
307
+ * invented one.
308
+ * @param {string} text - message body.
309
+ * @param {object} [source] - a `MessageSourceMap` entry; defaults to `{ kind: 'user-approval' }`.
310
+ * @returns {object} frozen user message.
311
+ */
312
+ export function approvalFeedbackMessage(text, source = { kind: 'user-approval' }) {
313
+ return createUserMessage({ content: [{ type: 'text', text }], source });
314
+ }
315
+
294
316
  /**
295
317
  * One run's execution deadline, with a real pause and resume.
296
318
  *
@@ -670,6 +692,9 @@ export async function driveAgent(deps, request) {
670
692
  // Removes the `approval/request` answerer when the run ends. Null when the run
671
693
  // had no bridge, which is the ordinary worker run.
672
694
  permissionAnswerer: null,
695
+ // Removes the `user-questions/request` answerer when the run ends. Null when the
696
+ // run had no question bridge or the harness exposes no such seam.
697
+ questionAnswerer: null,
673
698
  // The execution deadline this run owns. It is PAUSED around every permission
674
699
  // wait, so the wait is not charged to the operator's execution budget.
675
700
  deadline: null,
@@ -874,6 +899,19 @@ export async function driveAgent(deps, request) {
874
899
  // The owning fiber disposes the listener on unload; this is best effort.
875
900
  }
876
901
  }
902
+ // The QUESTION answerer is removed on the SAME every-exit path, for the same reason:
903
+ // a finished run must not keep a listener that could answer a question for an Agent it
904
+ // no longer drives. Removing it here (not only at dispose) is what lets the ordinary
905
+ // UI answerer take that Agent's questions again as soon as the run is over.
906
+ if (state.questionAnswerer !== null) {
907
+ const remove = state.questionAnswerer;
908
+ state.questionAnswerer = null;
909
+ try {
910
+ remove();
911
+ } catch {
912
+ // Best effort, exactly like the approval answerer above.
913
+ }
914
+ }
877
915
  }
878
916
 
879
917
  /**
@@ -965,6 +1003,11 @@ export async function driveAgent(deps, request) {
965
1003
  policy: bridged?.approvalPolicy ?? null,
966
1004
  bridged: bridged?.bridged === true,
967
1005
  };
1006
+ // The QUESTION bridge is independent of the approval stance: asking a question
1007
+ // is not granting anything, so a run whose approval policy is `never` may still
1008
+ // ask. Its answerer is registered after the composition exists and before the
1009
+ // prompt, so no turn can ask with nothing listening.
1010
+ bindQuestionBridge(agent, runRequest);
968
1011
  } catch (error) {
969
1012
  // A bridge refusal keeps its own code: it is a different operator problem from
970
1013
  // a policy that could not be installed, and reporting it as one would send an
@@ -988,6 +1031,41 @@ export async function driveAgent(deps, request) {
988
1031
  }
989
1032
  }
990
1033
 
1034
+ /**
1035
+ * Arm the run's QUESTION bridge and register its answerer for this Agent.
1036
+ *
1037
+ * A run with no question bridge is the ordinary worker run: nothing is registered and
1038
+ * the native chain falls through as before. A supplied bridge that cannot be armed is
1039
+ * a REFUSAL rather than a silent downgrade, because the caller believes questions are
1040
+ * surfaced; the operator would otherwise see a task sit in `execute` while its worker
1041
+ * waits for an answer nobody can give.
1042
+ * @param {object} agent - the live native Agent the run will drive.
1043
+ * @param {object} runRequest - the run request carrying the optional bridge.
1044
+ * @returns {void}
1045
+ * @throws {RunError} when a supplied question bridge cannot be armed or registered.
1046
+ */
1047
+ function bindQuestionBridge(agent, runRequest) {
1048
+ const bridge = runRequest?.questionBridge ?? null;
1049
+ if (bridge === null || bridge === undefined) return;
1050
+ if (typeof bridge.arm !== 'function' || typeof bridge.answer !== 'function') {
1051
+ throw new RunError(
1052
+ RUN_CODES.questionBridgeUnavailable,
1053
+ 'the requested question bridge cannot be used for this run, so the worker was not started',
1054
+ { reason: 'the bridge exposes no arm()/answer()' },
1055
+ );
1056
+ }
1057
+ try {
1058
+ bridge.arm(agent);
1059
+ } catch (error) {
1060
+ throw new RunError(
1061
+ RUN_CODES.questionBridgeUnavailable,
1062
+ 'the question bridge could not be bound to the delegated session, so the worker was not started',
1063
+ { reason: typeof error?.details?.reason === 'string' ? error.details.reason : 'the bridge refused this agent' },
1064
+ );
1065
+ }
1066
+ installQuestionAnswerer(agent?.ctx ?? null, bridge);
1067
+ }
1068
+
991
1069
  /**
992
1070
  * Arm the run's permission bridge for the Agent this run will drive.
993
1071
  *
@@ -1118,6 +1196,93 @@ export async function driveAgent(deps, request) {
1118
1196
  };
1119
1197
  }
1120
1198
 
1199
+ /**
1200
+ * Register this run's QUESTION bridge as the answerer for its own Agent.
1201
+ *
1202
+ * The seam is the native, agent-scoped waterfall `'user-questions/request'`
1203
+ * (`UserQuestionService.ask()` dispatches
1204
+ * `ctx.waterfall(scopeTarget(agent, agent), 'user-questions/request', …)`); a listener
1205
+ * on the AGENT's own context therefore sees only that Agent's questions, so an
1206
+ * ordinary DSH session keeps whatever answerer it already has.
1207
+ *
1208
+ * `prepend: true` is REQUIRED for the same reason the approval answerer needs it: the
1209
+ * waterfall gives the request to the FIRST listener that returns a value, and this run
1210
+ * exists to surface the question to the COMMANDER. Registered plainly, a UI answerer
1211
+ * that was composed earlier would claim it first and the commander would never learn
1212
+ * the worker was asking — which is exactly the acceptance failure (the task sat in
1213
+ * `execute` for ten minutes). The listener still falls through for every other agent.
1214
+ *
1215
+ * A question that cannot be answered (an approval intent, a malformed or oversized
1216
+ * set) makes the bridge THROW: the native seam turns a thrown answerer into a failed
1217
+ * tool result carrying the code, so the worker learns why immediately instead of
1218
+ * waiting out the run.
1219
+ * @param {object} agentCtx - the agent's scoped context (listener target).
1220
+ * @param {object} bridge - the armed question bridge.
1221
+ * @returns {() => void} disposer removing the listener.
1222
+ * @throws {RunError} when the context cannot register a question answerer.
1223
+ */
1224
+ function installQuestionAnswerer(agentCtx, bridge) {
1225
+ if (agentCtx === null || agentCtx === undefined || typeof agentCtx.on !== 'function') {
1226
+ // A context that cannot register a listener has NOT been wired: returning a no-op
1227
+ // would let the run report a bridged question channel it does not have, and the
1228
+ // worker's question would then wait for an answerer that was never installed.
1229
+ throw new RunError(
1230
+ RUN_CODES.questionBridgeUnavailable,
1231
+ 'the delegated agent exposes no context a question answerer could be registered on, so the worker was not started',
1232
+ { reason: 'agent context unavailable' },
1233
+ );
1234
+ }
1235
+ let disposer;
1236
+ try {
1237
+ disposer = agentCtx.on('user-questions/request', async (request, next) => {
1238
+ if (bridge.owns(request) !== true) {
1239
+ // Not this Agent's question: leave the chain untouched, so an ordinary
1240
+ // session keeps the answerer it actually has.
1241
+ return await next();
1242
+ }
1243
+ // PAUSE the run's execution deadline for the duration of the wait, exactly as
1244
+ // the approval answerer does: a worker waiting for a human answer is not
1245
+ // consuming its work budget, and the pause is repaid on every exit.
1246
+ const deadline = state.deadline;
1247
+ const pausedAt = Date.now();
1248
+ deadline?.pause();
1249
+ try {
1250
+ return await bridge.answer(request);
1251
+ } finally {
1252
+ if (deadline !== null) {
1253
+ deadline.notePaused(Date.now() - pausedAt);
1254
+ deadline.resume();
1255
+ }
1256
+ }
1257
+ }, { prepend: true });
1258
+ } catch (error) {
1259
+ throw new RunError(
1260
+ RUN_CODES.questionBridgeUnavailable,
1261
+ 'the question answerer could not be registered for the delegated session',
1262
+ { reason: typeof error?.code === 'string' ? error.code : 'agent context refused the answerer' },
1263
+ );
1264
+ }
1265
+ if (typeof disposer !== 'function') {
1266
+ // A registration that returns no disposer cannot be removed, so it would outlive the
1267
+ // run and keep answering that Agent's questions from a finished task.
1268
+ throw new RunError(
1269
+ RUN_CODES.questionBridgeUnavailable,
1270
+ 'the question answerer registration returned no disposer, so it could not be removed when the run ended',
1271
+ { reason: 'no disposer' },
1272
+ );
1273
+ }
1274
+ state.questionAnswerer = disposer;
1275
+ return () => {
1276
+ const remove = state.questionAnswerer;
1277
+ state.questionAnswerer = null;
1278
+ try {
1279
+ remove?.();
1280
+ } catch {
1281
+ // Best effort: the owning fiber disposes it on unload.
1282
+ }
1283
+ };
1284
+ }
1285
+
1121
1286
  /**
1122
1287
  * Release one handle at the end of a run.
1123
1288
  *