dsh-taskbridge 1.4.1 → 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 (41) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/README.md +10 -19
  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 +6 -3
  9. package/docs/conversation-placement.md +44 -7
  10. package/docs/plugin-market.md +2 -2
  11. package/docs/redaction-contract.md +47 -4
  12. package/docs/releases/1.4.2.zh.md +23 -0
  13. package/docs/releases/1.5.0-token-benchmark.zh.md +73 -0
  14. package/docs/releases/1.5.0.zh.md +51 -0
  15. package/docs/runtime-compatibility.md +30 -51
  16. package/docs/silent-wait.md +84 -0
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +154 -17
  19. package/lib/client.js +3 -0
  20. package/package.json +11 -9
  21. package/src/client/api.js +26 -0
  22. package/src/codex/installer.js +18 -0
  23. package/src/config/redact.js +72 -11
  24. package/src/http/execution-plane.js +76 -5
  25. package/src/index.d.ts +285 -0
  26. package/src/index.js +72 -2
  27. package/src/jobs/activity.js +10 -0
  28. package/src/jobs/continuation-identity.js +278 -0
  29. package/src/jobs/engine.js +326 -36
  30. package/src/jobs/history.js +53 -0
  31. package/src/mcp/continuation.js +317 -0
  32. package/src/mcp/metrics.js +343 -0
  33. package/src/mcp/server.js +1079 -47
  34. package/src/mcp/wait.js +266 -74
  35. package/src/review/prompts.js +145 -126
  36. package/src/runtime/agent-runner.js +165 -0
  37. package/src/runtime/permissions.js +192 -2
  38. package/src/runtime/question-call.js +162 -0
  39. package/src/runtime/questions.js +909 -0
  40. package/src/runtime/session-placement.js +78 -5
  41. package/src/version.js +99 -0
@@ -0,0 +1,317 @@
1
+ // The two predicates the post-decision continuation needs — and nothing else.
2
+ //
3
+ // `delegate_permission_decide({ waitAfterDecision: true })` answers in the SAME shape a
4
+ // `delegate_wait` answers in, because the commander's next decision is the same decision
5
+ // either way. That means the continuation must be THE wait loop (`./wait.js`): the same
6
+ // 25-second internal observation, the same default deadline, the same heartbeat handling,
7
+ // the same `interrupted` classification and the same bounded deadline semantics. This
8
+ // module therefore contains no loop, no timeout and no reason vocabulary of its own; it
9
+ // supplies only the two facts the shared loop cannot know:
10
+ //
11
+ // 1. **Rollover.** After a decision the engine may still publish the settled request in
12
+ // `task.permission.pending` until the paused native call actually resumes (the
13
+ // bridge's `onSettled` fires when the call continues, not when the decision is made).
14
+ // A loop that answered that would present the commander's own decision back as a new
15
+ // question. {@link decidedRequestMatcher} is the predicate the shared loop uses to
16
+ // keep waiting, and it matches on the FULL identity — `requestId` AND `fingerprint` —
17
+ // so a new request id, or the same id with a changed operation, is never inherited.
18
+ //
19
+ // 2. **Receipt evidence.** {@link decisionReceipt} reads the harness's answer to the
20
+ // decision and states exactly what can be proven about it, including the case where
21
+ // the transport failed and nobody can know whether it was applied.
22
+
23
+ /**
24
+ * The pending operation a wait-shaped answer carries, if any.
25
+ * @param {object | null | undefined} observation - an observation.
26
+ * @returns {object | null} the pending operation.
27
+ */
28
+ export function pendingOperationOf(observation) {
29
+ const block = observation?.permission;
30
+ if (block === null || typeof block !== 'object') return null;
31
+ const operation = block.pending !== undefined ? block.pending : block;
32
+ if (operation === null || typeof operation !== 'object' || Array.isArray(operation)) return null;
33
+ return operation;
34
+ }
35
+
36
+ /**
37
+ * Build the predicate that decides whether an observation describes the request this call
38
+ * already decided.
39
+ *
40
+ * The match requires BOTH the request id and the fingerprint. That is the whole rule:
41
+ *
42
+ * * same id, same fingerprint → the settled request still in its slot → keep waiting;
43
+ * * a different request id → a NEW question → answered immediately;
44
+ * * same id, different fingerprint → the operation changed → a NEW question, because a
45
+ * decision is bound to one exact operation and inheriting it would grant an operation
46
+ * the commander never reviewed.
47
+ *
48
+ * Cost asymmetry: wrongly treating a settled request as new costs one host turn; wrongly
49
+ * treating a new request as settled would leave a worker paused with nothing reported. So
50
+ * every field is required to match, and nothing is assumed.
51
+ * @param {{ requestId?: string | null, fingerprint?: string | null }} receipt - the decision.
52
+ * @returns {(observation: object) => boolean} predicate for the shared wait loop.
53
+ */
54
+ export function decidedRequestMatcher(receipt) {
55
+ const requestId = typeof receipt?.requestId === 'string' && receipt.requestId !== '' ? receipt.requestId : null;
56
+ const fingerprint = typeof receipt?.fingerprint === 'string' && receipt.fingerprint !== ''
57
+ ? receipt.fingerprint
58
+ : null;
59
+ if (requestId === null || fingerprint === null) {
60
+ // Without BOTH halves of the identity nothing can be proven to be the decided request,
61
+ // so nothing is skipped: a request already settled is refused by the engine as
62
+ // `PERMISSION_REQUEST_NOT_PENDING`, which is a refusal the host can act on.
63
+ return () => false;
64
+ }
65
+ return (observation) => {
66
+ const operation = pendingOperationOf(observation);
67
+ if (operation === null) return false;
68
+ return operation.requestId === requestId && operation.fingerprint === fingerprint;
69
+ };
70
+ }
71
+
72
+ /**
73
+ * The ONE settled state that means "this request was decided".
74
+ *
75
+ * `expired`, `cancelled` and `unavailable` are settled records too, but none of them is a
76
+ * decision this call applied — an `expired` request carrying a stale `allowed-once` outcome
77
+ * is exactly the shape that must never read as confirmed.
78
+ */
79
+ const CONFIRMED_STATE = 'decided';
80
+
81
+ /** The closed native outcomes a settled allow/reject record can carry. */
82
+ const SETTLED_OUTCOMES = Object.freeze(['allowed-once', 'rejected', 'cancelled', 'unavailable']);
83
+
84
+ /**
85
+ * The verification checks an `allowed-once` must report as TRUE to confirm the allow.
86
+ *
87
+ * These are the four claims the harness makes when it grants one call: the caller quoted the
88
+ * fingerprint, the arguments were complete, the operation was re-read from the Session log,
89
+ * and the turn was still open. A record that reports any of them false is not evidence for an
90
+ * allow, whatever its `outcome` says. A `reject` needs none of them.
91
+ */
92
+ const VERIFIED_REQUIRED = Object.freeze(['fingerprintQuoted', 'argumentsComplete', 'callReread', 'turnOpen']);
93
+
94
+ const asString = (value) => (typeof value === 'string' && value !== '' ? value : null);
95
+
96
+ /**
97
+ * What can honestly be said about one decision, from the harness's own answer.
98
+ *
99
+ * The ONLY thing that makes a decision `applied` is a permission answer whose own fields
100
+ * confirm it, and the check is deliberately strict because a false `applied: true` is the
101
+ * worst outcome this tool can produce: it tells a commander an authorization is in force
102
+ * when it is not (or one operation when another was settled). The real permission route
103
+ * answers:
104
+ *
105
+ * ```js
106
+ * { ok: true,
107
+ * task: { taskId, ... },
108
+ * permission: { taskId, requestId, fingerprint, state: 'decided',
109
+ * outcome: 'allowed-once' | 'rejected', verified?, grant?, decision? } }
110
+ * ```
111
+ *
112
+ * `decision` is sometimes `null` in the real bridge, so it is NOT required; the settled
113
+ * `outcome` is. `verified`/`grant` exist only for an `allowed-once`, so a `reject` is never
114
+ * required to have them.
115
+ *
116
+ * Two outcomes, and the difference between them is the point:
117
+ *
118
+ * * **applied** — the answer is `ok: true`, names the SAME task (both task ids, when both
119
+ * appear, must agree), the SAME request and the SAME operation fingerprint the decision
120
+ * was bound to, is in state `decided`, and its `outcome` matches the decision
121
+ * (`allowed-once` for allow-once, `rejected` for reject). An allow additionally needs
122
+ * every {@link VERIFIED_REQUIRED} check to be true. Only then is the decision in force.
123
+ * * **unknown** — the call failed before an answer existed (transport, timeout, malformed
124
+ * body), or the answer is `ok: false`, or it lacks the evidence above, or its identity
125
+ * CONTRADICTS the request that was decided. Nobody can say whether the decision applied,
126
+ * so it is never claimed, never continued and never resent automatically.
127
+ * * **refused** — the harness's own refusal code: the decision was definitely not applied.
128
+ *
129
+ * A QUOTED fingerprint must be matched by evidence. The caller's value is never silently
130
+ * replaced by a conflicting backend one, and an answer that omits it cannot confirm that
131
+ * operation. A `reject` that quoted no fingerprint is not required to produce one.
132
+ * @param {object} options - `taskId`, `requestId`, `decision`, `fingerprint` (the quoted one,
133
+ * or null), `answer` (the harness answer, or null), `error` (the thrown failure, or null).
134
+ * @returns {{ applied: boolean | null, confirmation: 'applied' | 'unknown' | 'refused',
135
+ * taskId: string | null, requestId: string | null, decision: 'allow-once' | 'reject' | null,
136
+ * fingerprint: string | null, outcome?: string, verified?: object, grant?: object,
137
+ * decidedAt?: number, reason?: string, error?: object, evidence?: object }} the receipt fields.
138
+ */
139
+ export function decisionReceipt(options) {
140
+ const error = options.error ?? null;
141
+ const answer = options.answer ?? null;
142
+ const settled = answer?.permission ?? null;
143
+ const answerTask = answer?.task ?? null;
144
+ const requestedTaskId = asString(options.taskId);
145
+ const requestedRequestId = asString(options.requestId);
146
+ const quotedFingerprint = asString(options.fingerprint);
147
+ const decision = options.decision === 'allow-once' || options.decision === 'reject'
148
+ ? options.decision
149
+ : null;
150
+
151
+ /** The identity the receipt may safely publish: only values the caller itself supplied. */
152
+ const identity = {
153
+ taskId: requestedTaskId,
154
+ requestId: requestedRequestId,
155
+ decision,
156
+ fingerprint: quotedFingerprint,
157
+ };
158
+
159
+ /** Build an UNCONFIRMED receipt that keeps the caller's own identity and says why. */
160
+ const unconfirmed = (reason, extra = {}) => ({
161
+ ...identity,
162
+ // Never `false`: "not applied" would be a fact nobody established.
163
+ applied: null,
164
+ confirmation: 'unknown',
165
+ reason,
166
+ ...extra,
167
+ });
168
+
169
+ if (error !== null) {
170
+ const code = typeof error.code === 'string' ? error.code : 'MCP_CALL_FAILED';
171
+ // A refusal the harness produced is a fact about the decision; every other failure
172
+ // happened before an answer existed, so the outcome is genuinely unknown.
173
+ if (options.refusedByHarness === true) {
174
+ return {
175
+ ...identity,
176
+ applied: false,
177
+ confirmation: 'refused',
178
+ error: { code, message: 'the harness refused this decision' },
179
+ };
180
+ }
181
+ return unconfirmed(
182
+ 'the decision call did not produce a harness answer, so whether it was applied is unknown; '
183
+ + 'read the task\'s real state with delegate_result before deciding whether to send it again',
184
+ { error: { code, message: 'the decision could not be confirmed' } },
185
+ );
186
+ }
187
+
188
+ // ---- What the answer itself proves -------------------------------------------------
189
+ if (answer === null || typeof answer !== 'object' || answer.ok !== true) {
190
+ return unconfirmed('the harness answer was not ok, so the decision cannot be confirmed as applied');
191
+ }
192
+ if (settled === null || typeof settled !== 'object' || Array.isArray(settled)) {
193
+ return unconfirmed('the harness answer carried no settled permission record to confirm the decision');
194
+ }
195
+ const settledTaskId = asString(settled.taskId);
196
+ const outerTaskId = asString(answerTask?.taskId);
197
+ const answerRequestId = asString(settled.requestId);
198
+ const answerFingerprint = asString(settled.fingerprint);
199
+ const answerState = asString(settled.state);
200
+ const answerOutcome = asString(settled.outcome);
201
+ if (answerRequestId === null || answerState === null || answerOutcome === null) {
202
+ return unconfirmed('the harness answer did not carry the identity and outcome needed to confirm the decision', {
203
+ evidence: { taskId: settledTaskId ?? outerTaskId, requestId: answerRequestId, state: answerState, outcome: answerOutcome },
204
+ });
205
+ }
206
+ // Identity must MATCH what was decided. A different task, request or operation is a
207
+ // CONTRADICTION: the answer describes something this call did not decide.
208
+ //
209
+ // BOTH task ids are checked when both appear, and they must ALSO agree with each other. A
210
+ // matching outer `task.taskId` cannot vouch for a settled record that names another task:
211
+ // the settled record is the thing being confirmed, so an internal disagreement means the
212
+ // answer is not one coherent settlement of this task.
213
+ if (settledTaskId !== null && outerTaskId !== null && settledTaskId !== outerTaskId) {
214
+ return unconfirmed('the harness answer contradicted itself: its task and its settled record name different tasks', {
215
+ evidence: { answeredTaskId: settledTaskId, surroundingTaskId: outerTaskId },
216
+ });
217
+ }
218
+ const answerTaskId = settledTaskId ?? outerTaskId;
219
+ if (answerTaskId === null) {
220
+ return unconfirmed('the harness answer did not name the task it settled', {
221
+ evidence: { taskId: null },
222
+ });
223
+ }
224
+ if (requestedTaskId !== null && answerTaskId !== requestedTaskId) {
225
+ return unconfirmed('the harness confirmed a DIFFERENT task than the one this decision named', {
226
+ evidence: { answeredTaskId: answerTaskId },
227
+ });
228
+ }
229
+ if (requestedRequestId !== null && answerRequestId !== requestedRequestId) {
230
+ return unconfirmed('the harness confirmed a DIFFERENT request than the one this decision named', {
231
+ evidence: { answeredRequestId: answerRequestId },
232
+ });
233
+ }
234
+ // The operation is part of the identity. A QUOTED fingerprint must be matched by evidence:
235
+ // an answer that omits it cannot confirm that THIS operation was settled, and a conflicting
236
+ // backend value is never allowed to replace the quoted one.
237
+ if (quotedFingerprint !== null) {
238
+ if (answerFingerprint === null) {
239
+ return unconfirmed('the harness settled without reporting the operation fingerprint this decision quoted', {
240
+ evidence: { answeredFingerprint: null },
241
+ });
242
+ }
243
+ if (answerFingerprint !== quotedFingerprint) {
244
+ return unconfirmed('the harness settled a DIFFERENT operation than the fingerprint this decision quoted', {
245
+ evidence: { answeredFingerprint: answerFingerprint },
246
+ });
247
+ }
248
+ }
249
+ // Only `decided` is a settled DECISION. `expired`, `cancelled` and `unavailable` are also
250
+ // settled records, but none of them means "this decision was applied".
251
+ if (answerState !== CONFIRMED_STATE) {
252
+ return unconfirmed(`the harness reported state ${JSON.stringify(answerState)}, which is not a decided request`, {
253
+ evidence: { state: answerState },
254
+ });
255
+ }
256
+ if (!SETTLED_OUTCOMES.includes(answerOutcome)) {
257
+ return unconfirmed(`the harness reported outcome ${JSON.stringify(answerOutcome)}, which is not a settled decision`, {
258
+ evidence: { outcome: answerOutcome },
259
+ });
260
+ }
261
+ // The outcome must be the one this decision asked for. `allowed-once` is the only grant,
262
+ // and a reject must read `rejected`; anything else is not this decision's confirmation.
263
+ const expectedOutcome = decision === 'allow-once' ? 'allowed-once' : decision === 'reject' ? 'rejected' : null;
264
+ if (expectedOutcome === null) {
265
+ return unconfirmed('the decision argument was not a recognized decision');
266
+ }
267
+ if (answerOutcome !== expectedOutcome) {
268
+ return unconfirmed(
269
+ `the harness settled ${JSON.stringify(answerOutcome)}, not the ${JSON.stringify(expectedOutcome)} this decision asked for`,
270
+ { evidence: { outcome: answerOutcome } },
271
+ );
272
+ }
273
+ // An allow must be backed by the checks it claims, and every required one must be TRUE: a
274
+ // record whose own verification says the fingerprint was not quoted, the arguments were not
275
+ // complete, the call was not re-read or the turn was not open is not evidence for an allow.
276
+ // A reject needs none of them.
277
+ if (decision === 'allow-once') {
278
+ const verified = settled.verified;
279
+ if (verified === null || typeof verified !== 'object' || Array.isArray(verified)) {
280
+ return unconfirmed('an allowed-once was reported without the verification evidence an allow requires');
281
+ }
282
+ const failed = VERIFIED_REQUIRED.filter((key) => verified[key] !== true);
283
+ if (failed.length > 0) {
284
+ return unconfirmed(
285
+ `an allowed-once reported verification that does not hold (${failed.join(', ')}), so it cannot confirm the allow`,
286
+ { evidence: { unverified: failed } },
287
+ );
288
+ }
289
+ }
290
+ return {
291
+ taskId: answerTaskId,
292
+ requestId: answerRequestId,
293
+ decision,
294
+ // The confirmed operation. It equals the quoted fingerprint here — a mismatch returned
295
+ // above — so publishing the harness's own value is a restatement, not a substitution.
296
+ fingerprint: answerFingerprint ?? quotedFingerprint,
297
+ applied: true,
298
+ confirmation: 'applied',
299
+ outcome: answerOutcome,
300
+ ...(settled.verified !== undefined ? { verified: settled.verified } : {}),
301
+ ...(settled.decidedAt !== undefined ? { decidedAt: settled.decidedAt } : {}),
302
+ ...(settled.grant !== undefined ? { grant: settled.grant } : {}),
303
+ // Whether the rejection reason reached the worker, stated as the SHORT fact only. The
304
+ // note text is the worker's own message and is stored in history; repeating it here
305
+ // would multiply the receipt for no gain, so only delivery and its reason travel.
306
+ ...(settled.rejectionFeedback !== undefined && settled.rejectionFeedback !== null
307
+ ? {
308
+ rejectionFeedback: {
309
+ delivered: settled.rejectionFeedback.delivered === true,
310
+ reason: typeof settled.rejectionFeedback.reason === 'string'
311
+ ? settled.rejectionFeedback.reason
312
+ : null,
313
+ },
314
+ }
315
+ : {}),
316
+ };
317
+ }
@@ -0,0 +1,343 @@
1
+ // Minimal, honest accounting for the MCP surface.
2
+ //
3
+ // What this module is, in one sentence: a bounded census of what this MCP PROCESS did —
4
+ // which tools were exercised, how many waits it ran and why they returned, how many
5
+ // per-call permission decisions were applied, and how many bytes of tool text it handed
6
+ // back — with each post-decision wait tied to the decision that led into it.
7
+ //
8
+ // What it deliberately is NOT:
9
+ //
10
+ // * **Not a wake-up counter.** `delegate_wait` is one MCP call the host chose to make; a
11
+ // count of calls, observations or returns says how much the PROGRAM waited, never how
12
+ // many times a model was woken. The host's own model turns, token usage and cost are
13
+ // not visible to this process at all, so they are reported as `not-integrated` rather
14
+ // than as `0` — a zero would be a measurement this code never took.
15
+ // * **Not a content store.** Every counter is a number, a duration, a closed-vocabulary
16
+ // reason or a byte size. No tool arguments, no reasoning text, no answer body and no
17
+ // credential is retained, so no projection of this module can leak one.
18
+ // * **Not persistent.** The census lives for the life of the MCP process and is reported
19
+ // through one read-only call and the exit diagnostics line.
20
+ //
21
+ // Two counting rules are load-bearing:
22
+ //
23
+ // 1. **Totals are cumulative; the sample lists are bounded.** The `recent*` arrays are
24
+ // the last N entries so a caller can audit individual waits. Every total is summed at
25
+ // record time, so a long session's numbers never shrink when the sample rotates.
26
+ // 2. **Byte counts are of the FINAL tool text.** They are measured by the server on the
27
+ // bounded, redacted `content[0].text` with `Buffer.byteLength(..., 'utf8')`, after
28
+ // `boundedJson` has decided what the host receives — never `String#length`, which
29
+ // counts UTF-16 units and would misreport Chinese text and emoji, and never a size the
30
+ // answer carries about itself.
31
+
32
+ /** The closed vocabulary of what one wait returned, mirrored from the wait loop. */
33
+ export const METRIC_WAIT_REASONS = Object.freeze([
34
+ 'attention', 'permission', 'question', 'ready', 'failed', 'cancelled', 'interrupted', 'wait-limit', 'refused',
35
+ ]);
36
+
37
+ /** Outcomes of one decision, as the receipt states them. */
38
+ export const METRIC_DECISION_STATES = Object.freeze(['applied', 'unknown', 'refused']);
39
+
40
+ /**
41
+ * The decision kind that records an ordinary QUESTION answer.
42
+ *
43
+ * Kept apart from `allow-once`/`reject` because answering a question authorizes nothing:
44
+ * counting it in the permission buckets would report a refusal that never happened, or an
45
+ * authorization that does not exist.
46
+ */
47
+ export const QUESTION_ANSWER_KIND = 'question-answer';
48
+
49
+ /**
50
+ * Facts this process cannot observe, and therefore must not report as zero.
51
+ *
52
+ * The host model's own turns, token usage and cost happen in the host process. This one
53
+ * only ever sees the tool calls the host decided to make.
54
+ */
55
+ export const NOT_INTEGRATED = 'not-integrated';
56
+
57
+ /**
58
+ * Create the census for one MCP server instance.
59
+ *
60
+ * Every entry point is defensive: this module is fed by the server's hot paths, and a
61
+ * malformed value must degrade one counter rather than throw inside an answer path.
62
+ * @param {object} [options] - `now` (clock seam), `limit` (how many samples to keep).
63
+ * @returns {object} census with `recordToolCall`, `recordReturn`, `recordWait`,
64
+ * `recordDecision`, `snapshot`, `diagnosticsLine`.
65
+ */
66
+ export function createCallMetrics(options = {}) {
67
+ const now = typeof options.now === 'function' ? options.now : () => Date.now();
68
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 64;
69
+
70
+ /** Cumulative tool calls by name. */
71
+ const toolCalls = new Map();
72
+ /** Cumulative wait returns by reason. */
73
+ const waitReturns = new Map();
74
+ /** Cumulative decision outcomes by state, and by decision kind for the applied ones. */
75
+ const decisionStates = new Map();
76
+ const appliedDecisions = new Map();
77
+ /** Question answers, kept out of the permission buckets. */
78
+ const questionAnswerStates = new Map();
79
+
80
+ /** Cumulative totals — summed at record time, never derived from the samples. */
81
+ let returns = 0;
82
+ let returnBytes = 0;
83
+ let unmeasuredReturns = 0;
84
+ let waits = 0;
85
+ let waitedTotalMs = 0;
86
+ let waitObservations = 0;
87
+ let decisions = 0;
88
+ let waitsAfterDecisions = 0;
89
+ let waitQuestionsAnswered = 0;
90
+ let questionAnswers = 0;
91
+
92
+ /** Bounded audit samples, newest last. */
93
+ const recentWaits = [];
94
+ const recentDecisions = [];
95
+
96
+ /**
97
+ * Count one value in a bounded map.
98
+ * @param {Map<string, number>} map - counter map.
99
+ * @param {string} key - closed-vocabulary key.
100
+ * @returns {void}
101
+ */
102
+ const bump = (map, key) => {
103
+ map.set(key, (map.get(key) ?? 0) + 1);
104
+ };
105
+
106
+ /**
107
+ * A non-negative integer, or 0.
108
+ * @param {unknown} value - candidate.
109
+ * @returns {number} bounded count.
110
+ */
111
+ const count = (value) => (Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0);
112
+
113
+ return {
114
+ /**
115
+ * Count one tool invocation, whatever its outcome.
116
+ * @param {string} tool - tool name.
117
+ * @returns {void}
118
+ */
119
+ recordToolCall(tool) {
120
+ if (typeof tool === 'string' && tool !== '') bump(toolCalls, tool);
121
+ },
122
+
123
+ /**
124
+ * Count one tool TEXT returned to the host, and its size.
125
+ *
126
+ * Called exactly once per `tools/call`, from the server, with the final
127
+ * `content[0].text` — the bounded, redacted text the client parses. `null` means no
128
+ * text was produced at all (which is a fact worth counting, not zero bytes).
129
+ * @param {string | null} text - the answer text, or null.
130
+ * @returns {void}
131
+ */
132
+ recordReturn(text) {
133
+ returns += 1;
134
+ if (typeof text !== 'string') {
135
+ // Stated as unmeasured rather than counted as 0 bytes: "no text" and "empty text"
136
+ // are different, and neither is a size this code guessed.
137
+ unmeasuredReturns += 1;
138
+ return;
139
+ }
140
+ let bytes;
141
+ try {
142
+ bytes = Buffer.byteLength(text, 'utf8');
143
+ } catch {
144
+ // A lone surrogate cannot be encoded; the text is not a size this run can state.
145
+ unmeasuredReturns += 1;
146
+ return;
147
+ }
148
+ returnBytes += bytes;
149
+ },
150
+
151
+ /**
152
+ * Record one wait's own accounting.
153
+ *
154
+ * One flat summary shape, whether the wait followed a decision or not: the wait loop
155
+ * reports `waitId`/`afterDecisionId`/`taskId`/`reason`/`durationMs`/counts and nothing
156
+ * else, so a plain wait and a post-decision wait are counted by the same rule.
157
+ * @param {object} summary - the wait loop's summary.
158
+ * @returns {void}
159
+ */
160
+ recordWait(summary) {
161
+ const known = METRIC_WAIT_REASONS.includes(summary?.reason);
162
+ const reason = known ? summary.reason : 'refused';
163
+ const durationMs = count(summary?.durationMs);
164
+ const waitId = typeof summary?.waitId === 'string' ? summary.waitId : null;
165
+ const afterDecisionId = typeof summary?.afterDecisionId === 'string' ? summary.afterDecisionId : null;
166
+ waits += 1;
167
+ waitedTotalMs += durationMs;
168
+ waitObservations += count(summary?.observationRequests);
169
+ bump(waitReturns, reason);
170
+ if (afterDecisionId !== null) waitsAfterDecisions += 1;
171
+ if (afterDecisionId !== null && reason === 'permission') waitQuestionsAnswered += 1;
172
+ recentWaits.push({
173
+ waitId,
174
+ afterDecisionId,
175
+ taskId: typeof summary?.taskId === 'string' ? summary.taskId : null,
176
+ reason,
177
+ durationMs,
178
+ observationRequests: count(summary?.observationRequests),
179
+ heartbeatsConsumed: count(summary?.heartbeatsConsumed),
180
+ settledRequestObservations: count(summary?.settledRequestObservations),
181
+ waitReturns: count(summary?.waitReturns),
182
+ at: now(),
183
+ });
184
+ if (recentWaits.length > limit) recentWaits.shift();
185
+ },
186
+
187
+ /**
188
+ * Record one ACTUAL permission decision and how far it got.
189
+ *
190
+ * Only the decision path calls this, and only with what the receipt could prove:
191
+ * `applied` for a confirmed decision, `unknown` when the call failed without an answer,
192
+ * `refused` when the harness said no. A refused or unconfirmed attempt is counted as an
193
+ * attempt and never as an authorization.
194
+ *
195
+ * The `applied` field of the recorded sample is the SAME three-valued fact the permission
196
+ * receipt publishes, not a boolean derived from the state label: `true` for `applied`,
197
+ * `false` for `refused`, and `null` for `unknown`. An unconfirmed attempt whose sample
198
+ * said `false` would contradict both the receipt (`applied: null`) and the cumulative
199
+ * `decisions.unknown` counter, and a reader could take "not applied" for a fact nobody
200
+ * established.
201
+ * @param {object} entry - `taskId`, `requestId`, `decision`, `fingerprint`, `applied`,
202
+ * `confirmation`, optional `receiptId`, `at`.
203
+ * @returns {void}
204
+ */
205
+ recordDecision(entry) {
206
+ const state = METRIC_DECISION_STATES.includes(entry?.confirmation)
207
+ ? entry.confirmation
208
+ : (entry?.applied === true ? 'applied' : entry?.applied === false ? 'refused' : 'unknown');
209
+ // A QUESTION ANSWER is not a permission decision: it grants nothing, so it is counted
210
+ // on its own axis and NEVER touches the permission buckets (its verb is neither
211
+ // allow-once nor reject, which would otherwise have been reported as a refusal).
212
+ if (entry?.decision === QUESTION_ANSWER_KIND) {
213
+ questionAnswers += 1;
214
+ bump(questionAnswerStates, state);
215
+ recentDecisions.push({
216
+ receiptId: typeof entry?.receiptId === 'string' ? entry.receiptId : null,
217
+ taskId: typeof entry?.taskId === 'string' ? entry.taskId : null,
218
+ requestId: typeof entry?.requestId === 'string' ? entry.requestId : null,
219
+ decision: QUESTION_ANSWER_KIND,
220
+ fingerprint: null,
221
+ applied: state === 'applied' ? true : state === 'refused' ? false : null,
222
+ state,
223
+ at: Number.isFinite(entry?.at) ? entry.at : now(),
224
+ });
225
+ if (recentDecisions.length > limit) recentDecisions.shift();
226
+ return;
227
+ }
228
+ const decision = entry?.decision === 'allow-once' || entry?.decision === 'reject' ? entry.decision : null;
229
+ decisions += 1;
230
+ bump(decisionStates, state);
231
+ if (state === 'applied' && decision !== null) bump(appliedDecisions, decision);
232
+ recentDecisions.push({
233
+ receiptId: typeof entry?.receiptId === 'string' ? entry.receiptId : null,
234
+ taskId: typeof entry?.taskId === 'string' ? entry.taskId : null,
235
+ requestId: typeof entry?.requestId === 'string' ? entry.requestId : null,
236
+ decision,
237
+ // A digest of the arguments the decision was bound to, never the arguments.
238
+ fingerprint: typeof entry?.fingerprint === 'string' ? entry.fingerprint : null,
239
+ // Three-valued on purpose: unknown is `null`, never `false`.
240
+ applied: state === 'applied' ? true : state === 'refused' ? false : null,
241
+ state,
242
+ at: Number.isFinite(entry?.at) ? entry.at : now(),
243
+ });
244
+ if (recentDecisions.length > limit) recentDecisions.shift();
245
+ },
246
+
247
+ /**
248
+ * The census, as a bounded read-only answer.
249
+ * @returns {object} snapshot with no content and no credentials.
250
+ */
251
+ snapshot() {
252
+ return {
253
+ schemaVersion: 1,
254
+ // What each counter MEANS, stated where the numbers are, so no reader can take
255
+ // `waitReturns` for a number of model wake-ups.
256
+ definitions: {
257
+ mcpToolCalls: 'tool invocations the HOST made on this MCP connection, by tool name',
258
+ returnedText: 'answers this process handed back, and their UTF-8 bytes as handed to the transport',
259
+ waitReturns: 'wait answers by reason; one per host call, NOT a model wake-up',
260
+ waitObservations: 'internal bounded observations issued by the wait loop; program-internal',
261
+ decisions: 'permission decisions by outcome; only `applied` authorized anything',
262
+ questionAnswers: 'ordinary question answers by outcome; they authorize NOTHING',
263
+ waitsAfterDecisions: 'waits that continued inside the same call as a permission decision',
264
+ waitQuestionsAnswered: 'post-decision waits that returned ANOTHER pending permission request',
265
+ hostModelResponses: 'host model turns; cannot be observed from this process',
266
+ hostTokenUsage: 'host token usage; cannot be observed from this process',
267
+ },
268
+ hostObservability: {
269
+ hostModelResponses: NOT_INTEGRATED,
270
+ hostTokenUsage: NOT_INTEGRATED,
271
+ hostCost: NOT_INTEGRATED,
272
+ reason: 'the host model runs in its own process; this server only sees the tool calls it receives',
273
+ },
274
+ tools: Object.fromEntries([...toolCalls.entries()].sort(([a], [b]) => a.localeCompare(b))),
275
+ returnedText: {
276
+ count: returns,
277
+ // Bytes of the final bounded, redacted tool text. Not a delivery receipt: the
278
+ // transport accepted it, which is not the same as the host having read it.
279
+ bytes: returnBytes,
280
+ unmeasured: unmeasuredReturns,
281
+ unit: 'utf8-bytes-of-serialized-tool-text',
282
+ },
283
+ waits: {
284
+ count: waits,
285
+ totalMs: waitedTotalMs,
286
+ observations: waitObservations,
287
+ reasons: Object.fromEntries([...waitReturns.entries()].sort(([a], [b]) => a.localeCompare(b))),
288
+ },
289
+ decisions: {
290
+ // Cumulative, not derived from the samples below: a 65th decision still counts.
291
+ count: decisions,
292
+ applied: decisionStates.get('applied') ?? 0,
293
+ unknown: decisionStates.get('unknown') ?? 0,
294
+ refused: decisionStates.get('refused') ?? 0,
295
+ allowed: appliedDecisions.get('allow-once') ?? 0,
296
+ rejected: appliedDecisions.get('reject') ?? 0,
297
+ },
298
+ // Ordinary question answers, reported apart from permission decisions because they
299
+ // authorize nothing. A question answer is never counted as a refusal.
300
+ questionAnswers: {
301
+ count: questionAnswers,
302
+ applied: questionAnswerStates.get('applied') ?? 0,
303
+ unknown: questionAnswerStates.get('unknown') ?? 0,
304
+ refused: questionAnswerStates.get('refused') ?? 0,
305
+ },
306
+ correlation: {
307
+ waitsAfterDecisions,
308
+ waitQuestionsAnswered,
309
+ // The bounded sample is what makes the counts auditable: one identifier per wait,
310
+ // its reason, its duration, and the decision it followed.
311
+ recentWaits: recentWaits.map((entry) => ({ ...entry })),
312
+ recentDecisions: recentDecisions.map((entry) => ({ ...entry })),
313
+ },
314
+ };
315
+ },
316
+
317
+ /**
318
+ * One bounded line for the exit diagnostics.
319
+ *
320
+ * Counts and byte totals only. Printed when the process ends, so an operator who never
321
+ * called `delegate_metrics` still learns how much this MCP process did — and that the
322
+ * host's own model activity is NOT part of it.
323
+ * @returns {string} single line, no task content.
324
+ */
325
+ diagnosticsLine() {
326
+ const reasons = [...waitReturns.entries()].map(([key, value]) => `${key}=${value}`).join(',') || 'none';
327
+ const total = [...toolCalls.values()].reduce((sum, value) => sum + value, 0);
328
+ return `dsh-delegate-mcp: calls=${total} returns=${returns} returnBytes=${returnBytes} `
329
+ + `waits=${waits} returns(${reasons}) decisions=${decisions} applied=${decisionStates.get('applied') ?? 0} `
330
+ + `waitsAfterDecisions=${waitsAfterDecisions} hostModelResponses=${NOT_INTEGRATED}`;
331
+ },
332
+ };
333
+ }
334
+
335
+ /**
336
+ * Build one stable identifier for a call chain.
337
+ * @param {string} prefix - `wait` or `decision`.
338
+ * @param {number} sequence - per-server counter.
339
+ * @returns {string} identifier.
340
+ */
341
+ export function correlationId(prefix, sequence) {
342
+ return `${prefix}-${Number.isInteger(sequence) ? sequence : 0}-${Date.now().toString(36)}`;
343
+ }