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.
- package/README.md +67 -10
- package/package.json +2 -2
- package/src/assets/linux-subreaper/linux-arm64/manifest.json +1 -1
- package/src/assets/linux-subreaper/linux-x64/manifest.json +1 -1
- package/src/command-help-index.json +2 -2
- package/src/commands/agent.js +20 -1
- package/src/commands/mcp-tasks.js +37 -4
- package/src/commands/mcp.js +24 -0
- package/src/commands/memory.js +131 -7
- package/src/data/changelog.json +26 -0
- package/src/generated/cc-agent-protocol.schema.json +175 -69
- package/src/harness/jsonl-session-store.js +4 -0
- package/src/harness/mcp-client.js +273 -48
- package/src/harness/prompt-compressor.js +1 -0
- package/src/harness/session-index.js +8 -0
- package/src/harness/session-list-index.js +2 -0
- package/src/lib/agent-session-export.js +19 -0
- package/src/lib/app-server/context-memory-notifications.js +11 -2
- package/src/lib/app-server/server.js +1 -0
- package/src/lib/background-launch-profile.js +38 -6
- package/src/lib/context-memory-kernel/local-semantic-source.js +426 -0
- package/src/lib/context-memory-kernel/local-semantic-worker.py +109 -0
- package/src/lib/context-memory-kernel/memory-service.js +35 -2
- package/src/lib/context-memory-kernel/provider-context.js +1 -1
- package/src/lib/context-memory-kernel/runtime.js +40 -0
- package/src/lib/evolution/evolution-artifact-ports.js +36 -1
- package/src/lib/evolution/evolution-ledger-file-manifest-head-store.js +19 -0
- package/src/lib/evolution/evolution-ledger-manifest-catalog.js +13 -0
- package/src/lib/evolution/evolution-ledger-manifest-head-store.js +17 -0
- package/src/lib/evolution/evolution-ledger-v2-manifest-backend.js +29 -2
- package/src/lib/formal-budget-authority.js +56 -3
- package/src/lib/formal-budget-contract.js +90 -5
- package/src/lib/mcp-client.js +1 -0
- package/src/lib/mcp-stateless-protocol.js +158 -0
- package/src/lib/mcp-task-continuation-contract.js +129 -0
- package/src/lib/mcp-task-continuation.js +147 -0
- package/src/lib/mcp-task-journal-projection.js +49 -4
- package/src/lib/mcp-task-runtime.js +148 -1
- package/src/lib/mcp-tasks.js +24 -0
- package/src/lib/session-host-snapshot.js +31 -0
- package/src/lib/session-input-lifecycle.js +147 -0
- package/src/lib/session-input-receipt.js +64 -0
- package/src/lib/session-message-provenance.js +6 -5
- package/src/lib/session-model-usage-recovery.js +115 -0
- package/src/lib/session-transcript-history.js +3 -0
- package/src/lib/session-transcript-structure.js +8 -1
- package/src/lib/storage-failure-cause-codes.js +79 -0
- package/src/repl/agent-repl.js +348 -23
- package/src/runtime/agent-core.js +29 -11
- package/src/runtime/headless-runner.js +1 -0
- package/src/runtime/headless-stream.js +40 -33
- package/src/runtime/mcp-config.js +5 -3
- package/src/runtime/policies/agent-policy.js +1 -0
|
@@ -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
|
-
|
|
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
|
};
|
|
@@ -20,6 +20,8 @@ const STATE_SCHEMA =
|
|
|
20
20
|
const STATE_KEYS = new Set(["head", "schema"]);
|
|
21
21
|
const DEFAULT_MAXIMUM_BYTES = 256 * 1024;
|
|
22
22
|
const DIRECTORY_BOUNDARIES = new WeakMap();
|
|
23
|
+
const LOAD_OWNERS = new WeakMap();
|
|
24
|
+
const CAS_OWNERS = new WeakMap();
|
|
23
25
|
|
|
24
26
|
function exactRecord(value, keys, label) {
|
|
25
27
|
if (
|
|
@@ -222,9 +224,26 @@ export function createEvolutionLedgerFileManifestHeadBackend({
|
|
|
222
224
|
backend,
|
|
223
225
|
captureEvolutionManifestStateReaderDirectoryBoundary(stateReader),
|
|
224
226
|
);
|
|
227
|
+
LOAD_OWNERS.set(backend.load, backend);
|
|
228
|
+
CAS_OWNERS.set(backend.compareAndSet, backend);
|
|
225
229
|
return backend;
|
|
226
230
|
}
|
|
227
231
|
|
|
232
|
+
/** A head-store factory must retain both original ports from the same backend. */
|
|
233
|
+
export function captureEvolutionLedgerFileManifestHeadPortsDirectoryBoundary(
|
|
234
|
+
load,
|
|
235
|
+
compareAndSet,
|
|
236
|
+
) {
|
|
237
|
+
if (arguments.length !== 2)
|
|
238
|
+
throw new TypeError("head directory capture takes two original ports");
|
|
239
|
+
const owner = LOAD_OWNERS.get(load);
|
|
240
|
+
if (!owner || CAS_OWNERS.get(compareAndSet) !== owner)
|
|
241
|
+
throw new TypeError(
|
|
242
|
+
"original load and CAS ports from one file head backend are required",
|
|
243
|
+
);
|
|
244
|
+
return captureEvolutionLedgerFileManifestHeadDirectoryBoundary(owner);
|
|
245
|
+
}
|
|
246
|
+
|
|
228
247
|
/** Original local head directory only; structural wrappers are not owners. */
|
|
229
248
|
export function captureEvolutionLedgerFileManifestHeadDirectoryBoundary(
|
|
230
249
|
backend,
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { types as utilTypes } from "node:util";
|
|
2
|
+
import { captureEvolutionLedgerFileManifestCatalogDirectoryBoundary } from "./evolution-ledger-file-manifest-catalog.js";
|
|
3
|
+
|
|
4
|
+
const ORIGINAL_BACKENDS = new WeakMap();
|
|
2
5
|
|
|
3
6
|
import {
|
|
4
7
|
captureEvolutionLedgerManifestAuthority,
|
|
@@ -437,9 +440,19 @@ export function createEvolutionLedgerManifestCatalog(options = undefined) {
|
|
|
437
440
|
readLatest,
|
|
438
441
|
});
|
|
439
442
|
CATALOGS.add(catalog);
|
|
443
|
+
ORIGINAL_BACKENDS.set(catalog, backend);
|
|
440
444
|
return catalog;
|
|
441
445
|
}
|
|
442
446
|
|
|
447
|
+
/** Reuse the exact backend retained by this factory, never its public path. */
|
|
448
|
+
export function captureEvolutionLedgerManifestCatalogDirectoryBoundary(value) {
|
|
449
|
+
if (arguments.length !== 1 || !ORIGINAL_BACKENDS.has(value))
|
|
450
|
+
throw new TypeError("one original manifest catalog is required");
|
|
451
|
+
return captureEvolutionLedgerFileManifestCatalogDirectoryBoundary(
|
|
452
|
+
ORIGINAL_BACKENDS.get(value),
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
|
|
443
456
|
export function captureEvolutionLedgerManifestCatalog(
|
|
444
457
|
value,
|
|
445
458
|
expected = undefined,
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { types as utilTypes } from "node:util";
|
|
2
|
+
import { captureEvolutionLedgerFileManifestHeadPortsDirectoryBoundary } from "./evolution-ledger-file-manifest-head-store.js";
|
|
3
|
+
|
|
4
|
+
const ORIGINAL_PORTS = new WeakMap();
|
|
2
5
|
|
|
3
6
|
import {
|
|
4
7
|
captureEvolutionLedgerManifestAuthority,
|
|
@@ -373,9 +376,23 @@ export function createEvolutionLedgerManifestHeadStore(options = undefined) {
|
|
|
373
376
|
},
|
|
374
377
|
});
|
|
375
378
|
STORES.add(store);
|
|
379
|
+
ORIGINAL_PORTS.set(store, Object.freeze({ load, compareAndSet }));
|
|
376
380
|
return store;
|
|
377
381
|
}
|
|
378
382
|
|
|
383
|
+
/** Only the same original raw backend can own both captured head-store ports. */
|
|
384
|
+
export function captureEvolutionLedgerManifestHeadStoreDirectoryBoundary(
|
|
385
|
+
value,
|
|
386
|
+
) {
|
|
387
|
+
if (arguments.length !== 1 || !ORIGINAL_PORTS.has(value))
|
|
388
|
+
throw new TypeError("one original manifest head store is required");
|
|
389
|
+
const ports = ORIGINAL_PORTS.get(value);
|
|
390
|
+
return captureEvolutionLedgerFileManifestHeadPortsDirectoryBoundary(
|
|
391
|
+
ports.load,
|
|
392
|
+
ports.compareAndSet,
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
|
|
379
396
|
export function captureEvolutionLedgerManifestHeadStore(
|
|
380
397
|
value,
|
|
381
398
|
expected = undefined,
|
|
@@ -9,8 +9,14 @@ import {
|
|
|
9
9
|
verifyEvolutionLedgerManifestChain,
|
|
10
10
|
readEvolutionLedgerManifestEvents,
|
|
11
11
|
} from "./evolution-ledger-manifest-chain.js";
|
|
12
|
-
import {
|
|
13
|
-
|
|
12
|
+
import {
|
|
13
|
+
captureEvolutionLedgerManifestHeadStore,
|
|
14
|
+
captureEvolutionLedgerManifestHeadStoreDirectoryBoundary,
|
|
15
|
+
} from "./evolution-ledger-manifest-head-store.js";
|
|
16
|
+
import {
|
|
17
|
+
captureEvolutionLedgerManifestCatalog,
|
|
18
|
+
captureEvolutionLedgerManifestCatalogDirectoryBoundary,
|
|
19
|
+
} from "./evolution-ledger-manifest-catalog.js";
|
|
14
20
|
import { captureEvolutionLedgerManifestWitnessAdapter } from "./evolution-ledger-manifest-witness-adapter.js";
|
|
15
21
|
|
|
16
22
|
export const EVOLUTION_LEDGER_V2_MANIFEST_BACKEND_SCHEMA =
|
|
@@ -52,6 +58,7 @@ const APPEND_KEYS = new Set([
|
|
|
52
58
|
]);
|
|
53
59
|
const VERIFY_KEYS = new Set();
|
|
54
60
|
const BACKENDS = new WeakSet();
|
|
61
|
+
const ORIGINAL_MANIFEST_COMPONENTS = new WeakMap();
|
|
55
62
|
|
|
56
63
|
export class EvolutionLedgerV2ManifestBackendError extends Error {
|
|
57
64
|
constructor(code, message, options = undefined) {
|
|
@@ -602,9 +609,29 @@ export function createEvolutionLedgerV2ManifestBackend(options = undefined) {
|
|
|
602
609
|
},
|
|
603
610
|
});
|
|
604
611
|
BACKENDS.add(backend);
|
|
612
|
+
ORIGINAL_MANIFEST_COMPONENTS.set(backend, {
|
|
613
|
+
catalog,
|
|
614
|
+
headStore,
|
|
615
|
+
boundaries: null,
|
|
616
|
+
});
|
|
605
617
|
return backend;
|
|
606
618
|
}
|
|
607
619
|
|
|
620
|
+
/** Local metadata only. Capturing these components does not authenticate state. */
|
|
621
|
+
export function captureEvolutionLedgerV2ManifestDirectoryBoundaries(value) {
|
|
622
|
+
if (arguments.length !== 1 || !ORIGINAL_MANIFEST_COMPONENTS.has(value))
|
|
623
|
+
throw new TypeError("one original v2 manifest backend is required");
|
|
624
|
+
const components = ORIGINAL_MANIFEST_COMPONENTS.get(value);
|
|
625
|
+
const catalog = captureEvolutionLedgerManifestCatalogDirectoryBoundary(
|
|
626
|
+
components.catalog,
|
|
627
|
+
);
|
|
628
|
+
const head = captureEvolutionLedgerManifestHeadStoreDirectoryBoundary(
|
|
629
|
+
components.headStore,
|
|
630
|
+
);
|
|
631
|
+
components.boundaries ??= Object.freeze({ catalog, head });
|
|
632
|
+
return components.boundaries;
|
|
633
|
+
}
|
|
634
|
+
|
|
608
635
|
export function captureEvolutionLedgerV2ManifestBackend(value) {
|
|
609
636
|
if (!BACKENDS.has(value)) {
|
|
610
637
|
throw new TypeError(
|
|
@@ -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
|
-
|
|
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", {
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
333
|
-
cached * BigInt(
|
|
334
|
-
output * BigInt(
|
|
417
|
+
(input - cached) * BigInt(rates.inputMicrosPerMillion) +
|
|
418
|
+
cached * BigInt(rates.cachedMicrosPerMillion) +
|
|
419
|
+
output * BigInt(rates.outputMicrosPerMillion),
|
|
335
420
|
1_000_000n,
|
|
336
|
-
) + BigInt(
|
|
421
|
+
) + BigInt(rates.fixedFeeMicros),
|
|
337
422
|
);
|
|
338
423
|
}
|
|
339
424
|
export function convertToUsd(nativeMicros, rate) {
|
package/src/lib/mcp-client.js
CHANGED
|
@@ -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
|
+
}
|