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
@@ -198,12 +198,24 @@ export class PermissionError extends Error {
198
198
  /**
199
199
  * Bounds on what one request keeps, so a hostile argument blob cannot become a
200
200
  * memory or history problem. Every bound is applied to a REDACTED value.
201
+ *
202
+ * The two text caps are set from the EVIDENCE, not from a round number. An allow is
203
+ * only possible on a complete operation, so any cap that fires turns a legitimate
204
+ * one-line request into an unapprovable one. A Windows absolute path plus a
205
+ * read-back command is ~400 characters on its own — that size was refused by an
206
+ * earlier `argumentValueChars: 400`, and a real platform refusal was the result. The
207
+ * caps below hold roughly an 8 KiB command field and a 16 KiB argument object: far
208
+ * more than any single tool call this surface reviews, and still a hard, stated
209
+ * limit — a value past it is `truncated`, `argumentsComplete: false`, and cannot be
210
+ * allowed (see {@link PermissionBridge#allowRefusalReason}). The protection the
211
+ * caps provide is the same as before; only the point where a normal request stops
212
+ * fitting moved.
201
213
  */
202
214
  export const PERMISSION_BOUNDS = Object.freeze({
203
215
  /** Maximum characters retained for the redacted JSON arguments. */
204
- argumentsChars: 4000,
216
+ argumentsChars: 16_384,
205
217
  /** Maximum characters retained for any single redacted argument scalar. */
206
- argumentValueChars: 400,
218
+ argumentValueChars: 8_192,
207
219
  /** Maximum depth retained when projecting arguments. */
208
220
  argumentDepth: 6,
209
221
  /** Maximum argument keys retained per object. */
@@ -593,6 +605,62 @@ export function openTurnAt(session, fromSeq) {
593
605
  return null;
594
606
  }
595
607
 
608
+ /**
609
+ * The text sent back into the worker after its call was rejected.
610
+ *
611
+ * It is written for the MODEL, not for a log, and every sentence is load-bearing:
612
+ *
613
+ * * the decision is final — the call was rejected and stays rejected;
614
+ * * nothing was widened — not the sandbox, not the grant, not the mode;
615
+ * * the note is not an authorization — a later attempt needs its own approval;
616
+ * * what to do: rewrite the operation to fit the stated reason and ask again.
617
+ *
618
+ * The reason is already redacted and bounded by the caller, so this function only
619
+ * composes. The operation is named by tool and call id so the worker can tell WHICH
620
+ * call was refused when several are in flight.
621
+ * @param {object} pending - the settled request.
622
+ * @param {string} reason - the commander's reason, redacted and bounded.
623
+ * @returns {string} the message body.
624
+ */
625
+ export function rejectionFeedbackText(pending, reason) {
626
+ const tool = typeof pending?.toolName === 'string' && pending.toolName !== '' ? pending.toolName : 'the requested tool call';
627
+ const callId = typeof pending?.callId === 'string' && pending.callId !== '' ? pending.callId : 'unknown';
628
+ const requestId = typeof pending?.requestId === 'string' && pending.requestId !== '' ? pending.requestId : 'unknown';
629
+ const taskId = typeof pending?.taskId === 'string' && pending.taskId !== '' ? pending.taskId : 'unknown';
630
+ const stated = typeof reason === 'string' && reason.trim() !== ''
631
+ ? reason.trim()
632
+ : 'no reason was given';
633
+ return [
634
+ `The commander REJECTED your ${tool} call (task ${taskId}, request ${requestId}, call id ${callId}).`,
635
+ `Reason for rejecting this one operation: ${stated}`,
636
+ 'The rejection stands: this call was not approved and will not run.',
637
+ 'Nothing was granted or widened. Sandbox permissions, the delegation switch, the session policy and your standing sandbox mode are unchanged.',
638
+ 'This note is NOT a new authorization and grants nothing by itself. If you still need the operation, change it to fit the reason above and request approval again; the new request will be decided on its own.',
639
+ ].join(' ');
640
+ }
641
+
642
+ /**
643
+ * The message shape an Agent's inbox accepts, built without the native LLM package.
644
+ *
645
+ * `agent.inject()` takes a user message object; the native helper is `createUserMessage`
646
+ * from `@deepseek-ai/dsh-llm`, which this module deliberately does not import (the stdio
647
+ * executable links it). This default therefore produces the same minimum shape, and the
648
+ * plugin's own composition injects the REAL factory so production never depends on it.
649
+ *
650
+ * The source kind is `'user-approval'` — the value the native approval service already
651
+ * uses for its own policy notices — so the message is a recognised producer's message, not
652
+ * an invented source. Nothing here claims to be a user instruction.
653
+ * @param {string} text - message body.
654
+ * @returns {{ role: 'user', content: { type: 'text', text: string }[], source: { kind: string } }} message.
655
+ */
656
+ export function defaultUserMessage(text) {
657
+ return {
658
+ role: 'user',
659
+ content: [{ type: 'text', text }],
660
+ source: { kind: 'user-approval' },
661
+ };
662
+ }
663
+
596
664
  /**
597
665
  * The permission bridge for ONE delegated run.
598
666
  *
@@ -648,6 +716,16 @@ export class PermissionBridge {
648
716
  // `this.session` so a replaced `agent.session` is detectable rather than silently
649
717
  // followed (see {@link liveBindingRefusal}).
650
718
  this.boundSessionId = null;
719
+ // Request id -> the id of the message that carried its rejection reason. One entry
720
+ // per delivered note, so a repeated reject, a retried decision or a restart cannot
721
+ // deliver the same feedback twice.
722
+ this.feedbackSent = new Map();
723
+ // The message factory. Injected so this module stays free of a hard dependency on the
724
+ // native LLM package (the stdio executable imports this file); the plugin passes the
725
+ // real `createUserMessage`, and the default below builds the same shape.
726
+ this.createMessage = typeof options.createUserMessage === 'function'
727
+ ? options.createUserMessage
728
+ : defaultUserMessage;
651
729
  }
652
730
 
653
731
  /** Maximum settled requests retained on one run. */
@@ -1231,6 +1309,19 @@ export class PermissionBridge {
1231
1309
  }
1232
1310
  this.history.push(this.publicView(pending));
1233
1311
  if (this.history.length > PermissionBridge.HISTORY_BOUND) this.history.shift();
1312
+ // The reason is delivered to the worker BEFORE the paused tool call is released, so
1313
+ // the note is already in the Agent's inbox by the time the model can take its next
1314
+ // step. It is delivered only for a REJECT: an allow needs no explanation, and a
1315
+ // cancellation is not a decision about the operation.
1316
+ let feedback = null;
1317
+ if (pending.settledOutcome === 'rejected' && pending.decidedBy === 'commander') {
1318
+ feedback = this.deliverRejectionFeedback(pending, pending.decisionReason);
1319
+ // Recorded on the settled view as a verified fact, so "the worker was told why" is
1320
+ // never claimed merely because a reason was stored.
1321
+ const last = this.history.at(-1);
1322
+ if (last !== null && last !== undefined) last.rejectionFeedback = feedback;
1323
+ pending.rejectionFeedback = feedback;
1324
+ }
1234
1325
  const resolvePromise = pending.resolve;
1235
1326
  pending.resolve = null;
1236
1327
  if (typeof resolvePromise === 'function') resolvePromise(pending.settledOutcome);
@@ -1243,6 +1334,105 @@ export class PermissionBridge {
1243
1334
  return true;
1244
1335
  }
1245
1336
 
1337
+ /**
1338
+ * Send the commander's REJECTION REASON back into the same Agent.
1339
+ *
1340
+ * The native approval protocol cannot carry prose: `ApprovalService.request()`
1341
+ * resolves one of four closed outcomes, so the reason a commander typed never reached
1342
+ * the worker — it was recorded in history and the tool received a bare `rejected`.
1343
+ * The acceptance report is exactly that: the worker could not know it should narrow
1344
+ * its request and ask again.
1345
+ *
1346
+ * The real channel for prose is the Agent's own inbox. The native approval service
1347
+ * itself uses it for its policy notices
1348
+ * (`agent.inject(createUserMessage({ content, source }))`), and `dsh-user-questions`
1349
+ * uses the same call to steer a late answer. So this method injects ONE user message
1350
+ * describing the rejection.
1351
+ *
1352
+ * What the message says, and what it must never be read as:
1353
+ *
1354
+ * * WHY this one call was rejected, quoted from the decision;
1355
+ * * that the rejection STANDS — the call is not approved, and nothing was widened;
1356
+ * * that this is NOT a new authorization and grants nothing by itself;
1357
+ * * what to do next: rewrite the operation to fit and request approval again.
1358
+ *
1359
+ * The reason is redacted and bounded before it is sent, by the same rules the stored
1360
+ * evidence uses. A send failure is returned as a bounded outcome and NEVER changes the
1361
+ * settlement: `rejected` already happened, and reporting a failed notice as success,
1362
+ * or un-rejecting the call because the notice failed, would both be lies.
1363
+ *
1364
+ * Delivery is tracked per request id so a repeated reject, a retried decision or a
1365
+ * plugin restart cannot deliver the same feedback twice. Only an ACTUAL injection on
1366
+ * the bound Agent counts as delivered; anything else stays `not-sent` and is reported.
1367
+ * @param {object} pending - the request that was just settled.
1368
+ * @param {string} reason - the commander's decision reason (already redacted and bounded).
1369
+ * @returns {{ delivered: boolean, requestId: string, callId: string | null,
1370
+ * messageId: string | null, reason: string }} the outcome, never a rejection.
1371
+ */
1372
+ deliverRejectionFeedback(pending, reason) {
1373
+ const requestId = typeof pending?.requestId === 'string' ? pending.requestId : '';
1374
+ // One delivery per request, ever. A duplicate reject and a restart both land here.
1375
+ if (this.feedbackSent.has(requestId)) {
1376
+ return {
1377
+ delivered: false,
1378
+ requestId,
1379
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1380
+ messageId: this.feedbackSent.get(requestId),
1381
+ reason: 'already-delivered',
1382
+ };
1383
+ }
1384
+ const agent = this.agent;
1385
+ const sessionRefusal = this.liveBindingRefusal();
1386
+ if (agent === null || typeof agent?.inject !== 'function' || sessionRefusal !== null) {
1387
+ return {
1388
+ delivered: false,
1389
+ requestId,
1390
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1391
+ messageId: null,
1392
+ reason: sessionRefusal ?? 'no-injectable-agent',
1393
+ };
1394
+ }
1395
+ const text = rejectionFeedbackText(pending, reason);
1396
+ let message;
1397
+ try {
1398
+ message = this.createMessage(text);
1399
+ } catch (error) {
1400
+ return {
1401
+ delivered: false,
1402
+ requestId,
1403
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1404
+ messageId: null,
1405
+ reason: typeof error?.code === 'string' ? error.code : 'message-unavailable',
1406
+ };
1407
+ }
1408
+ try {
1409
+ agent.inject(message);
1410
+ } catch (error) {
1411
+ // The rejection is already in force. This only reports that the NOTE did not reach
1412
+ // the worker, which is a different, smaller fact than the decision itself.
1413
+ this.logger?.warn?.('dsh-delegate: the rejection reason could not be delivered', String(error?.code ?? ''));
1414
+ return {
1415
+ delivered: false,
1416
+ requestId,
1417
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1418
+ messageId: null,
1419
+ reason: 'inject-failed',
1420
+ };
1421
+ }
1422
+ const messageId = typeof message?.id === 'string' ? message.id : null;
1423
+ this.feedbackSent.set(requestId, messageId);
1424
+ return {
1425
+ delivered: true,
1426
+ requestId,
1427
+ callId: typeof pending?.callId === 'string' ? pending.callId : null,
1428
+ messageId,
1429
+ reason: 'delivered',
1430
+ // The record states what was said, so "feedback happened" is auditable rather than
1431
+ // claimed: the exact text is the evidence.
1432
+ text,
1433
+ };
1434
+ }
1435
+
1246
1436
  /**
1247
1437
  * Clear the pending slot of an answered request.
1248
1438
  * @param {object} pending - pending record.
@@ -0,0 +1,162 @@
1
+ // Which native `ask_user_question` call a pending question belongs to.
2
+ //
3
+ // An answer is delivered by RESUMING the paused tool call, so the bridge must know exactly
4
+ // which call that is. The rule is deliberately narrow, and it never searches for "some"
5
+ // call:
6
+ //
7
+ // 1. the request's own `wait.callId` is the declared identity (the native tool sets it);
8
+ // 2. that id must be found in the Session log as a `tool/call` whose name is
9
+ // `ask_user_question`;
10
+ // 3. it must be the NEWEST such call: a repeated id is the live one, an older duplicate
11
+ // is a finished turn;
12
+ // 4. it must have NO `tool/result` after it — a call that already returned is history, and
13
+ // an answer delivered to it would resume nothing;
14
+ // 5. its turn must still be the OPEN turn. A call whose turn closed can only arrive as a
15
+ // new turn, so an answer cannot be replayed onto it.
16
+ //
17
+ // A legacy request that carries no `wait` at all is bound only when the open turn holds
18
+ // exactly ONE live `ask_user_question` call: with one candidate the identity is proven, and
19
+ // with two it is ambiguous, which is a refusal rather than a guess.
20
+
21
+ /** The tool whose calls a question may bind to. */
22
+ export const QUESTION_TOOL_NAME = 'ask_user_question';
23
+
24
+ /**
25
+ * Find one `tool/call` record by id, newest first.
26
+ * @param {object} session - Session with `seq` and `eventAt`.
27
+ * @param {string} callId - the id to find.
28
+ * @returns {{ event: object, index: number } | null} the newest match.
29
+ */
30
+ function findCall(session, callId) {
31
+ for (let index = session.seq - 1; index >= 0; index -= 1) {
32
+ const event = session.eventAt(index);
33
+ if (event === null || typeof event !== 'object' || event.type !== 'tool/call') continue;
34
+ if (event.data?.callId === callId) return { event, index };
35
+ }
36
+ return null;
37
+ }
38
+
39
+ /**
40
+ * The index of the last `turn/start` with no `turn/end` after it, or `null`.
41
+ * @param {object} session - Session with `seq` and `eventAt`.
42
+ * @returns {number | null} the open turn's start offset.
43
+ */
44
+ function openTurnStart(session) {
45
+ for (let index = session.seq - 1; index >= 0; index -= 1) {
46
+ const event = session.eventAt(index);
47
+ if (event === null || typeof event !== 'object') continue;
48
+ if (event.type === 'turn/end') return null;
49
+ if (event.type === 'turn/start') return index;
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /**
55
+ * The tool-call id one `tool/result` event answers.
56
+ *
57
+ * DSH records the id under `data.message.toolCallId` (the result message carries the call it
58
+ * belongs to); older/synthetic logs put it directly on `data.callId`. BOTH are read, because a
59
+ * matcher that only knew one shape would report "no result yet" for a call that already
60
+ * returned — and an answer would then be delivered to a finished call.
61
+ * @param {object} event - a `tool/result` event.
62
+ * @returns {string | null} the call id, or null when the event names none.
63
+ */
64
+ function resultCallId(event) {
65
+ const nested = event?.data?.message?.toolCallId;
66
+ if (typeof nested === 'string' && nested !== '') return nested;
67
+ const flat = event?.data?.callId;
68
+ if (typeof flat === 'string' && flat !== '') return flat;
69
+ return null;
70
+ }
71
+
72
+ /**
73
+ * Whether a call at one offset has already produced a `tool/result`.
74
+ * @param {object} session - Session with `seq` and `eventAt`.
75
+ * @param {string} callId - the call id.
76
+ * @param {number} fromIndex - the call's own offset.
77
+ * @returns {boolean} true when a result was recorded after it.
78
+ */
79
+ function hasResult(session, callId, fromIndex) {
80
+ for (let index = fromIndex + 1; index < session.seq; index += 1) {
81
+ const event = session.eventAt(index);
82
+ if (event === null || typeof event !== 'object' || event.type !== 'tool/result') continue;
83
+ if (resultCallId(event) === callId) return true;
84
+ }
85
+ return false;
86
+ }
87
+
88
+ /**
89
+ * The live `ask_user_question` calls of the OPEN turn, oldest first.
90
+ * @param {object} session - Session with `seq` and `eventAt`.
91
+ * @param {number} turnStart - the open turn's start offset.
92
+ * @returns {{ callId: string, seq: number, turn: number | null }[]} live calls.
93
+ */
94
+ function liveCallsOfTurn(session, turnStart) {
95
+ const calls = [];
96
+ for (let index = turnStart; index < session.seq; index += 1) {
97
+ const event = session.eventAt(index);
98
+ if (event === null || typeof event !== 'object' || event.type !== 'tool/call') continue;
99
+ const name = event.data?.name;
100
+ const callId = event.data?.callId;
101
+ if (name !== QUESTION_TOOL_NAME || typeof callId !== 'string' || callId === '') continue;
102
+ if (hasResult(session, callId, index)) continue;
103
+ calls.push({
104
+ callId,
105
+ seq: index,
106
+ turn: typeof event.data?.turn === 'number' ? event.data.turn : null,
107
+ });
108
+ }
109
+ return calls;
110
+ }
111
+
112
+ /**
113
+ * Resolve the ONE native call a question belongs to.
114
+ * @param {object} request - `session`, `declaredCallId` (from `request.wait.callId`), `toolName`.
115
+ * @returns {{ ok: true, callId: string, seq: number, turn: number | null }
116
+ * | { ok: false, detail: string }} the binding, or why it is impossible.
117
+ */
118
+ export function QUESTION_CALL_BINDING(request) {
119
+ const session = request?.session ?? null;
120
+ if (session === null || typeof session !== 'object'
121
+ || typeof session.eventAt !== 'function' || !Number.isInteger(session.seq)) {
122
+ return { ok: false, detail: 'the asking session keeps no readable log' };
123
+ }
124
+ const turnStart = openTurnStart(session);
125
+ if (turnStart === null) {
126
+ return { ok: false, detail: 'no turn is open, so the question belongs to no live call' };
127
+ }
128
+ const declared = typeof request?.declaredCallId === 'string' && request.declaredCallId !== ''
129
+ ? request.declaredCallId
130
+ : null;
131
+ if (declared !== null) {
132
+ const found = findCall(session, declared);
133
+ if (found === null) return { ok: false, detail: 'the declared call id is not in the session log' };
134
+ const name = found.event.data?.name;
135
+ if (name !== QUESTION_TOOL_NAME) {
136
+ return { ok: false, detail: `the declared call is a ${String(name)} call, not a question` };
137
+ }
138
+ if (found.index < turnStart) {
139
+ return { ok: false, detail: 'the declared call belongs to an earlier turn' };
140
+ }
141
+ if (hasResult(session, declared, found.index)) {
142
+ return { ok: false, detail: 'the declared call already produced a result' };
143
+ }
144
+ return {
145
+ ok: true,
146
+ callId: declared,
147
+ seq: found.index,
148
+ turn: typeof found.event.data?.turn === 'number' ? found.event.data.turn : null,
149
+ };
150
+ }
151
+ // A legacy request names no call. It is bound only when the open turn holds exactly ONE
152
+ // live question call: two candidates make the identity ambiguous, and a guess could
153
+ // resume the wrong operation.
154
+ const candidates = liveCallsOfTurn(session, turnStart);
155
+ if (candidates.length === 0) {
156
+ return { ok: false, detail: 'the open turn holds no live question call' };
157
+ }
158
+ if (candidates.length > 1) {
159
+ return { ok: false, detail: `the open turn holds ${candidates.length} live question calls, so the binding is ambiguous` };
160
+ }
161
+ return { ok: true, ...candidates[0] };
162
+ }