chainlesschain 0.166.145 → 0.166.146

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 (49) hide show
  1. package/README.md +55 -10
  2. package/package.json +2 -2
  3. package/src/assets/linux-subreaper/linux-arm64/manifest.json +1 -1
  4. package/src/assets/linux-subreaper/linux-x64/manifest.json +1 -1
  5. package/src/command-help-index.json +2 -2
  6. package/src/commands/agent.js +20 -1
  7. package/src/commands/mcp-tasks.js +37 -4
  8. package/src/commands/mcp.js +24 -0
  9. package/src/commands/memory.js +131 -7
  10. package/src/data/changelog.json +13 -0
  11. package/src/generated/cc-agent-protocol.schema.json +175 -69
  12. package/src/harness/jsonl-session-store.js +4 -0
  13. package/src/harness/mcp-client.js +273 -48
  14. package/src/harness/prompt-compressor.js +1 -0
  15. package/src/harness/session-index.js +8 -0
  16. package/src/harness/session-list-index.js +2 -0
  17. package/src/lib/agent-session-export.js +19 -0
  18. package/src/lib/app-server/context-memory-notifications.js +11 -2
  19. package/src/lib/app-server/server.js +1 -0
  20. package/src/lib/background-launch-profile.js +38 -6
  21. package/src/lib/context-memory-kernel/local-semantic-source.js +426 -0
  22. package/src/lib/context-memory-kernel/local-semantic-worker.py +109 -0
  23. package/src/lib/context-memory-kernel/memory-service.js +35 -2
  24. package/src/lib/context-memory-kernel/provider-context.js +1 -1
  25. package/src/lib/context-memory-kernel/runtime.js +40 -0
  26. package/src/lib/evolution/evolution-artifact-ports.js +36 -1
  27. package/src/lib/formal-budget-authority.js +56 -3
  28. package/src/lib/formal-budget-contract.js +90 -5
  29. package/src/lib/mcp-client.js +1 -0
  30. package/src/lib/mcp-stateless-protocol.js +158 -0
  31. package/src/lib/mcp-task-continuation-contract.js +129 -0
  32. package/src/lib/mcp-task-continuation.js +147 -0
  33. package/src/lib/mcp-task-journal-projection.js +49 -4
  34. package/src/lib/mcp-task-runtime.js +148 -1
  35. package/src/lib/mcp-tasks.js +24 -0
  36. package/src/lib/session-host-snapshot.js +31 -0
  37. package/src/lib/session-input-lifecycle.js +147 -0
  38. package/src/lib/session-input-receipt.js +64 -0
  39. package/src/lib/session-message-provenance.js +6 -5
  40. package/src/lib/session-model-usage-recovery.js +115 -0
  41. package/src/lib/session-transcript-history.js +3 -0
  42. package/src/lib/session-transcript-structure.js +8 -1
  43. package/src/lib/storage-failure-cause-codes.js +79 -0
  44. package/src/repl/agent-repl.js +348 -23
  45. package/src/runtime/agent-core.js +29 -11
  46. package/src/runtime/headless-runner.js +1 -0
  47. package/src/runtime/headless-stream.js +40 -33
  48. package/src/runtime/mcp-config.js +5 -3
  49. package/src/runtime/policies/agent-policy.js +1 -0
@@ -305,7 +305,7 @@ export async function prepareCanonicalProviderContext(
305
305
  });
306
306
  options.signal?.throwIfAborted();
307
307
  const recall = recallEnabled
308
- ? await runtime.kernel.recallMemory(
308
+ ? await runtime.recallMemory(
309
309
  {
310
310
  query,
311
311
  sink,
@@ -1,3 +1,4 @@
1
+ import { createLocalSemanticSource } from "./local-semantic-source.js";
1
2
  import { ContextMemoryKernel } from "@chainlesschain/context-memory-kernel";
2
3
  import { SegmentedMemoryPort } from "./segmented-memory-port.js";
3
4
  import { JsonlSessionContextPort } from "./jsonl-session-context-port.js";
@@ -56,7 +57,46 @@ export function createCliContextMemoryRuntime(options = {}) {
56
57
  ...(options.randomUUID ? { randomUUID: options.randomUUID } : {}),
57
58
  purgePorts,
58
59
  });
60
+ const semanticSource = createLocalSemanticSource({
61
+ memoryPort,
62
+ env: options.env || process.env,
63
+ clock: options.clock || Date.now,
64
+ });
65
+ async function recallMemory(request, controls = {}) {
66
+ controls.signal?.throwIfAborted();
67
+ const useLocalSource =
68
+ decision.canonical &&
69
+ request.semanticCandidates === undefined &&
70
+ semanticSource.isEnabled() &&
71
+ request.query !== "*";
72
+ const sourceRevision = useLocalSource
73
+ ? await memoryPort.getRevision(controls)
74
+ : null;
75
+ controls.signal?.throwIfAborted();
76
+ const candidates = useLocalSource
77
+ ? await semanticSource.candidates(request, controls)
78
+ : undefined;
79
+ controls.signal?.throwIfAborted();
80
+ const result = await kernel.recallMemory(
81
+ {
82
+ ...request,
83
+ ...(candidates === undefined ? {} : { semanticCandidates: candidates }),
84
+ },
85
+ controls,
86
+ );
87
+ controls.signal?.throwIfAborted();
88
+ if (sourceRevision !== null && result.memoryRevision !== sourceRevision) {
89
+ const error = new Error(
90
+ "Memory changed during local semantic inference; prepare a fresh recall",
91
+ );
92
+ error.code = "revision_conflict";
93
+ error.noReplay = true;
94
+ throw error;
95
+ }
96
+ return result;
97
+ }
59
98
  return Object.freeze({
99
+ recallMemory,
60
100
  decision,
61
101
  kernel,
62
102
  memoryPort,
@@ -11,6 +11,7 @@
11
11
  import crypto from "node:crypto";
12
12
  import fs from "node:fs";
13
13
  import path from "node:path";
14
+ import { performance } from "node:perf_hooks";
14
15
  import { types as utilTypes } from "node:util";
15
16
  import {
16
17
  ArtifactStore,
@@ -27,6 +28,7 @@ import {
27
28
  import {
28
29
  recordStorageFailureReason,
29
30
  recordStorageFailureStage,
31
+ recordStorageFailureClockWindow,
30
32
  } from "../storage-failure-cause-codes.js";
31
33
  import { artifactPhysicalIdentity as physicalIdentity } from "./evolution-artifact-identity.js";
32
34
  import { withEvolutionFileIdentity } from "./evolution-file-identity.js";
@@ -4421,6 +4423,13 @@ export class EvolutionArtifactPorts {
4421
4423
  chunks.push(frozenCanonicalClone(chunk));
4422
4424
  }
4423
4425
  const readHistory = (directoryScope) => {
4426
+ // Monotonic timing is observation only. Never substitute it for #clock().
4427
+ let observationStartedAt = null;
4428
+ try {
4429
+ observationStartedAt = performance.now();
4430
+ } catch {
4431
+ /* optional */
4432
+ }
4424
4433
  const snapshot = readTrustedIndexSnapshot(this.#store.layout);
4425
4434
  this.#indexLedgerBatchEntries(snapshot.entries);
4426
4435
  const window = [];
@@ -4478,10 +4487,36 @@ export class EvolutionArtifactPorts {
4478
4487
  completed < entry.checkedAt || completed >= entry.expiresAt,
4479
4488
  )
4480
4489
  ) {
4481
- throw artifactError(
4490
+ const error = artifactError(
4482
4491
  EVOLUTION_ARTIFACT_EXPIRED_CODE,
4483
4492
  "artifact authority expired before ledger history release",
4484
4493
  );
4494
+ try {
4495
+ let elapsedMs = null;
4496
+ try {
4497
+ if (observationStartedAt !== null)
4498
+ elapsedMs = performance.now() - observationStartedAt;
4499
+ } catch {
4500
+ /* optional; retain the authoritative window observations */
4501
+ }
4502
+ recordStorageFailureClockWindow(error, {
4503
+ windowSize: window.length,
4504
+ backwardCount: window.filter((entry) => completed < entry.checkedAt)
4505
+ .length,
4506
+ expiredCount: window.filter((entry) => completed >= entry.expiresAt)
4507
+ .length,
4508
+ minRemainingMs: Math.min(
4509
+ ...window.map((entry) => entry.expiresAt - completed),
4510
+ ),
4511
+ maxReadAgeMs: Math.max(
4512
+ ...window.map((entry) => completed - entry.checkedAt),
4513
+ ),
4514
+ elapsedMs,
4515
+ });
4516
+ } catch {
4517
+ // Even a failed observer must preserve this exact rejection.
4518
+ }
4519
+ throw error;
4485
4520
  }
4486
4521
  return Object.freeze(results);
4487
4522
  };
@@ -12,6 +12,7 @@ import {
12
12
  validateRequest,
13
13
  validateResponse,
14
14
  quoteNative,
15
+ nativePricingWindowAt,
15
16
  convertToUsd,
16
17
  } from "./formal-budget-contract.js";
17
18
 
@@ -107,7 +108,28 @@ export class FormalBudgetAuthority {
107
108
  config.plan.digest === planDigest,
108
109
  "Authority lineage/plan mismatch",
109
110
  );
110
- this.#config = validateActivation(config, verifyEvidence, now());
111
+ const activations = this.#db
112
+ .prepare("SELECT body FROM event WHERE kind='initialized'")
113
+ .all();
114
+ requireBudget(
115
+ activations.length === 1,
116
+ "Unique durable activation witness required",
117
+ );
118
+ const activation = JSON.parse(activations[0].body);
119
+ const openedAt = now();
120
+ requireBudget(
121
+ activation.activationDigest === row.digest &&
122
+ Number.isSafeInteger(activation.at) &&
123
+ activation.at >= 0 &&
124
+ Number.isSafeInteger(openedAt) &&
125
+ activation.at <= openedAt,
126
+ "Invalid durable activation time or identity",
127
+ );
128
+ // Reopening is also needed to settle an already dispatched request after
129
+ // its price/FX validity ends. Verify the original activation against its
130
+ // durable time, then recheck today's expiry in #contract before every
131
+ // new reservation/dispatch. No expired contract can start a new call.
132
+ this.#config = validateActivation(config, verifyEvidence, activation.at);
111
133
  requireBudget(
112
134
  this.#db.pragma("quick_check", { simple: true }) === "ok",
113
135
  "Corrupt budget database",
@@ -509,10 +531,17 @@ export class FormalBudgetAuthority {
509
531
  validateRequest(contract, body) === call.request_digest,
510
532
  "Reserved request changed",
511
533
  );
534
+ const dispatchedAt = this.#now();
535
+ const pricingWindow = nativePricingWindowAt(contract, dispatchedAt);
512
536
  this.#db
513
537
  .prepare("UPDATE call SET state='dispatched' WHERE id=?")
514
538
  .run(callId);
515
- this.#event("dispatch", { callId });
539
+ this.#event("dispatch", {
540
+ callId,
541
+ ...(pricingWindow
542
+ ? { nativePricing: { dispatchedAt, windowId: pricingWindow.id } }
543
+ : {}),
544
+ });
516
545
  return JSON.parse(canonical(contract));
517
546
  });
518
547
  }
@@ -590,7 +619,30 @@ export class FormalBudgetAuthority {
590
619
  (rate) => rate.currency === contract.currency,
591
620
  );
592
621
  const usage = validateResponse(contract, receipt);
593
- const native = quoteNative(contract, usage),
622
+ let nativePricing;
623
+ if (Object.hasOwn(contract, "pricingWindows")) {
624
+ const witnesses = this.#db
625
+ .prepare(
626
+ "SELECT body FROM event WHERE kind='dispatch' AND json_extract(body,'$.callId')=?",
627
+ )
628
+ .all(callId);
629
+ requireBudget(
630
+ witnesses.length === 1,
631
+ "A unique durable dispatch pricing witness is required",
632
+ );
633
+ nativePricing = JSON.parse(witnesses[0].body).nativePricing;
634
+ requireBudget(
635
+ nativePricing &&
636
+ Object.keys(nativePricing).length === 2 &&
637
+ Object.keys(nativePricing).every((key) =>
638
+ ["dispatchedAt", "windowId"].includes(key),
639
+ ) &&
640
+ nativePricingWindowAt(contract, nativePricing.dispatchedAt)
641
+ ?.id === nativePricing.windowId,
642
+ "Dispatch pricing witness differs from the attested schedule",
643
+ );
644
+ }
645
+ const native = quoteNative(contract, usage, nativePricing),
594
646
  usd = convertToUsd(native, fx);
595
647
  requireBudget(
596
648
  native <= call.reserved_native && usd <= call.reserved_usd,
@@ -612,6 +664,7 @@ export class FormalBudgetAuthority {
612
664
  costUsdMicros: usd,
613
665
  costNativeMicros: native,
614
666
  currency: contract.currency,
667
+ ...(nativePricing ? { nativePricing } : {}),
615
668
  });
616
669
  return {
617
670
  costUsdMicros: usd,
@@ -185,6 +185,7 @@ export function validateActivation(config, verifyEvidence, now = Date.now()) {
185
185
  contract.cachedMicrosPerMillion <= contract.inputMicrosPerMillion,
186
186
  "Cache cannot exceed reserved input price",
187
187
  );
188
+ validateNativePricingWindows(contract);
188
189
  requireBudget(
189
190
  Array.isArray(contract.responseTiers) &&
190
191
  contract.responseTiers.length > 0 &&
@@ -321,7 +322,91 @@ function safeNumber(value) {
321
322
  return Number(value);
322
323
  }
323
324
  const ceil = (n, d) => (n + d - 1n) / d;
324
- export function quoteNative(contract, usage = null) {
325
+
326
+ const NATIVE_RATE_FIELDS = [
327
+ "inputMicrosPerMillion",
328
+ "cachedMicrosPerMillion",
329
+ "outputMicrosPerMillion",
330
+ "fixedFeeMicros",
331
+ ];
332
+
333
+ /** Optional account-attested absolute windows, with a fixed liability ceiling.
334
+ * The trusted account contract must explicitly establish dispatch-time billing;
335
+ * public list prices or the client response time cannot establish that rule. */
336
+ export function validateNativePricingWindows(contract) {
337
+ const present = Object.hasOwn(contract, "pricingWindows");
338
+ requireBudget(
339
+ present || !Object.hasOwn(contract, "pricingTimeBasis"),
340
+ "Pricing time basis requires a complete window schedule",
341
+ );
342
+ if (!present) return;
343
+ requireBudget(
344
+ contract.pricingTimeBasis === "host-dispatch" &&
345
+ Array.isArray(contract.pricingWindows) &&
346
+ contract.pricingWindows.length > 0 &&
347
+ contract.pricingWindows.length <= 4096,
348
+ "Account-attested dispatch-time pricing windows required",
349
+ );
350
+ const ids = new Set();
351
+ let boundary = contract.validFrom;
352
+ for (const window of contract.pricingWindows) {
353
+ requireBudget(
354
+ window &&
355
+ typeof window === "object" &&
356
+ !Array.isArray(window) &&
357
+ Object.keys(window).length === 7 &&
358
+ Object.keys(window).every((key) =>
359
+ ["id", "validFrom", "validUntil", ...NATIVE_RATE_FIELDS].includes(
360
+ key,
361
+ ),
362
+ ),
363
+ "Unsupported native price window fields",
364
+ );
365
+ label(window.id, "native price window ID");
366
+ requireBudget(!ids.has(window.id), "Duplicate native price window ID");
367
+ ids.add(window.id);
368
+ integer(window.validFrom, "Price window start");
369
+ integer(window.validUntil, "Price window end", 1);
370
+ requireBudget(
371
+ window.validFrom === boundary && window.validUntil > window.validFrom,
372
+ "Price windows must be ordered, contiguous and non-overlapping",
373
+ );
374
+ for (const field of NATIVE_RATE_FIELDS) {
375
+ integer(window[field], `Price window ${field}`);
376
+ requireBudget(
377
+ window[field] <= contract[field],
378
+ "Native price window exceeds the reserved liability ceiling",
379
+ );
380
+ }
381
+ requireBudget(
382
+ window.cachedMicrosPerMillion <= window.inputMicrosPerMillion,
383
+ "Window cache price exceeds input price",
384
+ );
385
+ boundary = window.validUntil;
386
+ }
387
+ requireBudget(
388
+ boundary === contract.validUntil,
389
+ "Price windows must cover the complete contract validity interval",
390
+ );
391
+ }
392
+
393
+ export function nativePricingWindowAt(contract, dispatchedAt) {
394
+ validateNativePricingWindows(contract);
395
+ if (!Object.hasOwn(contract, "pricingWindows")) return null;
396
+ integer(dispatchedAt, "Trusted dispatch timestamp");
397
+ const window = contract.pricingWindows.find(
398
+ (item) => item.validFrom <= dispatchedAt && dispatchedAt < item.validUntil,
399
+ );
400
+ requireBudget(window, "Dispatch falls outside the attested price schedule");
401
+ return window;
402
+ }
403
+
404
+ export function quoteNative(contract, usage = null, { dispatchedAt } = {}) {
405
+ // Reservation always retains the contract's worst-case rates. Settlement
406
+ // uses the durable dispatch witness, even across restart/window expiry.
407
+ const rates = usage
408
+ ? nativePricingWindowAt(contract, dispatchedAt) || contract
409
+ : contract;
325
410
  const input = BigInt(usage?.prompt_tokens ?? contract.maxInputTokens);
326
411
  const cached = BigInt(usage?.prompt_tokens_details?.cached_tokens ?? 0);
327
412
  const output = usage
@@ -329,11 +414,11 @@ export function quoteNative(contract, usage = null) {
329
414
  : BigInt(contract.maxAnswerTokens) + BigInt(contract.maxReasoningTokens);
330
415
  return safeNumber(
331
416
  ceil(
332
- (input - cached) * BigInt(contract.inputMicrosPerMillion) +
333
- cached * BigInt(contract.cachedMicrosPerMillion) +
334
- output * BigInt(contract.outputMicrosPerMillion),
417
+ (input - cached) * BigInt(rates.inputMicrosPerMillion) +
418
+ cached * BigInt(rates.cachedMicrosPerMillion) +
419
+ output * BigInt(rates.outputMicrosPerMillion),
335
420
  1_000_000n,
336
- ) + BigInt(contract.fixedFeeMicros),
421
+ ) + BigInt(rates.fixedFeeMicros),
337
422
  );
338
423
  }
339
424
  export function convertToUsd(nativeMicros, rate) {
@@ -25,5 +25,6 @@ export {
25
25
  isTransientMcpError,
26
26
  SUPPORTED_MCP_PROTOCOL_VERSIONS,
27
27
  assertSupportedMcpProtocolVersion,
28
+ mcpProtocolVersionField,
28
29
  _deps,
29
30
  } from "../harness/mcp-client.js";
@@ -0,0 +1,158 @@
1
+ import { admitMcpToolResult } from "./mcp-tool-result.js";
2
+ import { VERSION } from "../constants.js";
3
+ import {
4
+ admitMcpTaskResponse,
5
+ mcpTaskError,
6
+ MCP_TASKS_EXTENSION,
7
+ MCP_STATELESS_PROTOCOL_VERSION,
8
+ } from "./mcp-tasks.js";
9
+
10
+ const NAME_FIELDS = Object.freeze({
11
+ "tools/call": "name",
12
+ "prompts/get": "name",
13
+ "resources/read": "uri",
14
+ "tasks/get": "taskId",
15
+ "tasks/update": "taskId",
16
+ "tasks/cancel": "taskId",
17
+ });
18
+ const object = (value) =>
19
+ value !== null && typeof value === "object" && !Array.isArray(value);
20
+ const invalid = () =>
21
+ mcpTaskError(
22
+ "CC_MCP_STATELESS_RESULT_INVALID",
23
+ "MCP stateless response is invalid",
24
+ true,
25
+ );
26
+
27
+ /** Only the explicit task API advertises Tasks. Ordinary calls cannot silently
28
+ * create an untracked background operation, and no input/sampling authority is
29
+ * advertised by this polling transport. */
30
+ export function statelessMcpRequest(
31
+ method,
32
+ params = {},
33
+ { tasks = false } = {},
34
+ ) {
35
+ const field = Object.hasOwn(NAME_FIELDS, method) ? NAME_FIELDS[method] : null;
36
+ const name = field ? params[field] : null;
37
+ const encodedName =
38
+ typeof name === "string"
39
+ ? /^[\x21-\x7e]+$/.test(name) && !name.startsWith("=?base64?")
40
+ ? name
41
+ : `=?base64?${Buffer.from(name, "utf8").toString("base64")}?=`
42
+ : null;
43
+ return {
44
+ params: {
45
+ ...params,
46
+ _meta: {
47
+ ...params._meta,
48
+ "io.modelcontextprotocol/protocolVersion":
49
+ MCP_STATELESS_PROTOCOL_VERSION,
50
+ "io.modelcontextprotocol/clientInfo": {
51
+ name: "chainlesschain-cli",
52
+ version: VERSION,
53
+ },
54
+ "io.modelcontextprotocol/clientCapabilities": tasks
55
+ ? { extensions: { [MCP_TASKS_EXTENSION]: {} } }
56
+ : {},
57
+ },
58
+ },
59
+ headers: {
60
+ "MCP-Protocol-Version": MCP_STATELESS_PROTOCOL_VERSION,
61
+ "Mcp-Method": method,
62
+ ...(encodedName === null ? {} : { "Mcp-Name": encodedName }),
63
+ },
64
+ };
65
+ }
66
+
67
+ /** Map the new wire vocabulary into the existing verified journal shape.
68
+ * Result association comes from the validated tasks/get identity, never from
69
+ * peer-controlled metadata or a synthetic tool/user message. */
70
+ export function admitStatelessMcpTask(
71
+ serverName,
72
+ value,
73
+ config,
74
+ { create = false, taskId } = {},
75
+ ) {
76
+ const wire = admitMcpToolResult(serverName, value, config).result;
77
+ if (
78
+ wire.resultType !== (create ? "task" : "complete") ||
79
+ ["task", "ttl", "pollInterval"].some((key) => Object.hasOwn(wire, key)) ||
80
+ (create &&
81
+ (Object.hasOwn(wire, "isError") ||
82
+ (wire.content !== undefined &&
83
+ (!Array.isArray(wire.content) || wire.content.length !== 0))))
84
+ )
85
+ throw invalid();
86
+ const task = admitMcpTaskResponse(
87
+ serverName,
88
+ {
89
+ taskId: wire.taskId,
90
+ status: wire.status,
91
+ createdAt: wire.createdAt,
92
+ lastUpdatedAt: wire.lastUpdatedAt,
93
+ ttl: wire.ttlMs,
94
+ ...(wire.pollIntervalMs === undefined
95
+ ? {}
96
+ : { pollInterval: wire.pollIntervalMs }),
97
+ ...(wire.statusMessage === undefined
98
+ ? {}
99
+ : { statusMessage: wire.statusMessage }),
100
+ },
101
+ config,
102
+ { kind: "get", taskId },
103
+ );
104
+ if (
105
+ (wire.status !== "completed" && Object.hasOwn(wire, "result")) ||
106
+ (wire.status !== "failed" && Object.hasOwn(wire, "error")) ||
107
+ (wire.status !== "input_required" && Object.hasOwn(wire, "inputRequests"))
108
+ )
109
+ throw invalid();
110
+ if (
111
+ wire.status === "input_required" &&
112
+ (!object(wire.inputRequests) ||
113
+ Object.keys(wire.inputRequests).length === 0)
114
+ )
115
+ throw invalid();
116
+ if (
117
+ wire.status === "failed" &&
118
+ (!object(wire.error) ||
119
+ !Number.isInteger(wire.error.code) ||
120
+ typeof wire.error.message !== "string")
121
+ )
122
+ throw invalid();
123
+ let result;
124
+ if (wire.status === "completed" && Object.hasOwn(wire, "result")) {
125
+ if (
126
+ !object(wire.result) ||
127
+ (wire.result._meta !== undefined && !object(wire.result._meta)) ||
128
+ (wire.result.resultType !== undefined &&
129
+ wire.result.resultType !== "complete")
130
+ )
131
+ throw invalid();
132
+ const related = wire.result._meta?.["io.modelcontextprotocol/related-task"];
133
+ if (related !== undefined && related?.taskId !== task.taskId)
134
+ throw invalid();
135
+ result = admitMcpTaskResponse(
136
+ serverName,
137
+ {
138
+ ...wire.result,
139
+ _meta: {
140
+ ...wire.result._meta,
141
+ "io.modelcontextprotocol/related-task": { taskId: task.taskId },
142
+ },
143
+ },
144
+ config,
145
+ { kind: "result", taskId: task.taskId },
146
+ );
147
+ } else if (!create && wire.status === "completed") throw invalid();
148
+ return Object.freeze({ task, ...(result ? { result } : {}) });
149
+ }
150
+
151
+ export function assertStatelessMcpAck(serverName, value, config) {
152
+ const wire = admitMcpToolResult(serverName, value, config).result;
153
+ if (
154
+ wire.resultType !== "complete" ||
155
+ Object.keys(wire).some((key) => !["resultType", "_meta"].includes(key))
156
+ )
157
+ throw invalid();
158
+ }
@@ -0,0 +1,129 @@
1
+ import { summarizeMcpPayload } from "./mcp-call-ledger.js";
2
+
3
+ export const MCP_TASK_CONTINUATION_STARTED = "mcp_task_continuation_started";
4
+ export const MCP_TASK_CONTINUATION_FIELD = "_cc_mcp_task_continuation";
5
+ const START_FIELDS = [
6
+ "schemaVersion",
7
+ "sessionId",
8
+ "localId",
9
+ "deliveryId",
10
+ "deliveryEventHash",
11
+ "messageDigest",
12
+ "at",
13
+ ];
14
+ const END_FIELDS = [
15
+ "schemaVersion",
16
+ "sessionId",
17
+ "localId",
18
+ "deliveryId",
19
+ "deliveryEventHash",
20
+ "messageDigest",
21
+ "beginEventHash",
22
+ "outputDigest",
23
+ ];
24
+ const HASH = /^[a-f0-9]{64}$/u;
25
+
26
+ function invalid(reason) {
27
+ throw Object.assign(new Error("Invalid MCP task continuation: " + reason), {
28
+ code: "CC_MCP_TASK_CONTINUATION_INVALID",
29
+ });
30
+ }
31
+ function fields(value, expected) {
32
+ return (
33
+ value !== null &&
34
+ typeof value === "object" &&
35
+ !Array.isArray(value) &&
36
+ Object.keys(value).length === expected.length &&
37
+ Object.keys(value).every((key) => expected.includes(key))
38
+ );
39
+ }
40
+ function source(data, delivery, sessionId) {
41
+ if (
42
+ !delivery ||
43
+ data?.schemaVersion !== 1 ||
44
+ data.sessionId !== sessionId ||
45
+ data.sessionId !== delivery.sessionId ||
46
+ data.localId !== delivery.localId ||
47
+ data.deliveryId !== delivery.deliveryId ||
48
+ data.deliveryEventHash !== delivery.eventHash ||
49
+ data.messageDigest !== delivery.messageDigest ||
50
+ !HASH.test(data.deliveryEventHash)
51
+ )
52
+ invalid("delivery binding");
53
+ }
54
+
55
+ export function createMcpTaskContinuationStart(
56
+ delivery,
57
+ at = new Date().toISOString(),
58
+ ) {
59
+ return Object.freeze({
60
+ schemaVersion: 1,
61
+ sessionId: delivery.sessionId,
62
+ localId: delivery.localId,
63
+ deliveryId: delivery.deliveryId,
64
+ deliveryEventHash: delivery.eventHash,
65
+ messageDigest: delivery.messageDigest,
66
+ at,
67
+ });
68
+ }
69
+
70
+ export function assertMcpTaskContinuationStart(
71
+ data,
72
+ delivery,
73
+ sessionId,
74
+ prior,
75
+ ) {
76
+ if (
77
+ !fields(data, START_FIELDS) ||
78
+ prior ||
79
+ typeof data.at !== "string" ||
80
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u.test(data.at) ||
81
+ !Number.isFinite(Date.parse(data.at))
82
+ )
83
+ invalid("start schema or duplicate");
84
+ source(data, delivery, sessionId);
85
+ return data;
86
+ }
87
+
88
+ export function createMcpTaskContinuationMessage(started, content) {
89
+ if (typeof content !== "string") invalid("assistant response");
90
+ const message = { role: "assistant", content };
91
+ return Object.freeze({
92
+ ...message,
93
+ [MCP_TASK_CONTINUATION_FIELD]: Object.freeze({
94
+ schemaVersion: 1,
95
+ sessionId: started.sessionId,
96
+ localId: started.localId,
97
+ deliveryId: started.deliveryId,
98
+ deliveryEventHash: started.deliveryEventHash,
99
+ messageDigest: started.messageDigest,
100
+ beginEventHash: started.beginEventHash,
101
+ outputDigest: summarizeMcpPayload(message).sha256,
102
+ }),
103
+ });
104
+ }
105
+
106
+ export function assertMcpTaskContinuationMessage(
107
+ message,
108
+ delivery,
109
+ sessionId,
110
+ prior,
111
+ ) {
112
+ const data = message?.[MCP_TASK_CONTINUATION_FIELD];
113
+ if (
114
+ !fields(message, ["role", "content", MCP_TASK_CONTINUATION_FIELD]) ||
115
+ message.role !== "assistant" ||
116
+ typeof message.content !== "string" ||
117
+ !fields(data, END_FIELDS) ||
118
+ !prior ||
119
+ prior.phase !== "started" ||
120
+ !HASH.test(data.beginEventHash) ||
121
+ data.beginEventHash !== prior.beginEventHash ||
122
+ data.outputDigest !==
123
+ summarizeMcpPayload({ role: "assistant", content: message.content })
124
+ .sha256
125
+ )
126
+ invalid("settlement schema, output or start binding");
127
+ source(data, delivery, sessionId);
128
+ return data;
129
+ }