@tangle-network/agent-app 0.44.4 → 0.44.6
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/budget-BOucfcb_.d.ts +142 -0
- package/dist/chat-routes/index.d.ts +11 -2
- package/dist/chat-routes/index.js +9 -3
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/{chunk-CHLOH4DG.js → chunk-DEXBRUZR.js} +1 -1
- package/dist/chunk-DEXBRUZR.js.map +1 -0
- package/dist/{chunk-JHYJZSFX.js → chunk-JXIQSGOV.js} +22 -2
- package/dist/chunk-JXIQSGOV.js.map +1 -0
- package/dist/chunk-LWSJK546.js +129 -0
- package/dist/chunk-LWSJK546.js.map +1 -0
- package/dist/model-resolution/index.js +1 -1
- package/dist/profile/index.d.ts +3 -37
- package/dist/profile/index.js +7 -43
- package/dist/profile/index.js.map +1 -1
- package/dist/sandbox/index.d.ts +2 -1
- package/dist/sandbox/index.js +2 -2
- package/package.json +2 -1
- package/dist/chunk-CHLOH4DG.js.map +0 -1
- package/dist/chunk-IVUN7FL7.js +0 -72
- package/dist/chunk-IVUN7FL7.js.map +0 -1
- package/dist/chunk-JHYJZSFX.js.map +0 -1
- package/dist/fingerprint-DbmOgy0n.d.ts +0 -69
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// src/profile/budget.ts
|
|
2
|
+
var DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 4e4;
|
|
3
|
+
function assertBudgetPolicy(budget) {
|
|
4
|
+
const raisedCap = budget.maxSystemPromptBytes !== void 0 && budget.maxSystemPromptBytes > DEFAULT_MAX_SYSTEM_PROMPT_BYTES;
|
|
5
|
+
if (!raisedCap && !budget.warnOnly) return;
|
|
6
|
+
if ((budget.overBudgetReason ?? "").trim() !== "") return;
|
|
7
|
+
const weakened = raisedCap ? `maxSystemPromptBytes ${budget.maxSystemPromptBytes} exceeds the ${DEFAULT_MAX_SYSTEM_PROMPT_BYTES}-byte default` : "warnOnly downgrades the over-budget throw to a warning";
|
|
8
|
+
throw new Error(
|
|
9
|
+
`${weakened} without an overBudgetReason. Oversized system prompts degrade toward empty answers, so the cap is not a formality. Before raising it: rank the prompt with largestPromptSections() \u2014 reference material (playbooks, checklists, corpora) belongs in resources.files via corpusSkills()/userSkillMounts() or composeSkills({ mode: 'mounted' }), which puts the bodies on disk in the sandbox and leaves a short index in the prompt. Only content the agent must obey without a tool call should stay inline. If the prompt is genuinely irreducible, set overBudgetReason to the sentence that says so.`
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
function largestPromptSections(prompt, top = 3) {
|
|
13
|
+
const encoder = new TextEncoder();
|
|
14
|
+
const sections = [];
|
|
15
|
+
let title = "(preamble)";
|
|
16
|
+
let start = 0;
|
|
17
|
+
const flush = (end) => {
|
|
18
|
+
const body = prompt.slice(start, end);
|
|
19
|
+
if (body.trim()) sections.push({ title, bytes: encoder.encode(body).byteLength });
|
|
20
|
+
};
|
|
21
|
+
const headingRe = /^#{1,6}\s+(.+)$/gm;
|
|
22
|
+
for (const match of prompt.matchAll(headingRe)) {
|
|
23
|
+
flush(match.index);
|
|
24
|
+
title = (match[1] ?? "").trim() || "(untitled section)";
|
|
25
|
+
start = match.index;
|
|
26
|
+
}
|
|
27
|
+
flush(prompt.length);
|
|
28
|
+
return sections.sort((a, b) => b.bytes - a.bytes).slice(0, top);
|
|
29
|
+
}
|
|
30
|
+
function assertSystemPromptWithinBudget(systemPrompt, budget = {}, origin = "composed systemPrompt") {
|
|
31
|
+
assertBudgetPolicy(budget);
|
|
32
|
+
const max = budget.maxSystemPromptBytes ?? DEFAULT_MAX_SYSTEM_PROMPT_BYTES;
|
|
33
|
+
const bytes = new TextEncoder().encode(systemPrompt).byteLength;
|
|
34
|
+
if (bytes <= max) return;
|
|
35
|
+
const sections = largestPromptSections(systemPrompt).map((s) => `"${s.title}" (${s.bytes}B)`).join(", ");
|
|
36
|
+
const message = `${origin} is ${bytes} bytes \u2014 over the ${max}-byte budget (oversized prompts degrade to empty answers). ` + (sections ? `Largest sections: ${sections}. ` : "") + `Move reference material to resources.files (corpusSkills/userSkillMounts, or composeSkills({ mode: 'mounted' })) so the bodies land on disk in the sandbox and the prompt keeps only an index; keep inline only what the agent must obey without a tool call. Raising maxSystemPromptBytes requires an overBudgetReason.`;
|
|
37
|
+
if (budget.warnOnly) {
|
|
38
|
+
console.warn(`[profile] ${message}`);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
throw new Error(message);
|
|
42
|
+
}
|
|
43
|
+
function assertProfilePromptWithinBudget(profile, budget = {}, origin = "profile systemPrompt", hint = "") {
|
|
44
|
+
const systemPrompt = profile?.prompt?.systemPrompt;
|
|
45
|
+
if (typeof systemPrompt !== "string") return;
|
|
46
|
+
try {
|
|
47
|
+
assertSystemPromptWithinBudget(systemPrompt, budget, origin);
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (!hint) throw err;
|
|
50
|
+
throw new Error(`${err.message} ${hint}`, { cause: err });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/profile/fingerprint.ts
|
|
55
|
+
async function sha256Hex(text) {
|
|
56
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
57
|
+
return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
58
|
+
}
|
|
59
|
+
async function fingerprintAgentProfile(profile, context) {
|
|
60
|
+
const systemPrompt = profile.prompt?.systemPrompt ?? "";
|
|
61
|
+
const promptSha = await sha256Hex(systemPrompt);
|
|
62
|
+
const mcpKeys = Object.keys(profile.mcp ?? {}).sort();
|
|
63
|
+
const subagentNames = Object.keys(profile.subagents ?? {}).sort();
|
|
64
|
+
const fileMountPaths = (profile.resources?.files ?? []).map((mount) => mount.path).sort();
|
|
65
|
+
const connectionIds = (profile.connections ?? []).map((connection) => connection.alias ? `${connection.connectionId}:${connection.alias}` : connection.connectionId).sort();
|
|
66
|
+
const hash = await sha256Hex(
|
|
67
|
+
JSON.stringify([
|
|
68
|
+
promptSha,
|
|
69
|
+
mcpKeys,
|
|
70
|
+
subagentNames,
|
|
71
|
+
fileMountPaths,
|
|
72
|
+
connectionIds,
|
|
73
|
+
context?.model ?? null,
|
|
74
|
+
context?.harness ?? null
|
|
75
|
+
])
|
|
76
|
+
);
|
|
77
|
+
return {
|
|
78
|
+
hash,
|
|
79
|
+
promptSha,
|
|
80
|
+
promptBytes: new TextEncoder().encode(systemPrompt).length,
|
|
81
|
+
mcpKeys,
|
|
82
|
+
subagentNames,
|
|
83
|
+
fileMountPaths,
|
|
84
|
+
connectionIds,
|
|
85
|
+
model: context?.model,
|
|
86
|
+
harness: context?.harness
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function channelValue(fingerprint, channel) {
|
|
90
|
+
const value = fingerprint[channel];
|
|
91
|
+
if (Array.isArray(value)) return value.length === 0 ? "(none)" : value.join(",");
|
|
92
|
+
return String(value ?? "(unset)");
|
|
93
|
+
}
|
|
94
|
+
var DRIFT_CHANNELS = [
|
|
95
|
+
"promptSha",
|
|
96
|
+
"promptBytes",
|
|
97
|
+
"mcpKeys",
|
|
98
|
+
"subagentNames",
|
|
99
|
+
"fileMountPaths",
|
|
100
|
+
"connectionIds",
|
|
101
|
+
"model",
|
|
102
|
+
"harness"
|
|
103
|
+
];
|
|
104
|
+
function diffProfileFingerprints(a, b) {
|
|
105
|
+
const drift = [];
|
|
106
|
+
for (const channel of DRIFT_CHANNELS) {
|
|
107
|
+
const left = channelValue(a, channel);
|
|
108
|
+
const right = channelValue(b, channel);
|
|
109
|
+
if (left !== right) drift.push({ channel, a: left, b: right });
|
|
110
|
+
}
|
|
111
|
+
return { equal: drift.length === 0, drift };
|
|
112
|
+
}
|
|
113
|
+
function formatProfileDrift(drift) {
|
|
114
|
+
if (drift.equal) return "profiles identical";
|
|
115
|
+
const lines = drift.drift.map((entry) => ` ${entry.channel}: ${entry.a} != ${entry.b}`);
|
|
116
|
+
return `profile drift on ${drift.drift.length} channel(s):
|
|
117
|
+
${lines.join("\n")}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export {
|
|
121
|
+
DEFAULT_MAX_SYSTEM_PROMPT_BYTES,
|
|
122
|
+
largestPromptSections,
|
|
123
|
+
assertSystemPromptWithinBudget,
|
|
124
|
+
assertProfilePromptWithinBudget,
|
|
125
|
+
fingerprintAgentProfile,
|
|
126
|
+
diffProfileFingerprints,
|
|
127
|
+
formatProfileDrift
|
|
128
|
+
};
|
|
129
|
+
//# sourceMappingURL=chunk-LWSJK546.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/profile/budget.ts","../src/profile/fingerprint.ts"],"sourcesContent":["/**\n * The composed-system-prompt byte budget, split out of `./index` so it imports\n * NOTHING.\n *\n * `./index` pulls `@tangle-network/agent-eval` (the evolvable-section seam), so\n * `/sandbox` — which has no agent-eval import and must not gain one — could not\n * enforce the budget from there. The gate is the same function either way; only\n * its module home moved. `./index` re-exports every symbol below, so the\n * published `/profile` surface is byte-identical.\n *\n * Why the gate belongs at more than one call site: `composeAgentProfile` is\n * OPT-IN. A product may hand-build its `AgentProfile`, and one does —\n * creative-agent's create-time profile is deliberately minimal and its full\n * system prompt rides the PER-TURN backend (`buildPromptBackend`), which never\n * touches the composer. `/sandbox` therefore runs this gate at the three points\n * where the profile that actually executes exists.\n */\n\n/** Byte budget on the FINAL composed `prompt.systemPrompt`. Past this the\n * model degrades sharply (a 122,659-byte prompt shipped once and the model\n * returned empty answers), so the default gate throws well before that. */\nexport const DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 40_000\n\n/** Budget config for the composed system prompt. */\nexport interface ComposeProfileBudget {\n /** Byte cap on the composed `prompt.systemPrompt`.\n * Default {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES}. */\n maxSystemPromptBytes?: number\n /** Downgrade the over-budget throw to a `console.warn` — the escape hatch\n * for a product with a known-big prompt that must still ship (it yells on\n * every compose instead of blocking). */\n warnOnly?: boolean\n /** Required to raise {@link maxSystemPromptBytes} above\n * {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES} or to set {@link warnOnly}: a\n * written reason naming what stays inline and why it cannot be mounted.\n * Weakening the cap is a product decision that outlives the person making\n * it, and the usual cause is reference material concatenated into the prompt\n * that belongs in `resources.files`; demanding the sentence here keeps that\n * from happening by accident. */\n overBudgetReason?: string\n}\n\n/** Reject a budget that weakens the cap without stating why. Runs before the\n * size check so it fires on every compose, not only once a prompt has already\n * grown past the raised ceiling. */\nfunction assertBudgetPolicy(budget: ComposeProfileBudget): void {\n const raisedCap =\n budget.maxSystemPromptBytes !== undefined &&\n budget.maxSystemPromptBytes > DEFAULT_MAX_SYSTEM_PROMPT_BYTES\n if (!raisedCap && !budget.warnOnly) return\n if ((budget.overBudgetReason ?? '').trim() !== '') return\n const weakened = raisedCap\n ? `maxSystemPromptBytes ${budget.maxSystemPromptBytes} exceeds the ${DEFAULT_MAX_SYSTEM_PROMPT_BYTES}-byte default`\n : 'warnOnly downgrades the over-budget throw to a warning'\n throw new Error(\n `${weakened} without an overBudgetReason. Oversized system prompts degrade toward empty answers, so the cap is not a formality. ` +\n 'Before raising it: rank the prompt with largestPromptSections() — reference material (playbooks, checklists, corpora) belongs in resources.files ' +\n \"via corpusSkills()/userSkillMounts() or composeSkills({ mode: 'mounted' }), which puts the bodies on disk in the sandbox and leaves a short index in the prompt. \" +\n 'Only content the agent must obey without a tool call should stay inline. If the prompt is genuinely irreducible, set overBudgetReason to the sentence that says so.',\n )\n}\n\n/** Largest markdown-heading-delimited sections of a prompt, by UTF-8 bytes.\n * Cheap heuristic: split on `#`-heading lines; the preamble before the first\n * heading reports as \"(preamble)\". */\nexport function largestPromptSections(\n prompt: string,\n top = 3,\n): Array<{ title: string; bytes: number }> {\n const encoder = new TextEncoder()\n const sections: Array<{ title: string; bytes: number }> = []\n let title = '(preamble)'\n let start = 0\n const flush = (end: number) => {\n const body = prompt.slice(start, end)\n if (body.trim()) sections.push({ title, bytes: encoder.encode(body).byteLength })\n }\n const headingRe = /^#{1,6}\\s+(.+)$/gm\n for (const match of prompt.matchAll(headingRe)) {\n flush(match.index)\n title = (match[1] ?? '').trim() || '(untitled section)'\n start = match.index\n }\n flush(prompt.length)\n return sections.sort((a, b) => b.bytes - a.bytes).slice(0, top)\n}\n\n/** Enforce {@link ComposeProfileBudget} on a composed system prompt: over\n * budget throws (or warns with `warnOnly`) with the actual size and the\n * top-3 largest sections. Exported so a product assembling its prompt\n * outside `composeAgentProfile` (e.g. via the `/prompt` assembler) can\n * run the same gate at its own final-composition point. */\nexport function assertSystemPromptWithinBudget(\n systemPrompt: string,\n budget: ComposeProfileBudget = {},\n /** Prefixed to the message so a throw from a turn/provision choke point says\n * WHERE it fired — \"composed systemPrompt\" alone reads like a compose-time\n * error even when it fired on `driveSandboxTurn`. */\n origin = 'composed systemPrompt',\n): void {\n assertBudgetPolicy(budget)\n const max = budget.maxSystemPromptBytes ?? DEFAULT_MAX_SYSTEM_PROMPT_BYTES\n const bytes = new TextEncoder().encode(systemPrompt).byteLength\n if (bytes <= max) return\n const sections = largestPromptSections(systemPrompt)\n .map((s) => `\"${s.title}\" (${s.bytes}B)`)\n .join(', ')\n const message =\n `${origin} is ${bytes} bytes — over the ${max}-byte budget ` +\n `(oversized prompts degrade to empty answers). ` +\n (sections ? `Largest sections: ${sections}. ` : '') +\n `Move reference material to resources.files (corpusSkills/userSkillMounts, or composeSkills({ mode: 'mounted' })) so the bodies land on disk in the sandbox ` +\n `and the prompt keeps only an index; keep inline only what the agent must obey without a tool call. Raising maxSystemPromptBytes requires an overBudgetReason.`\n if (budget.warnOnly) {\n console.warn(`[profile] ${message}`)\n return\n }\n throw new Error(message)\n}\n\n/** Run {@link assertSystemPromptWithinBudget} over a profile-shaped object's\n * `prompt.systemPrompt`. Structural on purpose: `/sandbox` calls this on the\n * SDK's `AgentProfile` and on the product-supplied seam result without either\n * module importing the other's types. A profile with no string systemPrompt\n * is a no-op — there is nothing to measure.\n *\n * The `hint` exists because this gate can fire on a product that ALREADY made\n * a deliberate budget decision somewhere else. gtm-agent composes with\n * `{ maxSystemPromptBytes: 50_000 }`; without the hint, the shell's 40 KB\n * default reads as the gate contradicting a choice the product already made\n * rather than as \"declare the same number here too\". */\nexport function assertProfilePromptWithinBudget(\n profile: { prompt?: { systemPrompt?: unknown } } | undefined,\n budget: ComposeProfileBudget = {},\n origin = 'profile systemPrompt',\n hint = '',\n): void {\n const systemPrompt = profile?.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string') return\n try {\n assertSystemPromptWithinBudget(systemPrompt, budget, origin)\n } catch (err) {\n if (!hint) throw err\n throw new Error(`${(err as Error).message} ${hint}`, { cause: err })\n }\n}\n","/**\n * Profile fingerprinting — prove WHICH profile a turn actually executed.\n *\n * The backtest invariant this exists to enforce: an eval's score is only worth\n * publishing if the benchmarked profile IS the shipped profile. The failure\n * mode is structural, not hypothetical — a product's eval composed the\n * production profile in one module, executed a hand-rolled stub in another,\n * and stamped the composed profile's identity onto the stub's scorecard.\n * Nothing compared the two, so nothing could notice.\n *\n * A `ProfileFingerprint` is a channelled identity of the profile handed to the\n * sandbox SDK: the system-prompt digest plus the names of every capability\n * surface (MCP servers, subagents, file mounts, hub connections) and the\n * model/harness the turn dispatched at. It is deliberately NOT a byte-exhaustive\n * serialization — channels are what drift in practice, and a channelled diff\n * names the surface that moved instead of reporting \"bytes differ\".\n *\n * The write half of the seam is `StreamSandboxPromptOptions.onProfileResolved`\n * (`/sandbox`): the one place the final profile exists is inside\n * `streamSandboxPrompt` after the system-prompt override, the MCP merge, and\n * reasoning-effort attachment, so that is where the fingerprint is taken. A\n * caller re-deriving a profile to fingerprint it would reintroduce the exact\n * gap this closes.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\n\n/** The dispatch context a profile cannot see but a turn's identity includes. */\nexport interface ProfileFingerprintContext {\n model?: string\n harness?: string\n}\n\n/** Channelled identity of one executed (or composed) profile. */\nexport interface ProfileFingerprint {\n /** sha256 over every channel below — one value to log/compare. */\n hash: string\n /** sha256 of `prompt.systemPrompt` ('' when absent). */\n promptSha: string\n /** UTF-8 byte length of `prompt.systemPrompt`. */\n promptBytes: number\n /** Sorted MCP server keys. */\n mcpKeys: string[]\n /** Sorted subagent names. */\n subagentNames: string[]\n /** Sorted `resources.files[].path` mounts. */\n fileMountPaths: string[]\n /** Sorted hub connection ids (alias-qualified when present). */\n connectionIds: string[]\n model?: string\n harness?: string\n}\n\nasync function sha256Hex(text: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/** Fingerprint a profile as the SDK would receive it. */\nexport async function fingerprintAgentProfile(\n profile: AgentProfile,\n context?: ProfileFingerprintContext,\n): Promise<ProfileFingerprint> {\n const systemPrompt = profile.prompt?.systemPrompt ?? ''\n const promptSha = await sha256Hex(systemPrompt)\n const mcpKeys = Object.keys(profile.mcp ?? {}).sort()\n const subagentNames = Object.keys(profile.subagents ?? {}).sort()\n const fileMountPaths = (profile.resources?.files ?? []).map((mount) => mount.path).sort()\n const connectionIds = (profile.connections ?? [])\n .map((connection) => (connection.alias ? `${connection.connectionId}:${connection.alias}` : connection.connectionId))\n .sort()\n const hash = await sha256Hex(\n JSON.stringify([\n promptSha,\n mcpKeys,\n subagentNames,\n fileMountPaths,\n connectionIds,\n context?.model ?? null,\n context?.harness ?? null,\n ]),\n )\n return {\n hash,\n promptSha,\n promptBytes: new TextEncoder().encode(systemPrompt).length,\n mcpKeys,\n subagentNames,\n fileMountPaths,\n connectionIds,\n model: context?.model,\n harness: context?.harness,\n }\n}\n\n/** One drifted channel between two fingerprints, rendered as comparable strings. */\nexport interface ProfileDriftEntry {\n channel: 'promptSha' | 'promptBytes' | 'mcpKeys' | 'subagentNames' | 'fileMountPaths' | 'connectionIds' | 'model' | 'harness'\n a: string\n b: string\n}\n\nexport interface ProfileDrift {\n equal: boolean\n drift: ProfileDriftEntry[]\n}\n\nfunction channelValue(fingerprint: ProfileFingerprint, channel: ProfileDriftEntry['channel']): string {\n const value = fingerprint[channel]\n if (Array.isArray(value)) return value.length === 0 ? '(none)' : value.join(',')\n return String(value ?? '(unset)')\n}\n\nconst DRIFT_CHANNELS: ProfileDriftEntry['channel'][] = [\n 'promptSha',\n 'promptBytes',\n 'mcpKeys',\n 'subagentNames',\n 'fileMountPaths',\n 'connectionIds',\n 'model',\n 'harness',\n]\n\n/** Channel-by-channel comparison of two fingerprints. */\nexport function diffProfileFingerprints(a: ProfileFingerprint, b: ProfileFingerprint): ProfileDrift {\n const drift: ProfileDriftEntry[] = []\n for (const channel of DRIFT_CHANNELS) {\n const left = channelValue(a, channel)\n const right = channelValue(b, channel)\n if (left !== right) drift.push({ channel, a: left, b: right })\n }\n return { equal: drift.length === 0, drift }\n}\n\n/** Human-readable drift report; exactly 'profiles identical' when equal. */\nexport function formatProfileDrift(drift: ProfileDrift): string {\n if (drift.equal) return 'profiles identical'\n const lines = drift.drift.map((entry) => ` ${entry.channel}: ${entry.a} != ${entry.b}`)\n return `profile drift on ${drift.drift.length} channel(s):\\n${lines.join('\\n')}`\n}\n"],"mappings":";AAqBO,IAAM,kCAAkC;AAwB/C,SAAS,mBAAmB,QAAoC;AAC9D,QAAM,YACJ,OAAO,yBAAyB,UAChC,OAAO,uBAAuB;AAChC,MAAI,CAAC,aAAa,CAAC,OAAO,SAAU;AACpC,OAAK,OAAO,oBAAoB,IAAI,KAAK,MAAM,GAAI;AACnD,QAAM,WAAW,YACb,wBAAwB,OAAO,oBAAoB,gBAAgB,+BAA+B,kBAClG;AACJ,QAAM,IAAI;AAAA,IACR,GAAG,QAAQ;AAAA,EAIb;AACF;AAKO,SAAS,sBACd,QACA,MAAM,GACmC;AACzC,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,WAAoD,CAAC;AAC3D,MAAI,QAAQ;AACZ,MAAI,QAAQ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;AACpG,QAAM,QAAQ,YAAY,OAAO;AACjC,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,WAAW,IAAI,WAAW,MAAM,KAAK,GAAG;AAC/E,SAAO,OAAO,SAAS,SAAS;AAClC;AAEA,IAAM,iBAAiD;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,SAAS,wBAAwB,GAAuB,GAAqC;AAClG,QAAM,QAA6B,CAAC;AACpC,aAAW,WAAW,gBAAgB;AACpC,UAAM,OAAO,aAAa,GAAG,OAAO;AACpC,UAAM,QAAQ,aAAa,GAAG,OAAO;AACrC,QAAI,SAAS,MAAO,OAAM,KAAK,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAAA,EAC/D;AACA,SAAO,EAAE,OAAO,MAAM,WAAW,GAAG,MAAM;AAC5C;AAGO,SAAS,mBAAmB,OAA6B;AAC9D,MAAI,MAAM,MAAO,QAAO;AACxB,QAAM,QAAQ,MAAM,MAAM,IAAI,CAAC,UAAU,KAAK,MAAM,OAAO,KAAK,MAAM,CAAC,OAAO,MAAM,CAAC,EAAE;AACvF,SAAO,oBAAoB,MAAM,MAAM,MAAM;AAAA,EAAiB,MAAM,KAAK,IAAI,CAAC;AAChF;","names":[]}
|
package/dist/profile/index.d.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { profile } from '@tangle-network/agent-eval';
|
|
|
3
3
|
export { profile } from '@tangle-network/agent-eval';
|
|
4
4
|
import { SkillEntry } from '../skills/index.js';
|
|
5
5
|
export { ComposeShellResourcesInput, ComposedSkills, CorpusEntry, CorpusLoadResult, GlobModules, LoadCorpusOptions, ParsedSkill, SkillDeliveryMode, SkillFrontmatter, assertSkillDeliveryDisjoint, composeShellResources, composeSkills, corpusSkills, loadMarkdownCorpus, mergeComposedSkills, parseCorpusSkills, parseSkillFrontmatter, registrySkills, renderInlineSkills, renderSkillIndex, skillEntryFromMarkdown, skillMountPath, skillRefs } from '../skills/index.js';
|
|
6
|
-
|
|
6
|
+
import { C as ComposeProfileBudget } from '../budget-BOucfcb_.js';
|
|
7
|
+
export { D as DEFAULT_MAX_SYSTEM_PROMPT_BYTES, P as ProfileDrift, a as ProfileDriftEntry, b as ProfileFingerprint, c as ProfileFingerprintContext, d as assertProfilePromptWithinBudget, e as assertSystemPromptWithinBudget, f as diffProfileFingerprints, g as fingerprintAgentProfile, h as formatProfileDrift, l as largestPromptSections } from '../budget-BOucfcb_.js';
|
|
7
8
|
import '@tangle-network/agent-interface';
|
|
8
9
|
|
|
9
10
|
/**
|
|
@@ -102,41 +103,6 @@ interface ProfileOverlay {
|
|
|
102
103
|
/** Profile `name` override. When unset, the base name is kept. */
|
|
103
104
|
name?: string;
|
|
104
105
|
}
|
|
105
|
-
/** Byte budget on the FINAL composed `prompt.systemPrompt`. Past this the
|
|
106
|
-
* model degrades sharply (a 122,659-byte prompt shipped once and the model
|
|
107
|
-
* returned empty answers), so the default gate throws well before that. */
|
|
108
|
-
declare const DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 40000;
|
|
109
|
-
/** Budget config for the composed system prompt. */
|
|
110
|
-
interface ComposeProfileBudget {
|
|
111
|
-
/** Byte cap on the composed `prompt.systemPrompt`.
|
|
112
|
-
* Default {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES}. */
|
|
113
|
-
maxSystemPromptBytes?: number;
|
|
114
|
-
/** Downgrade the over-budget throw to a `console.warn` — the escape hatch
|
|
115
|
-
* for a product with a known-big prompt that must still ship (it yells on
|
|
116
|
-
* every compose instead of blocking). */
|
|
117
|
-
warnOnly?: boolean;
|
|
118
|
-
/** Required to raise {@link maxSystemPromptBytes} above
|
|
119
|
-
* {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES} or to set {@link warnOnly}: a
|
|
120
|
-
* written reason naming what stays inline and why it cannot be mounted.
|
|
121
|
-
* Weakening the cap is a product decision that outlives the person making
|
|
122
|
-
* it, and the usual cause is reference material concatenated into the prompt
|
|
123
|
-
* that belongs in `resources.files`; demanding the sentence here keeps that
|
|
124
|
-
* from happening by accident. */
|
|
125
|
-
overBudgetReason?: string;
|
|
126
|
-
}
|
|
127
|
-
/** Largest markdown-heading-delimited sections of a prompt, by UTF-8 bytes.
|
|
128
|
-
* Cheap heuristic: split on `#`-heading lines; the preamble before the first
|
|
129
|
-
* heading reports as "(preamble)". */
|
|
130
|
-
declare function largestPromptSections(prompt: string, top?: number): Array<{
|
|
131
|
-
title: string;
|
|
132
|
-
bytes: number;
|
|
133
|
-
}>;
|
|
134
|
-
/** Enforce {@link ComposeProfileBudget} on a composed system prompt: over
|
|
135
|
-
* budget throws (or warns with `warnOnly`) with the actual size and the
|
|
136
|
-
* top-3 largest sections. Exported so a product assembling its prompt
|
|
137
|
-
* outside {@link composeAgentProfile} (e.g. via the `/prompt` assembler) can
|
|
138
|
-
* run the same gate at its own final-composition point. */
|
|
139
|
-
declare function assertSystemPromptWithinBudget(systemPrompt: string, budget?: ComposeProfileBudget): void;
|
|
140
106
|
/** Project per-user skills onto SDK file mounts at the harness skill-discovery
|
|
141
107
|
* path. No tier gate — a user skill is mounted because the user added it.
|
|
142
108
|
* Sorted by path for determinism (matches {@link registrySkills}). */
|
|
@@ -198,4 +164,4 @@ interface EvolvableSectionInput {
|
|
|
198
164
|
*/
|
|
199
165
|
declare function makeEvolvableSection(input: EvolvableSectionInput): profile.AgentProfileSection;
|
|
200
166
|
|
|
201
|
-
export {
|
|
167
|
+
export { ComposeProfileBudget, type EvolvableSectionInput, type ProfileChannels, type ProfileOverlay, SkillEntry, type UserSkill, composeAgentProfile, makeEvolvableSection, stripComments, userSkillMounts };
|
package/dist/profile/index.js
CHANGED
|
@@ -15,55 +15,18 @@ import {
|
|
|
15
15
|
skillRefs
|
|
16
16
|
} from "../chunk-34M7AUWO.js";
|
|
17
17
|
import {
|
|
18
|
+
DEFAULT_MAX_SYSTEM_PROMPT_BYTES,
|
|
19
|
+
assertProfilePromptWithinBudget,
|
|
20
|
+
assertSystemPromptWithinBudget,
|
|
18
21
|
diffProfileFingerprints,
|
|
19
22
|
fingerprintAgentProfile,
|
|
20
|
-
formatProfileDrift
|
|
21
|
-
|
|
23
|
+
formatProfileDrift,
|
|
24
|
+
largestPromptSections
|
|
25
|
+
} from "../chunk-LWSJK546.js";
|
|
22
26
|
|
|
23
27
|
// src/profile/index.ts
|
|
24
28
|
import { mergeAgentProfiles } from "@tangle-network/sandbox";
|
|
25
29
|
import { profile } from "@tangle-network/agent-eval";
|
|
26
|
-
var DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 4e4;
|
|
27
|
-
function assertBudgetPolicy(budget) {
|
|
28
|
-
const raisedCap = budget.maxSystemPromptBytes !== void 0 && budget.maxSystemPromptBytes > DEFAULT_MAX_SYSTEM_PROMPT_BYTES;
|
|
29
|
-
if (!raisedCap && !budget.warnOnly) return;
|
|
30
|
-
if ((budget.overBudgetReason ?? "").trim() !== "") return;
|
|
31
|
-
const weakened = raisedCap ? `maxSystemPromptBytes ${budget.maxSystemPromptBytes} exceeds the ${DEFAULT_MAX_SYSTEM_PROMPT_BYTES}-byte default` : "warnOnly downgrades the over-budget throw to a warning";
|
|
32
|
-
throw new Error(
|
|
33
|
-
`${weakened} without an overBudgetReason. Oversized system prompts degrade toward empty answers, so the cap is not a formality. Before raising it: rank the prompt with largestPromptSections() \u2014 reference material (playbooks, checklists, corpora) belongs in resources.files via corpusSkills()/userSkillMounts() or composeSkills({ mode: 'mounted' }), which puts the bodies on disk in the sandbox and leaves a short index in the prompt. Only content the agent must obey without a tool call should stay inline. If the prompt is genuinely irreducible, set overBudgetReason to the sentence that says so.`
|
|
34
|
-
);
|
|
35
|
-
}
|
|
36
|
-
function largestPromptSections(prompt, top = 3) {
|
|
37
|
-
const encoder = new TextEncoder();
|
|
38
|
-
const sections = [];
|
|
39
|
-
let title = "(preamble)";
|
|
40
|
-
let start = 0;
|
|
41
|
-
const flush = (end) => {
|
|
42
|
-
const body = prompt.slice(start, end);
|
|
43
|
-
if (body.trim()) sections.push({ title, bytes: encoder.encode(body).byteLength });
|
|
44
|
-
};
|
|
45
|
-
const headingRe = /^#{1,6}\s+(.+)$/gm;
|
|
46
|
-
for (const match of prompt.matchAll(headingRe)) {
|
|
47
|
-
flush(match.index);
|
|
48
|
-
title = (match[1] ?? "").trim() || "(untitled section)";
|
|
49
|
-
start = match.index;
|
|
50
|
-
}
|
|
51
|
-
flush(prompt.length);
|
|
52
|
-
return sections.sort((a, b) => b.bytes - a.bytes).slice(0, top);
|
|
53
|
-
}
|
|
54
|
-
function assertSystemPromptWithinBudget(systemPrompt, budget = {}) {
|
|
55
|
-
assertBudgetPolicy(budget);
|
|
56
|
-
const max = budget.maxSystemPromptBytes ?? DEFAULT_MAX_SYSTEM_PROMPT_BYTES;
|
|
57
|
-
const bytes = new TextEncoder().encode(systemPrompt).byteLength;
|
|
58
|
-
if (bytes <= max) return;
|
|
59
|
-
const sections = largestPromptSections(systemPrompt).map((s) => `"${s.title}" (${s.bytes}B)`).join(", ");
|
|
60
|
-
const message = `composed systemPrompt is ${bytes} bytes \u2014 over the ${max}-byte budget (oversized prompts degrade to empty answers). ` + (sections ? `Largest sections: ${sections}. ` : "") + `Move reference material to resources.files (corpusSkills/userSkillMounts, or composeSkills({ mode: 'mounted' })) so the bodies land on disk in the sandbox and the prompt keeps only an index; keep inline only what the agent must obey without a tool call. Raising maxSystemPromptBytes requires an overBudgetReason.`;
|
|
61
|
-
if (budget.warnOnly) {
|
|
62
|
-
console.warn(`[profile] ${message}`);
|
|
63
|
-
return;
|
|
64
|
-
}
|
|
65
|
-
throw new Error(message);
|
|
66
|
-
}
|
|
67
30
|
function userSkillMounts(userSkills) {
|
|
68
31
|
return userSkills.map(
|
|
69
32
|
(s) => ({
|
|
@@ -122,6 +85,7 @@ function makeEvolvableSection(input) {
|
|
|
122
85
|
}
|
|
123
86
|
export {
|
|
124
87
|
DEFAULT_MAX_SYSTEM_PROMPT_BYTES,
|
|
88
|
+
assertProfilePromptWithinBudget,
|
|
125
89
|
assertSkillDeliveryDisjoint,
|
|
126
90
|
assertSystemPromptWithinBudget,
|
|
127
91
|
composeAgentProfile,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/profile/index.ts"],"sourcesContent":["/**\n * Profile composer + evolvable-section seam for agent products.\n *\n * The standard \"load a deployable AgentProfile, including skills, plus the\n * skills the end user added to their own instance\" entry point. A product holds\n * a canonical base `AgentProfile` (role/environment/tool-conventions rendered\n * into `prompt.systemPrompt`, baseline skills, baseline MCP). At deploy/turn\n * time it layers four file-mount channels onto `resources.files` —\n *\n * 1. skills — the always-mounted product skill corpus\n * 2. knowledge — a second always-mounted corpus (domain knowledge pack)\n * 3. registry — the tier-gated installable registry (free -> boot-mounted)\n * 4. userSkills — per-user / per-workspace skills the END USER adds to their\n * own instance, mounted at `~/.claude/skills/<id>/SKILL.md`\n * exactly like the registry's free tier\n *\n * plus an optional MCP overlay (delegation + per-turn app-tool side channel), a\n * per-turn `systemPrompt` override, and a `name` override. The merge is the SDK\n * `mergeAgentProfiles`: `mcp` is last-wins per key (base -> overlay), `resources`\n * arrays are concatenated (base ++ overlay), `prompt` is shallow-merged so an\n * overlay carrying only `systemPrompt` overrides it while keeping base\n * instructions. The compose algebra is DATA — the product injects the base\n * profile, the channel mounts (built with the `skills` subpath primitives), the\n * delegation/app-tool MCP map, and the override strings; nothing here reaches\n * for env, a glob, or a specific product's profile.\n *\n * The evolvable-section seam is the loader closure. A product's single\n * self-improvable domain section (the one `applyDomainPatch` targets) loads its\n * body from a deployed markdown override, falling back to an in-tree baseline.\n * The `import.meta.glob('<lit>', ...)` literal must stay at the CONSUMER call\n * site (Vite static-analyzes it), so `makeEvolvableSection` takes the loader as\n * a closure and a REQUIRED `baseline` — it never constructs a glob and never\n * defaults the baseline, so a product can't render an empty learned-guidance\n * section. `stripComments` is the shared \"is this addendum really empty?\" test.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n AgentProfileResourceRef,\n} from '@tangle-network/sandbox'\nimport { mergeAgentProfiles } from '@tangle-network/sandbox'\nimport { profile } from '@tangle-network/agent-eval'\nimport {\n composeShellResources,\n registrySkills,\n skillMountPath,\n type ComposeShellResourcesInput,\n type SkillEntry,\n} from '../skills/index'\n\n/** Re-expose the agent-eval section/render substrate so a product wires the\n * evolvable surface through ONE subpath: `makeEvolvableSection` builds the\n * section, `profile.renderProfile` renders it, `profile.applyDomainPatch` lets\n * the loop patch it by id. The rendering/patching engine stays in agent-eval;\n * reach it through this namespace (re-exporting the bare fns would leak\n * agent-eval's un-nameable AgentProfile type into our generated d.ts). */\nexport { profile }\n\n/** The file-mount channels layered onto `resources.files`. The first three\n * mirror {@link ComposeShellResourcesInput}; `userSkills` is the per-user /\n * per-workspace channel — skills the END USER added to their own instance,\n * mounted at the harness skill-discovery path like the registry's free tier. */\nexport interface ProfileChannels {\n /** Always-mounted skill corpus (pass `corpusSkills(...)`). */\n skills?: AgentProfileFileMount[]\n /** Always-mounted knowledge corpus (pass `corpusSkills(...)` for the pack). */\n knowledge?: AgentProfileFileMount[]\n /** Single-file evolvable / learned-guidance corpora, if mounted as files. */\n evolvable?: AgentProfileFileMount[]\n /** Tier-gated installable registry (pass the registry array; free tier is\n * mounted, paid is install-on-demand). Gated through {@link registrySkills}. */\n registry?: SkillEntry[]\n /** Per-user / per-workspace skills the end user adds to their own instance.\n * Mounted at `~/.claude/skills/<id>/SKILL.md`, the same harness path the\n * registry uses, so a user skill and a registry skill with the same id\n * collide deterministically (the user skill, appended last, wins). */\n userSkills?: UserSkill[]\n /** Final skip filter applied to the composed mount list by mount `path`. */\n filesPredicate?: (mount: AgentProfileFileMount) => boolean\n /** Typed `resources.skills` channel — refs the platform materializer places\n * at the harness-native skill dir (see {@link skillRefs} and\n * `@tangle-network/agent-app/skills-placement`'s `composeSkillsForHarness`).\n * The successor to path-baked mounts: `registry`/`userSkills` above mount\n * files at the hardcoded claude-code path via {@link skillMountPath};\n * `skillRefs` instead rides the provider-neutral `resources.skills` field\n * the platform resolves per harness. */\n skillRefs?: AgentProfileResourceRef[]\n /** Tier passed to {@link registrySkills} for the `registry` channel.\n * Previously hardcoded `'free'`; default unchanged. */\n registryTier?: string\n}\n\n/** A per-user / per-workspace skill: an id and an inline `SKILL.md` body. The\n * user-facing analogue of a registry {@link SkillEntry} with no tier gate —\n * every user skill is mounted (the user opted in by adding it). */\nexport interface UserSkill {\n id: string\n /** Inline `SKILL.md` body mounted at {@link skillMountPath}. */\n skillMd: string\n}\n\n/** Overlay overrides applied on top of the channel mounts. */\nexport interface ProfileOverlay {\n /** Extra MCP servers merged into the profile `mcp` map (last-wins per key over\n * the base servers). The product builds this from its delegation MCP entry\n * and any per-turn app-tool side-channel servers. An absent/`undefined` entry\n * is dropped — pass only the servers that resolved (fail-closed at the seam,\n * not here). */\n mcp?: Record<string, AgentProfileMcpServer>\n /** Per-turn system-prompt override. When set, replaces the base\n * `prompt.systemPrompt` while keeping base `prompt.instructions`. When unset,\n * the base prompt passes through unchanged. */\n systemPrompt?: string\n /** Extra instruction lines merged onto the active prompt (e.g. a per-turn\n * domain/integration directive). Appended to base `prompt.instructions` by\n * the SDK merge. */\n instructions?: string[]\n /** Profile `name` override. When unset, the base name is kept. */\n name?: string\n}\n\n/** Byte budget on the FINAL composed `prompt.systemPrompt`. Past this the\n * model degrades sharply (a 122,659-byte prompt shipped once and the model\n * returned empty answers), so the default gate throws well before that. */\nexport const DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 40_000\n\n/** Budget config for the composed system prompt. */\nexport interface ComposeProfileBudget {\n /** Byte cap on the composed `prompt.systemPrompt`.\n * Default {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES}. */\n maxSystemPromptBytes?: number\n /** Downgrade the over-budget throw to a `console.warn` — the escape hatch\n * for a product with a known-big prompt that must still ship (it yells on\n * every compose instead of blocking). */\n warnOnly?: boolean\n /** Required to raise {@link maxSystemPromptBytes} above\n * {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES} or to set {@link warnOnly}: a\n * written reason naming what stays inline and why it cannot be mounted.\n * Weakening the cap is a product decision that outlives the person making\n * it, and the usual cause is reference material concatenated into the prompt\n * that belongs in `resources.files`; demanding the sentence here keeps that\n * from happening by accident. */\n overBudgetReason?: string\n}\n\n/** Reject a budget that weakens the cap without stating why. Runs before the\n * size check so it fires on every compose, not only once a prompt has already\n * grown past the raised ceiling. */\nfunction assertBudgetPolicy(budget: ComposeProfileBudget): void {\n const raisedCap =\n budget.maxSystemPromptBytes !== undefined &&\n budget.maxSystemPromptBytes > DEFAULT_MAX_SYSTEM_PROMPT_BYTES\n if (!raisedCap && !budget.warnOnly) return\n if ((budget.overBudgetReason ?? '').trim() !== '') return\n const weakened = raisedCap\n ? `maxSystemPromptBytes ${budget.maxSystemPromptBytes} exceeds the ${DEFAULT_MAX_SYSTEM_PROMPT_BYTES}-byte default`\n : 'warnOnly downgrades the over-budget throw to a warning'\n throw new Error(\n `${weakened} without an overBudgetReason. Oversized system prompts degrade toward empty answers, so the cap is not a formality. ` +\n 'Before raising it: rank the prompt with largestPromptSections() — reference material (playbooks, checklists, corpora) belongs in resources.files ' +\n \"via corpusSkills()/userSkillMounts() or composeSkills({ mode: 'mounted' }), which puts the bodies on disk in the sandbox and leaves a short index in the prompt. \" +\n 'Only content the agent must obey without a tool call should stay inline. If the prompt is genuinely irreducible, set overBudgetReason to the sentence that says so.',\n )\n}\n\n/** Largest markdown-heading-delimited sections of a prompt, by UTF-8 bytes.\n * Cheap heuristic: split on `#`-heading lines; the preamble before the first\n * heading reports as \"(preamble)\". */\nexport function largestPromptSections(\n prompt: string,\n top = 3,\n): Array<{ title: string; bytes: number }> {\n const encoder = new TextEncoder()\n const sections: Array<{ title: string; bytes: number }> = []\n let title = '(preamble)'\n let start = 0\n const flush = (end: number) => {\n const body = prompt.slice(start, end)\n if (body.trim()) sections.push({ title, bytes: encoder.encode(body).byteLength })\n }\n const headingRe = /^#{1,6}\\s+(.+)$/gm\n for (const match of prompt.matchAll(headingRe)) {\n flush(match.index)\n title = (match[1] ?? '').trim() || '(untitled section)'\n start = match.index\n }\n flush(prompt.length)\n return sections.sort((a, b) => b.bytes - a.bytes).slice(0, top)\n}\n\n/** Enforce {@link ComposeProfileBudget} on a composed system prompt: over\n * budget throws (or warns with `warnOnly`) with the actual size and the\n * top-3 largest sections. Exported so a product assembling its prompt\n * outside {@link composeAgentProfile} (e.g. via the `/prompt` assembler) can\n * run the same gate at its own final-composition point. */\nexport function assertSystemPromptWithinBudget(\n systemPrompt: string,\n budget: ComposeProfileBudget = {},\n): void {\n assertBudgetPolicy(budget)\n const max = budget.maxSystemPromptBytes ?? DEFAULT_MAX_SYSTEM_PROMPT_BYTES\n const bytes = new TextEncoder().encode(systemPrompt).byteLength\n if (bytes <= max) return\n const sections = largestPromptSections(systemPrompt)\n .map((s) => `\"${s.title}\" (${s.bytes}B)`)\n .join(', ')\n const message =\n `composed systemPrompt is ${bytes} bytes — over the ${max}-byte budget ` +\n `(oversized prompts degrade to empty answers). ` +\n (sections ? `Largest sections: ${sections}. ` : '') +\n `Move reference material to resources.files (corpusSkills/userSkillMounts, or composeSkills({ mode: 'mounted' })) so the bodies land on disk in the sandbox ` +\n `and the prompt keeps only an index; keep inline only what the agent must obey without a tool call. Raising maxSystemPromptBytes requires an overBudgetReason.`\n if (budget.warnOnly) {\n console.warn(`[profile] ${message}`)\n return\n }\n throw new Error(message)\n}\n\n/** Project per-user skills onto SDK file mounts at the harness skill-discovery\n * path. No tier gate — a user skill is mounted because the user added it.\n * Sorted by path for determinism (matches {@link registrySkills}). */\nexport function userSkillMounts(userSkills: UserSkill[]): AgentProfileFileMount[] {\n return userSkills\n .map(\n (s) =>\n ({\n path: skillMountPath(s.id),\n resource: { kind: 'inline', name: s.id, content: s.skillMd },\n }) satisfies AgentProfileFileMount,\n )\n .sort((a, b) => a.path.localeCompare(b.path))\n}\n\n/**\n * Compose a deployable `AgentProfile` from a canonical base plus the four\n * file-mount channels and the overlay overrides.\n *\n * Files: base `resources.files` come first; the four channels follow in\n * `skills -> knowledge -> evolvable -> registry -> userSkills` order (so a\n * userSkill that mounts at the same path as a registry skill is the last write\n * and wins). MCP: base servers first, the overlay `mcp` last (last-wins per\n * key). Prompt: the overlay `systemPrompt`, when set, replaces the base one;\n * base instructions are preserved. Name: the overlay `name`, when set, wins.\n *\n * The merge delegates to the SDK `mergeAgentProfiles` (overlay-wins on records,\n * arrays concatenated) — the deterministic algebra is the overlay we hand it,\n * not a hand-rolled spread. `mergeAgentProfiles(base, overlay)` returns\n * `undefined` only when BOTH are `undefined`; `base` is always defined here, so\n * the result is non-`undefined` by construction and we assert that to the caller.\n *\n * The composed `prompt.systemPrompt` is byte-budgeted here — the single point\n * where the FINAL prompt exists ({@link assertSystemPromptWithinBudget};\n * default {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES}, `warnOnly` escape hatch).\n */\nexport function composeAgentProfile(\n base: AgentProfile,\n channels: ProfileChannels = {},\n overlay: ProfileOverlay = {},\n budget: ComposeProfileBudget = {},\n): AgentProfile {\n const shellInput: ComposeShellResourcesInput = {\n skills: channels.skills,\n knowledge: channels.knowledge,\n evolvable: channels.evolvable,\n registry: channels.registry\n ? registrySkills(channels.registry, channels.registryTier ?? 'free')\n : undefined,\n predicate: channels.filesPredicate,\n }\n const channelFiles = composeShellResources(shellInput)\n const userFiles = channels.userSkills ? userSkillMounts(channels.userSkills) : []\n const overlayFiles = channels.filesPredicate\n ? userFiles.filter(channels.filesPredicate)\n : userFiles\n const files = [...channelFiles, ...overlayFiles]\n\n const promptOverlay: { systemPrompt?: string; instructions?: string[] } = {}\n if (overlay.systemPrompt) promptOverlay.systemPrompt = overlay.systemPrompt\n if (overlay.instructions && overlay.instructions.length > 0) promptOverlay.instructions = overlay.instructions\n\n const overlayProfile: AgentProfile = {\n ...(overlay.name ? { name: overlay.name } : {}),\n ...(Object.keys(promptOverlay).length > 0 ? { prompt: promptOverlay } : {}),\n ...(overlay.mcp ? { mcp: overlay.mcp } : {}),\n resources: {\n files,\n ...(channels.skillRefs && channels.skillRefs.length > 0 ? { skills: channels.skillRefs } : {}),\n },\n }\n\n const merged = mergeAgentProfiles(base, overlayProfile)\n if (!merged)\n throw new Error('composeAgentProfile: mergeAgentProfiles returned undefined for a defined base')\n // Byte-budget gate on the FINAL composed systemPrompt — this is the single\n // point where every channel and overlay has been merged in.\n const systemPrompt = merged.prompt?.systemPrompt\n if (typeof systemPrompt === 'string') assertSystemPromptWithinBudget(systemPrompt, budget)\n return pruneEmptyResourceChannels(merged)\n}\n\n/** Drop empty resource channels the SDK merge normalizes in (`tools`/`skills`/\n * `agents`/`commands`: `[]`), so the composed profile's wire payload carries\n * only the channels that actually have content — one canonical shape every app\n * emits, instead of a sidecar payload full of empty arrays. */\nfunction pruneEmptyResourceChannels(profile: AgentProfile): AgentProfile {\n if (!profile.resources) return profile\n const kept = Object.fromEntries(\n Object.entries(profile.resources).filter(([, value]) => !(Array.isArray(value) && value.length === 0)),\n ) as AgentProfile['resources']\n const out: AgentProfile = { ...profile, resources: kept }\n if (kept && Object.keys(kept).length === 0) delete out.resources\n return out\n}\n\n/** True body of an addendum file with HTML comments stripped — an all-comment\n * placeholder counts as empty, so the loader falls back to the baseline. */\nexport function stripComments(raw: string): string {\n return raw.replace(/<!--[\\s\\S]*?-->/g, '').trim()\n}\n\n/** Inputs to {@link makeEvolvableSection}. */\nexport interface EvolvableSectionInput {\n /** Section id the self-improvement loop targets with `applyDomainPatch`. */\n id: string\n /** Section title rendered as `### <title>`. */\n title: string\n /**\n * Load the deployed section body. The CONSUMER supplies this closure and runs\n * its own `import.meta.glob('<lit>', { eager: true, query: '?raw', import:\n * 'default' })` inside it — the literal must stay at the call site so Vite can\n * static-analyze it; a glob constructed here would not resolve the product's\n * files. Return the raw markdown (comments and all); `makeEvolvableSection`\n * applies {@link stripComments} to decide whether it is really populated.\n */\n load: () => string\n /**\n * The in-tree fallback body, used when `load()` returns an\n * all-comments/empty placeholder. REQUIRED — no internal default — so a\n * product can never accidentally render an empty evolvable section.\n */\n baseline: string\n}\n\n/**\n * Build the one evolvable (`evolvable: true`) domain section whose body comes\n * from the product's loader, falling back to the required baseline when the\n * loaded body is empty after stripping comments. Returns the agent-eval\n * `AgentProfileSection` shape — drop it straight into `prodProfile`'s shipped\n * sections. The loader is the only seam; the empty-vs-populated rule and the\n * baseline fallback are the lifted algebra.\n */\nexport function makeEvolvableSection(input: EvolvableSectionInput): profile.AgentProfileSection {\n const loaded = input.load()\n const body = stripComments(loaded) ? loaded.trim() : input.baseline\n return { id: input.id, title: input.title, body, evolvable: true }\n}\n\nexport {\n assertSkillDeliveryDisjoint,\n composeShellResources,\n composeSkills,\n corpusSkills,\n loadMarkdownCorpus,\n mergeComposedSkills,\n parseCorpusSkills,\n parseSkillFrontmatter,\n registrySkills,\n renderInlineSkills,\n renderSkillIndex,\n skillEntryFromMarkdown,\n skillMountPath,\n skillRefs,\n} from '../skills/index'\nexport type {\n ComposedSkills,\n ComposeShellResourcesInput,\n CorpusEntry,\n CorpusLoadResult,\n GlobModules,\n LoadCorpusOptions,\n ParsedSkill,\n SkillDeliveryMode,\n SkillEntry,\n SkillFrontmatter,\n} from '../skills/index'\nexport {\n diffProfileFingerprints,\n fingerprintAgentProfile,\n formatProfileDrift,\n} from './fingerprint'\nexport type {\n ProfileDrift,\n ProfileDriftEntry,\n ProfileFingerprint,\n ProfileFingerprintContext,\n} from './fingerprint'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAS,0BAA0B;AACnC,SAAS,eAAe;AAmFjB,IAAM,kCAAkC;AAwB/C,SAAS,mBAAmB,QAAoC;AAC9D,QAAM,YACJ,OAAO,yBAAyB,UAChC,OAAO,uBAAuB;AAChC,MAAI,CAAC,aAAa,CAAC,OAAO,SAAU;AACpC,OAAK,OAAO,oBAAoB,IAAI,KAAK,MAAM,GAAI;AACnD,QAAM,WAAW,YACb,wBAAwB,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;AAAA,IAC9F;AAAA,EACF;AAEA,QAAM,SAAS,mBAAmB,MAAM,cAAc;AACtD,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,+EAA+E;AAGjG,QAAM,eAAe,OAAO,QAAQ;AACpC,MAAI,OAAO,iBAAiB,SAAU,gCAA+B,cAAc,MAAM;AACzF,SAAO,2BAA2B,MAAM;AAC1C;AAMA,SAAS,2BAA2BA,UAAqC;AACvE,MAAI,CAACA,SAAQ,UAAW,QAAOA;AAC/B,QAAM,OAAO,OAAO;AAAA,IAClB,OAAO,QAAQA,SAAQ,SAAS,EAAE,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,EAAE;AAAA,EACvG;AACA,QAAM,MAAoB,EAAE,GAAGA,UAAS,WAAW,KAAK;AACxD,MAAI,QAAQ,OAAO,KAAK,IAAI,EAAE,WAAW,EAAG,QAAO,IAAI;AACvD,SAAO;AACT;AAIO,SAAS,cAAc,KAAqB;AACjD,SAAO,IAAI,QAAQ,oBAAoB,EAAE,EAAE,KAAK;AAClD;AAiCO,SAAS,qBAAqB,OAA2D;AAC9F,QAAM,SAAS,MAAM,KAAK;AAC1B,QAAM,OAAO,cAAc,MAAM,IAAI,OAAO,KAAK,IAAI,MAAM;AAC3D,SAAO,EAAE,IAAI,MAAM,IAAI,OAAO,MAAM,OAAO,MAAM,WAAW,KAAK;AACnE;","names":["profile"]}
|
|
1
|
+
{"version":3,"sources":["../../src/profile/index.ts"],"sourcesContent":["/**\n * Profile composer + evolvable-section seam for agent products.\n *\n * The standard \"load a deployable AgentProfile, including skills, plus the\n * skills the end user added to their own instance\" entry point. A product holds\n * a canonical base `AgentProfile` (role/environment/tool-conventions rendered\n * into `prompt.systemPrompt`, baseline skills, baseline MCP). At deploy/turn\n * time it layers four file-mount channels onto `resources.files` —\n *\n * 1. skills — the always-mounted product skill corpus\n * 2. knowledge — a second always-mounted corpus (domain knowledge pack)\n * 3. registry — the tier-gated installable registry (free -> boot-mounted)\n * 4. userSkills — per-user / per-workspace skills the END USER adds to their\n * own instance, mounted at `~/.claude/skills/<id>/SKILL.md`\n * exactly like the registry's free tier\n *\n * plus an optional MCP overlay (delegation + per-turn app-tool side channel), a\n * per-turn `systemPrompt` override, and a `name` override. The merge is the SDK\n * `mergeAgentProfiles`: `mcp` is last-wins per key (base -> overlay), `resources`\n * arrays are concatenated (base ++ overlay), `prompt` is shallow-merged so an\n * overlay carrying only `systemPrompt` overrides it while keeping base\n * instructions. The compose algebra is DATA — the product injects the base\n * profile, the channel mounts (built with the `skills` subpath primitives), the\n * delegation/app-tool MCP map, and the override strings; nothing here reaches\n * for env, a glob, or a specific product's profile.\n *\n * The evolvable-section seam is the loader closure. A product's single\n * self-improvable domain section (the one `applyDomainPatch` targets) loads its\n * body from a deployed markdown override, falling back to an in-tree baseline.\n * The `import.meta.glob('<lit>', ...)` literal must stay at the CONSUMER call\n * site (Vite static-analyzes it), so `makeEvolvableSection` takes the loader as\n * a closure and a REQUIRED `baseline` — it never constructs a glob and never\n * defaults the baseline, so a product can't render an empty learned-guidance\n * section. `stripComments` is the shared \"is this addendum really empty?\" test.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n AgentProfileResourceRef,\n} from '@tangle-network/sandbox'\nimport { mergeAgentProfiles } from '@tangle-network/sandbox'\nimport { profile } from '@tangle-network/agent-eval'\nimport {\n composeShellResources,\n registrySkills,\n skillMountPath,\n type ComposeShellResourcesInput,\n type SkillEntry,\n} from '../skills/index'\nimport { assertSystemPromptWithinBudget, type ComposeProfileBudget } from './budget'\n\n/** The prompt byte budget lives in `./budget` (import-free) so `/sandbox` can\n * run the same gate without pulling agent-eval through this module. Re-exported\n * here so the published `/profile` surface is unchanged. */\nexport {\n assertProfilePromptWithinBudget,\n assertSystemPromptWithinBudget,\n DEFAULT_MAX_SYSTEM_PROMPT_BYTES,\n largestPromptSections,\n type ComposeProfileBudget,\n} from './budget'\n\n/** Re-expose the agent-eval section/render substrate so a product wires the\n * evolvable surface through ONE subpath: `makeEvolvableSection` builds the\n * section, `profile.renderProfile` renders it, `profile.applyDomainPatch` lets\n * the loop patch it by id. The rendering/patching engine stays in agent-eval;\n * reach it through this namespace (re-exporting the bare fns would leak\n * agent-eval's un-nameable AgentProfile type into our generated d.ts). */\nexport { profile }\n\n/** The file-mount channels layered onto `resources.files`. The first three\n * mirror {@link ComposeShellResourcesInput}; `userSkills` is the per-user /\n * per-workspace channel — skills the END USER added to their own instance,\n * mounted at the harness skill-discovery path like the registry's free tier. */\nexport interface ProfileChannels {\n /** Always-mounted skill corpus (pass `corpusSkills(...)`). */\n skills?: AgentProfileFileMount[]\n /** Always-mounted knowledge corpus (pass `corpusSkills(...)` for the pack). */\n knowledge?: AgentProfileFileMount[]\n /** Single-file evolvable / learned-guidance corpora, if mounted as files. */\n evolvable?: AgentProfileFileMount[]\n /** Tier-gated installable registry (pass the registry array; free tier is\n * mounted, paid is install-on-demand). Gated through {@link registrySkills}. */\n registry?: SkillEntry[]\n /** Per-user / per-workspace skills the end user adds to their own instance.\n * Mounted at `~/.claude/skills/<id>/SKILL.md`, the same harness path the\n * registry uses, so a user skill and a registry skill with the same id\n * collide deterministically (the user skill, appended last, wins). */\n userSkills?: UserSkill[]\n /** Final skip filter applied to the composed mount list by mount `path`. */\n filesPredicate?: (mount: AgentProfileFileMount) => boolean\n /** Typed `resources.skills` channel — refs the platform materializer places\n * at the harness-native skill dir (see {@link skillRefs} and\n * `@tangle-network/agent-app/skills-placement`'s `composeSkillsForHarness`).\n * The successor to path-baked mounts: `registry`/`userSkills` above mount\n * files at the hardcoded claude-code path via {@link skillMountPath};\n * `skillRefs` instead rides the provider-neutral `resources.skills` field\n * the platform resolves per harness. */\n skillRefs?: AgentProfileResourceRef[]\n /** Tier passed to {@link registrySkills} for the `registry` channel.\n * Previously hardcoded `'free'`; default unchanged. */\n registryTier?: string\n}\n\n/** A per-user / per-workspace skill: an id and an inline `SKILL.md` body. The\n * user-facing analogue of a registry {@link SkillEntry} with no tier gate —\n * every user skill is mounted (the user opted in by adding it). */\nexport interface UserSkill {\n id: string\n /** Inline `SKILL.md` body mounted at {@link skillMountPath}. */\n skillMd: string\n}\n\n/** Overlay overrides applied on top of the channel mounts. */\nexport interface ProfileOverlay {\n /** Extra MCP servers merged into the profile `mcp` map (last-wins per key over\n * the base servers). The product builds this from its delegation MCP entry\n * and any per-turn app-tool side-channel servers. An absent/`undefined` entry\n * is dropped — pass only the servers that resolved (fail-closed at the seam,\n * not here). */\n mcp?: Record<string, AgentProfileMcpServer>\n /** Per-turn system-prompt override. When set, replaces the base\n * `prompt.systemPrompt` while keeping base `prompt.instructions`. When unset,\n * the base prompt passes through unchanged. */\n systemPrompt?: string\n /** Extra instruction lines merged onto the active prompt (e.g. a per-turn\n * domain/integration directive). Appended to base `prompt.instructions` by\n * the SDK merge. */\n instructions?: string[]\n /** Profile `name` override. When unset, the base name is kept. */\n name?: string\n}\n\n/** Project per-user skills onto SDK file mounts at the harness skill-discovery\n * path. No tier gate — a user skill is mounted because the user added it.\n * Sorted by path for determinism (matches {@link registrySkills}). */\nexport function userSkillMounts(userSkills: UserSkill[]): AgentProfileFileMount[] {\n return userSkills\n .map(\n (s) =>\n ({\n path: skillMountPath(s.id),\n resource: { kind: 'inline', name: s.id, content: s.skillMd },\n }) satisfies AgentProfileFileMount,\n )\n .sort((a, b) => a.path.localeCompare(b.path))\n}\n\n/**\n * Compose a deployable `AgentProfile` from a canonical base plus the four\n * file-mount channels and the overlay overrides.\n *\n * Files: base `resources.files` come first; the four channels follow in\n * `skills -> knowledge -> evolvable -> registry -> userSkills` order (so a\n * userSkill that mounts at the same path as a registry skill is the last write\n * and wins). MCP: base servers first, the overlay `mcp` last (last-wins per\n * key). Prompt: the overlay `systemPrompt`, when set, replaces the base one;\n * base instructions are preserved. Name: the overlay `name`, when set, wins.\n *\n * The merge delegates to the SDK `mergeAgentProfiles` (overlay-wins on records,\n * arrays concatenated) — the deterministic algebra is the overlay we hand it,\n * not a hand-rolled spread. `mergeAgentProfiles(base, overlay)` returns\n * `undefined` only when BOTH are `undefined`; `base` is always defined here, so\n * the result is non-`undefined` by construction and we assert that to the caller.\n *\n * The composed `prompt.systemPrompt` is byte-budgeted here — the single point\n * where the FINAL prompt exists ({@link assertSystemPromptWithinBudget};\n * default {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES}, `warnOnly` escape hatch).\n */\nexport function composeAgentProfile(\n base: AgentProfile,\n channels: ProfileChannels = {},\n overlay: ProfileOverlay = {},\n budget: ComposeProfileBudget = {},\n): AgentProfile {\n const shellInput: ComposeShellResourcesInput = {\n skills: channels.skills,\n knowledge: channels.knowledge,\n evolvable: channels.evolvable,\n registry: channels.registry\n ? registrySkills(channels.registry, channels.registryTier ?? 'free')\n : undefined,\n predicate: channels.filesPredicate,\n }\n const channelFiles = composeShellResources(shellInput)\n const userFiles = channels.userSkills ? userSkillMounts(channels.userSkills) : []\n const overlayFiles = channels.filesPredicate\n ? userFiles.filter(channels.filesPredicate)\n : userFiles\n const files = [...channelFiles, ...overlayFiles]\n\n const promptOverlay: { systemPrompt?: string; instructions?: string[] } = {}\n if (overlay.systemPrompt) promptOverlay.systemPrompt = overlay.systemPrompt\n if (overlay.instructions && overlay.instructions.length > 0) promptOverlay.instructions = overlay.instructions\n\n const overlayProfile: AgentProfile = {\n ...(overlay.name ? { name: overlay.name } : {}),\n ...(Object.keys(promptOverlay).length > 0 ? { prompt: promptOverlay } : {}),\n ...(overlay.mcp ? { mcp: overlay.mcp } : {}),\n resources: {\n files,\n ...(channels.skillRefs && channels.skillRefs.length > 0 ? { skills: channels.skillRefs } : {}),\n },\n }\n\n const merged = mergeAgentProfiles(base, overlayProfile)\n if (!merged)\n throw new Error('composeAgentProfile: mergeAgentProfiles returned undefined for a defined base')\n // Byte-budget gate on the FINAL composed systemPrompt — this is the single\n // point where every channel and overlay has been merged in.\n const systemPrompt = merged.prompt?.systemPrompt\n if (typeof systemPrompt === 'string') assertSystemPromptWithinBudget(systemPrompt, budget)\n return pruneEmptyResourceChannels(merged)\n}\n\n/** Drop empty resource channels the SDK merge normalizes in (`tools`/`skills`/\n * `agents`/`commands`: `[]`), so the composed profile's wire payload carries\n * only the channels that actually have content — one canonical shape every app\n * emits, instead of a sidecar payload full of empty arrays. */\nfunction pruneEmptyResourceChannels(profile: AgentProfile): AgentProfile {\n if (!profile.resources) return profile\n const kept = Object.fromEntries(\n Object.entries(profile.resources).filter(([, value]) => !(Array.isArray(value) && value.length === 0)),\n ) as AgentProfile['resources']\n const out: AgentProfile = { ...profile, resources: kept }\n if (kept && Object.keys(kept).length === 0) delete out.resources\n return out\n}\n\n/** True body of an addendum file with HTML comments stripped — an all-comment\n * placeholder counts as empty, so the loader falls back to the baseline. */\nexport function stripComments(raw: string): string {\n return raw.replace(/<!--[\\s\\S]*?-->/g, '').trim()\n}\n\n/** Inputs to {@link makeEvolvableSection}. */\nexport interface EvolvableSectionInput {\n /** Section id the self-improvement loop targets with `applyDomainPatch`. */\n id: string\n /** Section title rendered as `### <title>`. */\n title: string\n /**\n * Load the deployed section body. The CONSUMER supplies this closure and runs\n * its own `import.meta.glob('<lit>', { eager: true, query: '?raw', import:\n * 'default' })` inside it — the literal must stay at the call site so Vite can\n * static-analyze it; a glob constructed here would not resolve the product's\n * files. Return the raw markdown (comments and all); `makeEvolvableSection`\n * applies {@link stripComments} to decide whether it is really populated.\n */\n load: () => string\n /**\n * The in-tree fallback body, used when `load()` returns an\n * all-comments/empty placeholder. REQUIRED — no internal default — so a\n * product can never accidentally render an empty evolvable section.\n */\n baseline: string\n}\n\n/**\n * Build the one evolvable (`evolvable: true`) domain section whose body comes\n * from the product's loader, falling back to the required baseline when the\n * loaded body is empty after stripping comments. Returns the agent-eval\n * `AgentProfileSection` shape — drop it straight into `prodProfile`'s shipped\n * sections. The loader is the only seam; the empty-vs-populated rule and the\n * baseline fallback are the lifted algebra.\n */\nexport function makeEvolvableSection(input: EvolvableSectionInput): profile.AgentProfileSection {\n const loaded = input.load()\n const body = stripComments(loaded) ? loaded.trim() : input.baseline\n return { id: input.id, title: input.title, body, evolvable: true }\n}\n\nexport {\n assertSkillDeliveryDisjoint,\n composeShellResources,\n composeSkills,\n corpusSkills,\n loadMarkdownCorpus,\n mergeComposedSkills,\n parseCorpusSkills,\n parseSkillFrontmatter,\n registrySkills,\n renderInlineSkills,\n renderSkillIndex,\n skillEntryFromMarkdown,\n skillMountPath,\n skillRefs,\n} from '../skills/index'\nexport type {\n ComposedSkills,\n ComposeShellResourcesInput,\n CorpusEntry,\n CorpusLoadResult,\n GlobModules,\n LoadCorpusOptions,\n ParsedSkill,\n SkillDeliveryMode,\n SkillEntry,\n SkillFrontmatter,\n} from '../skills/index'\nexport {\n diffProfileFingerprints,\n fingerprintAgentProfile,\n formatProfileDrift,\n} from './fingerprint'\nexport type {\n ProfileDrift,\n ProfileDriftEntry,\n ProfileFingerprint,\n ProfileFingerprintContext,\n} from './fingerprint'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAS,0BAA0B;AACnC,SAAS,eAAe;AA+FjB,SAAS,gBAAgB,YAAkD;AAChF,SAAO,WACJ;AAAA,IACC,CAAC,OACE;AAAA,MACC,MAAM,eAAe,EAAE,EAAE;AAAA,MACzB,UAAU,EAAE,MAAM,UAAU,MAAM,EAAE,IAAI,SAAS,EAAE,QAAQ;AAAA,IAC7D;AAAA,EACJ,EACC,KAAK,CAAC,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAChD;AAuBO,SAAS,oBACd,MACA,WAA4B,CAAC,GAC7B,UAA0B,CAAC,GAC3B,SAA+B,CAAC,GAClB;AACd,QAAM,aAAyC;AAAA,IAC7C,QAAQ,SAAS;AAAA,IACjB,WAAW,SAAS;AAAA,IACpB,WAAW,SAAS;AAAA,IACpB,UAAU,SAAS,WACf,eAAe,SAAS,UAAU,SAAS,gBAAgB,MAAM,IACjE;AAAA,IACJ,W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AGA,UAAS,WAAW,KAAK;AACxD,MAAI,QAAQ,OAAO,KAAK,IAAI,EAAE,WAAW,EAAG,QAAO,IAAI;AACvD,SAAO;AACT;AAIO,SAAS,cAAc,KAAqB;AACjD,SAAO,IAAI,QAAQ,oBAAoB,EAAE,EAAE,KAAK;AAClD;AAiCO,SAAS,qBAAqB,OAA2D;AAC9F,QAAM,SAAS,MAAM,KAAK;AAC1B,QAAM,OAAO,cAAc,MAAM,IAAI,OAAO,KAAK,IAAI,MAAM;AAC3D,SAAO,EAAE,IAAI,MAAM,IAAI,OAAO,MAAM,OAAO,MAAM,WAAW,KAAK;AACnE;","names":["profile"]}
|
package/dist/sandbox/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { T as ToolHeaderNames } from '../auth-anc7mv2W.js';
|
|
|
4
4
|
import { b as AppToolName, a as AppToolContext } from '../types-BCxK0wyS.js';
|
|
5
5
|
import { Harness } from '../harness/index.js';
|
|
6
6
|
import { a as TangleExecutionEnvironment } from '../model-CdCDfBA9.js';
|
|
7
|
-
import { b as ProfileFingerprint } from '../
|
|
7
|
+
import { b as ProfileFingerprint, C as ComposeProfileBudget } from '../budget-BOucfcb_.js';
|
|
8
8
|
import '@tangle-network/agent-interface';
|
|
9
9
|
|
|
10
10
|
/** Represent success or failure of an operation with corresponding value or error information */
|
|
@@ -448,6 +448,7 @@ interface SandboxRuntimeConfig {
|
|
|
448
448
|
recoverStoppedSandbox?: (failure: StoppedSandboxResumeFailure) => Promise<Outcome<StoppedSandboxResumeRecovery | null>>;
|
|
449
449
|
backendModelAtCreate?: boolean;
|
|
450
450
|
deferProfileFiles?: boolean;
|
|
451
|
+
promptBudget?: ComposeProfileBudget;
|
|
451
452
|
}
|
|
452
453
|
/** Define default resource limits and settings for sandbox environments */
|
|
453
454
|
declare const DEFAULT_SANDBOX_RESOURCES: SandboxResourceConfig;
|
package/dist/sandbox/index.js
CHANGED
|
@@ -59,8 +59,8 @@ import {
|
|
|
59
59
|
verifySandboxTerminalToken,
|
|
60
60
|
verifyTerminalProxyToken,
|
|
61
61
|
writeProfileFilesToBox
|
|
62
|
-
} from "../chunk-
|
|
63
|
-
import "../chunk-
|
|
62
|
+
} from "../chunk-JXIQSGOV.js";
|
|
63
|
+
import "../chunk-LWSJK546.js";
|
|
64
64
|
import "../chunk-CQZSAR77.js";
|
|
65
65
|
import "../chunk-ICOHEZK6.js";
|
|
66
66
|
import "../chunk-3EJ6SFJI.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.44.
|
|
3
|
+
"version": "0.44.6",
|
|
4
4
|
"packageManager": "pnpm@10.33.4",
|
|
5
5
|
"description": "Application-shell framework for Tangle agent products: a bounded tool loop, the structured agent→app tool side channel, integration-hub client, per-workspace billing, and crypto — composed over the Tangle agent substrate through typed seams.",
|
|
6
6
|
"keywords": [
|
|
@@ -405,6 +405,7 @@
|
|
|
405
405
|
"dev": "tsup --watch",
|
|
406
406
|
"prepare": "tsup",
|
|
407
407
|
"test": "vitest run",
|
|
408
|
+
"test:gates": "vitest run src/sandbox/index.test.ts src/profile/index.test.ts tests/chat-stream.test.ts tests/browser-safe-subpaths.test.ts tests/test-quality.test.ts tests/knip-entries-fresh.test.ts",
|
|
408
409
|
"test:watch": "vitest",
|
|
409
410
|
"typecheck": "tsc --noEmit",
|
|
410
411
|
"docs:gen": "agent-docs",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/model-resolution/failover.ts"],"sourcesContent":["/**\n * Model failover — the answer to \"one upstream hit a quota wall and the customer\n * got a Bad Gateway even though the router had abundant healthy capacity\".\n *\n * This is deliberately NOT a health probe. Probing before every turn buys a\n * round-trip of latency on the happy path and still races the outage (a model\n * healthy at probe time can 502 a second later). Failover is REACTIVE: run the\n * preferred model, and on an upstream-outage signal move to the next model in\n * the chain. Zero added latency when the preferred model works.\n *\n * Two facts drive the design, both measured against a live box during the\n * 2026-07-25 Anthropic/DeepSeek outage:\n *\n * 1. An outage is NOT always a thrown error. The sandbox resolves with a\n * payload — `{ success: false, errorCode: 'provider_inference_unavailable' }`\n * — so a classifier that only inspects `catch` misses the customer-visible\n * case entirely. `isUpstreamUnavailable` inspects resolved values too.\n * 2. Catalog membership is NOT liveness. The router's `/v1/models` still listed\n * every dead model during the outage, so `validateChatModelId` admitted\n * `claude-sonnet-4-6` while every call to it returned 502. Nothing upstream\n * of the actual call can be trusted to tell you a model is serving.\n *\n * Substrate-free: the caller injects `run`, so this composes with a sandbox\n * turn, a router chat completion, or a test fake without importing any of them.\n */\n\n/**\n * Error codes that mean \"this model's upstream is unavailable — a different\n * model may still work\". Deliberately excludes codes that would fail identically\n * on every model (bad request, auth, content filter): retrying those down a\n * chain burns latency and money to reach the same failure.\n */\nexport const UPSTREAM_UNAVAILABLE_CODES: readonly string[] = [\n 'provider_inference_unavailable',\n 'upstream_unavailable',\n 'insufficient_quota',\n 'model_not_available',\n 'server_error',\n 'bad_gateway',\n 'service_unavailable',\n]\n\n/** HTTP statuses that indicate an upstream capacity/availability problem. */\nexport const UPSTREAM_UNAVAILABLE_STATUSES: readonly number[] = [429, 500, 502, 503, 504]\n\n/**\n * Statuses that mean the REQUEST is wrong, so every model in the chain would\n * fail on it identically. Listed explicitly rather than as \"any 4xx\" because\n * 404 is NOT one of them: a model the endpoint cannot find is model-scoped, and\n * the next model in the chain may well be there. 429 is absent for the same\n * reason in reverse — it is a capacity signal and lives in the list above.\n */\nconst REQUEST_ERROR_STATUSES: readonly number[] = [400, 401, 403, 405, 413, 422]\n\n/**\n * Message fragments emitted by real upstreams during this class of outage.\n * Matched case-insensitively as a last resort, after code and status.\n */\nconst UPSTREAM_UNAVAILABLE_MESSAGES: readonly string[] = [\n 'bad gateway',\n 'service unavailable',\n 'inference temporarily unavailable',\n 'provider inference is unavailable',\n 'insufficient balance',\n 'usage limits',\n 'quota exceeded',\n 'rate limit',\n 'overloaded',\n 'temporarily unavailable',\n // Model-SCOPED unavailability. A different model in the chain can still\n // serve, so this belongs here and not with the client errors. Measured on a\n // real box 2026-07-27: the sandbox now reports an unservable model as a\n // terminal `error` whose data is `{\"message\":\"Session error:\n // {\\\"error\\\":{\\\"name\\\":\\\"UnknownError\\\",\\\"data\\\":{\\\"message\\\":\\\"Model not\n // found: openai-compat/zai/glm-4.7.\\\"}}}\"}` — no `code`, no numeric status,\n // and none of the fragments above. The shipped live product-path proof went\n // red on exactly this: `usedFallback:false`, `failed:true`, an error row to\n // the customer where a fallback was available and would have answered.\n 'model not found',\n 'is not currently available',\n]\n\n/**\n * Textual forms an HTTP status arrives in when NO numeric field carries it.\n *\n * The case that forced this is the Cloudflare EDGE 502. Captured verbatim from\n * `router.tangle.tools` on 2026-07-27 17:48:12 GMT (cf-ray\n * `a21d793899f6cef3-DEN`): `HTTP/2 502`, `content-type: text/plain;\n * charset=UTF-8`, a 16-byte body reading `error code: 502\\n`, `server:\n * cloudflare`, and **zero `x-tangle-*` headers** where a healthy 200 from the\n * same endpoint carries nine of them. Zero means the origin never executed —\n * so the router's own upstream failover, which lives inside the origin,\n * structurally cannot fire. Only a client OUTSIDE the edge can rescue that\n * turn, which is why this classifier has to recognize a failure shape that\n * nobody upstream will ever label for it.\n *\n * Every pattern below matches a string a real producer emits:\n * - `error code: 502` — Cloudflare's edge body (the capture above).\n * - `(HTTP 502)` — `src/runtime/openai-stream.ts` wrapping a non-ok response.\n * - `returned 502` — `src/runtime/model-catalog.ts`.\n * - `failed with status 502` — `src/turn-stream/adapters.ts`.\n * - `502 Bad Gateway` — an HTTP/1.1 status line. HTTP/2 carries no reason\n * phrase at all, which is precisely why matching the phrase alone (the\n * `'bad gateway'` fragment below) read the capture as a non-outage.\n */\nconst HTTP_STATUS_HINT_PATTERNS: readonly RegExp[] = [\n /\\berror\\s+code:?\\s*([1-5]\\d{2})\\b/i,\n /\\bhttp(?:\\/[\\d.]+)?[\\s:]\\s*([1-5]\\d{2})\\b/i,\n /\\bstatus(?:\\s*code)?[\\s:=]\\s*([1-5]\\d{2})\\b/i,\n /\\b(?:returned|responded(?:\\s+with)?)\\s+([1-5]\\d{2})\\b/i,\n /\\b([1-5]\\d{2})\\s+(?:bad\\s+gateway|service\\s+unavailable|gateway\\s+time-?out|internal\\s+server\\s+error|too\\s+many\\s+requests)\\b/i,\n]\n\n/**\n * The HTTP status a message states in prose, or `undefined` when it states\n * none. Deliberately NOT \"any three digits in the string\" — an unanchored digit\n * scan would read a token count or a duration as a status.\n */\nexport function readHttpStatusHint(text: string): number | undefined {\n for (const pattern of HTTP_STATUS_HINT_PATTERNS) {\n const match = pattern.exec(text)\n if (match?.[1]) return Number(match[1])\n }\n return undefined\n}\n\nfunction readString(source: Record<string, unknown>, key: string): string | undefined {\n const value = source[key]\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\n/**\n * True when `signal` — a thrown error OR a resolved result payload — indicates\n * the model's upstream is unavailable and another model is worth trying.\n *\n * Checked in order of decreasing confidence: explicit code, HTTP status, then\n * message text. A resolved payload only counts as a failure when it carries an\n * explicit failure marker (`success: false`, or an `error`/`errorCode` field) —\n * a successful result is never misread as an outage.\n */\nexport function isUpstreamUnavailable(signal: unknown): boolean {\n if (signal === null || typeof signal !== 'object') return false\n const record = signal as Record<string, unknown>\n\n // A resolved payload that explicitly reports success is never an outage.\n if (record.success === true) return false\n\n const nested = record.error\n const nestedRecord = nested !== null && typeof nested === 'object' ? (nested as Record<string, unknown>) : undefined\n\n const code =\n readString(record, 'errorCode') ??\n readString(record, 'code') ??\n (nestedRecord ? (readString(nestedRecord, 'code') ?? readString(nestedRecord, 'type')) : undefined)\n if (code && UPSTREAM_UNAVAILABLE_CODES.includes(code)) return true\n\n for (const key of ['status', 'statusCode', 'httpStatus']) {\n const value = record[key]\n if (typeof value === 'number' && UPSTREAM_UNAVAILABLE_STATUSES.includes(value)) return true\n }\n\n const message =\n readString(record, 'message') ??\n readString(record, 'error') ??\n (nestedRecord ? readString(nestedRecord, 'message') : undefined)\n if (!message) return false\n\n // A status carried as PROSE, checked before the fragment list because it is\n // the stronger signal and it cuts BOTH ways. An edge 502 names no exception\n // type and sets no numeric field, so without this the shipped classifier read\n // `error code: 502` as a non-outage and handed the customer a Bad Gateway\n // instead of trying the next model — the exact failure the router cannot\n // rescue from inside its own origin.\n const hinted = readHttpStatusHint(message)\n if (hinted !== undefined) {\n if (UPSTREAM_UNAVAILABLE_STATUSES.includes(hinted)) return true\n // An explicit REQUEST-error status is decisive the OTHER way. A 400\n // carrying a validation message must surface rather than walk the chain,\n // even when its body happens to contain a word from the fragment list —\n // the router's own `Function tools with reasoning_effort are not supported`\n // 400 is a request-shaping bug that fails identically on every model.\n if (REQUEST_ERROR_STATUSES.includes(hinted)) return false\n }\n\n const lowered = message.toLowerCase()\n return UPSTREAM_UNAVAILABLE_MESSAGES.some((fragment) => lowered.includes(fragment))\n}\n\n/** One model tried, and how it went. */\nexport interface ModelFailoverAttempt {\n model: string\n ok: boolean\n /** Why this model was abandoned. Absent when `ok`. */\n reason?: string\n}\n\n/** The outcome of a failover run: the value plus the full attempt trail. */\nexport interface ModelFailoverResult<T> {\n value: T\n /** The model that actually produced `value`. */\n model: string\n attempts: ModelFailoverAttempt[]\n /** True when the preferred (first) model did not serve the request. */\n usedFallback: boolean\n}\n\n/** Every model in the chain failed; carries the trail for logging. */\nexport class ModelFailoverExhaustedError extends Error {\n readonly attempts: ModelFailoverAttempt[]\n constructor(attempts: ModelFailoverAttempt[]) {\n const trail = attempts.map((a) => `${a.model}: ${a.reason ?? 'failed'}`).join(' | ')\n super(`All ${attempts.length} model(s) failed. ${trail}`)\n this.name = 'ModelFailoverExhaustedError'\n this.attempts = attempts\n }\n}\n\n/** Inputs to {@link runWithModelFailover}. */\nexport interface RunWithModelFailoverInput<T> {\n /** Preferred model first, then fallbacks in descending preference. */\n models: readonly string[]\n /** Executes one turn with the given model. */\n run: (model: string) => Promise<T>\n /**\n * Classifies a resolved result as an upstream outage. Defaults to\n * {@link isUpstreamUnavailable}, which understands the sandbox's\n * `{ success: false, errorCode }` payload.\n */\n isUnavailableResult?: (result: T) => boolean\n /** Classifies a thrown error. Defaults to {@link isUpstreamUnavailable}. */\n isUnavailableError?: (error: unknown) => boolean\n /** Observability hook fired each time a model is abandoned. */\n onFallback?: (attempt: ModelFailoverAttempt, nextModel: string) => void\n}\n\nfunction describe(signal: unknown): string {\n if (signal instanceof Error) return signal.message\n if (signal !== null && typeof signal === 'object') {\n const record = signal as Record<string, unknown>\n const message = readString(record, 'error') ?? readString(record, 'message') ?? readString(record, 'errorCode')\n if (message) return message\n }\n return String(signal)\n}\n\n/**\n * Run `run` against the first model in `models` that does not report an upstream\n * outage, falling through the chain in order.\n *\n * A non-outage failure (bad request, auth, content filter) is re-thrown\n * immediately rather than retried down the chain — those fail identically on\n * every model, so walking the chain would only multiply latency and spend.\n *\n * @throws ModelFailoverExhaustedError when every model reports an outage.\n */\nexport async function runWithModelFailover<T>(\n input: RunWithModelFailoverInput<T>,\n): Promise<ModelFailoverResult<T>> {\n const models = input.models.map((m) => m.trim()).filter((m) => m.length > 0)\n if (models.length === 0) throw new Error('runWithModelFailover requires at least one model')\n\n const isUnavailableResult = input.isUnavailableResult ?? ((r: T) => isUpstreamUnavailable(r))\n const isUnavailableError = input.isUnavailableError ?? isUpstreamUnavailable\n const attempts: ModelFailoverAttempt[] = []\n\n for (let index = 0; index < models.length; index += 1) {\n const model = models[index]!\n let result: T\n try {\n result = await input.run(model)\n } catch (error) {\n if (!isUnavailableError(error)) throw error\n const attempt: ModelFailoverAttempt = { model, ok: false, reason: describe(error) }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n\n if (isUnavailableResult(result)) {\n const attempt: ModelFailoverAttempt = { model, ok: false, reason: describe(result) }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n\n attempts.push({ model, ok: true })\n return { value: result, model, attempts, usedFallback: index > 0 }\n }\n\n throw new ModelFailoverExhaustedError(attempts)\n}\n\n/**\n * Build a failover chain: the preferred model first, then `fallbacks`, with\n * duplicates removed so a model is never retried twice in one turn.\n */\nexport function buildModelChain(preferred: string, fallbacks: readonly string[]): string[] {\n const chain: string[] = []\n for (const model of [preferred, ...fallbacks]) {\n const cleaned = typeof model === 'string' ? model.trim() : ''\n if (cleaned.length > 0 && !chain.includes(cleaned)) chain.push(cleaned)\n }\n return chain\n}\n"],"mappings":";AAgCO,IAAM,6BAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,gCAAmD,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG;AASxF,IAAM,yBAA4C,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG;AAM/E,IAAM,gCAAmD;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA;AAAA,EACA;AACF;AAyBA,IAAM,4BAA+C;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,SAAS,mBAAmB,MAAkC;AACnE,aAAW,WAAW,2BAA2B;AAC/C,UAAM,QAAQ,QAAQ,KAAK,IAAI;AAC/B,QAAI,QAAQ,CAAC,EAAG,QAAO,OAAO,MAAM,CAAC,CAAC;AAAA,EACxC;AACA,SAAO;AACT;AAEA,SAAS,WAAW,QAAiC,KAAiC;AACpF,QAAM,QAAQ,OAAO,GAAG;AACxB,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ;AACxE;AAWO,SAAS,sBAAsB,QAA0B;AAC9D,MAAI,WAAW,QAAQ,OAAO,WAAW,SAAU,QAAO;AAC1D,Q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cAAc,QAAQ,EAAE;AAAA,EACnE;AAEA,QAAM,IAAI,4BAA4B,QAAQ;AAChD;AAMO,SAAS,gBAAgB,WAAmB,WAAwC;AACzF,QAAM,QAAkB,CAAC;AACzB,aAAW,SAAS,CAAC,WAAW,GAAG,SAAS,GAAG;AAC7C,UAAM,UAAU,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;AAC3D,QAAI,QAAQ,SAAS,KAAK,CAAC,MAAM,SAAS,OAAO,EAAG,OAAM,KAAK,OAAO;AAAA,EACxE;AACA,SAAO;AACT;","names":[]}
|
package/dist/chunk-IVUN7FL7.js
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
// src/profile/fingerprint.ts
|
|
2
|
-
async function sha256Hex(text) {
|
|
3
|
-
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
4
|
-
return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
5
|
-
}
|
|
6
|
-
async function fingerprintAgentProfile(profile, context) {
|
|
7
|
-
const systemPrompt = profile.prompt?.systemPrompt ?? "";
|
|
8
|
-
const promptSha = await sha256Hex(systemPrompt);
|
|
9
|
-
const mcpKeys = Object.keys(profile.mcp ?? {}).sort();
|
|
10
|
-
const subagentNames = Object.keys(profile.subagents ?? {}).sort();
|
|
11
|
-
const fileMountPaths = (profile.resources?.files ?? []).map((mount) => mount.path).sort();
|
|
12
|
-
const connectionIds = (profile.connections ?? []).map((connection) => connection.alias ? `${connection.connectionId}:${connection.alias}` : connection.connectionId).sort();
|
|
13
|
-
const hash = await sha256Hex(
|
|
14
|
-
JSON.stringify([
|
|
15
|
-
promptSha,
|
|
16
|
-
mcpKeys,
|
|
17
|
-
subagentNames,
|
|
18
|
-
fileMountPaths,
|
|
19
|
-
connectionIds,
|
|
20
|
-
context?.model ?? null,
|
|
21
|
-
context?.harness ?? null
|
|
22
|
-
])
|
|
23
|
-
);
|
|
24
|
-
return {
|
|
25
|
-
hash,
|
|
26
|
-
promptSha,
|
|
27
|
-
promptBytes: new TextEncoder().encode(systemPrompt).length,
|
|
28
|
-
mcpKeys,
|
|
29
|
-
subagentNames,
|
|
30
|
-
fileMountPaths,
|
|
31
|
-
connectionIds,
|
|
32
|
-
model: context?.model,
|
|
33
|
-
harness: context?.harness
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
function channelValue(fingerprint, channel) {
|
|
37
|
-
const value = fingerprint[channel];
|
|
38
|
-
if (Array.isArray(value)) return value.length === 0 ? "(none)" : value.join(",");
|
|
39
|
-
return String(value ?? "(unset)");
|
|
40
|
-
}
|
|
41
|
-
var DRIFT_CHANNELS = [
|
|
42
|
-
"promptSha",
|
|
43
|
-
"promptBytes",
|
|
44
|
-
"mcpKeys",
|
|
45
|
-
"subagentNames",
|
|
46
|
-
"fileMountPaths",
|
|
47
|
-
"connectionIds",
|
|
48
|
-
"model",
|
|
49
|
-
"harness"
|
|
50
|
-
];
|
|
51
|
-
function diffProfileFingerprints(a, b) {
|
|
52
|
-
const drift = [];
|
|
53
|
-
for (const channel of DRIFT_CHANNELS) {
|
|
54
|
-
const left = channelValue(a, channel);
|
|
55
|
-
const right = channelValue(b, channel);
|
|
56
|
-
if (left !== right) drift.push({ channel, a: left, b: right });
|
|
57
|
-
}
|
|
58
|
-
return { equal: drift.length === 0, drift };
|
|
59
|
-
}
|
|
60
|
-
function formatProfileDrift(drift) {
|
|
61
|
-
if (drift.equal) return "profiles identical";
|
|
62
|
-
const lines = drift.drift.map((entry) => ` ${entry.channel}: ${entry.a} != ${entry.b}`);
|
|
63
|
-
return `profile drift on ${drift.drift.length} channel(s):
|
|
64
|
-
${lines.join("\n")}`;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export {
|
|
68
|
-
fingerprintAgentProfile,
|
|
69
|
-
diffProfileFingerprints,
|
|
70
|
-
formatProfileDrift
|
|
71
|
-
};
|
|
72
|
-
//# sourceMappingURL=chunk-IVUN7FL7.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/profile/fingerprint.ts"],"sourcesContent":["/**\n * Profile fingerprinting — prove WHICH profile a turn actually executed.\n *\n * The backtest invariant this exists to enforce: an eval's score is only worth\n * publishing if the benchmarked profile IS the shipped profile. The failure\n * mode is structural, not hypothetical — a product's eval composed the\n * production profile in one module, executed a hand-rolled stub in another,\n * and stamped the composed profile's identity onto the stub's scorecard.\n * Nothing compared the two, so nothing could notice.\n *\n * A `ProfileFingerprint` is a channelled identity of the profile handed to the\n * sandbox SDK: the system-prompt digest plus the names of every capability\n * surface (MCP servers, subagents, file mounts, hub connections) and the\n * model/harness the turn dispatched at. It is deliberately NOT a byte-exhaustive\n * serialization — channels are what drift in practice, and a channelled diff\n * names the surface that moved instead of reporting \"bytes differ\".\n *\n * The write half of the seam is `StreamSandboxPromptOptions.onProfileResolved`\n * (`/sandbox`): the one place the final profile exists is inside\n * `streamSandboxPrompt` after the system-prompt override, the MCP merge, and\n * reasoning-effort attachment, so that is where the fingerprint is taken. A\n * caller re-deriving a profile to fingerprint it would reintroduce the exact\n * gap this closes.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\n\n/** The dispatch context a profile cannot see but a turn's identity includes. */\nexport interface ProfileFingerprintContext {\n model?: string\n harness?: string\n}\n\n/** Channelled identity of one executed (or composed) profile. */\nexport interface ProfileFingerprint {\n /** sha256 over every channel below — one value to log/compare. */\n hash: string\n /** sha256 of `prompt.systemPrompt` ('' when absent). */\n promptSha: string\n /** UTF-8 byte length of `prompt.systemPrompt`. */\n promptBytes: number\n /** Sorted MCP server keys. */\n mcpKeys: string[]\n /** Sorted subagent names. */\n subagentNames: string[]\n /** Sorted `resources.files[].path` mounts. */\n fileMountPaths: string[]\n /** Sorted hub connection ids (alias-qualified when present). */\n connectionIds: string[]\n model?: string\n harness?: string\n}\n\nasync function sha256Hex(text: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/** Fingerprint a profile as the SDK would receive it. */\nexport async function fingerprintAgentProfile(\n profile: AgentProfile,\n context?: ProfileFingerprintContext,\n): Promise<ProfileFingerprint> {\n const systemPrompt = profile.prompt?.systemPrompt ?? ''\n const promptSha = await sha256Hex(systemPrompt)\n const mcpKeys = Object.keys(profile.mcp ?? {}).sort()\n const subagentNames = Object.keys(profile.subagents ?? {}).sort()\n const fileMountPaths = (profile.resources?.files ?? []).map((mount) => mount.path).sort()\n const connectionIds = (profile.connections ?? [])\n .map((connection) => (connection.alias ? `${connection.connectionId}:${connection.alias}` : connection.connectionId))\n .sort()\n const hash = await sha256Hex(\n JSON.stringify([\n promptSha,\n mcpKeys,\n subagentNames,\n fileMountPaths,\n connectionIds,\n context?.model ?? null,\n context?.harness ?? null,\n ]),\n )\n return {\n hash,\n promptSha,\n promptBytes: new TextEncoder().encode(systemPrompt).length,\n mcpKeys,\n subagentNames,\n fileMountPaths,\n connectionIds,\n model: context?.model,\n harness: context?.harness,\n }\n}\n\n/** One drifted channel between two fingerprints, rendered as comparable strings. */\nexport interface ProfileDriftEntry {\n channel: 'promptSha' | 'promptBytes' | 'mcpKeys' | 'subagentNames' | 'fileMountPaths' | 'connectionIds' | 'model' | 'harness'\n a: string\n b: string\n}\n\nexport interface ProfileDrift {\n equal: boolean\n drift: ProfileDriftEntry[]\n}\n\nfunction channelValue(fingerprint: ProfileFingerprint, channel: ProfileDriftEntry['channel']): string {\n const value = fingerprint[channel]\n if (Array.isArray(value)) return value.length === 0 ? '(none)' : value.join(',')\n return String(value ?? '(unset)')\n}\n\nconst DRIFT_CHANNELS: ProfileDriftEntry['channel'][] = [\n 'promptSha',\n 'promptBytes',\n 'mcpKeys',\n 'subagentNames',\n 'fileMountPaths',\n 'connectionIds',\n 'model',\n 'harness',\n]\n\n/** Channel-by-channel comparison of two fingerprints. */\nexport function diffProfileFingerprints(a: ProfileFingerprint, b: ProfileFingerprint): ProfileDrift {\n const drift: ProfileDriftEntry[] = []\n for (const channel of DRIFT_CHANNELS) {\n const left = channelValue(a, channel)\n const right = channelValue(b, channel)\n if (left !== right) drift.push({ channel, a: left, b: right })\n }\n return { equal: drift.length === 0, drift }\n}\n\n/** Human-readable drift report; exactly 'profiles identical' when equal. */\nexport function formatProfileDrift(drift: ProfileDrift): string {\n if (drift.equal) return 'profiles identical'\n const lines = drift.drift.map((entry) => ` ${entry.channel}: ${entry.a} != ${entry.b}`)\n return `profile drift on ${drift.drift.length} channel(s):\\n${lines.join('\\n')}`\n}\n"],"mappings":";AAqDA,eAAe,UAAU,MAA+B;AACtD,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,YAAY,EAAE,OAAO,IAAI,CAAC;AACnF,SAAO,MAAM,KAAK,IAAI,WAAW,MAAM,CAAC,EACrC,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAChD,KAAK,EAAE;AACZ;AAGA,eAAsB,wBACpB,SACA,SAC6B;AAC7B,QAAM,eAAe,QAAQ,QAAQ,gBAAgB;AACrD,QAAM,YAAY,MAAM,UAAU,YAAY;AAC9C,QAAM,UAAU,OAAO,KAAK,QAAQ,OAAO,CAAC,CAAC,EAAE,KAAK;AACpD,QAAM,gBAAgB,OAAO,KAAK,QAAQ,aAAa,CAAC,CAAC,EAAE,KAAK;AAChE,QAAM,kBAAkB,QAAQ,WAAW,SAAS,CAAC,GAAG,IAAI,CAAC,UAAU,MAAM,IAAI,EAAE,KAAK;AACxF,QAAM,iBAAiB,QAAQ,eAAe,CAAC,GAC5C,IAAI,CAAC,eAAgB,WAAW,QAAQ,GAAG,WAAW,YAAY,IAAI,WAAW,KAAK,KAAK,WAAW,YAAa,EACnH,KAAK;AACR,QAAM,OAAO,MAAM;AAAA,IACjB,KAAK,UAAU;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,S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