chainlesschain 0.166.145 → 0.166.147

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 (53) hide show
  1. package/README.md +67 -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 +26 -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/evolution/evolution-ledger-file-manifest-head-store.js +19 -0
  28. package/src/lib/evolution/evolution-ledger-manifest-catalog.js +13 -0
  29. package/src/lib/evolution/evolution-ledger-manifest-head-store.js +17 -0
  30. package/src/lib/evolution/evolution-ledger-v2-manifest-backend.js +29 -2
  31. package/src/lib/formal-budget-authority.js +56 -3
  32. package/src/lib/formal-budget-contract.js +90 -5
  33. package/src/lib/mcp-client.js +1 -0
  34. package/src/lib/mcp-stateless-protocol.js +158 -0
  35. package/src/lib/mcp-task-continuation-contract.js +129 -0
  36. package/src/lib/mcp-task-continuation.js +147 -0
  37. package/src/lib/mcp-task-journal-projection.js +49 -4
  38. package/src/lib/mcp-task-runtime.js +148 -1
  39. package/src/lib/mcp-tasks.js +24 -0
  40. package/src/lib/session-host-snapshot.js +31 -0
  41. package/src/lib/session-input-lifecycle.js +147 -0
  42. package/src/lib/session-input-receipt.js +64 -0
  43. package/src/lib/session-message-provenance.js +6 -5
  44. package/src/lib/session-model-usage-recovery.js +115 -0
  45. package/src/lib/session-transcript-history.js +3 -0
  46. package/src/lib/session-transcript-structure.js +8 -1
  47. package/src/lib/storage-failure-cause-codes.js +79 -0
  48. package/src/repl/agent-repl.js +348 -23
  49. package/src/runtime/agent-core.js +29 -11
  50. package/src/runtime/headless-runner.js +1 -0
  51. package/src/runtime/headless-stream.js +40 -33
  52. package/src/runtime/mcp-config.js +5 -3
  53. package/src/runtime/policies/agent-policy.js +1 -0
@@ -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
+ }
@@ -0,0 +1,147 @@
1
+ import {
2
+ appendAuthorityEventWithVerifiedProjection,
3
+ readVerifiedProjection,
4
+ } from "../harness/jsonl-session-store.js";
5
+ import { assertSessionHostWriteAuthority } from "./session-host-lease.js";
6
+ import { readMcpTaskJournal } from "./mcp-task-journal.js";
7
+ import { createMcpTaskJournalProjection } from "./mcp-task-journal-projection.js";
8
+ import {
9
+ MCP_TASK_CONTINUATION_STARTED,
10
+ MCP_TASK_CONTINUATION_FIELD,
11
+ createMcpTaskContinuationStart,
12
+ assertMcpTaskContinuationStart,
13
+ createMcpTaskContinuationMessage,
14
+ assertMcpTaskContinuationMessage,
15
+ } from "./mcp-task-continuation-contract.js";
16
+
17
+ function error(code, message) {
18
+ return Object.assign(new Error(message), { code });
19
+ }
20
+ function requireLease(sessionId) {
21
+ if (!assertSessionHostWriteAuthority(sessionId))
22
+ throw error(
23
+ "CC_MCP_TASK_CONTINUATION_LEASE_REQUIRED",
24
+ "MCP continuation requires the owning session lease",
25
+ );
26
+ }
27
+
28
+ /** A started continuation is never automatically repeated, even if dispatch or
29
+ * result persistence was interrupted. Text mentioning an ID is not authority. */
30
+ export function beginMcpTaskContinuation(sessionId, localId) {
31
+ requireLease(sessionId);
32
+ const before = readMcpTaskJournal(sessionId);
33
+ const delivery = before.deliveries.find((item) => item.localId === localId);
34
+ if (!delivery)
35
+ throw error(
36
+ "CC_MCP_TASK_CONTINUATION_DELIVERY_REQUIRED",
37
+ "Deliver the verified result before continuing",
38
+ );
39
+ if (before.continuations.some((item) => item.localId === localId))
40
+ throw error(
41
+ "CC_MCP_TASK_CONTINUATION_ALREADY_STARTED",
42
+ "A prior continuation exists; inspect its outcome instead of replaying it",
43
+ );
44
+ const messages = readVerifiedProjection(sessionId, () => ({
45
+ accept() {},
46
+ finish(authority) {
47
+ return authority.readMessages();
48
+ },
49
+ }));
50
+ if (!messages.some((item) => item.role === "user"))
51
+ throw error(
52
+ "CC_MCP_TASK_CONTINUATION_USER_TASK_REQUIRED",
53
+ "Submit a real user request before automatic continuation",
54
+ );
55
+ const legacy = `Continue from the verified background MCP task result (deliveryId: ${delivery.deliveryId}).`;
56
+ if (messages.some((item) => item.role === "user" && item.content === legacy))
57
+ throw error(
58
+ "CC_MCP_TASK_CONTINUATION_LEGACY_REVIEW_REQUIRED",
59
+ "A legacy continuation may have run; use an explicit user prompt after inspection",
60
+ );
61
+ const data = createMcpTaskContinuationStart(delivery);
62
+ const options = {
63
+ createProjection: () => createMcpTaskJournalProjection(sessionId),
64
+ validateProjection(current) {
65
+ assertMcpTaskContinuationStart(
66
+ data,
67
+ current.deliveries.find((item) => item.localId === localId),
68
+ sessionId,
69
+ current.continuations.find((item) => item.localId === localId),
70
+ );
71
+ },
72
+ };
73
+ try {
74
+ appendAuthorityEventWithVerifiedProjection(
75
+ sessionId,
76
+ MCP_TASK_CONTINUATION_STARTED,
77
+ data,
78
+ options,
79
+ );
80
+ } catch (cause) {
81
+ if (!["unknown", "committed"].includes(cause?.commitState)) throw cause;
82
+ const confirmed = readMcpTaskJournal(sessionId).continuations.find(
83
+ (item) => item.localId === localId,
84
+ );
85
+ if (
86
+ !confirmed ||
87
+ confirmed.at !== data.at ||
88
+ confirmed.deliveryEventHash !== data.deliveryEventHash
89
+ )
90
+ throw cause;
91
+ }
92
+ const started = readMcpTaskJournal(sessionId).continuations.find(
93
+ (item) => item.localId === localId,
94
+ );
95
+ if (!started || started.phase !== "started")
96
+ throw error(
97
+ "CC_MCP_TASK_CONTINUATION_UNVERIFIED",
98
+ "Continuation start was not confirmed",
99
+ );
100
+ return Object.freeze({ ...started, delivery });
101
+ }
102
+
103
+ /** One existing assistant_message event atomically publishes both the model
104
+ * answer and its exact consumption binding. No synthetic user message. */
105
+ export function settleMcpTaskContinuation(sessionId, started, content) {
106
+ requireLease(sessionId);
107
+ const message = createMcpTaskContinuationMessage(started, content);
108
+ const localId = started.localId;
109
+ try {
110
+ appendAuthorityEventWithVerifiedProjection(
111
+ sessionId,
112
+ "assistant_message",
113
+ message,
114
+ {
115
+ createProjection: () => createMcpTaskJournalProjection(sessionId),
116
+ validateProjection(current) {
117
+ assertMcpTaskContinuationMessage(
118
+ message,
119
+ current.deliveries.find((item) => item.localId === localId),
120
+ sessionId,
121
+ current.continuations.find((item) => item.localId === localId),
122
+ );
123
+ },
124
+ },
125
+ );
126
+ } catch (cause) {
127
+ if (!["unknown", "committed"].includes(cause?.commitState)) throw cause;
128
+ const confirmed = readMcpTaskJournal(sessionId).continuations.find(
129
+ (item) => item.localId === localId,
130
+ );
131
+ if (
132
+ confirmed?.phase !== "settled" ||
133
+ confirmed.outputDigest !==
134
+ message[MCP_TASK_CONTINUATION_FIELD].outputDigest
135
+ )
136
+ throw cause;
137
+ }
138
+ const settled = readMcpTaskJournal(sessionId).continuations.find(
139
+ (item) => item.localId === localId,
140
+ );
141
+ if (settled?.phase !== "settled")
142
+ throw error(
143
+ "CC_MCP_TASK_CONTINUATION_UNVERIFIED",
144
+ "Continuation result was not confirmed",
145
+ );
146
+ return settled;
147
+ }
@@ -14,6 +14,12 @@ import {
14
14
  assertMcpTaskDeliverySource,
15
15
  renderMcpTaskDeliveryMessage,
16
16
  } from "./mcp-task-delivery-contract.js";
17
+ import {
18
+ MCP_TASK_CONTINUATION_STARTED,
19
+ MCP_TASK_CONTINUATION_FIELD,
20
+ assertMcpTaskContinuationStart,
21
+ assertMcpTaskContinuationMessage,
22
+ } from "./mcp-task-continuation-contract.js";
17
23
 
18
24
  export const MCP_TASK_JOURNAL_EVENT = "mcp_task_ledger";
19
25
  const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u;
@@ -267,6 +273,7 @@ export function createMcpTaskJournalProjection(
267
273
  if (typeof retainResults !== "boolean") fail("retention options");
268
274
  const records = new Map();
269
275
  const deliveries = new Map();
276
+ const continuations = new Map();
270
277
  const requestedCalls = createMcpLedgerEventReducer({
271
278
  sessionId,
272
279
  verified: true,
@@ -280,6 +287,7 @@ export function createMcpTaskJournalProjection(
280
287
  sessionId,
281
288
  records: [...records.values()],
282
289
  deliveries: [...deliveries.values()],
290
+ continuations: [...continuations.values()],
283
291
  callRecovery,
284
292
  headHash: callRecovery.headHash,
285
293
  });
@@ -313,11 +321,14 @@ export function createMcpTaskJournalProjection(
313
321
  event.type === "mcp_call_ledger"
314
322
  ? event.data?.record?.sessionId
315
323
  : event.type === MCP_TASK_JOURNAL_EVENT ||
316
- event.type === MCP_TASK_DELIVERY_EVENT
324
+ event.type === MCP_TASK_DELIVERY_EVENT ||
325
+ event.type === MCP_TASK_CONTINUATION_STARTED
317
326
  ? event.data?.sessionId
318
- : event.type === "system"
319
- ? event.data?._cc_fork_authority?.sourceSessionId
320
- : null;
327
+ : event.data?.[MCP_TASK_CONTINUATION_FIELD] !== undefined
328
+ ? event.data[MCP_TASK_CONTINUATION_FIELD]?.sessionId
329
+ : event.type === "system"
330
+ ? event.data?._cc_fork_authority?.sourceSessionId
331
+ : null;
321
332
  if (typeof hint === "string" && text(hint)) {
322
333
  // A candidate origin must not erase incidents already seen in the
323
334
  // generation-less prefix before the first usable identity hint.
@@ -368,6 +379,7 @@ export function createMcpTaskJournalProjection(
368
379
  scopes.add(activeSessionId);
369
380
  records.clear();
370
381
  deliveries.clear();
382
+ continuations.clear();
371
383
  calls = createMcpLedgerEventReducer({
372
384
  sessionId: activeSessionId,
373
385
  verified: true,
@@ -393,6 +405,39 @@ export function createMcpTaskJournalProjection(
393
405
  );
394
406
  return;
395
407
  }
408
+ if (event.type === MCP_TASK_CONTINUATION_STARTED) {
409
+ const data = assertMcpTaskContinuationStart(
410
+ event.data,
411
+ deliveries.get(event.data?.localId),
412
+ activeSessionId,
413
+ continuations.get(event.data?.localId),
414
+ );
415
+ continuations.set(
416
+ data.localId,
417
+ freeze({ ...data, phase: "started", beginEventHash: event.hash }),
418
+ );
419
+ return;
420
+ }
421
+ if (event.data?.[MCP_TASK_CONTINUATION_FIELD] !== undefined) {
422
+ if (event.type !== "assistant_message") fail("continuation event type");
423
+ const localId = event.data[MCP_TASK_CONTINUATION_FIELD]?.localId;
424
+ const data = assertMcpTaskContinuationMessage(
425
+ event.data,
426
+ deliveries.get(localId),
427
+ activeSessionId,
428
+ continuations.get(localId),
429
+ );
430
+ continuations.set(
431
+ localId,
432
+ freeze({
433
+ ...continuations.get(localId),
434
+ phase: "settled",
435
+ outputDigest: data.outputDigest,
436
+ endEventHash: event.hash,
437
+ }),
438
+ );
439
+ return;
440
+ }
396
441
  if (event.type !== MCP_TASK_JOURNAL_EVENT) return;
397
442
  const data = snapshotMcpTaskJournalEvent(activeSessionId, event.data);
398
443
  let record = transitionMcpTaskJournalRecord(
@@ -1,4 +1,5 @@
1
1
  import { deliverMcpTaskResult } from "./mcp-task-delivery.js";
2
+ import { raceWithAbort, throwIfAborted } from "./abort-utils.js";
2
3
  import { randomBytes, randomUUID } from "node:crypto";
3
4
  import { createSecretStore } from "./secret-store.js";
4
5
  import { createSessionMcpLedgerSink } from "./mcp-call-ledger-store.js";
@@ -17,7 +18,36 @@ function failure(code, message, details = {}) {
17
18
  return Object.assign(new Error(message), { code, ...details });
18
19
  }
19
20
 
21
+ function waitForTaskPoll(ms, signal, leaseSignal) {
22
+ const delay = Math.max(0, Math.min(60_000, Number(ms) || 0));
23
+ if (delay === 0) return Promise.resolve();
24
+ const combined = signal
25
+ ? AbortSignal.any([leaseSignal, signal])
26
+ : leaseSignal;
27
+ if (combined.aborted) return Promise.reject(combined.reason);
28
+ return new Promise((resolve, reject) => {
29
+ const abort = () => {
30
+ clearTimeout(timer);
31
+ combined.removeEventListener("abort", abort);
32
+ reject(
33
+ combined.reason ||
34
+ new DOMException("The operation was aborted", "AbortError"),
35
+ );
36
+ };
37
+ // The timer is the only successful completion path; remove the listener
38
+ // before resolving so repeated polling does not retain old closures.
39
+ const timer = setTimeout(() => {
40
+ combined.removeEventListener("abort", abort);
41
+ resolve();
42
+ }, delay);
43
+ combined.addEventListener("abort", abort, { once: true });
44
+ });
45
+ }
46
+
20
47
  function publicRecord(record, projection) {
48
+ const continuation = projection.continuations.find(
49
+ (item) => item.localId === record.localId,
50
+ );
21
51
  const call = projection.callRecovery.records.find(
22
52
  (item) => item.ledgerId === record.ledgerId,
23
53
  );
@@ -34,6 +64,11 @@ function publicRecord(record, projection) {
34
64
  revision: record.revision,
35
65
  taskId: record.task?.taskId ?? null,
36
66
  remoteStatus: record.task?.status ?? null,
67
+ pollIntervalMs:
68
+ Number.isSafeInteger(record.task?.pollInterval) &&
69
+ record.task.pollInterval >= 0
70
+ ? record.task.pollInterval
71
+ : null,
37
72
  cancelRequested: record.cancelRequested,
38
73
  cancelUnknown: record.cancelUnknown,
39
74
  resultSaved: record.result !== null,
@@ -42,6 +77,8 @@ function publicRecord(record, projection) {
42
77
  ),
43
78
  callStatus: call?.status ?? null,
44
79
  outcomeUnknown: record.task === null && call?.status === "started",
80
+ continuationStatus: continuation?.phase ?? null,
81
+ continuationOutcomeUnknown: continuation?.phase === "started",
45
82
  expiresAt:
46
83
  expiresMs === null ||
47
84
  !Number.isFinite(expiresMs) ||
@@ -387,6 +424,114 @@ export function createDurableMcpTaskRuntime({
387
424
  });
388
425
  },
389
426
 
427
+ /**
428
+ * Opt-in foreground/background tracking for one accepted task. This only
429
+ * polls and durably delivers the verified result; it never starts a model
430
+ * turn or injects data into conversation history.
431
+ */
432
+ async watch(
433
+ localId,
434
+ {
435
+ intervalMs = null,
436
+ timeoutMs = 15 * 60 * 1000,
437
+ signal,
438
+ deliver = true,
439
+ onUpdate = null,
440
+ onDelivery = null,
441
+ } = {},
442
+ ) {
443
+ const requestedInterval = intervalMs == null ? null : Number(intervalMs);
444
+ const requestedTimeout = Number(timeoutMs);
445
+ if (
446
+ (requestedInterval !== null &&
447
+ (!Number.isSafeInteger(requestedInterval) ||
448
+ requestedInterval < 0 ||
449
+ requestedInterval > 60_000)) ||
450
+ !Number.isSafeInteger(requestedTimeout) ||
451
+ requestedTimeout < 1 ||
452
+ requestedTimeout > 24 * 60 * 60 * 1000
453
+ ) {
454
+ throw failure(
455
+ "CC_MCP_TASK_WATCH_OPTIONS_INVALID",
456
+ "MCP task watch interval/timeout is outside the allowed bounds",
457
+ );
458
+ }
459
+ const deadline = new AbortController();
460
+ const combined = AbortSignal.any(
461
+ [signal, lease.signal, deadline.signal].filter(Boolean),
462
+ );
463
+ const timeout = failure(
464
+ "CC_MCP_TASK_WATCH_TIMEOUT",
465
+ "MCP task did not produce a verified result before the watch timeout",
466
+ { localId },
467
+ );
468
+ const timer = setTimeout(() => deadline.abort(timeout), requestedTimeout);
469
+ try {
470
+ throwIfAborted(combined);
471
+ let latest = null;
472
+ for (;;) {
473
+ // Bound queueing, transport and sleep with one deadline. Passing the
474
+ // same signal also prevents queued work dispatching after timeout.
475
+ latest = await raceWithAbort(
476
+ this.poll(localId, { signal: combined }),
477
+ combined,
478
+ );
479
+ onUpdate?.(latest);
480
+ throwIfAborted(combined);
481
+ if (latest.resultSaved) break;
482
+ if (
483
+ ["completed", "failed", "cancelled"].includes(latest.remoteStatus)
484
+ ) {
485
+ latest = await raceWithAbort(
486
+ this.result(localId, { signal: combined }),
487
+ combined,
488
+ );
489
+ onUpdate?.(latest);
490
+ break;
491
+ }
492
+ await waitForTaskPoll(
493
+ requestedInterval ?? latest.pollIntervalMs ?? 1000,
494
+ combined,
495
+ lease.signal,
496
+ );
497
+ }
498
+ throwIfAborted(combined);
499
+ if (!deliver) return latest;
500
+ const receipt = await raceWithAbort(
501
+ this.deliver(localId, { signal: combined }),
502
+ combined,
503
+ );
504
+ const delivery = read().deliveries.find(
505
+ (item) =>
506
+ item.localId === localId && item.deliveryId === receipt.deliveryId,
507
+ );
508
+ // Retain the original session binding and verified external reference.
509
+ onDelivery?.(receipt, delivery || null);
510
+ return Object.freeze({ ...receipt, watched: true });
511
+ } finally {
512
+ clearTimeout(timer);
513
+ }
514
+ },
515
+
516
+ /** Start an opt-in timer without detaching it from the session lease. */
517
+ startTracking(localId, options = {}) {
518
+ const stopController = new AbortController();
519
+ const signal = options.signal
520
+ ? AbortSignal.any([options.signal, stopController.signal])
521
+ : stopController.signal;
522
+ const promise = this.watch(localId, { ...options, signal });
523
+ return Object.freeze({
524
+ promise,
525
+ stop() {
526
+ stopController.abort(
527
+ Object.assign(new Error("MCP task tracking stopped"), {
528
+ code: "CC_MCP_TASK_TRACKING_STOPPED",
529
+ }),
530
+ );
531
+ },
532
+ });
533
+ },
534
+
390
535
  result(localId, { signal } = {}) {
391
536
  return enqueue(async () => {
392
537
  const projection = read();
@@ -418,8 +563,9 @@ export function createDurableMcpTaskRuntime({
418
563
  });
419
564
  },
420
565
 
421
- deliver(localId) {
566
+ deliver(localId, { signal } = {}) {
422
567
  return enqueue(async () => {
568
+ throwIfAborted(signal);
423
569
  const projection = read();
424
570
  const record = find(localId, projection);
425
571
  if (record.result === null) {
@@ -429,6 +575,7 @@ export function createDurableMcpTaskRuntime({
429
575
  );
430
576
  }
431
577
  await repairSettlement(record);
578
+ throwIfAborted(signal);
432
579
  return deliverMcpTaskResult(sessionId, localId);
433
580
  });
434
581
  },
@@ -8,6 +8,8 @@ const STATES = new Set([
8
8
  "cancelled",
9
9
  ]);
10
10
  const RELATED_TASK = "io.modelcontextprotocol/related-task";
11
+ export const MCP_TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
12
+ export const MCP_STATELESS_PROTOCOL_VERSION = "2026-07-28";
11
13
 
12
14
  export function mcpTaskError(code, message, dispatched = false) {
13
15
  return Object.assign(new Error(message), {
@@ -31,6 +33,17 @@ function record(value) {
31
33
  }
32
34
 
33
35
  export function requireMcpTaskCapability(entry, operation) {
36
+ if (entry?.protocolVersion === MCP_STATELESS_PROTOCOL_VERSION) {
37
+ if (
38
+ operation !== "list" &&
39
+ record(entry.capabilities?.extensions?.[MCP_TASKS_EXTENSION])
40
+ )
41
+ return;
42
+ throw mcpTaskError(
43
+ "CC_MCP_TASK_UNSUPPORTED",
44
+ "MCP task extension operation was not discovered",
45
+ );
46
+ }
34
47
  const tasks = entry?.capabilities?.tasks;
35
48
  const capability =
36
49
  operation === "call"
@@ -58,6 +71,17 @@ export function requireMcpToolTaskMode(entry, toolName, augmented) {
58
71
  "MCP tool has invalid task support metadata",
59
72
  );
60
73
  }
74
+ if (entry?.protocolVersion === MCP_STATELESS_PROTOCOL_VERSION) {
75
+ if (augmented) {
76
+ requireMcpTaskCapability(entry, "call");
77
+ if (mode === "forbidden")
78
+ throw mcpTaskError(
79
+ "CC_MCP_TASK_FORBIDDEN",
80
+ "MCP tool forbids task execution",
81
+ );
82
+ }
83
+ return;
84
+ }
61
85
  if (augmented) {
62
86
  requireMcpTaskCapability(entry, "call");
63
87
  if (mode !== "required" && mode !== "optional") {
@@ -1,3 +1,4 @@
1
+ import { createSessionModelUsageRecoveryProjection } from "./session-model-usage-recovery.js";
1
2
  import {
2
3
  MCP_TASK_DELIVERY_EVENT,
3
4
  projectMcpTaskDeliveryMessage,
@@ -33,6 +34,8 @@ import {
33
34
  import { createSessionTranscriptStructureProjection } from "./session-transcript-structure.js";
34
35
  import { projectToolRoundMessages } from "./session-tool-round.js";
35
36
  import { normalizeSessionBudgetRootConfig } from "./session-budget-production-root.js";
37
+ import { projectSessionInputMessages } from "./session-input-lifecycle.js";
38
+ import { createSessionInputLifecycleProjection } from "./session-input-lifecycle.js";
36
39
  import {
37
40
  createDeferredQuestionEventReducer,
38
41
  reduceDeferredQuestionEvents,
@@ -98,6 +101,9 @@ function replayMessagesFromVerifiedEvents(events) {
98
101
  } else if (event?.type === "ws_turn") {
99
102
  const turn = projectWsTurnMessages(event);
100
103
  if (turn) suffix.push(turn.assistant, turn.user);
104
+ } else if (event?.type === "session_input_settled") {
105
+ const turn = projectSessionInputMessages(event);
106
+ if (turn) suffix.push(turn[1], turn[0]);
101
107
  }
102
108
  }
103
109
  suffix.reverse();
@@ -306,6 +312,11 @@ export function projectVerifiedSessionHostSnapshot(sessionId, events) {
306
312
  verified: true,
307
313
  });
308
314
  const deferred = reduceDeferredQuestionEvents(safeEvents, { sessionId });
315
+ const modelUsage = createSessionModelUsageRecoveryProjection();
316
+ const inputLifecycle = createSessionInputLifecycleProjection();
317
+ for (const event of safeEvents) modelUsage.accept(event);
318
+ for (const event of safeEvents) inputLifecycle.accept(event);
319
+ const inputRecovery = inputLifecycle.finish();
309
320
  return Object.freeze({
310
321
  snapshot: projectSessionHostObservation({
311
322
  sessionId,
@@ -319,10 +330,22 @@ export function projectVerifiedSessionHostSnapshot(sessionId, events) {
319
330
  deferredAnswers: deferred.answers,
320
331
  deferredQuestionSequence: deferred.maxSequence,
321
332
  sessionBudgetRoot: sessionBudgetRootFromEvents(safeEvents),
333
+ modelUsageRecovery: modelUsage.finish(),
334
+ inputRecovery,
335
+ mcpTaskReferenceDigests: Object.freeze([
336
+ ...new Set(
337
+ safeEvents
338
+ .filter((event) => event.type === MCP_TASK_DELIVERY_EVENT)
339
+ .map((event) => event.data.messageDigest),
340
+ ),
341
+ ]),
322
342
  });
323
343
  }
324
344
 
325
345
  function createStreamingSessionHostProjection(sessionId) {
346
+ const modelUsage = createSessionModelUsageRecoveryProjection();
347
+ const inputLifecycle = createSessionInputLifecycleProjection();
348
+ const mcpTaskReferenceDigests = new Set();
326
349
  let title = "Untitled";
327
350
  let lastEventType = null;
328
351
  let sessionBudgetRoot = null;
@@ -344,6 +367,10 @@ function createStreamingSessionHostProjection(sessionId) {
344
367
  throw new TypeError("Verified session event must be plain JSON data");
345
368
  }
346
369
  structure.accept(safeEvent);
370
+ if (safeEvent.type === MCP_TASK_DELIVERY_EVENT)
371
+ mcpTaskReferenceDigests.add(safeEvent.data.messageDigest);
372
+ modelUsage.accept(safeEvent);
373
+ inputLifecycle.accept(safeEvent);
347
374
  if (safeEvent.type === "session_start") {
348
375
  if (safeEvent.data?.title) title = String(safeEvent.data.title);
349
376
  if (Object.hasOwn(safeEvent.data || {}, "sessionBudgetRoot")) {
@@ -373,6 +400,7 @@ function createStreamingSessionHostProjection(sessionId) {
373
400
  );
374
401
  const recovery = mcpReducer.finish();
375
402
  const deferred = deferredQuestionReducer.finish();
403
+ const inputRecovery = inputLifecycle.finish();
376
404
  return Object.freeze({
377
405
  snapshot: projectSessionHostProjection({
378
406
  sessionId,
@@ -389,6 +417,9 @@ function createStreamingSessionHostProjection(sessionId) {
389
417
  deferredAnswers: deferred.answers,
390
418
  deferredQuestionSequence: deferred.maxSequence,
391
419
  sessionBudgetRoot,
420
+ modelUsageRecovery: modelUsage.finish(),
421
+ inputRecovery,
422
+ mcpTaskReferenceDigests: Object.freeze([...mcpTaskReferenceDigests]),
392
423
  });
393
424
  },
394
425
  };