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
@@ -0,0 +1,147 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ // Acceptance is evidence for local inspection, never a provider message.
4
+ // A single settled event publishes the complete conversation pair.
5
+ export const SESSION_INPUT_ACCEPTED = "session_input_accepted";
6
+ export const SESSION_INPUT_SETTLED = "session_input_settled";
7
+ const SCHEMA_VERSION = 1;
8
+ const MAX_PENDING_INPUTS = 100_000;
9
+
10
+ function invalid(detail) {
11
+ return Object.assign(
12
+ new Error(`Invalid session input lifecycle: ${detail}`),
13
+ {
14
+ code: "CC_SESSION_INPUT_LIFECYCLE_INVALID",
15
+ },
16
+ );
17
+ }
18
+
19
+ function identity(value, field) {
20
+ if (typeof value !== "string" || !/^[A-Za-z0-9_:.-]{1,160}$/u.test(value))
21
+ throw invalid(field);
22
+ return value;
23
+ }
24
+
25
+ function text(value, field) {
26
+ if (typeof value !== "string") throw invalid(field);
27
+ return value;
28
+ }
29
+
30
+ function hash(value, field) {
31
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/u.test(value))
32
+ throw invalid(field);
33
+ return value;
34
+ }
35
+
36
+ export function sessionInputDigest(prompt) {
37
+ return createHash("sha256")
38
+ .update(JSON.stringify(text(prompt, "prompt")))
39
+ .digest("hex");
40
+ }
41
+
42
+ export function createSessionInputAccepted({ inputId, turnId, prompt }) {
43
+ return Object.freeze({
44
+ schemaVersion: SCHEMA_VERSION,
45
+ inputId: identity(inputId, "inputId"),
46
+ turnId: identity(turnId, "turnId"),
47
+ prompt: text(prompt, "prompt"),
48
+ inputDigest: sessionInputDigest(prompt),
49
+ });
50
+ }
51
+
52
+ function acceptedData(value) {
53
+ const canonical = createSessionInputAccepted(value || {});
54
+ if (
55
+ value?.schemaVersion !== SCHEMA_VERSION ||
56
+ value.inputDigest !== canonical.inputDigest
57
+ )
58
+ throw invalid("acceptance schema or digest");
59
+ return canonical;
60
+ }
61
+
62
+ export function createSessionInputSettled(accepted, acceptanceHash, response) {
63
+ const data = acceptedData(accepted);
64
+ return Object.freeze({
65
+ schemaVersion: SCHEMA_VERSION,
66
+ inputId: data.inputId,
67
+ turnId: data.turnId,
68
+ inputDigest: data.inputDigest,
69
+ acceptanceHash: hash(acceptanceHash, "acceptanceHash"),
70
+ user: Object.freeze({ role: "user", content: data.prompt }),
71
+ assistant: Object.freeze({
72
+ role: "assistant",
73
+ content: text(response, "response"),
74
+ }),
75
+ });
76
+ }
77
+
78
+ export function projectSessionInputMessages(event) {
79
+ if (event?.type !== SESSION_INPUT_SETTLED) return null;
80
+ const data = event.data;
81
+ const accepted = createSessionInputAccepted({
82
+ inputId: data?.inputId,
83
+ turnId: data?.turnId,
84
+ prompt: data?.user?.content,
85
+ });
86
+ const settled = createSessionInputSettled(
87
+ accepted,
88
+ data?.acceptanceHash,
89
+ data?.assistant?.content,
90
+ );
91
+ if (
92
+ data?.schemaVersion !== SCHEMA_VERSION ||
93
+ data?.user?.role !== "user" ||
94
+ data?.assistant?.role !== "assistant" ||
95
+ data?.inputDigest !== settled.inputDigest
96
+ )
97
+ throw invalid("settlement schema, roles or digest");
98
+ return Object.freeze([settled.user, settled.assistant]);
99
+ }
100
+
101
+ /** Feed only events from the canonical verified chain. Private content must
102
+ * never be attached to the public host snapshot or runtime event stream. */
103
+ export function createSessionInputLifecycleProjection() {
104
+ const pending = new Map();
105
+ return {
106
+ accept(event) {
107
+ if (event?.type === SESSION_INPUT_ACCEPTED) {
108
+ const data = acceptedData(event.data);
109
+ if (pending.has(data.inputId)) throw invalid("duplicate acceptance");
110
+ if (pending.size >= MAX_PENDING_INPUTS)
111
+ throw invalid("pending capacity");
112
+ pending.set(
113
+ data.inputId,
114
+ Object.freeze({
115
+ ...data,
116
+ acceptanceHash: hash(event.hash, "acceptance event hash"),
117
+ }),
118
+ );
119
+ } else if (event?.type === SESSION_INPUT_SETTLED) {
120
+ projectSessionInputMessages(event);
121
+ const prior = pending.get(event.data.inputId);
122
+ if (
123
+ !prior ||
124
+ prior.turnId !== event.data.turnId ||
125
+ prior.inputDigest !== event.data.inputDigest ||
126
+ prior.acceptanceHash !== event.data.acceptanceHash
127
+ )
128
+ throw invalid("settlement does not match pending acceptance");
129
+ pending.delete(event.data.inputId);
130
+ }
131
+ },
132
+ finish() {
133
+ const inputs = Object.freeze([...pending.values()]);
134
+ return Object.freeze({
135
+ pendingInputs: inputs,
136
+ summary: Object.freeze({
137
+ pendingCount: inputs.length,
138
+ inputs: Object.freeze(
139
+ inputs.map(({ inputId, turnId, inputDigest }) =>
140
+ Object.freeze({ inputId, turnId, inputDigest }),
141
+ ),
142
+ ),
143
+ }),
144
+ });
145
+ },
146
+ };
147
+ }
@@ -1,8 +1,16 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import {
3
3
  appendAuthorityEventWithVerifiedProjection,
4
+ appendAuthorityEvent,
4
5
  readVerifiedProjection,
5
6
  } from "../harness/jsonl-session-store.js";
7
+ import {
8
+ SESSION_INPUT_ACCEPTED,
9
+ SESSION_INPUT_SETTLED,
10
+ createSessionInputAccepted,
11
+ createSessionInputSettled,
12
+ createSessionInputLifecycleProjection,
13
+ } from "./session-input-lifecycle.js";
6
14
 
7
15
  export function validateClientMessageId(value) {
8
16
  if (typeof value !== "string" || !/^[a-zA-Z0-9_-]{1,80}$/u.test(value)) {
@@ -108,3 +116,59 @@ export function appendSessionInputWithReceipt(
108
116
  throw error;
109
117
  }
110
118
  }
119
+
120
+ export function readSessionInputAcceptance(sessionId, inputId) {
121
+ const projection = createSessionInputLifecycleProjection();
122
+ const state = readVerifiedProjection(sessionId, () => projection);
123
+ const pending = state?.pendingInputs?.find(
124
+ (item) => item.inputId === inputId,
125
+ );
126
+ return pending || null;
127
+ }
128
+
129
+ /** Persist the accepted prompt in a non-replay event before provider dispatch. */
130
+ export function appendSessionInputAcceptance(
131
+ sessionId,
132
+ { inputId, turnId, prompt },
133
+ ) {
134
+ const existing = readSessionInputAcceptance(sessionId, inputId);
135
+ const accepted = createSessionInputAccepted({ inputId, turnId, prompt });
136
+ if (existing) {
137
+ if (
138
+ existing.turnId !== accepted.turnId ||
139
+ existing.inputDigest !== accepted.inputDigest
140
+ )
141
+ throw new Error("inputId was already accepted for different input");
142
+ return { ...existing, duplicate: true };
143
+ }
144
+ const appended = appendAuthorityEvent(
145
+ sessionId,
146
+ SESSION_INPUT_ACCEPTED,
147
+ accepted,
148
+ );
149
+ return {
150
+ ...accepted,
151
+ acceptanceHash: appended.hash,
152
+ duplicate: false,
153
+ };
154
+ }
155
+
156
+ /** Publish the complete user/assistant pair as one replayable event. */
157
+ export function appendSessionInputSettlement(sessionId, accepted, response) {
158
+ const pending = readSessionInputAcceptance(sessionId, accepted?.inputId);
159
+ if (
160
+ !pending ||
161
+ pending.turnId !== accepted?.turnId ||
162
+ pending.inputDigest !== accepted?.inputDigest ||
163
+ pending.acceptanceHash !== accepted?.acceptanceHash
164
+ ) {
165
+ throw new Error("Settlement does not match the pending accepted input");
166
+ }
167
+ const data = createSessionInputSettled(
168
+ accepted,
169
+ accepted.acceptanceHash,
170
+ response,
171
+ );
172
+ const appended = appendAuthorityEvent(sessionId, SESSION_INPUT_SETTLED, data);
173
+ return { ...data, eventHash: appended.hash };
174
+ }
@@ -219,6 +219,7 @@ function cloneWithoutWireTag(snapshot) {
219
219
  // lookup/deduplication still verifies the original event and digest. Apply this
220
220
  // only after the full JSON-safe clone, including for historical checkpoints.
221
221
  function conversationMessage(clean) {
222
+ if (clean) delete clean._cc_mcp_task_continuation;
222
223
  if (clean?.role === "user") {
223
224
  delete clean.clientMessageId;
224
225
  delete clean.inputDigest;
@@ -240,11 +241,11 @@ function validWireTag(value) {
240
241
  const snapshot = plainDataSnapshot(value);
241
242
  return Boolean(
242
243
  snapshot &&
243
- snapshot.keys.length === 2 &&
244
- snapshot.keys.includes("schema") &&
245
- snapshot.keys.includes("kind") &&
246
- dataValue(snapshot, "schema") === SESSION_MESSAGE_PROVENANCE_SCHEMA &&
247
- DURABLE_KINDS.has(dataValue(snapshot, "kind")),
244
+ snapshot.keys.length === 2 &&
245
+ snapshot.keys.includes("schema") &&
246
+ snapshot.keys.includes("kind") &&
247
+ dataValue(snapshot, "schema") === SESSION_MESSAGE_PROVENANCE_SCHEMA &&
248
+ DURABLE_KINDS.has(dataValue(snapshot, "kind")),
248
249
  );
249
250
  }
250
251
 
@@ -0,0 +1,115 @@
1
+ import {
2
+ projectRuntimeTokenUsage,
3
+ projectRuntimeUsageBoundary,
4
+ } from "./runtime-usage-ledger.js";
5
+ /**
6
+ * Local model-call recovery from the host's verified event sample.
7
+ * No observabilityScope authority or complete billing assurance is granted.
8
+ */
9
+ const MAX_PENDING_CALLS = 100_000;
10
+
11
+ function sameIdentity(left, right) {
12
+ return (
13
+ right !== null &&
14
+ ["provider", "model", "source", "operationId"].every(
15
+ (key) => (left[key] ?? null) === (right[key] ?? null),
16
+ )
17
+ );
18
+ }
19
+
20
+ export function createSessionModelUsageRecoveryProjection() {
21
+ // Retain only unresolved calls, not the entire settled session history.
22
+ const calls = new Map();
23
+ function remember(id, record) {
24
+ if (!calls.has(id) && calls.size >= MAX_PENDING_CALLS) {
25
+ throw Object.assign(
26
+ new Error("Local model usage recovery exceeds 100000 pending calls"),
27
+ {
28
+ code: "CC_MODEL_USAGE_RECOVERY_CAPACITY",
29
+ },
30
+ );
31
+ }
32
+ calls.set(id, record);
33
+ }
34
+ return {
35
+ accept(event) {
36
+ const id = event?.data?.callId;
37
+ if (typeof id !== "string" || !id) return;
38
+ const previous = calls.get(id);
39
+ if (event.type === "model_usage_started") {
40
+ // A reused historical id is conservatively pending again; no stored
41
+ // token settlement is removed and no known charge is reset.
42
+ if (!previous)
43
+ remember(id, {
44
+ status: "started",
45
+ ...projectRuntimeUsageBoundary(event.data, "started"),
46
+ });
47
+ } else if (event.type === "model_usage_unknown") {
48
+ const observed = projectRuntimeUsageBoundary(event.data, "unknown");
49
+ if (!previous) remember(id, { status: "unknown", ...observed });
50
+ else if (sameIdentity(previous, observed)) previous.status = "unknown";
51
+ } else if (event.type === "token_usage" && previous) {
52
+ try {
53
+ const projected = projectRuntimeTokenUsage(event.data);
54
+ const observed = projectRuntimeUsageBoundary(projected, "started");
55
+ if (
56
+ event.data.source != null &&
57
+ event.data.source !== observed.source
58
+ )
59
+ return;
60
+ if (sameIdentity(previous, observed)) calls.delete(id);
61
+ } catch {
62
+ // Keep the interrupted call unknown when the shared runtime ledger
63
+ // rejects a malformed/ambiguous token settlement.
64
+ }
65
+ }
66
+ },
67
+ finish() {
68
+ const unsettledCallIds = [];
69
+ const unknownCallIds = [];
70
+ for (const [id, record] of calls) {
71
+ if (record.status === "started") unsettledCallIds.push(id);
72
+ else if (record.status === "unknown") unknownCallIds.push(id);
73
+ }
74
+ const byCode = [];
75
+ if (unsettledCallIds.length)
76
+ byCode.push(
77
+ Object.freeze({
78
+ code: "model-usage-unsettled",
79
+ count: unsettledCallIds.length,
80
+ }),
81
+ );
82
+ if (unknownCallIds.length)
83
+ byCode.push(
84
+ Object.freeze({
85
+ code: "model-usage-unknown",
86
+ count: unknownCallIds.length,
87
+ }),
88
+ );
89
+ return Object.freeze({
90
+ schema: "chainlesschain.local-session-model-usage-recovery/v1",
91
+ assurance: "recorded-model-call-ledger-only",
92
+ billingComplete: false,
93
+ telemetryComplete: byCode.length === 0,
94
+ retainedCallCount: calls.size,
95
+ unsettledCallIds: Object.freeze(unsettledCallIds),
96
+ unknownCallIds: Object.freeze(unknownCallIds),
97
+ unknownEvidence: Object.freeze({ byCode: Object.freeze(byCode) }),
98
+ });
99
+ },
100
+ };
101
+ }
102
+ export function formatSessionModelUsageRecoveryNotice(sessionId, recovery) {
103
+ const ids = [
104
+ ...(recovery?.unsettledCallIds || []),
105
+ ...(recovery?.unknownCallIds || []),
106
+ ];
107
+ if (!ids.length) return null;
108
+ // JSON quoting prevents persisted identifiers from injecting terminal lines.
109
+ const listed = ids
110
+ .slice(0, 20)
111
+ .map((id) => JSON.stringify(id))
112
+ .join(", ");
113
+ const remaining = ids.length > 20 ? ` (+${ids.length - 20} more)` : "";
114
+ return `[recovery] Session ${JSON.stringify(sessionId)} has interrupted model request(s) ${listed}${remaining}; usage and cost remain unknown. Original prompt may not have been saved. Inspect the saved session and reconcile provider usage before explicitly resubmitting; requests are not retried automatically.`;
115
+ }
@@ -16,6 +16,7 @@ import {
16
16
  import { createSessionHistoryOrigins } from "./session-history-origins.js";
17
17
  import { getDurableSystemMessageProvenance } from "./session-message-provenance.js";
18
18
  import { projectToolRoundMessages } from "./session-tool-round.js";
19
+ import { projectSessionInputMessages } from "./session-input-lifecycle.js";
19
20
  import {
20
21
  BRANCH_HISTORY_SCHEMA,
21
22
  BRANCH_HISTORY_SYSTEM_ORIGINS_SCHEMA,
@@ -50,6 +51,8 @@ function eventMessages(event, imported = null) {
50
51
  const pair = projectWsTurnMessages(event);
51
52
  if (pair) return [pair.user, pair.assistant];
52
53
  }
54
+ if (event.type === "session_input_settled")
55
+ return projectSessionInputMessages(event) || [];
53
56
  return [];
54
57
  }
55
58
  const displayable = (message) =>
@@ -1,6 +1,10 @@
1
1
  import { projectToolRoundMessages } from "./session-tool-round.js";
2
2
  import { createMcpTaskJournalProjection } from "./mcp-task-journal-projection.js";
3
3
  import { MCP_TASK_DELIVERY_EVENT } from "./mcp-task-delivery-contract.js";
4
+ import {
5
+ MCP_TASK_CONTINUATION_STARTED,
6
+ MCP_TASK_CONTINUATION_FIELD,
7
+ } from "./mcp-task-continuation-contract.js";
4
8
  /**
5
9
  * Streaming structural authority for canonical session transcripts.
6
10
  *
@@ -85,7 +89,10 @@ export function createSessionTranscriptStructureProjection(
85
89
  return Object.freeze({
86
90
  accept(event) {
87
91
  headHash = event?.hash || null;
88
- hasDelivery ||= event?.type === MCP_TASK_DELIVERY_EVENT;
92
+ hasDelivery ||=
93
+ event?.type === MCP_TASK_DELIVERY_EVENT ||
94
+ event?.type === MCP_TASK_CONTINUATION_STARTED ||
95
+ event?.data?.[MCP_TASK_CONTINUATION_FIELD] !== undefined;
89
96
  if (!taskJournalError && taskJournal) {
90
97
  try {
91
98
  taskJournal.accept(event);
@@ -216,6 +216,15 @@ const REASON_MARKER = " [storage_reason: ";
216
216
  const MARKER = " [storage_cause_codes: ";
217
217
  const STAGE_MARKER = " [storage_stage: ";
218
218
  const FAILURE_STAGES = new WeakMap();
219
+ const FAILURE_CLOCK_WINDOWS = new WeakMap();
220
+ const CLOCK_WINDOW_FIELDS = [
221
+ "windowSize",
222
+ "backwardCount",
223
+ "expiredCount",
224
+ "minRemainingMs",
225
+ "maxReadAgeMs",
226
+ "elapsedMs",
227
+ ];
219
228
  const ARTIFACT_TYPES = new Set([
220
229
  "source-evidence",
221
230
  "model-projection",
@@ -329,6 +338,76 @@ function ownData(value, key) {
329
338
  return descriptor && "value" in descriptor ? descriptor.value : undefined;
330
339
  }
331
340
 
341
+ /** Numeric observations only; this neither adjudicates nor renews a lease. */
342
+ export function recordStorageFailureClockWindow(error, observation) {
343
+ try {
344
+ if (
345
+ error === null ||
346
+ typeof error !== "object" ||
347
+ types.isProxy(error) ||
348
+ ownData(error, "code") !== "CC_EVOLUTION_ARTIFACT_EXPIRED" ||
349
+ ownData(error, "message") !==
350
+ "artifact authority expired before ledger history release" ||
351
+ observation === null ||
352
+ typeof observation !== "object" ||
353
+ types.isProxy(observation) ||
354
+ Reflect.ownKeys(observation).length !== CLOCK_WINDOW_FIELDS.length
355
+ )
356
+ return error;
357
+ const safe = {};
358
+ for (const field of CLOCK_WINDOW_FIELDS) {
359
+ const value = ownData(observation, field);
360
+ const count = field === "windowSize" || field.endsWith("Count");
361
+ if (
362
+ count
363
+ ? !Number.isSafeInteger(value) || value < 0
364
+ : value !== null &&
365
+ (typeof value !== "number" ||
366
+ !Number.isFinite(value) ||
367
+ Math.abs(value) > Number.MAX_SAFE_INTEGER ||
368
+ (field === "elapsedMs" && value < 0))
369
+ )
370
+ return error;
371
+ safe[field] = value;
372
+ }
373
+ if (
374
+ safe.windowSize < 1 ||
375
+ safe.backwardCount > safe.windowSize ||
376
+ safe.expiredCount > safe.windowSize ||
377
+ safe.backwardCount + safe.expiredCount < 1
378
+ )
379
+ return error;
380
+ FAILURE_CLOCK_WINDOWS.set(error, Object.freeze(safe));
381
+ } catch {
382
+ // Diagnostics cannot replace the original exception.
383
+ }
384
+ return error;
385
+ }
386
+
387
+ /** Follow only bounded own-data causes; never read arbitrary error metadata. */
388
+ export function storageFailureClockWindow(error) {
389
+ try {
390
+ const seen = new Set();
391
+ let current = error;
392
+ for (let depth = 0; depth < MAX_CAUSES; depth++) {
393
+ if (
394
+ current === null ||
395
+ typeof current !== "object" ||
396
+ types.isProxy(current) ||
397
+ seen.has(current)
398
+ )
399
+ break;
400
+ seen.add(current);
401
+ const observation = FAILURE_CLOCK_WINDOWS.get(current);
402
+ if (observation) return observation;
403
+ current = ownData(current, "cause");
404
+ }
405
+ } catch {
406
+ // Observation must never change the original error or exit outcome.
407
+ }
408
+ return null;
409
+ }
410
+
332
411
  /** Preserve the original error; retain only an allow-listed branch token. */
333
412
  export function recordStorageFailureReason(error, reason) {
334
413
  try {