@full-self-browsing/lattice 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +306 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8036 -163
- package/dist/index.js.map +1 -1
- package/dist/{run-crew-DDznbc3G.js → run-crew-CKdBjh5P.js} +138 -16
- package/dist/run-crew-CKdBjh5P.js.map +1 -0
- package/dist/{runtime-BTi8lr_O.js → runtime-D25ehzCj.js} +6 -3
- package/dist/runtime-D25ehzCj.js.map +1 -0
- package/package.json +7 -5
- package/dist/run-crew-DDznbc3G.js.map +0 -1
- package/dist/runtime-BTi8lr_O.js.map +0 -1
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-CiIaOW0V.js";
|
|
2
|
-
import { a as createNoopAgentHost, f as validateSchemaOutput, n as runAgentInternal, p as formatToolsForProvider, u as createNoopSurvivabilityAdapter, y as createReceipt } from "./runtime-
|
|
2
|
+
import { O as isArtifactRef, a as createNoopAgentHost, f as validateSchemaOutput, k as toArtifactRef, n as runAgentInternal, p as formatToolsForProvider, u as createNoopSurvivabilityAdapter, y as createReceipt } from "./runtime-D25ehzCj.js";
|
|
3
|
+
import canonicalize from "canonicalize";
|
|
4
|
+
//#region src/receipts/cid.ts
|
|
5
|
+
/**
|
|
6
|
+
* Derive the content-addressed CID of a receipt envelope.
|
|
7
|
+
*
|
|
8
|
+
* Returns `sha256:<hex>` where `<hex>` is the 64-char lowercase SHA-256
|
|
9
|
+
* digest of the decoded DSSE payload bytes. No KeySet, signer, or other
|
|
10
|
+
* key material is required — callers chaining receipts (parentReceiptCid)
|
|
11
|
+
* compute this from the parent envelope alone.
|
|
12
|
+
*/
|
|
13
|
+
async function receiptCid(envelope) {
|
|
14
|
+
const bytes = Uint8Array.from(atob(envelope.payload), (c) => c.charCodeAt(0));
|
|
15
|
+
const copy = new Uint8Array(bytes.byteLength);
|
|
16
|
+
copy.set(bytes);
|
|
17
|
+
const digest = await crypto.subtle.digest("SHA-256", copy.buffer);
|
|
18
|
+
return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
3
21
|
//#region src/agent/infra/cost-tracker.ts
|
|
4
22
|
const WARNING_THRESHOLD = .8;
|
|
5
23
|
function createCostTracker() {
|
|
@@ -30,21 +48,119 @@ function createCostTracker() {
|
|
|
30
48
|
};
|
|
31
49
|
}
|
|
32
50
|
//#endregion
|
|
33
|
-
//#region src/receipts/
|
|
51
|
+
//#region src/receipts/lineage.ts
|
|
52
|
+
const encoder = new TextEncoder();
|
|
53
|
+
const LEAF_DOMAIN = encoder.encode("lattice-lineage-leaf-v1:");
|
|
54
|
+
const NODE_DOMAIN = encoder.encode("lattice-lineage-node-v1:");
|
|
34
55
|
/**
|
|
35
|
-
*
|
|
56
|
+
* Compute a deterministic descriptor-only merkle root for artifact lineage.
|
|
36
57
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* key material is required — callers chaining receipts (parentReceiptCid)
|
|
40
|
-
* compute this from the parent envelope alone.
|
|
58
|
+
* The root commits to `ArtifactRef` descriptors and nested lineage graphs, not
|
|
59
|
+
* raw artifact values. Returns undefined when no lineage metadata exists.
|
|
41
60
|
*/
|
|
42
|
-
async function
|
|
43
|
-
const
|
|
61
|
+
async function computeArtifactLineageMerkleRoot(artifacts) {
|
|
62
|
+
const leaves = artifacts.filter((artifact) => artifact.lineage !== void 0).map((artifact) => canonicalLineageLeaf(artifact));
|
|
63
|
+
if (leaves.length === 0) return void 0;
|
|
64
|
+
let level = (await Promise.all(leaves.map((leaf) => sha256(concatBytes(LEAF_DOMAIN, leaf))))).sort(compareBytes);
|
|
65
|
+
while (level.length > 1) {
|
|
66
|
+
const next = [];
|
|
67
|
+
for (let i = 0; i < level.length; i += 2) {
|
|
68
|
+
const left = level[i];
|
|
69
|
+
const right = level[i + 1] ?? left;
|
|
70
|
+
next.push(await sha256(concatBytes(NODE_DOMAIN, left, right)));
|
|
71
|
+
}
|
|
72
|
+
level = next.sort(compareBytes);
|
|
73
|
+
}
|
|
74
|
+
return `sha256:${bytesToHex(level[0])}`;
|
|
75
|
+
}
|
|
76
|
+
function canonicalLineageLeaf(artifact) {
|
|
77
|
+
const json = canonicalize(sanitizeArtifactRef(artifact));
|
|
78
|
+
if (json === void 0) throw new Error("computeArtifactLineageMerkleRoot: lineage descriptor is not canonicalizable.");
|
|
79
|
+
return encoder.encode(json);
|
|
80
|
+
}
|
|
81
|
+
function sanitizeArtifactRef(input) {
|
|
82
|
+
const ref = toArtifactRef(input);
|
|
83
|
+
return compactObject({
|
|
84
|
+
id: ref.id,
|
|
85
|
+
kind: ref.kind,
|
|
86
|
+
source: ref.source,
|
|
87
|
+
privacy: ref.privacy,
|
|
88
|
+
mediaType: ref.mediaType,
|
|
89
|
+
label: ref.label,
|
|
90
|
+
metadata: sanitizeUnknown(ref.metadata),
|
|
91
|
+
size: sanitizeUnknown(ref.size),
|
|
92
|
+
fingerprint: sanitizeUnknown(ref.fingerprint),
|
|
93
|
+
storage: sanitizeUnknown(ref.storage),
|
|
94
|
+
lineage: ref.lineage !== void 0 ? sanitizeLineage(ref.lineage) : void 0
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
function sanitizeLineage(lineage) {
|
|
98
|
+
return compactObject({
|
|
99
|
+
parents: lineage.parents.map((parent) => sanitizeArtifactRef(parent)).sort(compareCanonicalJson),
|
|
100
|
+
transform: compactObject({
|
|
101
|
+
kind: lineage.transform.kind,
|
|
102
|
+
name: lineage.transform.name,
|
|
103
|
+
metadata: sanitizeUnknown(lineage.transform.metadata)
|
|
104
|
+
})
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
function sanitizeUnknown(value) {
|
|
108
|
+
if (value === void 0) return void 0;
|
|
109
|
+
if (value === null) return null;
|
|
110
|
+
switch (typeof value) {
|
|
111
|
+
case "string":
|
|
112
|
+
case "boolean": return value;
|
|
113
|
+
case "number": return Number.isFinite(value) ? value : void 0;
|
|
114
|
+
case "bigint": return value.toString();
|
|
115
|
+
case "object": {
|
|
116
|
+
if (Array.isArray(value)) return value.map((item) => sanitizeUnknown(item)).filter((item) => item !== void 0);
|
|
117
|
+
const out = {};
|
|
118
|
+
for (const key of Object.keys(value).sort()) {
|
|
119
|
+
const child = sanitizeUnknown(value[key]);
|
|
120
|
+
if (child !== void 0) out[key] = child;
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
default: return;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function compactObject(input) {
|
|
128
|
+
const out = {};
|
|
129
|
+
for (const key of Object.keys(input).sort()) {
|
|
130
|
+
const value = input[key];
|
|
131
|
+
if (value !== void 0) out[key] = value;
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
function compareCanonicalJson(a, b) {
|
|
136
|
+
const aJson = canonicalize(a) ?? "";
|
|
137
|
+
const bJson = canonicalize(b) ?? "";
|
|
138
|
+
return aJson.localeCompare(bJson);
|
|
139
|
+
}
|
|
140
|
+
async function sha256(bytes) {
|
|
141
|
+
const digest = await crypto.subtle.digest("SHA-256", toArrayBuffer(bytes));
|
|
142
|
+
return new Uint8Array(digest);
|
|
143
|
+
}
|
|
144
|
+
function concatBytes(...chunks) {
|
|
145
|
+
const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
|
|
146
|
+
const out = new Uint8Array(total);
|
|
147
|
+
let offset = 0;
|
|
148
|
+
for (const chunk of chunks) {
|
|
149
|
+
out.set(chunk, offset);
|
|
150
|
+
offset += chunk.byteLength;
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
function compareBytes(a, b) {
|
|
155
|
+
return bytesToHex(a).localeCompare(bytesToHex(b));
|
|
156
|
+
}
|
|
157
|
+
function bytesToHex(bytes) {
|
|
158
|
+
return Array.from(bytes).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
159
|
+
}
|
|
160
|
+
function toArrayBuffer(bytes) {
|
|
44
161
|
const copy = new Uint8Array(bytes.byteLength);
|
|
45
162
|
copy.set(bytes);
|
|
46
|
-
|
|
47
|
-
return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
163
|
+
return copy.buffer;
|
|
48
164
|
}
|
|
49
165
|
//#endregion
|
|
50
166
|
//#region src/agent/infra/action-history.ts
|
|
@@ -172,7 +288,9 @@ function createDispatcherNode(spec, ctx, shared) {
|
|
|
172
288
|
return result;
|
|
173
289
|
}
|
|
174
290
|
const receipts = [];
|
|
291
|
+
const childArtifacts = extractArtifacts(childResult);
|
|
175
292
|
if (ctx.signer !== void 0) try {
|
|
293
|
+
const lineageMerkleRoot = await computeArtifactLineageMerkleRoot(childArtifacts);
|
|
176
294
|
const envelope = await createReceipt({
|
|
177
295
|
runId: shared.runId,
|
|
178
296
|
model: {
|
|
@@ -186,6 +304,7 @@ function createDispatcherNode(spec, ctx, shared) {
|
|
|
186
304
|
},
|
|
187
305
|
...ctx.crewRootCid !== void 0 ? { parentReceiptCid: ctx.crewRootCid } : {},
|
|
188
306
|
usage: childResult.usage,
|
|
307
|
+
...lineageMerkleRoot !== void 0 ? { lineageMerkleRoot } : {},
|
|
189
308
|
contractVerdict: "success",
|
|
190
309
|
contractHash: null,
|
|
191
310
|
inputHashes: [],
|
|
@@ -197,7 +316,7 @@ function createDispatcherNode(spec, ctx, shared) {
|
|
|
197
316
|
} catch {}
|
|
198
317
|
const envelope = {
|
|
199
318
|
summary: extractSummary(childResult.output),
|
|
200
|
-
artifacts:
|
|
319
|
+
artifacts: childArtifacts,
|
|
201
320
|
receipts
|
|
202
321
|
};
|
|
203
322
|
const validation = await validateSchemaOutput(childSpec.id, childSpec.summaryReturnSchema, envelope);
|
|
@@ -350,7 +469,7 @@ function extractSummary(output) {
|
|
|
350
469
|
}
|
|
351
470
|
function extractArtifacts(result) {
|
|
352
471
|
const artifacts = result.artifacts;
|
|
353
|
-
return Array.isArray(artifacts) ?
|
|
472
|
+
return Array.isArray(artifacts) ? artifacts.filter(isArtifactRef).map(toArtifactRef) : [];
|
|
354
473
|
}
|
|
355
474
|
/**
|
|
356
475
|
* Wrap a survivability adapter so serialized child snapshots carry the
|
|
@@ -676,7 +795,8 @@ async function runAgentCrew(options, config = {}) {
|
|
|
676
795
|
usage: parentResult.usage,
|
|
677
796
|
signer: options.signer,
|
|
678
797
|
parentReceiptCid: crewRoot.cid,
|
|
679
|
-
success: parentResult.kind === "success"
|
|
798
|
+
success: parentResult.kind === "success",
|
|
799
|
+
artifacts: parentResult.kind === "success" ? parentResult.artifacts ?? [] : []
|
|
680
800
|
});
|
|
681
801
|
receipts.push(parentEnvelope);
|
|
682
802
|
}
|
|
@@ -819,6 +939,7 @@ async function maybeMintCrewRoot(input) {
|
|
|
819
939
|
};
|
|
820
940
|
}
|
|
821
941
|
async function createAgentCompletionReceipt(input) {
|
|
942
|
+
const lineageMerkleRoot = await computeArtifactLineageMerkleRoot(input.artifacts ?? []);
|
|
822
943
|
return createReceipt({
|
|
823
944
|
runId: input.runId,
|
|
824
945
|
model: {
|
|
@@ -831,6 +952,7 @@ async function createAgentCompletionReceipt(input) {
|
|
|
831
952
|
attemptNumber: 1
|
|
832
953
|
},
|
|
833
954
|
parentReceiptCid: input.parentReceiptCid,
|
|
955
|
+
...lineageMerkleRoot !== void 0 ? { lineageMerkleRoot } : {},
|
|
834
956
|
usage: input.usage,
|
|
835
957
|
contractVerdict: input.success ? "success" : "execution-failed",
|
|
836
958
|
contractHash: null,
|
|
@@ -883,6 +1005,6 @@ function buildCrewBudgetFailure(parentResult) {
|
|
|
883
1005
|
};
|
|
884
1006
|
}
|
|
885
1007
|
//#endregion
|
|
886
|
-
export { STUCK_REASONS as a, createCostTracker as c, withRateLimit as i, run_crew_exports as n, createActionHistory as o, createRateLimitGroup as r,
|
|
1008
|
+
export { STUCK_REASONS as a, createCostTracker as c, withRateLimit as i, receiptCid as l, run_crew_exports as n, createActionHistory as o, createRateLimitGroup as r, computeArtifactLineageMerkleRoot as s, runAgentCrew as t };
|
|
887
1009
|
|
|
888
|
-
//# sourceMappingURL=run-crew-
|
|
1010
|
+
//# sourceMappingURL=run-crew-CKdBjh5P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-crew-CKdBjh5P.js","names":["minDefined"],"sources":["../src/receipts/cid.ts","../src/agent/infra/cost-tracker.ts","../src/receipts/lineage.ts","../src/agent/infra/action-history.ts","../src/agent/crew/dispatcher.ts","../src/agent/crew/crew-policy.ts","../src/agent/infra/rate-limit-group.ts","../src/agent/crew/run-crew.ts"],"sourcesContent":["/**\n * Receipt CID — Phase 39 (v1.3). Content address = sha256 of the DSSE\n * canonical payload bytes (the exact bytes that were signed).\n *\n * The CID is derivable from any envelope WITHOUT key material: it digests\n * `envelope.payload` (the base64-encoded RFC 8785 JCS canonical body) after\n * decoding. verifyReceipt proves payload byte-equality on every accepted\n * envelope (verify.ts re-canonicalization step), so two envelopes with the\n * same signed body always share a CID and any body tamper changes it.\n *\n * Web-standard APIs only (atob + crypto.subtle) — no Node-specific byte\n * types, matching the checkpoint.ts / fingerprint.ts precedents.\n */\n\nimport type { ReceiptEnvelope } from \"./types.js\";\n\n/**\n * Derive the content-addressed CID of a receipt envelope.\n *\n * Returns `sha256:<hex>` where `<hex>` is the 64-char lowercase SHA-256\n * digest of the decoded DSSE payload bytes. No KeySet, signer, or other\n * key material is required — callers chaining receipts (parentReceiptCid)\n * compute this from the parent envelope alone.\n */\nexport async function receiptCid(envelope: ReceiptEnvelope): Promise<string> {\n // Decode base64 via atob — web-standard, runtime-agnostic (checkpoint.ts:255).\n const bytes = Uint8Array.from(atob(envelope.payload), (c) => c.charCodeAt(0));\n\n // Copy into a freshly-allocated backing store so crypto.subtle.digest\n // never sees a view over a larger shared allocation (fingerprint.ts idiom).\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n\n const digest = await crypto.subtle.digest(\"SHA-256\", copy.buffer);\n\n const hex = Array.from(new Uint8Array(digest), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n\n return `sha256:${hex}`;\n}\n","/**\n * CostTracker — Phase 21 (v1.2).\n *\n * Pure accumulator over per-iteration `Usage`. Standalone (no dependency\n * on the agent runtime); callers can plug it in via a hook handler or\n * read it after a run completes.\n */\n\nimport type { BudgetInvariant } from \"../../contract/contract.js\";\nimport type { Usage } from \"../../providers/provider.js\";\n\nexport type CostBudgetStatus = \"ok\" | \"warning\" | \"exceeded\";\n\nexport interface CostTracker {\n readonly kind: \"cost-tracker\";\n /** Append a per-iteration Usage record. Mutates internal state. */\n recordIteration(usage: Usage): void;\n /** Returns the running sum across all recorded iterations. */\n total(): Usage;\n /**\n * Reports budget status against `contract.budget`:\n * - \"ok\" — under 80% of maxCostUsd.\n * - \"warning\" — at or over 80% but under 100%.\n * - \"exceeded\" — at or over 100% of maxCostUsd.\n * Returns \"ok\" when no budget is declared or when cumulative cost is null.\n */\n budgetStatus(budget?: BudgetInvariant): CostBudgetStatus;\n}\n\nconst WARNING_THRESHOLD = 0.8;\n\nexport function createCostTracker(): CostTracker {\n let promptTokens = 0;\n let completionTokens = 0;\n let costUsd: number | null = null;\n\n return {\n kind: \"cost-tracker\" as const,\n recordIteration(usage: Usage): void {\n promptTokens += usage.promptTokens;\n completionTokens += usage.completionTokens;\n if (usage.costUsd !== null) {\n costUsd = (costUsd ?? 0) + usage.costUsd;\n }\n },\n total(): Usage {\n return { promptTokens, completionTokens, costUsd };\n },\n budgetStatus(budget?: BudgetInvariant): CostBudgetStatus {\n const max = budget?.maxCostUsd;\n if (max === undefined || costUsd === null) return \"ok\";\n if (costUsd >= max) return \"exceeded\";\n if (costUsd >= max * WARNING_THRESHOLD) return \"warning\";\n return \"ok\";\n },\n };\n}\n","import canonicalize from \"canonicalize\";\n\nimport type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport type { ArtifactLineage, ArtifactParentRef } from \"../artifacts/lineage.js\";\n\ntype LineageArtifact = ArtifactInput | ArtifactRef | ArtifactParentRef;\ntype JsonValue =\n | null\n | string\n | number\n | boolean\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nconst encoder = new TextEncoder();\nconst LEAF_DOMAIN = encoder.encode(\"lattice-lineage-leaf-v1:\");\nconst NODE_DOMAIN = encoder.encode(\"lattice-lineage-node-v1:\");\n\n/**\n * Compute a deterministic descriptor-only merkle root for artifact lineage.\n *\n * The root commits to `ArtifactRef` descriptors and nested lineage graphs, not\n * raw artifact values. Returns undefined when no lineage metadata exists.\n */\nexport async function computeArtifactLineageMerkleRoot(\n artifacts: readonly LineageArtifact[],\n): Promise<string | undefined> {\n const leaves = artifacts\n .filter((artifact) => artifact.lineage !== undefined)\n .map((artifact) => canonicalLineageLeaf(artifact));\n\n if (leaves.length === 0) return undefined;\n\n let level = (await Promise.all(\n leaves.map((leaf) => sha256(concatBytes(LEAF_DOMAIN, leaf))),\n )).sort(compareBytes);\n\n while (level.length > 1) {\n const next: Uint8Array[] = [];\n for (let i = 0; i < level.length; i += 2) {\n const left = level[i]!;\n const right = level[i + 1] ?? left;\n next.push(await sha256(concatBytes(NODE_DOMAIN, left, right)));\n }\n level = next.sort(compareBytes);\n }\n\n return `sha256:${bytesToHex(level[0]!)}`;\n}\n\nfunction canonicalLineageLeaf(artifact: LineageArtifact): Uint8Array {\n const sanitized = sanitizeArtifactRef(artifact);\n const json = canonicalize(sanitized);\n if (json === undefined) {\n throw new Error(\n \"computeArtifactLineageMerkleRoot: lineage descriptor is not canonicalizable.\",\n );\n }\n return encoder.encode(json);\n}\n\nfunction sanitizeArtifactRef(input: LineageArtifact): JsonValue {\n const ref = toArtifactRef(input as ArtifactInput | ArtifactRef);\n return compactObject({\n id: ref.id,\n kind: ref.kind,\n source: ref.source,\n privacy: ref.privacy,\n mediaType: ref.mediaType,\n label: ref.label,\n metadata: sanitizeUnknown(ref.metadata),\n size: sanitizeUnknown(ref.size),\n fingerprint: sanitizeUnknown(ref.fingerprint),\n storage: sanitizeUnknown(ref.storage),\n lineage:\n ref.lineage !== undefined ? sanitizeLineage(ref.lineage) : undefined,\n });\n}\n\nfunction sanitizeLineage(lineage: ArtifactLineage): JsonValue {\n const parents = lineage.parents\n .map((parent) => sanitizeArtifactRef(parent))\n .sort(compareCanonicalJson);\n\n return compactObject({\n parents,\n transform: compactObject({\n kind: lineage.transform.kind,\n name: lineage.transform.name,\n metadata: sanitizeUnknown(lineage.transform.metadata),\n }),\n });\n}\n\nfunction sanitizeUnknown(value: unknown): JsonValue | undefined {\n if (value === undefined) return undefined;\n if (value === null) return null;\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n return value;\n case \"number\":\n return Number.isFinite(value) ? value : undefined;\n case \"bigint\":\n return value.toString();\n case \"object\": {\n if (Array.isArray(value)) {\n return value\n .map((item) => sanitizeUnknown(item))\n .filter((item): item is JsonValue => item !== undefined);\n }\n const out: Record<string, JsonValue> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n const child = sanitizeUnknown((value as Record<string, unknown>)[key]);\n if (child !== undefined) out[key] = child;\n }\n return out;\n }\n default:\n return undefined;\n }\n}\n\nfunction compactObject(\n input: Record<string, JsonValue | undefined>,\n): { readonly [key: string]: JsonValue } {\n const out: Record<string, JsonValue> = {};\n for (const key of Object.keys(input).sort()) {\n const value = input[key];\n if (value !== undefined) out[key] = value;\n }\n return out;\n}\n\nfunction compareCanonicalJson(a: JsonValue, b: JsonValue): number {\n const aJson = canonicalize(a) ?? \"\";\n const bJson = canonicalize(b) ?? \"\";\n return aJson.localeCompare(bJson);\n}\n\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n toArrayBuffer(bytes),\n );\n return new Uint8Array(digest);\n}\n\nfunction concatBytes(...chunks: readonly Uint8Array[]): Uint8Array {\n const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n return bytesToHex(a).localeCompare(bytesToHex(b));\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy.buffer as ArrayBuffer;\n}\n","/**\n * ActionHistory — Phase 21 (v1.2).\n *\n * Detects stuck patterns in the agent loop's tool-call sequence:\n * - \"consecutive-identical-tool-call\" — same (toolName, argsHash) N+ times in a row\n * - \"ping-pong\" — last 4 records alternate between 2 distinct (toolName, argsHash) pairs\n * - \"no-progress\" — reserved for callers wiring goal-progress feedback here\n *\n * Standalone (no dependency on the agent runtime); callers register the\n * primitive externally and pump `recordAction` from their loop or hook.\n */\n\nexport const STUCK_REASONS = [\n \"consecutive-identical-tool-call\",\n \"no-progress\",\n \"ping-pong\",\n] as const;\n\nexport type StuckReason = typeof STUCK_REASONS[number];\n\nexport interface ActionRecord {\n readonly iterationIndex: number;\n readonly toolName: string;\n readonly argsHash: string;\n}\n\nexport interface ActionHistoryOptions {\n /** Number of consecutive identical records that triggers the consecutive detector. Default 3. */\n readonly consecutiveLimit?: number;\n}\n\nexport interface ActionHistory {\n readonly kind: \"action-history\";\n /**\n * Append a record. Returns the latest StuckReason triggered by this\n * record, or null when no detector fires. The most recent reason wins\n * when multiple apply.\n */\n recordAction(action: ActionRecord): StuckReason | null;\n history(): readonly ActionRecord[];\n}\n\nfunction actionKey(record: ActionRecord): string {\n return `${record.toolName}::${record.argsHash}`;\n}\n\nexport function createActionHistory(options: ActionHistoryOptions = {}): ActionHistory {\n const consecutiveLimit = options.consecutiveLimit ?? 3;\n const records: ActionRecord[] = [];\n\n return {\n kind: \"action-history\" as const,\n recordAction(action: ActionRecord): StuckReason | null {\n records.push(action);\n // Consecutive identical detector.\n if (records.length >= consecutiveLimit) {\n const tail = records.slice(-consecutiveLimit);\n const firstKey = actionKey(tail[0]!);\n if (tail.every((r) => actionKey(r) === firstKey)) {\n return \"consecutive-identical-tool-call\";\n }\n }\n // Ping-pong detector (last 4 alternate between exactly 2 keys).\n if (records.length >= 4) {\n const last4 = records.slice(-4);\n const keys = last4.map(actionKey);\n const distinct = Array.from(new Set(keys));\n if (\n distinct.length === 2 &&\n keys[0] === keys[2] &&\n keys[1] === keys[3] &&\n keys[0] !== keys[1]\n ) {\n return \"ping-pong\";\n }\n }\n return null;\n },\n history(): readonly ActionRecord[] {\n return Object.freeze([...records]);\n },\n };\n}\n","/**\n * CrewDispatcher — Phase 39 (v1.3). The single chokepoint where ALL crew\n * concerns live (D-01/D-02).\n *\n * Hybrid dispatch model (D-01): the parent's MODEL sees each child agent as\n * a named tool (synthesized `ToolDefinition`-shaped declarations derived\n * from the child's `id`, `intent`, and `summaryReturnSchema`), but the\n * RUNTIME branches on the `kind: \"agent\"` discriminant at this chokepoint —\n * dispatch is routed through the 39-03 `runAgentInternal` seam\n * (`dispatchToolUse`), never through a tool closure. No policy logic is\n * smuggled into tool `execute` bodies (D-02): budget derivation, ancestry\n * cycle/depth enforcement, summary-return validation, classified failure\n * routing, and receipt minting all live HERE.\n *\n * Re-entry contract (D-04): a completed child returns a schema-validated\n * `{ summary, artifacts, receipts }` envelope that re-enters the parent\n * conversation as a standard `role: \"tool\"` turn over the existing\n * prompt-reencoded tool protocol. Recoverable failures return as structured\n * `{ error: { kind, reason, terminal } }` tool results (D-09); terminal\n * failures (D-10) are never re-dispatched — a per-dispatcher terminal-block\n * set caches the error and short-circuits without running the child.\n *\n * Ancestry convention (D-05): `CrewDispatchContext.ancestry` is the chain\n * of spec ids ABOVE the agent this dispatcher serves (parent-first,\n * exclusive of the agent itself — the root agent's dispatcher receives\n * `[]`). Cycle prevention rejects any dispatch whose target id equals the\n * current agent's id or already appears in the chain; the depth gate\n * rejects dispatch once `ancestry.length >= policy.maxDepth`. The full\n * root-first chain (including the child itself) is persisted on the\n * child's `AgentSnapshot.ancestry` via the survivability seam when\n * snapshots are captured.\n *\n * Receipt chain (research Pattern 2): when a signer is configured the\n * dispatcher mints the child completion receipt directly via\n * `createReceipt` with `parentReceiptCid = crew-root CID` (the anchor\n * minted by the 39-06 orchestrator BEFORE children run — Pitfall 2),\n * using synthetic route identifiers (checkpoint.ts DEFAULT_ROUTE\n * precedent). Per-iteration checkpoint receipts remain UNCHANGED (no\n * parentReceiptCid).\n */\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport type { ArtifactRef } from \"../../artifacts/artifact.js\";\nimport { isArtifactRef, toArtifactRef } from \"../../artifacts/artifact.js\";\nimport type { BudgetInvariant } from \"../../contract/contract.js\";\nimport { validateSchemaOutput } from \"../../outputs/validate.js\";\nimport type {\n ProviderAdapter,\n ProviderRunRequest,\n Usage,\n} from \"../../providers/provider.js\";\nimport { receiptCid } from \"../../receipts/cid.js\";\nimport { computeArtifactLineageMerkleRoot } from \"../../receipts/lineage.js\";\nimport { createReceipt } from \"../../receipts/receipt.js\";\nimport type { ReceiptEnvelope, ReceiptSigner } from \"../../receipts/types.js\";\nimport type { LatticeConfig } from \"../../runtime/config.js\";\nimport {\n createNoopSurvivabilityAdapter,\n type SurvivabilityAdapter,\n} from \"../../runtime/survivability.js\";\nimport type { ToolDefinition } from \"../../tools/tools.js\";\n\nimport { formatToolsForProvider } from \"../format-tools.js\";\nimport { STUCK_REASONS } from \"../infra/action-history.js\";\nimport type { AgentHost, AgentSnapshot, AgentTransport } from \"../host.js\";\nimport {\n runAgentInternal,\n type DispatchToolUseContext,\n type RunAgentInternalOptions,\n} from \"../runtime.js\";\nimport type {\n AgentFailure,\n AgentIntent,\n AgentResult,\n ToolUseRequest,\n} from \"../types.js\";\n\nimport type { AgentSpec } from \"./agent-spec.js\";\nimport type { ValidatedCrewPolicy } from \"./crew-policy.js\";\n\n/**\n * Context handed to `createCrewDispatcher` by the crew orchestrator\n * (39-06) — or by tests driving the dispatcher directly.\n */\nexport interface CrewDispatchContext {\n /** Normalized crew policy from `validateCrewPolicy` (39-03). */\n readonly policy: ValidatedCrewPolicy;\n /** Host every child loop runs against (`hosts.childHost`). */\n readonly childHost: AgentHost;\n /**\n * Spec-id chain ABOVE the agent this dispatcher serves, parent-first and\n * exclusive of the agent itself (D-05). Root dispatcher: `[]`.\n */\n readonly ancestry: readonly string[];\n /** Crew-root receipt CID — the chain anchor (absent when no signer). */\n readonly crewRootCid?: string;\n /** Crew-level signer threaded into children + completion receipts. */\n readonly signer?: ReceiptSigner;\n /**\n * Feeds the per-agent tracker + crew aggregator. Called exactly once per\n * child dispatch with the child run's cumulative usage (Pitfall 3).\n */\n readonly recordUsage: (agentId: string, usage: Usage) => void;\n /**\n * Optional richer telemetry hook for the 39-06 orchestrator. Kept\n * additive so dispatcher-only tests and direct consumers do not need to\n * know about CrewResult assembly.\n */\n readonly recordAgentResult?: (\n agentId: string,\n result: AgentResult,\n ) => void;\n /** Remaining crew pool (D-07). `undefined` = unbounded. */\n readonly remainingBudget: () => BudgetInvariant | undefined;\n /** Byte-stable crew cache prefix (\"\" = no prefix sharing). */\n readonly sharedPrefix: string;\n /** Collects per-agent completion envelopes for the CrewResult. */\n readonly mintedReceipts: (envelope: ReceiptEnvelope) => void;\n /** Provider config the child loops execute against (createAI config). */\n readonly config: LatticeConfig;\n /** Optional crew-level tracer threaded into child loops. */\n readonly tracer?: AgentIntent[\"tracer\"];\n /** Optional crew-level hook pipeline threaded into child loops. */\n readonly pipeline?: AgentIntent[\"pipeline\"];\n}\n\n/** Seam-compatible dispatch function (39-03 `runAgentInternal` options). */\nexport type DispatchToolUseFn = NonNullable<RunAgentInternalOptions[\"dispatchToolUse\"]>;\n\n/** The chokepoint surface consumed by the 39-06 orchestrator. */\nexport interface CrewDispatcher {\n /** Plugs into the 39-03 seam: `runAgentInternal(intent, config, { dispatchToolUse })`. */\n readonly dispatchToolUse: DispatchToolUseFn;\n /**\n * Synthesized child declarations for the parent's `intent.tools` —\n * real `ToolDefinition`-shaped values so `formatToolsForProvider` renders\n * them and Phase 37 `validateToolCalls` registries accept them (Pitfall 5).\n */\n readonly childToolDeclarations: ReadonlyArray<ToolDefinition<StandardSchemaV1>>;\n /**\n * Crew-ceiling signal (D-10): flips to `true` once a dispatch was\n * rejected with terminal `crew-budget-exceeded`. The 39-06 orchestrator\n * reads this to end the crew run. Shared across the recursive child\n * dispatchers of one crew.\n */\n readonly crewBudgetExhausted: () => boolean;\n}\n\n/** Structured tool-result error body (D-09 shape). */\nexport interface CrewDispatchError {\n readonly kind: string;\n readonly reason: string;\n readonly terminal: boolean;\n}\n\n/** Crew-run state shared across the recursive dispatcher tree. */\ninterface CrewSharedState {\n exhausted: boolean;\n readonly runId: string;\n}\n\n/**\n * Create the crew dispatch chokepoint for one agent spec.\n *\n * `spec` is the agent whose loop this dispatcher serves (its `childAgents`\n * are the dispatchable targets); `ctx` carries every crew-level concern.\n */\nexport function createCrewDispatcher(\n spec: AgentSpec,\n ctx: CrewDispatchContext,\n): CrewDispatcher {\n return createDispatcherNode(spec, ctx, {\n exhausted: false,\n runId: `lattice-crew-${crypto.randomUUID()}`,\n });\n}\n\nfunction createDispatcherNode(\n spec: AgentSpec,\n ctx: CrewDispatchContext,\n shared: CrewSharedState,\n): CrewDispatcher {\n const children = spec.childAgents ?? [];\n // D-10 terminal-block set: childId -> cached terminal error content.\n const terminalBlock = new Map<string, string>();\n // Cache-prefix hoist (DELEG-04): every child loop's transport is wrapped\n // so requests whose task starts with the byte-stable crew prefix are\n // hoisted to ProviderRunRequest.cacheSystemPrefix when (and ONLY when)\n // the executing adapter discloses quirks.promptCachingSupported. All\n // gating lives here in crew code — adapters stay dumb.\n const childHost: AgentHost =\n ctx.sharedPrefix.length > 0\n ? {\n ...ctx.childHost,\n transport: withCachePrefixHoist(ctx.sharedPrefix, ctx.childHost.transport),\n }\n : ctx.childHost;\n\n async function dispatchToolUse(\n req: ToolUseRequest,\n _loopCtx: DispatchToolUseContext,\n ): Promise<{ readonly content: string } | undefined> {\n void _loopCtx;\n const childSpec = children.find((child) => child.id === req.name);\n if (childSpec === undefined) {\n // Not a child agent — fall through to the default lookup/runTool path.\n return undefined;\n }\n\n // ---- Pre-run checks (Task 2a-c) -------------------------------------\n\n // (i) Terminal-block short-circuit (D-10): a terminally-failed child is\n // never re-dispatched — return the cached error WITHOUT running it.\n const blocked = terminalBlock.get(childSpec.id);\n if (blocked !== undefined) {\n return { content: blocked };\n }\n\n // (ii) Cycle check (D-05): reject when the target id equals the\n // dispatching agent's own id or already appears in the ancestry chain.\n if (req.name === spec.id || ctx.ancestry.includes(req.name)) {\n return errorResult({\n kind: \"crew-cycle-rejected\",\n reason:\n `Dispatch of \"${req.name}\" rejected: the id already appears in the ` +\n `crew ancestry chain (D-05 cycle prevention).`,\n terminal: false,\n });\n }\n\n // (iii) Depth check (D-05): ancestry holds the agents ABOVE this one,\n // so its length is this agent's depth — dispatching one level further\n // is rejected once that depth reaches policy.maxDepth.\n if (ctx.ancestry.length >= ctx.policy.maxDepth) {\n return errorResult({\n kind: \"crew-depth-exceeded\",\n reason:\n `Dispatch of \"${req.name}\" rejected: crew maxDepth ${ctx.policy.maxDepth} ` +\n `reached (ancestry depth ${ctx.ancestry.length}).`,\n terminal: false,\n });\n }\n\n // (iv) Crew ceiling (D-10): a fully-drained pool ends the run — emit\n // terminal crew-budget-exceeded and flip the orchestrator signal.\n const pool = ctx.remainingBudget();\n if (isPoolExhausted(pool)) {\n shared.exhausted = true;\n return errorResult({\n kind: \"crew-budget-exceeded\",\n reason: \"Crew budget pool exhausted — the crew run must end (D-10).\",\n terminal: true,\n });\n }\n\n // ---- Child pipeline (Task 1) ----------------------------------------\n\n // (1) Dispatch args: the model supplies { task: string } per the\n // synthesized declaration schema. Untrusted model output — reject\n // malformed args with a recoverable structured error instead of\n // throwing (T-39-14: failures are structured objects, not raw text).\n const task = extractTaskArg(req.args);\n if (task === null) {\n return errorResult({\n kind: \"invalid-dispatch-args\",\n reason: `Dispatch args for child agent \"${childSpec.id}\" must be { \"task\": string }.`,\n terminal: false,\n });\n }\n\n // (2) Effective budget (D-07): per-dimension min of the child's\n // contract budget and the remaining crew pool; iterations also capped\n // by policy.maxIterationsPerAgent. Null/absent cost dimensions never\n // poison min() (Pitfall 4).\n const effectiveBudget = deriveChildBudget(\n childSpec.contract?.budget,\n pool,\n ctx.policy.maxIterationsPerAgent,\n );\n\n // (3) Build the child AgentIntent and run the existing loop. The\n // child's dispatch context threads the extended ancestry chain (D-05);\n // when the child has its own childAgents, a recursive dispatcher node\n // (sharing this crew's state) serves its loop and its declarations\n // join the child's tool surface.\n const childAncestry: readonly string[] = [...ctx.ancestry, spec.id];\n const childNode =\n childSpec.childAgents !== undefined && childSpec.childAgents.length > 0\n ? createDispatcherNode(childSpec, { ...ctx, ancestry: childAncestry }, shared)\n : undefined;\n const childTools =\n childNode !== undefined\n ? [...childSpec.tools, ...childNode.childToolDeclarations]\n : childSpec.tools;\n\n const childIntent: AgentIntent = {\n task,\n tools: childTools,\n host: childHost,\n // Persist the full root-first chain (including the child itself) on\n // the child's AgentSnapshot when the childHost captures snapshots.\n survivabilityAdapter: withAncestrySnapshot(\n createNoopSurvivabilityAdapter<AgentSnapshot>(),\n [...childAncestry, childSpec.id],\n ),\n ...(effectiveBudget !== undefined\n ? { contract: { kind: \"capability-contract\", budget: effectiveBudget } }\n : {}),\n ...(ctx.signer !== undefined ? { signer: ctx.signer } : {}),\n ...(ctx.tracer !== undefined ? { tracer: ctx.tracer } : {}),\n ...(ctx.pipeline !== undefined ? { pipeline: ctx.pipeline } : {}),\n };\n const childResult = await runAgentInternal(\n childIntent,\n ctx.config,\n childNode !== undefined ? { dispatchToolUse: childNode.dispatchToolUse } : {},\n );\n\n // (5) Record child usage exactly once — success AND failure paths both\n // consumed provider budget (Pitfall 3: no double-counting; the crew\n // aggregator never sees this run again).\n ctx.recordUsage(childSpec.id, childResult.usage);\n ctx.recordAgentResult?.(childSpec.id, childResult);\n\n if (childResult.kind !== \"success\") {\n // (b) Classified failure routing (D-09/D-10).\n const classified = classifyChildFailure(childSpec.id, childResult);\n const result = errorResult(classified);\n if (classified.terminal) {\n terminalBlock.set(childSpec.id, result.content);\n if (classified.kind === \"crew-budget-exceeded\") {\n shared.exhausted = true;\n }\n }\n return result;\n }\n\n // (d) Receipt minting at the seam (D-02): child completion receipt\n // chained to the crew root. Best-effort (checkpoint.ts D-07 precedent) —\n // a mint failure never destroys the child's completed work.\n const receipts: string[] = [];\n const childArtifacts = extractArtifacts(childResult);\n if (ctx.signer !== undefined) {\n try {\n const lineageMerkleRoot =\n await computeArtifactLineageMerkleRoot(childArtifacts);\n const envelope = await createReceipt(\n {\n runId: shared.runId,\n model: { requested: \"lattice-crew/agent-completion\", observed: null },\n route: {\n providerId: \"lattice-crew\",\n capabilityId: \"lattice-crew/agent-completion\",\n attemptNumber: 1,\n },\n ...(ctx.crewRootCid !== undefined\n ? { parentReceiptCid: ctx.crewRootCid }\n : {}),\n usage: childResult.usage,\n ...(lineageMerkleRoot !== undefined ? { lineageMerkleRoot } : {}),\n contractVerdict: \"success\",\n contractHash: null,\n inputHashes: [],\n outputHash: null,\n stepName: `crew-agent-completion:${childSpec.id}`,\n },\n ctx.signer,\n );\n ctx.mintedReceipts(envelope);\n receipts.push(await receiptCid(envelope));\n } catch {\n // Best-effort: the summary simply carries no completion CID.\n }\n }\n\n // (4) Assemble + validate the summary envelope (children only — the\n // root agent's return is NOT schema-validated; research Open Q2).\n const envelope = {\n summary: extractSummary(childResult.output),\n artifacts: childArtifacts,\n receipts,\n };\n const validation = await validateSchemaOutput(\n childSpec.id,\n childSpec.summaryReturnSchema,\n envelope,\n );\n if (!validation.ok) {\n return errorResult({\n kind: \"summary-validation-failed\",\n reason: validation.issue.issues.map((issue) => issue.message).join(\"; \"),\n terminal: false,\n });\n }\n\n // (6) Re-enter the parent conversation as a standard tool turn (D-04).\n return { content: JSON.stringify(envelope) };\n }\n\n return {\n dispatchToolUse,\n childToolDeclarations: synthesizeChildDeclarations(children),\n crewBudgetExhausted: () => shared.exhausted,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Budget derivation (D-07, Pitfall 4)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-dimension `min(spec.contract?.budget, remaining crew pool)` with the\n * iteration dimension additionally capped by `maxIterationsPerAgent`.\n *\n * Cost-dimension min applies ONLY when both sides are numbers — a pool\n * derived from null-cost (unmeasured) usage omits `maxCostUsd`, and even a\n * literal `null` never poisons the arithmetic (Pitfall 4).\n */\nexport function deriveChildBudget(\n specBudget: BudgetInvariant | undefined,\n pool: BudgetInvariant | undefined,\n maxIterationsPerAgent?: number,\n): BudgetInvariant | undefined {\n const maxIterations = minDefined(\n minDefined(specBudget?.maxIterations, pool?.maxIterations),\n maxIterationsPerAgent,\n );\n const maxWallTimeMs = minDefined(specBudget?.maxWallTimeMs, pool?.maxWallTimeMs);\n const maxCostUsd = minDefined(specBudget?.maxCostUsd, pool?.maxCostUsd);\n\n if (maxIterations === undefined && maxWallTimeMs === undefined && maxCostUsd === undefined) {\n return undefined;\n }\n return {\n ...(maxIterations !== undefined ? { maxIterations } : {}),\n ...(maxWallTimeMs !== undefined ? { maxWallTimeMs } : {}),\n ...(maxCostUsd !== undefined ? { maxCostUsd } : {}),\n };\n}\n\n/** min() that only applies when BOTH sides are real numbers (Pitfall 4). */\nfunction minDefined(a: number | null | undefined, b: number | null | undefined): number | undefined {\n const aNum = typeof a === \"number\" && Number.isFinite(a) ? a : undefined;\n const bNum = typeof b === \"number\" && Number.isFinite(b) ? b : undefined;\n if (aNum !== undefined && bNum !== undefined) return Math.min(aNum, bNum);\n return aNum ?? bNum;\n}\n\n/**\n * Crew-ceiling predicate (D-10): the pool is exhausted when ANY bounded\n * dimension is at/below zero. Null/absent dimensions (unmeasured cost)\n * never count as exhausted (Pitfall 4).\n */\nfunction isPoolExhausted(pool: BudgetInvariant | undefined): boolean {\n if (pool === undefined) return false;\n return (\n (typeof pool.maxIterations === \"number\" && pool.maxIterations <= 0) ||\n (typeof pool.maxWallTimeMs === \"number\" && pool.maxWallTimeMs <= 0) ||\n (typeof pool.maxCostUsd === \"number\" && pool.maxCostUsd <= 0)\n );\n}\n\n// ---------------------------------------------------------------------------\n// Cache-prefix sharing (DELEG-04, research Pattern 3)\n// ---------------------------------------------------------------------------\n\n/**\n * Compose the byte-stable crew cache prefix for one tool surface: the\n * `describeForSystem()` block (tool descriptions + envelope instructions),\n * derived from deterministic, version-pinned inputs ONLY — no timestamps,\n * random ids, or unsorted keys (Phase 35 scaffold discipline; any\n * non-byte-stable fragment silently zeroes the cache-hit rate).\n *\n * The 39-06 orchestrator composes this ONCE per crew at crew start and\n * threads it as `CrewDispatchContext.sharedPrefix`. All members sharing a\n * tool surface share byte-identical prefix bytes across dispatches.\n */\nexport function composeCrewCachePrefix(\n tools: ReadonlyArray<ToolDefinition<StandardSchemaV1>>,\n): string {\n // The providerName argument does not branch the v1.2+ prompt-reencoded\n // implementation; a fixed literal keeps the bytes provider-independent.\n return formatToolsForProvider(\"lattice-crew\", tools).describeForSystem();\n}\n\n/**\n * Transport wrapper implementing the quirks-gated prefix hoist:\n *\n * - Adapter discloses `quirks.promptCachingSupported === true` (Anthropic\n * block-granular caching) AND the outgoing task starts with the shared\n * prefix → the prefix is hoisted to `cacheSystemPrefix` and `task`\n * carries ONLY the conversation body. The 39-03 byte-equality invariant\n * (`describeForSystem() + \"\\n\" + buildTaskBody(conv) === buildTask(conv)`)\n * guarantees the stripped remainder IS the body-only rendering — the\n * prefix is never duplicated.\n * - Any other adapter → the request passes through UNTOUCHED: no\n * `cacheSystemPrefix` own-property is ever created (Pitfall 6) and the\n * prefix stays at the head of `task` (OpenAI automatic token-prefix path).\n *\n * Composes over an existing `AgentTransport` (FSB offscreen bridge etc.);\n * when `inner` is absent it dispatches `provider.execute()` directly,\n * matching the runtime's default transport behavior.\n */\nexport function withCachePrefixHoist(\n sharedPrefix: string,\n inner?: AgentTransport,\n): AgentTransport {\n const marker = `${sharedPrefix}\\n`;\n return {\n async call(provider, request) {\n const hoist =\n sharedPrefix.length > 0 &&\n supportsPromptCaching(provider) &&\n request.task.startsWith(marker);\n const outbound: ProviderRunRequest = hoist\n ? {\n ...request,\n task: request.task.slice(marker.length),\n cacheSystemPrefix: sharedPrefix,\n }\n : request;\n if (inner !== undefined) {\n return inner.call(provider, outbound);\n }\n if (provider.execute === undefined) {\n throw new Error(\n `CrewDispatcher: provider \"${provider.id}\" has no execute() method.`,\n );\n }\n return provider.execute(outbound);\n },\n };\n}\n\n/** Quirks gate: only adapters that disclose block-granular prompt caching. */\nfunction supportsPromptCaching(provider: ProviderAdapter): boolean {\n const quirks = provider.quirks as\n | { readonly promptCachingSupported?: boolean }\n | undefined;\n return quirks?.promptCachingSupported === true;\n}\n\n// ---------------------------------------------------------------------------\n// Failure classification (D-09/D-10)\n// ---------------------------------------------------------------------------\n\n/**\n * Map a child `AgentFailure` to the structured tool-result error body.\n *\n * Terminal (D-10): tripwire violations and contract no-match (the\n * `isTerminal()` kinds in results/errors.ts — the agent loop reuses\n * `no-contract-match` for child cost-budget exhaustion), crew-ceiling\n * breaches, and non-stuck SAFETY-band denials (AgentDeniedError aligns\n * with TripwireViolationError terminal semantics). Recoverable (D-09):\n * iteration/wall-time exhaustion and STUCK_REASONS stalls — the parent\n * MAY re-dispatch.\n */\nexport function classifyChildFailure(\n childId: string,\n failure: AgentFailure,\n): CrewDispatchError {\n return {\n kind: failure.kind,\n reason:\n failure.reason ?? `Child agent \"${childId}\" failed with kind \"${failure.kind}\".`,\n terminal: isTerminalChildFailure(failure),\n };\n}\n\nfunction isTerminalChildFailure(failure: AgentFailure): boolean {\n if (\n failure.kind === \"tripwire-violated\" ||\n failure.kind === \"no-contract-match\" ||\n failure.kind === \"crew-budget-exceeded\"\n ) {\n return true;\n }\n if (failure.kind === \"agent-iteration-denied\") {\n // SAFETY-band stuck detection (STUCK_REASONS) is a recoverable stall;\n // every other denial carries AgentDeniedError's terminal semantics.\n const reason = failure.reason ?? \"\";\n return !STUCK_REASONS.some((stuck) => reason.includes(stuck));\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction errorResult(body: CrewDispatchError): { readonly content: string } {\n // D-09 exact shape: {\"error\":{\"kind\":...,\"reason\":...,\"terminal\":...}}.\n // Errors carry kind/reason strings ONLY — never request options, headers,\n // or key material (T-39-18).\n return {\n content: JSON.stringify({\n error: { kind: body.kind, reason: body.reason, terminal: body.terminal },\n }),\n };\n}\n\nfunction extractTaskArg(args: unknown): string | null {\n if (typeof args !== \"object\" || args === null) return null;\n const task = (args as Record<string, unknown>)[\"task\"];\n return typeof task === \"string\" ? task : null;\n}\n\nfunction extractSummary(output: unknown): string {\n if (typeof output === \"object\" && output !== null) {\n const answer = (output as Record<string, unknown>)[\"answer\"];\n if (typeof answer === \"string\") return answer;\n }\n if (typeof output === \"string\") return output;\n try {\n return JSON.stringify(output);\n } catch {\n return String(output);\n }\n}\n\nfunction extractArtifacts(result: unknown): ArtifactRef[] {\n const artifacts = (result as { readonly artifacts?: unknown }).artifacts;\n return Array.isArray(artifacts)\n ? artifacts.filter(isArtifactRef).map(toArtifactRef)\n : [];\n}\n\n/**\n * Wrap a survivability adapter so serialized child snapshots carry the\n * root-first ancestry chain (D-05; AgentSnapshot.ancestry from 39-03).\n * The `agent-snapshot/v1` version literal is unchanged — the field is\n * additive-optional (Pitfall 8).\n */\nfunction withAncestrySnapshot(\n base: SurvivabilityAdapter<AgentSnapshot>,\n ancestry: readonly string[],\n): SurvivabilityAdapter<AgentSnapshot> {\n return {\n ...base,\n serialize: (state) => base.serialize({ ...state, ancestry }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Child tool declarations (D-01, Pitfall 5)\n// ---------------------------------------------------------------------------\n\nfunction synthesizeChildDeclarations(\n children: ReadonlyArray<AgentSpec>,\n): ReadonlyArray<ToolDefinition<StandardSchemaV1>> {\n return children.map((child) => ({\n kind: \"tool\" as const,\n name: child.id,\n description:\n `Delegate a task to the \"${child.id}\" child agent. ` +\n `Agent intent: ${child.intent} ` +\n `Returns a JSON summary envelope { \"summary\": string, \"artifacts\": array, \"receipts\": array } ` +\n `validated against the agent's summaryReturnSchema.`,\n inputSchema: makeDispatchArgsSchema(child.id),\n // NEVER invoked: the CrewDispatcher intercepts matching names at the\n // dispatch seam BEFORE the default tool path. The body exists only so\n // the declaration is a real ToolDefinition for Phase 37 registries —\n // policy logic lives at the chokepoint, not in tool closures (D-01/D-02).\n execute: () => {\n throw new Error(\n `Child agent \"${child.id}\" must be dispatched through the CrewDispatcher ` +\n `(kind:\"agent\" branch) — direct tool execution is forbidden (D-01/D-02).`,\n );\n },\n }));\n}\n\n/**\n * Deterministic `~standard` schema for `{ task: string }` dispatch args.\n * Carries a fixed `toJSONSchema()` so `formatToolsForProvider` renders a\n * meaningful args_schema (byte-stable — no timestamps/random ids; the\n * declarations feed the shared cache prefix).\n */\nfunction makeDispatchArgsSchema(childId: string): StandardSchemaV1 {\n const schema = {\n \"~standard\": {\n version: 1,\n vendor: \"lattice-crew\",\n validate: (value: unknown) => {\n if (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>)[\"task\"] === \"string\"\n ) {\n return { value };\n }\n return {\n issues: [\n { message: `Dispatch args for child agent \"${childId}\" must be { \"task\": string }.` },\n ],\n };\n },\n },\n toJSONSchema: () => ({\n type: \"object\",\n properties: {\n task: { type: \"string\", description: \"The task to delegate to this child agent.\" },\n },\n required: [\"task\"],\n additionalProperties: false,\n }),\n };\n return schema as unknown as StandardSchemaV1;\n}\n","/**\n * CrewPolicy — Phase 39 (v1.3). Crew-level policy contract + normalizer\n * (D-06, D-11, D-16).\n *\n * `CrewPolicy.budget` reuses `BudgetInvariant` verbatim from\n * `contract/contract.ts` (D-06) — the crew-level shared pool. Structural\n * caps (`maxTotalIterations`, `maxIterationsPerAgent`,\n * `maxConcurrentChildren`, `maxDepth`) bound the crew shape independently\n * of cost.\n *\n * v1.3 executes children serially (D-11): the `maxConcurrentChildren`\n * field exists for forward compatibility but `validateCrewPolicy` rejects\n * values > 1 with a `TypeError` at entry (fail-fast, research Pattern 5 —\n * reject, not clamp, per the project's \"explicit config, no magic\" stance).\n *\n * `limits` is keyed by `adapter.id` and overrides the rate-limit-group\n * defaults per provider key (D-16). `coordination: \"unmanaged\"` is the\n * explicit escape hatch for consumers who handle 429s themselves.\n *\n * `validateCrewPolicy` follows the `contract()` factory template\n * (contract/contract.ts): conditional spread for optional members\n * (`exactOptionalPropertyTypes`-safe), `Object.freeze` on the result and\n * nested objects, input never mutated.\n */\n\nimport type { BudgetInvariant } from \"../../contract/contract.js\";\n\n/** Per-adapter rate-limit override (keyed by `adapter.id` in `limits`). */\nexport interface CrewRateLimitOverride {\n readonly requestsPerMinute?: number;\n readonly tokensPerMinute?: number;\n}\n\n/** Crew-level policy contract (D-06, D-11, D-16). */\nexport interface CrewPolicy {\n /** Crew-level shared budget pool — `BudgetInvariant` reused verbatim. */\n readonly budget?: BudgetInvariant;\n readonly maxTotalIterations?: number;\n readonly maxIterationsPerAgent?: number;\n /** Forward-compat field; the v1.3 runtime rejects values > 1 (D-11). */\n readonly maxConcurrentChildren?: number;\n /** Delegation depth cap; defaults to 1 (parent→child only, D-05). */\n readonly maxDepth?: number;\n /** Per-adapter-id rate-limit overrides (D-16). */\n readonly limits?: Readonly<Record<string, CrewRateLimitOverride>>;\n /** \"managed\" (default) wraps transports in the rate-limit group; \"unmanaged\" skips it. */\n readonly coordination?: \"managed\" | \"unmanaged\";\n}\n\n/**\n * Normalized policy returned by `validateCrewPolicy`: defaults applied,\n * structurally frozen.\n */\nexport interface ValidatedCrewPolicy extends CrewPolicy {\n readonly maxConcurrentChildren: number;\n readonly maxDepth: number;\n readonly coordination: \"managed\" | \"unmanaged\";\n}\n\n/**\n * Validates and normalizes a `CrewPolicy`.\n *\n * - Applies defaults: `maxDepth: 1`, `maxConcurrentChildren: 1`,\n * `coordination: \"managed\"`.\n * - Throws `TypeError` when `maxConcurrentChildren > 1` (serial-only v1.3\n * limit, D-11) or when any structural cap is a non-integer or < 1.\n * - Returns a frozen normalized policy; the input is never mutated.\n */\nexport function validateCrewPolicy(policy: CrewPolicy = {}): ValidatedCrewPolicy {\n assertStructuralCap(\"maxConcurrentChildren\", policy.maxConcurrentChildren);\n if (policy.maxConcurrentChildren !== undefined && policy.maxConcurrentChildren > 1) {\n throw new TypeError(\n \"CrewPolicy.maxConcurrentChildren > 1 is not supported in v1.3 — children execute serially (D-11).\",\n );\n }\n assertStructuralCap(\"maxDepth\", policy.maxDepth);\n assertStructuralCap(\"maxTotalIterations\", policy.maxTotalIterations);\n assertStructuralCap(\"maxIterationsPerAgent\", policy.maxIterationsPerAgent);\n\n return Object.freeze({\n ...(policy.budget !== undefined ? { budget: Object.freeze({ ...policy.budget }) } : {}),\n ...(policy.maxTotalIterations !== undefined\n ? { maxTotalIterations: policy.maxTotalIterations }\n : {}),\n ...(policy.maxIterationsPerAgent !== undefined\n ? { maxIterationsPerAgent: policy.maxIterationsPerAgent }\n : {}),\n maxConcurrentChildren: policy.maxConcurrentChildren ?? 1,\n maxDepth: policy.maxDepth ?? 1,\n ...(policy.limits !== undefined\n ? {\n limits: Object.freeze(\n Object.fromEntries(\n Object.entries(policy.limits).map(([adapterId, override]) => [\n adapterId,\n Object.freeze({ ...override }),\n ]),\n ),\n ),\n }\n : {}),\n coordination: policy.coordination ?? \"managed\",\n });\n}\n\nfunction assertStructuralCap(field: string, value: number | undefined): void {\n if (value === undefined) return;\n if (!Number.isInteger(value) || value < 1) {\n throw new TypeError(\n `CrewPolicy.${field} must be a positive integer (>= 1); received ${String(value)}.`,\n );\n }\n}\n","/**\n * RateLimitGroup — Phase 39 (v1.3).\n *\n * Standalone dual-dimension (requests/min + input tokens/min) token-bucket\n * rate limiter with a lease-based async interface. Pure infra following the\n * CostTracker precedent (Phase 21): no dependency on the agent runtime, and\n * usable to gate ANY async work — plain `runAgent` calls, crews, or consumer\n * code outside Lattice entirely (D-12).\n *\n * Zero new runtime dependencies (D-17/D-18). The implementation is in-process\n * only; the lease interface (`acquire`/`release`) is the seam a future\n * cross-process implementation (Redis / Durable Object) can satisfy without\n * changing callers.\n *\n * Drain model: continuous per-millisecond smoothing with LAZY refill — bucket\n * levels are recomputed from the `now()` delta on every acquire/release, and\n * at most ONE `setTimeout` is pending at a time, scheduled for the exact\n * deficit of the head waiter. No interval timers, no recurring background\n * timers (the anthropic.ts lazy-expiry rule: the library must not pin the\n * Node event loop). Anthropic itself enforces its limits with continuously\n * replenished token buckets, so this model matches the enforcer.\n *\n * Reconciliation: `acquire` reserves on ESTIMATED input tokens; `release`\n * reconciles against the actual `Usage.promptTokens` every adapter returns —\n * under-use is refunded to the token bucket, over-use is debited. Requests\n * are consumed at acquire time and never refunded.\n *\n * Failure policy (caller contract): on provider failure, release with the\n * original estimate (no refund) — quota may have been consumed despite the\n * error. `withRateLimit` implements this policy for the AgentTransport seam.\n */\n\nimport type { AgentTransport } from \"../host.js\";\nimport type {\n ProviderAdapter,\n ProviderRunRequest,\n ProviderRunResponse,\n} from \"../../providers/provider.js\";\n\n/** Anthropic Tier 1 requests/minute (fetched 2026-06-10). */\nconst DEFAULT_REQUESTS_PER_MINUTE = 50;\n/** Anthropic Tier 1 input tokens/minute, Sonnet-class (fetched 2026-06-10). */\nconst DEFAULT_TOKENS_PER_MINUTE = 30_000;\n\nconst MS_PER_MINUTE = 60_000;\n\n/**\n * Absorbs floating-point drift in two places: bucket-level comparisons\n * (`available >= need`) and deficit-wait rounding. 1e-6 of a token/request\n * (or millisecond) is far above accumulated IEEE-754 error at these\n * magnitudes and far below anything rate-limit-relevant.\n */\nconst FLOAT_EPSILON = 1e-6;\n\nexport interface RateLimitGroupOptions {\n /** Requests per minute. Defaults to 50 (Anthropic Tier 1). */\n readonly requestsPerMinute?: number;\n /** Input tokens per minute. Defaults to 30_000 (Anthropic Tier 1). */\n readonly tokensPerMinute?: number;\n /** Injectable clock for tests (defaults to `Date.now`). */\n readonly now?: () => number;\n}\n\nexport interface RateLimitLease {\n /**\n * Reconcile the reservation against actual usage. Refunds\n * `estimate - actual.promptTokens` to the token bucket when positive,\n * debits the difference when negative. Idempotent — only the first call\n * has an effect. Requests are never refunded.\n */\n release(actual: { promptTokens: number }): void;\n}\n\nexport interface RateLimitGroup {\n readonly kind: \"rate-limit-group\";\n /**\n * Reserve 1 request + `estimate.inputTokens` tokens. Resolves immediately\n * when both dimensions have capacity; otherwise the caller waits (FIFO)\n * until continuous drain refills the deficit.\n */\n acquire(estimate: { inputTokens: number }): Promise<RateLimitLease>;\n}\n\ninterface Bucket {\n available: number;\n readonly capacity: number;\n readonly perMsRate: number;\n}\n\ninterface Waiter {\n readonly inputTokens: number;\n readonly resolve: (lease: RateLimitLease) => void;\n}\n\nfunction createBucket(perMinute: number, label: string): Bucket {\n if (!Number.isFinite(perMinute) || perMinute <= 0) {\n throw new TypeError(\n `createRateLimitGroup: ${label} must be a positive finite number, got ${perMinute}.`,\n );\n }\n return {\n available: perMinute,\n capacity: perMinute,\n perMsRate: perMinute / MS_PER_MINUTE,\n };\n}\n\nexport function createRateLimitGroup(\n options: RateLimitGroupOptions = {},\n): RateLimitGroup {\n const now = options.now ?? Date.now;\n const requests = createBucket(\n options.requestsPerMinute ?? DEFAULT_REQUESTS_PER_MINUTE,\n \"requestsPerMinute\",\n );\n const tokens = createBucket(\n options.tokensPerMinute ?? DEFAULT_TOKENS_PER_MINUTE,\n \"tokensPerMinute\",\n );\n let lastRefillAt = now();\n const waiters: Waiter[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Lazy continuous refill from the clock delta — never a recurring timer. */\n function refill(): void {\n const t = now();\n const elapsed = t - lastRefillAt;\n if (elapsed <= 0) return;\n lastRefillAt = t;\n requests.available = Math.min(\n requests.capacity,\n requests.available + elapsed * requests.perMsRate,\n );\n tokens.available = Math.min(\n tokens.capacity,\n tokens.available + elapsed * tokens.perMsRate,\n );\n }\n\n /**\n * Token requirement for availability checks, clamped to capacity so an\n * oversized estimate (> bucket capacity) proceeds at full bucket instead\n * of deadlocking; the full amount is still debited (the bucket goes into\n * debt and recovers via drain).\n */\n function tokenNeed(inputTokens: number): number {\n return Math.min(inputTokens, tokens.capacity);\n }\n\n function tryDebit(inputTokens: number): boolean {\n if (\n requests.available + FLOAT_EPSILON >= 1 &&\n tokens.available + FLOAT_EPSILON >= tokenNeed(inputTokens)\n ) {\n requests.available -= 1;\n tokens.available -= inputTokens;\n return true;\n }\n return false;\n }\n\n /** Exact wait (ms) until both dimensions can cover the head waiter. */\n function deficitWaitMs(inputTokens: number): number {\n const requestDeficit = Math.max(0, 1 - requests.available);\n const tokenDeficit = Math.max(0, tokenNeed(inputTokens) - tokens.available);\n const requestWait = requestDeficit / requests.perMsRate;\n const tokenWait = tokenDeficit / tokens.perMsRate;\n return Math.max(requestWait, tokenWait);\n }\n\n function scheduleNext(): void {\n if (timer !== null) return;\n const head = waiters[0];\n if (head === undefined) return;\n const waitMs = Math.max(\n 1,\n Math.ceil(deficitWaitMs(head.inputTokens) - FLOAT_EPSILON),\n );\n timer = setTimeout(() => {\n timer = null;\n pump();\n }, waitMs);\n }\n\n /** Refill, resolve as many FIFO waiters as capacity allows, reschedule. */\n function pump(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n refill();\n while (waiters.length > 0) {\n const head = waiters[0];\n if (head === undefined || !tryDebit(head.inputTokens)) break;\n waiters.shift();\n head.resolve(createLease(head.inputTokens));\n }\n scheduleNext();\n }\n\n function createLease(estimateTokens: number): RateLimitLease {\n let released = false;\n return {\n release(actual: { promptTokens: number }): void {\n if (released) return;\n released = true;\n refill();\n const actualTokens =\n typeof actual.promptTokens === \"number\" &&\n Number.isFinite(actual.promptTokens)\n ? actual.promptTokens\n : estimateTokens;\n // Token bucket only — requests were consumed at acquire, never refunded.\n tokens.available = Math.min(\n tokens.capacity,\n tokens.available + (estimateTokens - actualTokens),\n );\n // A refund may unblock pending waiters (or shorten the head's wait).\n pump();\n },\n };\n }\n\n return {\n kind: \"rate-limit-group\" as const,\n async acquire(estimate: { inputTokens: number }): Promise<RateLimitLease> {\n refill();\n // Fast path only when nobody is queued — preserves FIFO fairness.\n if (waiters.length === 0 && tryDebit(estimate.inputTokens)) {\n return createLease(estimate.inputTokens);\n }\n return new Promise<RateLimitLease>((resolve) => {\n waiters.push({ inputTokens: estimate.inputTokens, resolve });\n scheduleNext();\n });\n },\n };\n}\n\n/**\n * chars/4 heuristic for lease reservation (matches the transcript-store\n * default `TokenEstimator`). Persistent estimation error is benign: `release`\n * reconciles every lease against the actual `Usage.promptTokens` (A2).\n */\nfunction estimateInputTokens(task: string): number {\n return Math.ceil(task.length / 4);\n}\n\n/**\n * Wrap an `AgentTransport` so every provider call is gated through `group`.\n *\n * Every transport wrapped with the SAME group instance shares one bucket —\n * `runAgentCrew` (39-06) wraps parent + child hosts with one shared group per\n * adapter instance, structurally guaranteeing crew-wide coordination (D-13).\n * `ProviderAdapter` is never modified (INV-03 parity invariant intact).\n *\n * - `inner` provided → dispatch nests through `inner.call(provider, request)`,\n * composing with consumer transports (e.g. cross-process bridges).\n * - `inner` undefined → falls through to `provider.execute(request)`, guarded\n * the same way as `createNoopAgentHost` (error names the provider id only).\n *\n * Release policy:\n * - Success → release with `normalizedUsage.promptTokens`; when usage is\n * missing or non-finite, fall back to the estimate (no NaN arithmetic —\n * the `costUsd: null` \"unmeasured\" discipline analog).\n * - Throw → release with the ORIGINAL estimate (burn — no refund; the\n * provider may have consumed quota despite the error) and rethrow the\n * same error unchanged. Request objects and headers are never serialized\n * into error paths.\n */\nexport function withRateLimit(\n group: RateLimitGroup,\n inner?: AgentTransport,\n): AgentTransport {\n return {\n async call(\n provider: ProviderAdapter,\n request: ProviderRunRequest,\n ): Promise<ProviderRunResponse> {\n const estimate = estimateInputTokens(request.task);\n const lease = await group.acquire({ inputTokens: estimate });\n try {\n let response: ProviderRunResponse;\n if (inner !== undefined) {\n response = await inner.call(provider, request);\n } else {\n if (provider.execute === undefined) {\n throw new Error(\n `AgentTransport: provider ${provider.id} has no execute() method.`,\n );\n }\n response = await provider.execute(request);\n }\n const actual = response.normalizedUsage?.promptTokens;\n lease.release({\n promptTokens:\n typeof actual === \"number\" && Number.isFinite(actual)\n ? actual\n : estimate,\n });\n return response;\n } catch (error) {\n // Burn the reservation: quota may have been consumed despite the error.\n lease.release({ promptTokens: estimate });\n throw error;\n }\n },\n };\n}\n","/**\n * runAgentCrew — Phase 39 (v1.3).\n *\n * Opt-in multi-agent orchestration over the existing single-agent runtime.\n * The crew surface composes a literal `AgentSpec` tree, validates a\n * serial-only `CrewPolicy`, shares budget/rate-limit state across parent\n * and children, and anchors per-agent completion receipts under one\n * crew-root receipt. Internal dispatch stays behind `createCrewDispatcher`;\n * public consumers call this function or `createAI(...).runAgentCrew(...)`.\n *\n * Rate-limit coordination keys by `ProviderAdapter` instance identity, not\n * by adapter id. The `policy.limits` map still addresses overrides by\n * `adapter.id`; two instances with the same id receive separate buckets\n * that share the same override values. `coordination: \"unmanaged\"` skips\n * all wrapping for consumers who already coordinate quota externally.\n */\n\nimport type { ArtifactRef } from \"../../artifacts/artifact.js\";\nimport type { BudgetInvariant } from \"../../contract/contract.js\";\nimport { createCostTracker, type CostTracker } from \"../infra/cost-tracker.js\";\nimport type {\n ProviderAdapter,\n ProviderRunRequest,\n ProviderRunResponse,\n Usage,\n} from \"../../providers/provider.js\";\nimport { receiptCid } from \"../../receipts/cid.js\";\nimport { computeArtifactLineageMerkleRoot } from \"../../receipts/lineage.js\";\nimport { createReceipt } from \"../../receipts/receipt.js\";\nimport type { ReceiptEnvelope, ReceiptSigner } from \"../../receipts/types.js\";\nimport type { LatticeConfig } from \"../../runtime/config.js\";\nimport type { TracerLike } from \"../../tracing/tracing.js\";\nimport type { HookPipeline } from \"../../contract/bands.js\";\n\nimport { createNoopAgentHost, type AgentHost, type AgentTransport } from \"../host.js\";\nimport { runAgentInternal } from \"../runtime.js\";\nimport type { AgentFailure, AgentIntent, AgentResult } from \"../types.js\";\n\nimport type { AgentSpec } from \"./agent-spec.js\";\nimport {\n composeCrewCachePrefix,\n createCrewDispatcher,\n deriveChildBudget,\n} from \"./dispatcher.js\";\nimport {\n type CrewPolicy,\n type ValidatedCrewPolicy,\n validateCrewPolicy,\n} from \"./crew-policy.js\";\nimport {\n createRateLimitGroup,\n type RateLimitGroup,\n type RateLimitGroupOptions,\n withRateLimit,\n} from \"../infra/rate-limit-group.js\";\n\nconst ZERO_USAGE: Usage = {\n promptTokens: 0,\n completionTokens: 0,\n costUsd: null,\n};\n\nexport interface RunAgentCrewOptions {\n readonly root: AgentSpec;\n readonly hosts: { readonly childHost: AgentHost };\n readonly policy?: CrewPolicy;\n /** Crew-level signer threaded into member loops and completion receipts. */\n readonly signer?: ReceiptSigner;\n /** Crew-level tracer threaded into member loops. */\n readonly tracer?: TracerLike;\n /** Crew-level hook pipeline threaded into member loops. */\n readonly pipeline?: HookPipeline;\n}\n\nexport interface CrewAgentResult {\n readonly id: string;\n readonly usage: Usage;\n readonly iterations: number;\n readonly receiptCids: readonly string[];\n}\n\nexport interface CrewResult {\n /** Parent result, with parent output untouched on success. */\n readonly result: AgentResult;\n /** Per-agent accounting records, including root parent and completed children. */\n readonly perAgent: ReadonlyArray<CrewAgentResult>;\n /** Crew aggregate usage: parent total + sum(child totals), no double-counting. */\n readonly usage: Usage;\n /** Total iterations across every recorded agent. */\n readonly totalIterations: number;\n /** All crew completion receipts, including the crew-root envelope. */\n readonly receipts: ReadonlyArray<ReceiptEnvelope>;\n readonly crewRootCid?: string;\n}\n\ninterface AgentAccounting {\n readonly tracker: CostTracker;\n iterations: number;\n}\n\ninterface MutableUsage {\n promptTokens: number;\n completionTokens: number;\n costUsd: number | null;\n}\n\ntype MutableBudgetInvariant = {\n -readonly [K in keyof BudgetInvariant]: BudgetInvariant[K];\n};\n\n/**\n * Execute a crew rooted at `options.root`.\n */\nexport async function runAgentCrew(\n options: RunAgentCrewOptions,\n config: LatticeConfig = {},\n): Promise<CrewResult> {\n const policy = validateCrewPolicy(options.policy);\n const runId = `runAgentCrew-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n const startedAt = Date.now();\n const accounting = new Map<string, AgentAccounting>();\n const receipts: ReceiptEnvelope[] = [];\n const receiptCidsByAgent = new Map<string, string[]>();\n\n const crewRoot = await maybeMintCrewRoot({\n runId,\n root: options.root,\n ...(options.signer !== undefined ? { signer: options.signer } : {}),\n });\n if (crewRoot !== undefined) {\n receipts.push(crewRoot.envelope);\n }\n\n const groupForProvider = createRateLimitGroupResolver(policy);\n const childHost = wrapHostWithRateLimits(\n options.hosts.childHost,\n groupForProvider,\n );\n\n function recordUsage(agentId: string, usage: Usage): void {\n entryFor(accounting, agentId).tracker.recordIteration(usage);\n }\n\n function recordAgentResult(agentId: string, result: AgentResult): void {\n const entry = entryFor(accounting, agentId);\n entry.iterations += result.iterations.length;\n }\n\n function remainingBudget(): BudgetInvariant | undefined {\n return deriveRemainingBudget({\n policy,\n usage: totalUsage(accounting),\n iterations: totalIterations(accounting),\n startedAt,\n });\n }\n\n const dispatcher = createCrewDispatcher(options.root, {\n policy,\n childHost,\n ancestry: [],\n recordUsage,\n recordAgentResult,\n remainingBudget,\n sharedPrefix: composeSharedPrefix(options.root),\n mintedReceipts(envelope) {\n receipts.push(envelope);\n },\n config,\n ...(crewRoot !== undefined ? { crewRootCid: crewRoot.cid } : {}),\n ...(options.signer !== undefined ? { signer: options.signer } : {}),\n ...(options.tracer !== undefined ? { tracer: options.tracer } : {}),\n ...(options.pipeline !== undefined ? { pipeline: options.pipeline } : {}),\n });\n\n const parentIntent: AgentIntent = {\n task: options.root.intent,\n tools: [...options.root.tools, ...dispatcher.childToolDeclarations],\n host: wrapHostWithRateLimits(createNoopAgentHost(), groupForProvider),\n ...(options.root.contract !== undefined ? { contract: options.root.contract } : {}),\n ...(options.signer !== undefined ? { signer: options.signer } : {}),\n ...(options.tracer !== undefined ? { tracer: options.tracer } : {}),\n ...(options.pipeline !== undefined ? { pipeline: options.pipeline } : {}),\n };\n\n const parentResult = await runAgentInternal(parentIntent, config, {\n dispatchToolUse: dispatcher.dispatchToolUse,\n });\n recordUsage(options.root.id, parentResult.usage);\n recordAgentResult(options.root.id, parentResult);\n\n if (options.signer !== undefined && crewRoot !== undefined) {\n const parentEnvelope = await createAgentCompletionReceipt({\n runId,\n agentId: options.root.id,\n usage: parentResult.usage,\n signer: options.signer,\n parentReceiptCid: crewRoot.cid,\n success: parentResult.kind === \"success\",\n artifacts: parentResult.kind === \"success\" ? parentResult.artifacts ?? [] : [],\n });\n receipts.push(parentEnvelope);\n }\n\n await populateReceiptCidIndex(receipts, receiptCidsByAgent);\n\n const result = dispatcher.crewBudgetExhausted() || crewBudgetViolated({\n policy,\n usage: totalUsage(accounting),\n iterations: totalIterations(accounting),\n startedAt,\n })\n ? buildCrewBudgetFailure(parentResult)\n : parentResult;\n\n return freezeCrewResult({\n result,\n perAgent: buildPerAgent(accounting, receiptCidsByAgent),\n usage: totalUsage(accounting),\n totalIterations: totalIterations(accounting),\n receipts,\n ...(crewRoot !== undefined ? { crewRootCid: crewRoot.cid } : {}),\n });\n}\n\nfunction entryFor(\n accounting: Map<string, AgentAccounting>,\n agentId: string,\n): AgentAccounting {\n let entry = accounting.get(agentId);\n if (entry === undefined) {\n entry = { tracker: createCostTracker(), iterations: 0 };\n accounting.set(agentId, entry);\n }\n return entry;\n}\n\nfunction totalUsage(accounting: Map<string, AgentAccounting>): Usage {\n const total: MutableUsage = {\n promptTokens: 0,\n completionTokens: 0,\n costUsd: null,\n };\n for (const entry of accounting.values()) {\n accumulate(total, entry.tracker.total());\n }\n return snapshot(total);\n}\n\nfunction totalIterations(accounting: Map<string, AgentAccounting>): number {\n let total = 0;\n for (const entry of accounting.values()) {\n total += entry.iterations;\n }\n return total;\n}\n\nfunction accumulate(total: MutableUsage, usage: Usage): void {\n total.promptTokens += usage.promptTokens;\n total.completionTokens += usage.completionTokens;\n if (usage.costUsd !== null) {\n total.costUsd = (total.costUsd ?? 0) + usage.costUsd;\n }\n}\n\nfunction snapshot(usage: MutableUsage): Usage {\n return {\n promptTokens: usage.promptTokens,\n completionTokens: usage.completionTokens,\n costUsd: usage.costUsd,\n };\n}\n\nfunction deriveRemainingBudget(input: {\n readonly policy: ValidatedCrewPolicy;\n readonly usage: Usage;\n readonly iterations: number;\n readonly startedAt: number;\n}): BudgetInvariant | undefined {\n const remaining: MutableBudgetInvariant = {};\n const budget = input.policy.budget;\n const iterationCeiling = minDefined(\n budget?.maxIterations,\n input.policy.maxTotalIterations,\n );\n if (iterationCeiling !== undefined) {\n remaining.maxIterations = iterationCeiling - input.iterations;\n }\n if (budget?.maxWallTimeMs !== undefined) {\n remaining.maxWallTimeMs = budget.maxWallTimeMs - (Date.now() - input.startedAt);\n }\n if (budget?.maxCostUsd !== undefined && input.usage.costUsd !== null) {\n remaining.maxCostUsd = budget.maxCostUsd - input.usage.costUsd;\n } else if (budget?.maxCostUsd !== undefined && input.usage.costUsd === null) {\n // Preserve the cap for measured descendants without treating null-cost\n // usage as zero-spend evidence that can exhaust the pool.\n remaining.maxCostUsd = budget.maxCostUsd;\n }\n if (budget?.p95LatencyMs !== undefined) {\n remaining.p95LatencyMs = budget.p95LatencyMs;\n }\n return Object.keys(remaining).length > 0 ? remaining : undefined;\n}\n\nfunction crewBudgetViolated(input: {\n readonly policy: ValidatedCrewPolicy;\n readonly usage: Usage;\n readonly iterations: number;\n readonly startedAt: number;\n}): boolean {\n const iterationCeiling = minDefined(\n input.policy.budget?.maxIterations,\n input.policy.maxTotalIterations,\n );\n if (iterationCeiling !== undefined && input.iterations > iterationCeiling) {\n return true;\n }\n const maxWallTimeMs = input.policy.budget?.maxWallTimeMs;\n if (maxWallTimeMs !== undefined && Date.now() - input.startedAt > maxWallTimeMs) {\n return true;\n }\n const maxCostUsd = input.policy.budget?.maxCostUsd;\n return (\n maxCostUsd !== undefined &&\n input.usage.costUsd !== null &&\n input.usage.costUsd > maxCostUsd\n );\n}\n\nfunction minDefined(\n a: number | undefined,\n b: number | undefined,\n): number | undefined {\n if (a !== undefined && b !== undefined) return Math.min(a, b);\n return a ?? b;\n}\n\nfunction createRateLimitGroupResolver(\n policy: ValidatedCrewPolicy,\n): (provider: ProviderAdapter) => RateLimitGroup | undefined {\n if (policy.coordination === \"unmanaged\") {\n return () => undefined;\n }\n const groups = new Map<ProviderAdapter, RateLimitGroup>();\n return (provider) => {\n let group = groups.get(provider);\n if (group === undefined) {\n group = createRateLimitGroup(rateLimitOptionsFor(policy, provider));\n groups.set(provider, group);\n }\n return group;\n };\n}\n\nfunction rateLimitOptionsFor(\n policy: ValidatedCrewPolicy,\n provider: ProviderAdapter,\n): RateLimitGroupOptions {\n const override = policy.limits?.[provider.id];\n return {\n ...(override?.requestsPerMinute !== undefined\n ? { requestsPerMinute: override.requestsPerMinute }\n : {}),\n ...(override?.tokensPerMinute !== undefined\n ? { tokensPerMinute: override.tokensPerMinute }\n : {}),\n };\n}\n\nfunction wrapHostWithRateLimits(\n host: AgentHost,\n groupForProvider: (provider: ProviderAdapter) => RateLimitGroup | undefined,\n): AgentHost {\n return {\n ...host,\n transport: wrapTransport(host.transport, groupForProvider),\n };\n}\n\nfunction wrapTransport(\n inner: AgentTransport | undefined,\n groupForProvider: (provider: ProviderAdapter) => RateLimitGroup | undefined,\n): AgentTransport {\n return {\n call(\n provider: ProviderAdapter,\n request: ProviderRunRequest,\n ): Promise<ProviderRunResponse> {\n const group = groupForProvider(provider);\n if (group !== undefined) {\n return withRateLimit(group, inner).call(provider, request);\n }\n if (inner !== undefined) {\n return inner.call(provider, request);\n }\n if (provider.execute === undefined) {\n throw new Error(`AgentTransport: provider ${provider.id} has no execute() method.`);\n }\n return provider.execute(request);\n },\n };\n}\n\nfunction composeSharedPrefix(root: AgentSpec): string {\n const firstChild = root.childAgents?.[0];\n return composeCrewCachePrefix(firstChild?.tools ?? root.tools);\n}\n\nasync function maybeMintCrewRoot(input: {\n readonly runId: string;\n readonly root: AgentSpec;\n readonly signer?: ReceiptSigner;\n}): Promise<{ readonly envelope: ReceiptEnvelope; readonly cid: string } | undefined> {\n if (input.signer === undefined) return undefined;\n const envelope = await createReceipt(\n {\n runId: input.runId,\n model: { requested: \"lattice-crew/root\", observed: null },\n route: {\n providerId: \"lattice-crew\",\n capabilityId: \"lattice-crew/run\",\n attemptNumber: 1,\n },\n usage: ZERO_USAGE,\n contractVerdict: \"success\",\n contractHash: null,\n inputHashes: [],\n outputHash: null,\n stepName: `crew-start:${input.root.id}`,\n },\n input.signer,\n );\n return { envelope, cid: await receiptCid(envelope) };\n}\n\nasync function createAgentCompletionReceipt(input: {\n readonly runId: string;\n readonly agentId: string;\n readonly usage: Usage;\n readonly signer: ReceiptSigner;\n readonly parentReceiptCid: string;\n readonly success: boolean;\n readonly artifacts?: readonly ArtifactRef[];\n}): Promise<ReceiptEnvelope> {\n const lineageMerkleRoot = await computeArtifactLineageMerkleRoot(\n input.artifacts ?? [],\n );\n return createReceipt(\n {\n runId: input.runId,\n model: { requested: \"lattice-crew/agent-completion\", observed: null },\n route: {\n providerId: \"lattice-crew\",\n capabilityId: \"lattice-crew/agent-completion\",\n attemptNumber: 1,\n },\n parentReceiptCid: input.parentReceiptCid,\n ...(lineageMerkleRoot !== undefined ? { lineageMerkleRoot } : {}),\n usage: input.usage,\n contractVerdict: input.success ? \"success\" : \"execution-failed\",\n contractHash: null,\n inputHashes: [],\n outputHash: null,\n stepName: `crew-agent-completion:${input.agentId}`,\n },\n input.signer,\n );\n}\n\nasync function populateReceiptCidIndex(\n receipts: readonly ReceiptEnvelope[],\n byAgent: Map<string, string[]>,\n): Promise<void> {\n for (const envelope of receipts) {\n const body = decodeReceiptBody(envelope);\n const agentId = parseCompletionAgentId(body.stepName);\n if (agentId === null) continue;\n const cids = byAgent.get(agentId) ?? [];\n cids.push(await receiptCid(envelope));\n byAgent.set(agentId, cids);\n }\n}\n\nfunction decodeReceiptBody(envelope: ReceiptEnvelope): { readonly stepName?: string } {\n return JSON.parse(atob(envelope.payload)) as { readonly stepName?: string };\n}\n\nfunction parseCompletionAgentId(stepName: string | undefined): string | null {\n const prefix = \"crew-agent-completion:\";\n if (stepName?.startsWith(prefix) !== true) return null;\n return stepName.slice(prefix.length);\n}\n\nfunction buildPerAgent(\n accounting: Map<string, AgentAccounting>,\n receiptCidsByAgent: Map<string, string[]>,\n): ReadonlyArray<CrewAgentResult> {\n return Object.freeze(\n Array.from(accounting.entries(), ([id, entry]) =>\n Object.freeze({\n id,\n usage: Object.freeze(entry.tracker.total()),\n iterations: entry.iterations,\n receiptCids: Object.freeze([...(receiptCidsByAgent.get(id) ?? [])]),\n }),\n ),\n );\n}\n\nfunction freezeCrewResult(result: CrewResult): CrewResult {\n return Object.freeze({\n result: result.result,\n perAgent: Object.freeze([...result.perAgent]),\n usage: Object.freeze({ ...result.usage }),\n totalIterations: result.totalIterations,\n receipts: Object.freeze([...result.receipts]),\n ...(result.crewRootCid !== undefined ? { crewRootCid: result.crewRootCid } : {}),\n });\n}\n\nfunction buildCrewBudgetFailure(parentResult: AgentResult): AgentFailure {\n return {\n kind: \"crew-budget-exceeded\",\n reason: \"Crew budget pool exhausted — the crew run ended with terminal semantics.\",\n usage: parentResult.usage,\n iterations: Object.freeze([...parentResult.iterations]),\n ...(parentResult.receipt !== undefined ? { receipt: parentResult.receipt } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,eAAsB,WAAW,UAA4C;CAE3E,MAAM,QAAQ,WAAW,KAAK,KAAK,SAAS,QAAQ,GAAG,MAAM,EAAE,WAAW,EAAE,CAAC;CAI7E,MAAM,OAAO,IAAI,WAAW,MAAM,WAAW;AAC7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OAAO,CAAC,GAAG,aAAa,WAAW,CAAC;EACvD,GAAI,aAAa,YAAY,KAAA,IAAY,EAAE,SAAS,aAAa,SAAS,GAAG,EAAE;EAChF"}
|
|
@@ -435,7 +435,7 @@ async function createReceipt(input, signer) {
|
|
|
435
435
|
const receiptId = input.receiptId ?? crypto.randomUUID();
|
|
436
436
|
const issuedAt = input.issuedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
437
437
|
const { body } = redactReceiptBody({
|
|
438
|
-
version: "lattice-receipt/v1.
|
|
438
|
+
version: "lattice-receipt/v1.3",
|
|
439
439
|
receiptId,
|
|
440
440
|
runId: input.runId,
|
|
441
441
|
issuedAt,
|
|
@@ -444,6 +444,7 @@ async function createReceipt(input, signer) {
|
|
|
444
444
|
route: input.route,
|
|
445
445
|
...input.modelClass !== void 0 ? { modelClass: input.modelClass } : {},
|
|
446
446
|
...input.parentReceiptCid !== void 0 ? { parentReceiptCid: input.parentReceiptCid } : {},
|
|
447
|
+
...input.lineageMerkleRoot !== void 0 ? { lineageMerkleRoot: input.lineageMerkleRoot } : {},
|
|
447
448
|
usage: usageToCanonical(input.usage),
|
|
448
449
|
contractVerdict: input.contractVerdict,
|
|
449
450
|
contractHash: input.contractHash,
|
|
@@ -1212,9 +1213,11 @@ async function runAgentInternal(intent, config = {}, internalOptions = {}) {
|
|
|
1212
1213
|
previousStepName: `agent-iteration-${iterationIndex}-before`
|
|
1213
1214
|
});
|
|
1214
1215
|
await host.storage?.clear();
|
|
1216
|
+
const artifactRefs = response.artifactRefs !== void 0 ? response.artifactRefs.map(toArtifactRef) : [];
|
|
1215
1217
|
return {
|
|
1216
1218
|
kind: "success",
|
|
1217
1219
|
output: { answer: responseText },
|
|
1220
|
+
...artifactRefs.length > 0 ? { artifacts: artifactRefs } : {},
|
|
1218
1221
|
usage: snapshotUsage(cumulativeUsage),
|
|
1219
1222
|
iterations: Object.freeze([...iterations])
|
|
1220
1223
|
};
|
|
@@ -1384,6 +1387,6 @@ function stableHash(input) {
|
|
|
1384
1387
|
}
|
|
1385
1388
|
}
|
|
1386
1389
|
//#endregion
|
|
1387
|
-
export { decodeEnvelope as C, artifact as D, createHookPipeline as E,
|
|
1390
|
+
export { decodeEnvelope as C, artifact as D, createHookPipeline as E, isArtifactRef as O, buildPae as S, BAND as T, STEP_TRANSITION_EVENT_NAME as _, createNoopAgentHost as a, PAYLOAD_TYPE as b, runTool as c, validateOutputMap as d, validateSchemaOutput as f, DEFAULT_CHECKPOINT_BAND as g, toolSchemaToJsonSchema as h, AgentDeniedError as i, toArtifactRef as k, toolArtifactRef as l, parseToolUseEnvelope as m, runAgentInternal as n, defineTool as o, formatToolsForProvider as p, runtime_exports as r, importMcpTools as s, runAgent as t, createNoopSurvivabilityAdapter as u, createCheckpointHook as v, canonicalizeReceiptBody as w, base64Encode as x, createReceipt as y };
|
|
1388
1391
|
|
|
1389
|
-
//# sourceMappingURL=runtime-
|
|
1392
|
+
//# sourceMappingURL=runtime-D25ehzCj.js.map
|