@tangle-network/agent-app 0.57.19 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VaultPane-UHLJSIND.js +7 -0
- package/dist/assistant/index.js +5 -4
- package/dist/assistant/index.js.map +1 -1
- package/dist/channels/index.js +1 -1
- package/dist/chunk-3NVVBQ2U.js +131 -0
- package/dist/chunk-3NVVBQ2U.js.map +1 -0
- package/dist/{chunk-EPZYYWCT.js → chunk-6ZIC6OG5.js} +8 -2
- package/dist/{chunk-EPZYYWCT.js.map → chunk-6ZIC6OG5.js.map} +1 -1
- package/dist/{chunk-OGFDE4IR.js → chunk-E2HFIKIZ.js} +2 -2
- package/dist/{chunk-Q3ZHNN5X.js → chunk-LSUELMHY.js} +2 -2
- package/dist/chunk-LSUELMHY.js.map +1 -0
- package/dist/chunk-M6WST7ZH.js +265 -0
- package/dist/chunk-M6WST7ZH.js.map +1 -0
- package/dist/{chunk-IOUPOUYB.js → chunk-XADC73A7.js} +2 -2
- package/dist/chunk-XADC73A7.js.map +1 -0
- package/dist/copy-quality/index.d.ts +88 -0
- package/dist/copy-quality/index.js +22 -0
- package/dist/copy-quality/index.js.map +1 -0
- package/dist/integrations-react/index.js +1 -1
- package/dist/legibility/cli.js +1 -1
- package/dist/legibility/index.js +1 -1
- package/dist/profile/agent-prompt.d.ts +91 -0
- package/dist/profile/index.d.ts +15 -49
- package/dist/profile/index.js +316 -10
- package/dist/profile/index.js.map +1 -1
- package/dist/profile/model-input.d.ts +94 -0
- package/dist/profile/operating-contract.d.ts +44 -0
- package/dist/profile/quality-skills.d.ts +33 -0
- package/dist/vault/index.js +1 -1
- package/dist/vault/lazy.js +1 -1
- package/dist/web-react/async/index.js +1 -1
- package/dist/web-react/async/state.d.ts +1 -1
- package/dist/web-react/index.js +2 -2
- package/dist/work-product/index.js +12 -118
- package/dist/work-product/index.js.map +1 -1
- package/package.json +6 -1
- package/dist/VaultPane-SDNMDGFC.js +0 -7
- package/dist/chunk-IOUPOUYB.js.map +0 -1
- package/dist/chunk-Q3ZHNN5X.js.map +0 -1
- /package/dist/{VaultPane-SDNMDGFC.js.map → VaultPane-UHLJSIND.js.map} +0 -0
- /package/dist/{chunk-OGFDE4IR.js.map → chunk-E2HFIKIZ.js.map} +0 -0
package/dist/profile/index.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CAP_WORDS,
|
|
3
|
+
bannedCopyVocabulary
|
|
4
|
+
} from "../chunk-M6WST7ZH.js";
|
|
5
|
+
import "../chunk-3NVVBQ2U.js";
|
|
1
6
|
import {
|
|
2
7
|
DEFAULT_HOME_LIMITS,
|
|
3
8
|
defaultHomeFiles,
|
|
@@ -32,6 +37,302 @@ import {
|
|
|
32
37
|
// src/profile/index.ts
|
|
33
38
|
import { mergeAgentProfiles } from "@tangle-network/agent-interface";
|
|
34
39
|
import { profile } from "@tangle-network/agent-eval";
|
|
40
|
+
|
|
41
|
+
// src/profile/operating-contract.ts
|
|
42
|
+
var OPERATING_CONTRACT_VERSION = 1;
|
|
43
|
+
var UNVERIFIED_LABEL_SLOT = "{unverified}";
|
|
44
|
+
var DEFAULT_UNVERIFIED_LABEL = "Unverified: <claim>";
|
|
45
|
+
var OPERATING_CONTRACT_CLAUSES = Object.freeze([
|
|
46
|
+
{
|
|
47
|
+
id: "deliver",
|
|
48
|
+
text: "Do the work instead of describing it. Produce the artifact the request needs, check it, and say what you checked. Done means produced and verified."
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
id: "evidence",
|
|
52
|
+
text: `Ground each material claim in a source you can name: a tool result, a file path, a document, or the user's own words. Keep what a source shows separate from what you infer. Mark a claim you cannot support with \`${UNVERIFIED_LABEL_SLOT}\` and name the lookup that would settle it. Never invent a source, quote, number, customer, or completed action.`
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
id: "inspect-results",
|
|
56
|
+
text: "Tools, integrations, and delegated tasks can fail. Read each result before you rely on it or report it as done, and state a failure plainly."
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
id: "authority",
|
|
60
|
+
text: "Research, drafts, and workspace edits inside the request are yours to do. Sending, publishing, spending, contacting someone, or changing an integration needs the user's explicit approval for that target and content. A plan is not approval, a pending approval is not execution, and you never approve your own request."
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
id: "this-turn",
|
|
64
|
+
text: "Promise only what this turn does. Do not offer to follow up, monitor, or remind later unless a tool confirmed it is scheduled; finish what you can now, then name what remains and what it needs."
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
id: "read-back",
|
|
68
|
+
text: "After you save a file or record, confirm it from the save result or by reading it back before you call it saved, and refer to it by its workspace path."
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
id: "vault-memory",
|
|
72
|
+
text: "Workspace files are your memory between turns. Read the relevant ones before you answer, and write decisions, evidence, and corrections back so the next turn starts from them."
|
|
73
|
+
}
|
|
74
|
+
]);
|
|
75
|
+
var CLAUSE_IDS = new Set(OPERATING_CONTRACT_CLAUSES.map((clause) => clause.id));
|
|
76
|
+
function renderOperatingContract(options = {}) {
|
|
77
|
+
const omit = new Set(options.omit ?? []);
|
|
78
|
+
const unknown = [...omit].filter((id) => !CLAUSE_IDS.has(id));
|
|
79
|
+
if (unknown.length > 0) {
|
|
80
|
+
throw new Error(`renderOperatingContract: unknown clause id(s) in omit: ${unknown.join(", ")}`);
|
|
81
|
+
}
|
|
82
|
+
const label = options.unverifiedLabel?.trim() || DEFAULT_UNVERIFIED_LABEL;
|
|
83
|
+
const kept = OPERATING_CONTRACT_CLAUSES.filter((clause) => !omit.has(clause.id));
|
|
84
|
+
const bullets = [
|
|
85
|
+
...kept.map((clause) => clause.text.replace(UNVERIFIED_LABEL_SLOT, label)),
|
|
86
|
+
...(options.additions ?? []).map((text) => text.trim()).filter((text) => text.length > 0)
|
|
87
|
+
];
|
|
88
|
+
return {
|
|
89
|
+
version: OPERATING_CONTRACT_VERSION,
|
|
90
|
+
text: `## Operating contract
|
|
91
|
+
|
|
92
|
+
${bullets.map((bullet) => `- ${bullet}`).join("\n")}`,
|
|
93
|
+
clauseIds: kept.map((clause) => clause.id)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/profile/agent-prompt.ts
|
|
98
|
+
var LEARNED_GUIDANCE_SECTION_ID = "learned-guidance";
|
|
99
|
+
var encoder = new TextEncoder();
|
|
100
|
+
function byteLength(text) {
|
|
101
|
+
return encoder.encode(text).byteLength;
|
|
102
|
+
}
|
|
103
|
+
function stripComments(raw) {
|
|
104
|
+
return raw.replace(/<!--[\s\S]*?-->/g, "").trim();
|
|
105
|
+
}
|
|
106
|
+
function renderAgentPrompt(input) {
|
|
107
|
+
const identity = input.identity.trim();
|
|
108
|
+
if (!identity) throw new Error("renderAgentPrompt: identity is empty");
|
|
109
|
+
const environment = input.environment.trim();
|
|
110
|
+
if (!environment) throw new Error("renderAgentPrompt: environment is empty");
|
|
111
|
+
const contract = renderOperatingContract(input.contract);
|
|
112
|
+
const sections = [
|
|
113
|
+
{ id: "identity", title: "Identity", text: identity },
|
|
114
|
+
{ id: "operating-contract", title: "Operating contract", text: contract.text },
|
|
115
|
+
{ id: "environment", title: "Environment", text: `## Environment
|
|
116
|
+
|
|
117
|
+
${environment}` }
|
|
118
|
+
];
|
|
119
|
+
const toolConventions = input.toolConventions?.trim();
|
|
120
|
+
if (toolConventions) {
|
|
121
|
+
sections.push({ id: "tool-conventions", title: "Tool conventions", text: `## Tool conventions
|
|
122
|
+
|
|
123
|
+
${toolConventions}` });
|
|
124
|
+
}
|
|
125
|
+
const skillIndex = input.skillIndex?.trim();
|
|
126
|
+
if (skillIndex) {
|
|
127
|
+
sections.push({ id: "skills", title: "Skills", text: skillIndex.startsWith("#") ? skillIndex : `## Skills
|
|
128
|
+
|
|
129
|
+
${skillIndex}` });
|
|
130
|
+
}
|
|
131
|
+
const learned = stripComments(input.learnedGuidance ?? "") || stripComments(input.learnedGuidanceBaseline ?? "");
|
|
132
|
+
const domain = [
|
|
133
|
+
...input.standards ?? [],
|
|
134
|
+
...learned ? [{ id: LEARNED_GUIDANCE_SECTION_ID, title: "Learned guidance", body: learned }] : []
|
|
135
|
+
];
|
|
136
|
+
sections.push(...headedGroup("Domain guidance", domain));
|
|
137
|
+
sections.push(...headedGroup("Workspace context", input.overlay ?? []));
|
|
138
|
+
const seen = /* @__PURE__ */ new Set();
|
|
139
|
+
for (const section of sections) {
|
|
140
|
+
if (seen.has(section.id)) throw new Error(`renderAgentPrompt: duplicate section id "${section.id}"`);
|
|
141
|
+
seen.add(section.id);
|
|
142
|
+
}
|
|
143
|
+
const prompt = sections.map((section) => section.text).join("\n\n");
|
|
144
|
+
if (input.budget) assertSystemPromptWithinBudget(prompt, input.budget, "rendered agent prompt");
|
|
145
|
+
return {
|
|
146
|
+
prompt,
|
|
147
|
+
bytes: byteLength(prompt),
|
|
148
|
+
contractVersion: contract.version,
|
|
149
|
+
contractClauseIds: contract.clauseIds,
|
|
150
|
+
sections: sections.map((section) => ({ ...section, bytes: byteLength(section.text) }))
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function headedGroup(heading, group) {
|
|
154
|
+
return group.map((section) => ({ ...section, body: section.body.trim() })).filter((section) => section.body.length > 0).map((section, index) => ({
|
|
155
|
+
id: section.id,
|
|
156
|
+
title: section.title,
|
|
157
|
+
text: `${index === 0 ? `## ${heading}
|
|
158
|
+
|
|
159
|
+
` : ""}### ${section.title}
|
|
160
|
+
|
|
161
|
+
${section.body}`
|
|
162
|
+
}));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// src/profile/quality-skills.ts
|
|
166
|
+
var HUMAN_PROSE_SKILL_ID = "human-prose";
|
|
167
|
+
var HUMAN_PROSE_DESCRIPTION = "Remove the structural tells that make prose read as machine-written. Load before writing anything for an audience: briefs, emails, posts, captions, ad copy, client replies.";
|
|
168
|
+
var HUMAN_PROSE_BODY = `# Write Like a Human
|
|
169
|
+
|
|
170
|
+
Load before writing anything for an audience: briefs, emails, posts, captions, ad copy, chat replies. This skill kills the *structural* tells, the sentence-level patterns that read as machine-written even when every word is allowed.
|
|
171
|
+
|
|
172
|
+
## The patterns to cut
|
|
173
|
+
|
|
174
|
+
**Throat-clearing openers.** Drop "Here's the thing", "The truth is", "It turns out", "Let me be clear", "The real X is", "I'll be honest". Open on the actual claim.
|
|
175
|
+
|
|
176
|
+
**Emphasis crutches.** No "Let that sink in", "Make no mistake", "This matters because", "Full stop". The point carries its own weight.
|
|
177
|
+
|
|
178
|
+
**Rhetorical setups and meta-commentary.** No "What if...?", "Think about it:", "Here's what I mean". No narrating your own writing: "Let me walk you through", "In this section", "As we'll see", "Plot twist:", "Spoiler:". Deliver the point; let the reader conclude.
|
|
179
|
+
|
|
180
|
+
**Telegraphed contrasts.** No "It's not X, it's Y" and no negative listings ("Not a tool. Not a framework. A..."). State what it is. The reader does not need the runway.
|
|
181
|
+
|
|
182
|
+
**Manufactured fragmentation.** No fragments for drama ("Revenue. That's it." / "Fast. Cheap. Done."). Use complete sentences and vary their length naturally instead of a staccato beat.
|
|
183
|
+
|
|
184
|
+
**Passive voice and false agency.** Every sentence has someone doing something. "A packet was sent" becomes "the SDR sent the packet". Do not anthropomorphize objects ("a complaint becomes a fix" becomes "the team fixed it that week"). Do not narrate from a distance; put the reader in the scene.
|
|
185
|
+
|
|
186
|
+
**Vague declaratives.** "The implications are significant", "the stakes are high", "the reasons are structural" say nothing. Name the specific implication, stake, or reason.
|
|
187
|
+
|
|
188
|
+
**Filler adverbs.** Delete "really, just, literally, actually, simply, honestly, genuinely, truly, fundamentally, importantly, crucially". The sentence is stronger without them.
|
|
189
|
+
|
|
190
|
+
**Punctuation.** Prefer commas and periods over em-dashes. Overusing the em-dash is itself a machine tell.
|
|
191
|
+
|
|
192
|
+
## Self-check before sending
|
|
193
|
+
|
|
194
|
+
Score the draft on five dimensions, 1-10 each:
|
|
195
|
+
- Directness: a statement, not an announcement?
|
|
196
|
+
- Rhythm: sentence length varied, not metronomic?
|
|
197
|
+
- Trust: respects the reader's intelligence, no over-explaining?
|
|
198
|
+
- Authenticity: sounds like a sharp person wrote it?
|
|
199
|
+
- Density: anything cuttable?
|
|
200
|
+
|
|
201
|
+
Below 35/50, cut and rewrite. Do not ship slop.`;
|
|
202
|
+
var HUMAN_PROSE_ATTRIBUTION = "Adapted from the stop-slop ruleset (github.com/hardikpandya/stop-slop).";
|
|
203
|
+
function vocabularySection(options) {
|
|
204
|
+
const banned = bannedCopyVocabulary((options.bannedWords ?? []).map((word) => word.trim()).filter(Boolean));
|
|
205
|
+
const capped = CAP_WORDS.filter((word) => !banned.includes(word));
|
|
206
|
+
const preferred = Object.entries(options.preferredTerms ?? {}).map(([avoid, use]) => [avoid.trim(), use.trim()]).filter(([avoid, use]) => avoid && use);
|
|
207
|
+
const parts = [
|
|
208
|
+
"## Vocabulary",
|
|
209
|
+
`Never use these in audience-facing prose: ${banned.join(", ")}.`,
|
|
210
|
+
`Use at most one of these per paragraph: ${capped.join(", ")}.`
|
|
211
|
+
];
|
|
212
|
+
if (preferred.length > 0) {
|
|
213
|
+
parts.push(["Use the product term:", ...preferred.map(([avoid, use]) => `- "${use}", not "${avoid}"`)].join("\n"));
|
|
214
|
+
}
|
|
215
|
+
return parts.join("\n\n");
|
|
216
|
+
}
|
|
217
|
+
function humanProseSkill(options = {}) {
|
|
218
|
+
const review = options.reviewSkillId?.trim();
|
|
219
|
+
const sections = [
|
|
220
|
+
HUMAN_PROSE_BODY,
|
|
221
|
+
vocabularySection(options),
|
|
222
|
+
review ? `For a long draft, finish with a full review pass using the \`${review}\` skill.` : "",
|
|
223
|
+
HUMAN_PROSE_ATTRIBUTION
|
|
224
|
+
].filter(Boolean);
|
|
225
|
+
const skillMd = [
|
|
226
|
+
"---",
|
|
227
|
+
`name: ${HUMAN_PROSE_SKILL_ID}`,
|
|
228
|
+
`description: ${JSON.stringify(HUMAN_PROSE_DESCRIPTION)}`,
|
|
229
|
+
"user-invocable: false",
|
|
230
|
+
"---",
|
|
231
|
+
"",
|
|
232
|
+
`${sections.join("\n\n")}
|
|
233
|
+
`
|
|
234
|
+
].join("\n");
|
|
235
|
+
return skillEntryFromMarkdown(skillMd, HUMAN_PROSE_SKILL_ID);
|
|
236
|
+
}
|
|
237
|
+
function defaultQualitySkills(options = {}) {
|
|
238
|
+
return [humanProseSkill(options.writing)];
|
|
239
|
+
}
|
|
240
|
+
function withDefaultQualitySkills(productSkills, options = {}) {
|
|
241
|
+
const defaults = defaultQualitySkills(options);
|
|
242
|
+
const defaultIds = new Set(defaults.map((skill) => skill.id));
|
|
243
|
+
const copies = productSkills.filter((skill) => defaultIds.has(skill.id)).map((skill) => skill.id);
|
|
244
|
+
if (copies.length > 0) {
|
|
245
|
+
throw new Error(
|
|
246
|
+
`withDefaultQualitySkills: product skill(s) ${copies.join(", ")} duplicate a default quality skill; delete the product copy and pass its additions as options`
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
return [...productSkills, ...defaults];
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// src/profile/model-input.ts
|
|
253
|
+
var MODEL_INPUT_RECORD_SCHEMA = "agent-app.model-input.v1";
|
|
254
|
+
var encoder2 = new TextEncoder();
|
|
255
|
+
async function sha256Hex(text) {
|
|
256
|
+
const digest = await crypto.subtle.digest("SHA-256", encoder2.encode(text));
|
|
257
|
+
return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
258
|
+
}
|
|
259
|
+
var DEFAULT_MEDIA_TYPE = {
|
|
260
|
+
"system-prompt": "text/markdown",
|
|
261
|
+
"workspace-plan": "application/json",
|
|
262
|
+
"turn-context": "text/markdown"
|
|
263
|
+
};
|
|
264
|
+
async function modelInputBlob(kind, content, mediaType = DEFAULT_MEDIA_TYPE[kind]) {
|
|
265
|
+
return { digest: await sha256Hex(content), kind, mediaType, bytes: encoder2.encode(content).byteLength, content };
|
|
266
|
+
}
|
|
267
|
+
function failed(error) {
|
|
268
|
+
return { succeeded: false, error };
|
|
269
|
+
}
|
|
270
|
+
async function captureModelInput(input) {
|
|
271
|
+
const rendered = typeof input.systemPrompt === "string" ? null : input.systemPrompt;
|
|
272
|
+
const prompt = rendered ? rendered.prompt : input.systemPrompt;
|
|
273
|
+
const blobs = await Promise.all([
|
|
274
|
+
modelInputBlob("system-prompt", prompt),
|
|
275
|
+
...(input.inputs ?? []).map((extra) => modelInputBlob(extra.kind, extra.content, extra.mediaType))
|
|
276
|
+
]);
|
|
277
|
+
for (const blob of blobs) {
|
|
278
|
+
let stored;
|
|
279
|
+
try {
|
|
280
|
+
stored = await input.store.put(blob);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
return failed(`model-input store threw storing ${blob.kind} ${blob.digest}: ${error instanceof Error ? error.message : String(error)}`);
|
|
283
|
+
}
|
|
284
|
+
if (!stored.succeeded) return failed(`model-input store refused ${blob.kind} ${blob.digest}: ${stored.error}`);
|
|
285
|
+
}
|
|
286
|
+
const sections = rendered ? await Promise.all(rendered.sections.map(async (section) => ({
|
|
287
|
+
id: section.id,
|
|
288
|
+
title: section.title,
|
|
289
|
+
bytes: section.bytes,
|
|
290
|
+
digest: await sha256Hex(section.text)
|
|
291
|
+
}))) : [];
|
|
292
|
+
const body = {
|
|
293
|
+
schema: MODEL_INPUT_RECORD_SCHEMA,
|
|
294
|
+
inputs: blobs.map((blob) => ({ digest: blob.digest, kind: blob.kind, mediaType: blob.mediaType, bytes: blob.bytes })),
|
|
295
|
+
sections,
|
|
296
|
+
contractVersion: rendered?.contractVersion ?? null,
|
|
297
|
+
planDigest: input.planDigest ?? null,
|
|
298
|
+
model: input.model ?? null,
|
|
299
|
+
harness: input.harness ?? null
|
|
300
|
+
};
|
|
301
|
+
return { succeeded: true, value: { ...body, digest: await sha256Hex(JSON.stringify(body)) } };
|
|
302
|
+
}
|
|
303
|
+
async function readModelInput(store, ref) {
|
|
304
|
+
let loaded;
|
|
305
|
+
try {
|
|
306
|
+
loaded = await store.get(ref.digest);
|
|
307
|
+
} catch (error) {
|
|
308
|
+
return failed(`model-input store threw reading ${ref.digest}: ${error instanceof Error ? error.message : String(error)}`);
|
|
309
|
+
}
|
|
310
|
+
if (!loaded.succeeded) return loaded;
|
|
311
|
+
if (!loaded.value) return failed(`model input ${ref.digest} is not in the store`);
|
|
312
|
+
const actual = await sha256Hex(loaded.value.content);
|
|
313
|
+
if (actual !== ref.digest) return failed(`model input ${ref.digest} content hashes to ${actual}`);
|
|
314
|
+
return { succeeded: true, value: loaded.value };
|
|
315
|
+
}
|
|
316
|
+
function createMemoryModelInputStore() {
|
|
317
|
+
const blobs = /* @__PURE__ */ new Map();
|
|
318
|
+
return {
|
|
319
|
+
get size() {
|
|
320
|
+
return blobs.size;
|
|
321
|
+
},
|
|
322
|
+
async put(blob) {
|
|
323
|
+
const actual = await sha256Hex(blob.content);
|
|
324
|
+
if (actual !== blob.digest) return failed(`digest ${blob.digest} does not match content (${actual})`);
|
|
325
|
+
if (!blobs.has(blob.digest)) blobs.set(blob.digest, { ...blob });
|
|
326
|
+
return { succeeded: true, value: void 0 };
|
|
327
|
+
},
|
|
328
|
+
async get(digest) {
|
|
329
|
+
const blob = blobs.get(digest);
|
|
330
|
+
return { succeeded: true, value: blob ? { ...blob } : null };
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// src/profile/index.ts
|
|
35
336
|
function userSkillMounts(userSkills) {
|
|
36
337
|
return userSkills.map(
|
|
37
338
|
(s) => ({
|
|
@@ -82,43 +383,48 @@ function pruneEmptyResourceChannels(profile2) {
|
|
|
82
383
|
if (kept && Object.keys(kept).length === 0) delete out.resources;
|
|
83
384
|
return out;
|
|
84
385
|
}
|
|
85
|
-
function stripComments(raw) {
|
|
86
|
-
return raw.replace(/<!--[\s\S]*?-->/g, "").trim();
|
|
87
|
-
}
|
|
88
|
-
function makeEvolvableSection(input) {
|
|
89
|
-
const loaded = input.load();
|
|
90
|
-
const body = stripComments(loaded) ? loaded.trim() : input.baseline;
|
|
91
|
-
return { id: input.id, title: input.title, body, evolvable: true };
|
|
92
|
-
}
|
|
93
386
|
export {
|
|
94
387
|
DEFAULT_HOME_LIMITS,
|
|
95
388
|
DEFAULT_MAX_SYSTEM_PROMPT_BYTES,
|
|
389
|
+
HUMAN_PROSE_SKILL_ID,
|
|
390
|
+
LEARNED_GUIDANCE_SECTION_ID,
|
|
391
|
+
MODEL_INPUT_RECORD_SCHEMA,
|
|
392
|
+
OPERATING_CONTRACT_CLAUSES,
|
|
393
|
+
OPERATING_CONTRACT_VERSION,
|
|
96
394
|
assertProfilePromptWithinBudget,
|
|
97
395
|
assertSkillDeliveryDisjoint,
|
|
98
396
|
assertSystemPromptWithinBudget,
|
|
397
|
+
captureModelInput,
|
|
99
398
|
composeAgentProfile,
|
|
100
399
|
composeShellResources,
|
|
101
400
|
composeSkills,
|
|
102
401
|
corpusSkills,
|
|
402
|
+
createMemoryModelInputStore,
|
|
103
403
|
defaultHomeFiles,
|
|
404
|
+
defaultQualitySkills,
|
|
104
405
|
diffProfileFingerprints,
|
|
105
406
|
fingerprintAgentProfile,
|
|
106
407
|
formatProfileDrift,
|
|
408
|
+
humanProseSkill,
|
|
107
409
|
largestPromptSections,
|
|
108
410
|
loadMarkdownCorpus,
|
|
109
|
-
makeEvolvableSection,
|
|
110
411
|
mergeComposedSkills,
|
|
412
|
+
modelInputBlob,
|
|
111
413
|
parseCorpusSkills,
|
|
112
414
|
parseSkillFrontmatter,
|
|
113
415
|
profile,
|
|
416
|
+
readModelInput,
|
|
114
417
|
registrySkills,
|
|
418
|
+
renderAgentPrompt,
|
|
115
419
|
renderInlineSkills,
|
|
420
|
+
renderOperatingContract,
|
|
116
421
|
renderSkillIndex,
|
|
117
422
|
skillEntryFromMarkdown,
|
|
118
423
|
skillMountPath,
|
|
119
424
|
skillRefs,
|
|
120
425
|
stripComments,
|
|
121
426
|
userSkillMounts,
|
|
122
|
-
withDefaultAgentHome
|
|
427
|
+
withDefaultAgentHome,
|
|
428
|
+
withDefaultQualitySkills
|
|
123
429
|
};
|
|
124
430
|
//# sourceMappingURL=index.js.map
|
|
@@ -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 canonical\n * `mergeAgentProfiles` contract makes `mcp` last-wins per key (base -> overlay),\n * concatenates `resources` arrays (base ++ overlay), and shallow-merges `prompt`\n * so an 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/agent-interface'\nimport { mergeAgentProfiles } from '@tangle-network/agent-interface'\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 absent and empty resource channels the canonical merge normalizes in,\n * 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]) =>\n value !== undefined && !(Array.isArray(value) && value.length === 0),\n ),\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\nexport { DEFAULT_HOME_LIMITS, defaultHomeFiles, withDefaultAgentHome } from './home'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAS,0BAA0B;AACnC,SAAS,eAAe;AA+FjB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,EAAE,QAAQ,SAAS,UAAU,IAAI,CAAC;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;AAAA,MAAO,CAAC,CAAC,EAAE,KAAK,MAChD,UAAU,UAAa,EAAE,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW;AAAA,IACpE;AAAA,EACF;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","../../src/profile/operating-contract.ts","../../src/profile/agent-prompt.ts","../../src/profile/quality-skills.ts","../../src/profile/model-input.ts"],"sourcesContent":["/**\n * Profile composer and system-prompt renderer 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 canonical\n * `mergeAgentProfiles` contract makes `mcp` last-wins per key (base -> overlay),\n * concatenates `resources` arrays (base ++ overlay), and shallow-merges `prompt`\n * so an 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 system prompt itself comes from `renderAgentPrompt` (./agent-prompt):\n * identity, the shared operating contract (./operating-contract), environment,\n * tool conventions, the skill index, domain guidance ending in the evolvable\n * learned guidance, and the workspace overlay. The default quality skills\n * (./quality-skills) join the product's skills, and `captureModelInput`\n * (./model-input) stores what the model saw for the turn's receipt.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n AgentProfileResourceRef,\n} from '@tangle-network/agent-interface'\nimport { mergeAgentProfiles } from '@tangle-network/agent-interface'\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 agent-eval's `profile` namespace for products that still render\n * through `profile.renderProfile`; new prompts use {@link renderAgentPrompt}.\n * Re-exporting the bare functions would leak agent-eval's un-nameable\n * AgentProfile type into our generated d.ts. */\nexport { profile }\n\nexport {\n LEARNED_GUIDANCE_SECTION_ID,\n renderAgentPrompt,\n stripComments,\n type AgentPromptInput,\n type AgentPromptSection,\n type RenderedAgentPrompt,\n type RenderedAgentPromptSection,\n} from './agent-prompt'\nexport {\n OPERATING_CONTRACT_CLAUSES,\n OPERATING_CONTRACT_VERSION,\n renderOperatingContract,\n type OperatingContractClause,\n type OperatingContractClauseId,\n type OperatingContractOptions,\n type RenderedOperatingContract,\n} from './operating-contract'\nexport {\n defaultQualitySkills,\n HUMAN_PROSE_SKILL_ID,\n humanProseSkill,\n withDefaultQualitySkills,\n type HumanProseSkillOptions,\n type QualitySkillOptions,\n} from './quality-skills'\nexport {\n captureModelInput,\n createMemoryModelInputStore,\n MODEL_INPUT_RECORD_SCHEMA,\n modelInputBlob,\n readModelInput,\n type CaptureModelInputInput,\n type ModelInputBlob,\n type ModelInputKind,\n type ModelInputMediaType,\n type ModelInputOutcome,\n type ModelInputRecord,\n type ModelInputRef,\n type ModelInputSectionRef,\n type ModelInputStore,\n} from './model-input'\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 absent and empty resource channels the canonical merge normalizes in,\n * 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]) =>\n value !== undefined && !(Array.isArray(value) && value.length === 0),\n ),\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\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\nexport { DEFAULT_HOME_LIMITS, defaultHomeFiles, withDefaultAgentHome } from './home'\n","/**\n * The shared operating contract: the rules every product agent follows whatever\n * its domain. Products used to hand-write these as \"How you operate\" bullets,\n * and the copies drifted apart (different labels for unsupported claims, a\n * read-back rule in one product and not the others). Rendering one contract\n * keeps them identical, and its version lets a receipt name the exact wording a\n * turn saw.\n *\n * Changing any clause text requires bumping {@link OPERATING_CONTRACT_VERSION};\n * the test suite pins the digest of each version's default rendering, so an\n * unversioned wording change fails there.\n */\n\n/** Version of the clause wording below. Bump it whenever any clause text changes. */\nexport const OPERATING_CONTRACT_VERSION = 1\n\nexport type OperatingContractClauseId =\n | 'deliver'\n | 'evidence'\n | 'inspect-results'\n | 'authority'\n | 'this-turn'\n | 'read-back'\n | 'vault-memory'\n\nexport interface OperatingContractClause {\n id: OperatingContractClauseId\n text: string\n}\n\n/** Stands in for the product's unsupported-claim label inside the evidence clause. */\nconst UNVERIFIED_LABEL_SLOT = '{unverified}'\n\nconst DEFAULT_UNVERIFIED_LABEL = 'Unverified: <claim>'\n\n/** The clauses in render order. */\nexport const OPERATING_CONTRACT_CLAUSES: readonly OperatingContractClause[] = Object.freeze([\n {\n id: 'deliver',\n text: 'Do the work instead of describing it. Produce the artifact the request needs, check it, and say what you checked. Done means produced and verified.',\n },\n {\n id: 'evidence',\n text: `Ground each material claim in a source you can name: a tool result, a file path, a document, or the user's own words. Keep what a source shows separate from what you infer. Mark a claim you cannot support with \\`${UNVERIFIED_LABEL_SLOT}\\` and name the lookup that would settle it. Never invent a source, quote, number, customer, or completed action.`,\n },\n {\n id: 'inspect-results',\n text: 'Tools, integrations, and delegated tasks can fail. Read each result before you rely on it or report it as done, and state a failure plainly.',\n },\n {\n id: 'authority',\n text: \"Research, drafts, and workspace edits inside the request are yours to do. Sending, publishing, spending, contacting someone, or changing an integration needs the user's explicit approval for that target and content. A plan is not approval, a pending approval is not execution, and you never approve your own request.\",\n },\n {\n id: 'this-turn',\n text: 'Promise only what this turn does. Do not offer to follow up, monitor, or remind later unless a tool confirmed it is scheduled; finish what you can now, then name what remains and what it needs.',\n },\n {\n id: 'read-back',\n text: 'After you save a file or record, confirm it from the save result or by reading it back before you call it saved, and refer to it by its workspace path.',\n },\n {\n id: 'vault-memory',\n text: 'Workspace files are your memory between turns. Read the relevant ones before you answer, and write decisions, evidence, and corrections back so the next turn starts from them.',\n },\n])\n\n/** Product adjustments to the shared contract. */\nexport interface OperatingContractOptions {\n /** Clauses that cannot apply on this lane, such as `vault-memory` and\n * `read-back` on a lane with no workspace files. The rendered result lists\n * the clauses kept, so a receipt shows what was left out. */\n omit?: readonly OperatingContractClauseId[]\n /** How the agent marks a claim it cannot support. Default\n * `Unverified: <claim>`; a product with a mandated format passes it here\n * instead of restating the evidence rule in its own words. */\n unverifiedLabel?: string\n /** Product clauses appended after the shared ones, one bullet each. */\n additions?: readonly string[]\n}\n\nexport interface RenderedOperatingContract {\n version: number\n /** `## Operating contract` followed by one bullet per clause. */\n text: string\n /** Shared clauses kept, in render order. */\n clauseIds: OperatingContractClauseId[]\n}\n\nconst CLAUSE_IDS = new Set<string>(OPERATING_CONTRACT_CLAUSES.map((clause) => clause.id))\n\n/** Render the contract as a prompt section. Throws on an unknown `omit` id so a\n * typo cannot silently keep a clause the product meant to drop. */\nexport function renderOperatingContract(options: OperatingContractOptions = {}): RenderedOperatingContract {\n const omit = new Set<string>(options.omit ?? [])\n const unknown = [...omit].filter((id) => !CLAUSE_IDS.has(id))\n if (unknown.length > 0) {\n throw new Error(`renderOperatingContract: unknown clause id(s) in omit: ${unknown.join(', ')}`)\n }\n const label = options.unverifiedLabel?.trim() || DEFAULT_UNVERIFIED_LABEL\n const kept = OPERATING_CONTRACT_CLAUSES.filter((clause) => !omit.has(clause.id))\n const bullets = [\n ...kept.map((clause) => clause.text.replace(UNVERIFIED_LABEL_SLOT, label)),\n ...(options.additions ?? []).map((text) => text.trim()).filter((text) => text.length > 0),\n ]\n return {\n version: OPERATING_CONTRACT_VERSION,\n text: `## Operating contract\\n\\n${bullets.map((bullet) => `- ${bullet}`).join('\\n')}`,\n clauseIds: kept.map((clause) => clause.id),\n }\n}\n","/**\n * The product system-prompt renderer: one layout for every product agent.\n *\n * identity who the agent is (product-owned, no heading)\n * ## Operating contract the shared, versioned rules (./operating-contract)\n * ## Environment facts about the machine and tools this turn has\n * ## Tool conventions product tool rules beyond the contract\n * ## Skills the task skill index (bodies stay mounted)\n * ## Domain guidance fixed product standards, then learned guidance\n * ## Workspace context the per-workspace overlay\n *\n * Products previously rendered this through agent-eval's `renderProfile` with a\n * hand-copied operating discipline, learned-guidance loader, and overlay. Two\n * defects came with the copies: an empty skill roster still rendered\n * `_No skills configured._` ahead of the product's real skill index, and an\n * empty learned-guidance section rendered a placeholder sentence. Empty\n * sections are omitted here instead.\n *\n * Learned guidance is the one section the self-improvement loop changes. The\n * loop renders a candidate by passing its body as `learnedGuidance`, so the\n * prompt it scores is byte-identical to the prompt production would render if\n * that candidate were promoted.\n */\n\nimport { assertSystemPromptWithinBudget, type ComposeProfileBudget } from './budget'\nimport {\n renderOperatingContract,\n type OperatingContractClauseId,\n type OperatingContractOptions,\n} from './operating-contract'\n\n/** Section id of the evolvable learned guidance, shared by every product and its loop. */\nexport const LEARNED_GUIDANCE_SECTION_ID = 'learned-guidance'\n\n/** A titled prompt section a product supplies. */\nexport interface AgentPromptSection {\n id: string\n title: string\n body: string\n}\n\n/** Inputs to {@link renderAgentPrompt}. */\nexport interface AgentPromptInput {\n /** Who the agent is and what it is for. Rendered first, without a heading. */\n identity: string\n /** Product adjustments to the shared operating contract, which always renders. */\n contract?: OperatingContractOptions\n /** Facts about the machine and tools this turn runs with. Pass the lane the\n * turn actually executes on; a sandbox description on a lane without one\n * sends the model after tools it does not have. */\n environment: string\n /** Product tool rules beyond the shared contract. Omitted when empty. */\n toolConventions?: string\n /** The task skill index, normally `composeSkillsForHarness(...).promptSection`.\n * A `## Skills` heading is added when the index has none. Omitted when empty. */\n skillIndex?: string\n /** Fixed product standards, rendered in order under `## Domain guidance`. */\n standards?: readonly AgentPromptSection[]\n /** Deployed or candidate learned guidance. Raw file content is fine: HTML\n * comments are stripped, and a body that is empty after stripping falls back\n * to {@link learnedGuidanceBaseline}. */\n learnedGuidance?: string\n /** In-tree guidance used until the loop promotes a body. */\n learnedGuidanceBaseline?: string\n /** Per-workspace overlay: workspace configuration, custom instructions, and\n * profile knowledge. Rendered last under `## Workspace context`; sections\n * with empty bodies are dropped. */\n overlay?: readonly AgentPromptSection[]\n /** Byte budget, enforced only when supplied. Pass the product's ceiling when\n * this render is the final system prompt; when later turn sections are\n * appended, gate the final string with `assertSystemPromptWithinBudget`. */\n budget?: ComposeProfileBudget\n}\n\n/** One rendered section, in prompt order. */\nexport interface RenderedAgentPromptSection {\n /** `identity`, `operating-contract`, `environment`, `tool-conventions`,\n * `skills`, a standard's id, {@link LEARNED_GUIDANCE_SECTION_ID}, or an\n * overlay section's id. */\n id: string\n title: string\n /** Exact text this section contributes, including its heading. */\n text: string\n bytes: number\n}\n\nexport interface RenderedAgentPrompt {\n /** Sections joined with a blank line. */\n prompt: string\n bytes: number\n contractVersion: number\n /** Shared contract clauses this prompt carries. */\n contractClauseIds: OperatingContractClauseId[]\n sections: RenderedAgentPromptSection[]\n}\n\nconst encoder = new TextEncoder()\n\nfunction byteLength(text: string): number {\n return encoder.encode(text).byteLength\n}\n\n/** Body of a loaded markdown file with HTML comments removed and whitespace\n * trimmed, so an all-comment placeholder counts as empty. */\nexport function stripComments(raw: string): string {\n return raw.replace(/<!--[\\s\\S]*?-->/g, '').trim()\n}\n\n/** Render the product system prompt. Throws on duplicate section ids, an empty\n * identity or environment, or a prompt over a supplied budget. */\nexport function renderAgentPrompt(input: AgentPromptInput): RenderedAgentPrompt {\n const identity = input.identity.trim()\n if (!identity) throw new Error('renderAgentPrompt: identity is empty')\n const environment = input.environment.trim()\n if (!environment) throw new Error('renderAgentPrompt: environment is empty')\n\n const contract = renderOperatingContract(input.contract)\n const sections: Array<Omit<RenderedAgentPromptSection, 'bytes'>> = [\n { id: 'identity', title: 'Identity', text: identity },\n { id: 'operating-contract', title: 'Operating contract', text: contract.text },\n { id: 'environment', title: 'Environment', text: `## Environment\\n\\n${environment}` },\n ]\n\n const toolConventions = input.toolConventions?.trim()\n if (toolConventions) {\n sections.push({ id: 'tool-conventions', title: 'Tool conventions', text: `## Tool conventions\\n\\n${toolConventions}` })\n }\n\n const skillIndex = input.skillIndex?.trim()\n if (skillIndex) {\n sections.push({ id: 'skills', title: 'Skills', text: skillIndex.startsWith('#') ? skillIndex : `## Skills\\n\\n${skillIndex}` })\n }\n\n const learned = stripComments(input.learnedGuidance ?? '') || stripComments(input.learnedGuidanceBaseline ?? '')\n const domain = [\n ...(input.standards ?? []),\n ...(learned ? [{ id: LEARNED_GUIDANCE_SECTION_ID, title: 'Learned guidance', body: learned }] : []),\n ]\n sections.push(...headedGroup('Domain guidance', domain))\n sections.push(...headedGroup('Workspace context', input.overlay ?? []))\n\n const seen = new Set<string>()\n for (const section of sections) {\n if (seen.has(section.id)) throw new Error(`renderAgentPrompt: duplicate section id \"${section.id}\"`)\n seen.add(section.id)\n }\n\n const prompt = sections.map((section) => section.text).join('\\n\\n')\n if (input.budget) assertSystemPromptWithinBudget(prompt, input.budget, 'rendered agent prompt')\n return {\n prompt,\n bytes: byteLength(prompt),\n contractVersion: contract.version,\n contractClauseIds: contract.clauseIds,\n sections: sections.map((section) => ({ ...section, bytes: byteLength(section.text) })),\n }\n}\n\n/** Render titled sections as `### title` blocks under one `## heading`, which\n * is attributed to the first section. Empty bodies are dropped; an empty group\n * renders nothing. */\nfunction headedGroup(\n heading: string,\n group: readonly AgentPromptSection[],\n): Array<Omit<RenderedAgentPromptSection, 'bytes'>> {\n return group\n .map((section) => ({ ...section, body: section.body.trim() }))\n .filter((section) => section.body.length > 0)\n .map((section, index) => ({\n id: section.id,\n title: section.title,\n text: `${index === 0 ? `## ${heading}\\n\\n` : ''}### ${section.title}\\n\\n${section.body}`,\n }))\n}\n","/**\n * Default quality skills every product agent mounts.\n *\n * `human-prose` was copied into three products byte-for-byte (GTM's catalog,\n * tax, creative), each with its own frontmatter. This module is now its one\n * source; a product adds its own vocabulary through options instead of editing\n * a copy. The vocabulary comes from the copy-quality scanner's ban and cap\n * tiers, so the words the skill tells the agent to avoid are the words the\n * scanner flags.\n */\n\nimport { bannedCopyVocabulary, CAP_WORDS } from '../copy-quality/index'\nimport { skillEntryFromMarkdown, type SkillEntry } from '../skills/index'\n\nexport const HUMAN_PROSE_SKILL_ID = 'human-prose'\n\n/** Product additions to the shared writing skill. */\nexport interface HumanProseSkillOptions {\n /** Product words to ban in addition to the copy-quality ban tier. */\n bannedWords?: readonly string[]\n /** Product terms, keyed by the wording to avoid. */\n preferredTerms?: Readonly<Record<string, string>>\n /** Id of a mounted skill for a full review-and-rewrite pass, named as the\n * next step for long drafts. Leave unset unless that skill is mounted. */\n reviewSkillId?: string\n}\n\nexport interface QualitySkillOptions {\n writing?: HumanProseSkillOptions\n}\n\nconst HUMAN_PROSE_DESCRIPTION =\n 'Remove the structural tells that make prose read as machine-written. Load before writing anything for an audience: briefs, emails, posts, captions, ad copy, client replies.'\n\nconst HUMAN_PROSE_BODY = `# Write Like a Human\n\nLoad before writing anything for an audience: briefs, emails, posts, captions, ad copy, chat replies. This skill kills the *structural* tells, the sentence-level patterns that read as machine-written even when every word is allowed.\n\n## The patterns to cut\n\n**Throat-clearing openers.** Drop \"Here's the thing\", \"The truth is\", \"It turns out\", \"Let me be clear\", \"The real X is\", \"I'll be honest\". Open on the actual claim.\n\n**Emphasis crutches.** No \"Let that sink in\", \"Make no mistake\", \"This matters because\", \"Full stop\". The point carries its own weight.\n\n**Rhetorical setups and meta-commentary.** No \"What if...?\", \"Think about it:\", \"Here's what I mean\". No narrating your own writing: \"Let me walk you through\", \"In this section\", \"As we'll see\", \"Plot twist:\", \"Spoiler:\". Deliver the point; let the reader conclude.\n\n**Telegraphed contrasts.** No \"It's not X, it's Y\" and no negative listings (\"Not a tool. Not a framework. A...\"). State what it is. The reader does not need the runway.\n\n**Manufactured fragmentation.** No fragments for drama (\"Revenue. That's it.\" / \"Fast. Cheap. Done.\"). Use complete sentences and vary their length naturally instead of a staccato beat.\n\n**Passive voice and false agency.** Every sentence has someone doing something. \"A packet was sent\" becomes \"the SDR sent the packet\". Do not anthropomorphize objects (\"a complaint becomes a fix\" becomes \"the team fixed it that week\"). Do not narrate from a distance; put the reader in the scene.\n\n**Vague declaratives.** \"The implications are significant\", \"the stakes are high\", \"the reasons are structural\" say nothing. Name the specific implication, stake, or reason.\n\n**Filler adverbs.** Delete \"really, just, literally, actually, simply, honestly, genuinely, truly, fundamentally, importantly, crucially\". The sentence is stronger without them.\n\n**Punctuation.** Prefer commas and periods over em-dashes. Overusing the em-dash is itself a machine tell.\n\n## Self-check before sending\n\nScore the draft on five dimensions, 1-10 each:\n- Directness: a statement, not an announcement?\n- Rhythm: sentence length varied, not metronomic?\n- Trust: respects the reader's intelligence, no over-explaining?\n- Authenticity: sounds like a sharp person wrote it?\n- Density: anything cuttable?\n\nBelow 35/50, cut and rewrite. Do not ship slop.`\n\nconst HUMAN_PROSE_ATTRIBUTION = 'Adapted from the stop-slop ruleset (github.com/hardikpandya/stop-slop).'\n\nfunction vocabularySection(options: HumanProseSkillOptions): string {\n const banned = bannedCopyVocabulary((options.bannedWords ?? []).map((word) => word.trim()).filter(Boolean))\n const capped = CAP_WORDS.filter((word) => !banned.includes(word))\n const preferred = Object.entries(options.preferredTerms ?? {})\n .map(([avoid, use]) => [avoid.trim(), use.trim()] as const)\n .filter(([avoid, use]) => avoid && use)\n const parts = [\n '## Vocabulary',\n `Never use these in audience-facing prose: ${banned.join(', ')}.`,\n `Use at most one of these per paragraph: ${capped.join(', ')}.`,\n ]\n if (preferred.length > 0) {\n parts.push(['Use the product term:', ...preferred.map(([avoid, use]) => `- \"${use}\", not \"${avoid}\"`)].join('\\n'))\n }\n return parts.join('\\n\\n')\n}\n\n/** The shared writing skill as a mountable {@link SkillEntry}. */\nexport function humanProseSkill(options: HumanProseSkillOptions = {}): SkillEntry {\n const review = options.reviewSkillId?.trim()\n const sections = [\n HUMAN_PROSE_BODY,\n vocabularySection(options),\n review ? `For a long draft, finish with a full review pass using the \\`${review}\\` skill.` : '',\n HUMAN_PROSE_ATTRIBUTION,\n ].filter(Boolean)\n const skillMd = [\n '---',\n `name: ${HUMAN_PROSE_SKILL_ID}`,\n `description: ${JSON.stringify(HUMAN_PROSE_DESCRIPTION)}`,\n 'user-invocable: false',\n '---',\n '',\n `${sections.join('\\n\\n')}\\n`,\n ].join('\\n')\n return skillEntryFromMarkdown(skillMd, HUMAN_PROSE_SKILL_ID)\n}\n\n/** The quality skills mounted by default. */\nexport function defaultQualitySkills(options: QualitySkillOptions = {}): SkillEntry[] {\n return [humanProseSkill(options.writing)]\n}\n\n/** Append the default quality skills to a product's skills. Throws when the\n * product still carries its own copy of a default skill: delete the copy and\n * move its additions into the options. */\nexport function withDefaultQualitySkills(\n productSkills: readonly SkillEntry[],\n options: QualitySkillOptions = {},\n): SkillEntry[] {\n const defaults = defaultQualitySkills(options)\n const defaultIds = new Set(defaults.map((skill) => skill.id))\n const copies = productSkills.filter((skill) => defaultIds.has(skill.id)).map((skill) => skill.id)\n if (copies.length > 0) {\n throw new Error(\n `withDefaultQualitySkills: product skill(s) ${copies.join(', ')} duplicate a default quality skill; delete the product copy and pass its additions as options`,\n )\n }\n return [...productSkills, ...defaults]\n}\n","/**\n * \"What the model saw\": content-addressed copies of the exact inputs a turn\n * sent to the model, linked from the turn's execution receipt.\n *\n * A receipt that names a profile revision cannot say what the prompt read once\n * the rendering code has changed. Storing each input by digest answers that\n * permanently: identical prompts across turns share one blob, so a turn adds a\n * small record of digests rather than another copy of the prompt.\n *\n * The store is a port. A product implements it over its own storage (an object\n * bucket, a database table, a vault directory); `createMemoryModelInputStore`\n * is the reference implementation and test double. A digest is the lowercase\n * sha256 hex of the UTF-8 content, the same encoding as\n * `ProfileFingerprint.promptSha`, so a fingerprint already on a receipt\n * resolves to its system-prompt blob directly.\n */\n\nimport type { RenderedAgentPrompt } from './agent-prompt'\n\nexport const MODEL_INPUT_RECORD_SCHEMA = 'agent-app.model-input.v1'\n\n/** What an input was. `workspace-plan` is the canonical JSON of the\n * materialized workspace plan; `turn-context` is per-turn text appended after\n * the system prompt. */\nexport type ModelInputKind = 'system-prompt' | 'workspace-plan' | 'turn-context'\n\nexport type ModelInputMediaType = 'text/markdown' | 'application/json' | 'text/plain'\n\nexport interface ModelInputBlob {\n digest: string\n kind: ModelInputKind\n mediaType: ModelInputMediaType\n bytes: number\n content: string\n}\n\n/** A blob without its content: what a record carries. */\nexport type ModelInputRef = Omit<ModelInputBlob, 'content'>\n\n/** One system-prompt section's identity, from {@link RenderedAgentPrompt}. Two\n * records compared section by section name the section that changed. */\nexport interface ModelInputSectionRef {\n id: string\n title: string\n bytes: number\n digest: string\n}\n\n/** The record an execution receipt embeds. */\nexport interface ModelInputRecord {\n schema: typeof MODEL_INPUT_RECORD_SCHEMA\n /** sha256 over the record's other fields; equal records have equal digests. */\n digest: string\n inputs: ModelInputRef[]\n /** Empty when the system prompt was a plain string. */\n sections: ModelInputSectionRef[]\n /** Operating-contract version, when the prompt came from `renderAgentPrompt`. */\n contractVersion: number | null\n /** ADC plan identity (`hashWorkspacePlan`), matching `ProfileTurnPin.planDigest`. */\n planDigest: string | null\n model: string | null\n harness: string | null\n}\n\nexport type ModelInputOutcome<T> = { succeeded: true; value: T } | { succeeded: false; error: string }\n\n/** Content-addressed blob storage for model inputs. */\nexport interface ModelInputStore {\n /** Store a blob. Idempotent: putting an existing digest succeeds. */\n put(blob: ModelInputBlob): Promise<ModelInputOutcome<void>>\n /** Load a blob; `null` when the digest is unknown. */\n get(digest: string): Promise<ModelInputOutcome<ModelInputBlob | null>>\n}\n\nconst encoder = new TextEncoder()\n\nasync function sha256Hex(text: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', encoder.encode(text))\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('')\n}\n\nconst DEFAULT_MEDIA_TYPE: Record<ModelInputKind, ModelInputMediaType> = {\n 'system-prompt': 'text/markdown',\n 'workspace-plan': 'application/json',\n 'turn-context': 'text/markdown',\n}\n\n/** Address one input by its content. */\nexport async function modelInputBlob(\n kind: ModelInputKind,\n content: string,\n mediaType: ModelInputMediaType = DEFAULT_MEDIA_TYPE[kind],\n): Promise<ModelInputBlob> {\n return { digest: await sha256Hex(content), kind, mediaType, bytes: encoder.encode(content).byteLength, content }\n}\n\nexport interface CaptureModelInputInput {\n store: ModelInputStore\n /** The final system prompt the model received. */\n systemPrompt: string | RenderedAgentPrompt\n /** Other inputs, such as the canonical workspace-plan JSON. */\n inputs?: ReadonlyArray<{ kind: ModelInputKind; content: string; mediaType?: ModelInputMediaType }>\n planDigest?: string | null\n model?: string | null\n harness?: string | null\n}\n\nfunction failed(error: string): { succeeded: false; error: string } {\n return { succeeded: false, error }\n}\n\n/** Store every input, then build the record a receipt links to. Returns a\n * failure, never a record, when any blob was not stored. */\nexport async function captureModelInput(input: CaptureModelInputInput): Promise<ModelInputOutcome<ModelInputRecord>> {\n const rendered = typeof input.systemPrompt === 'string' ? null : input.systemPrompt\n const prompt = rendered ? rendered.prompt : (input.systemPrompt as string)\n const blobs = await Promise.all([\n modelInputBlob('system-prompt', prompt),\n ...(input.inputs ?? []).map((extra) => modelInputBlob(extra.kind, extra.content, extra.mediaType)),\n ])\n for (const blob of blobs) {\n let stored: ModelInputOutcome<void>\n try {\n stored = await input.store.put(blob)\n } catch (error) {\n return failed(`model-input store threw storing ${blob.kind} ${blob.digest}: ${error instanceof Error ? error.message : String(error)}`)\n }\n if (!stored.succeeded) return failed(`model-input store refused ${blob.kind} ${blob.digest}: ${stored.error}`)\n }\n const sections = rendered\n ? await Promise.all(rendered.sections.map(async (section) => ({\n id: section.id,\n title: section.title,\n bytes: section.bytes,\n digest: await sha256Hex(section.text),\n })))\n : []\n const body = {\n schema: MODEL_INPUT_RECORD_SCHEMA,\n inputs: blobs.map((blob) => ({ digest: blob.digest, kind: blob.kind, mediaType: blob.mediaType, bytes: blob.bytes })),\n sections,\n contractVersion: rendered?.contractVersion ?? null,\n planDigest: input.planDigest ?? null,\n model: input.model ?? null,\n harness: input.harness ?? null,\n } satisfies Omit<ModelInputRecord, 'digest'>\n return { succeeded: true, value: { ...body, digest: await sha256Hex(JSON.stringify(body)) } }\n}\n\n/** Load one input back and verify its content still matches its digest. */\nexport async function readModelInput(\n store: ModelInputStore,\n ref: Pick<ModelInputRef, 'digest'>,\n): Promise<ModelInputOutcome<ModelInputBlob>> {\n let loaded: ModelInputOutcome<ModelInputBlob | null>\n try {\n loaded = await store.get(ref.digest)\n } catch (error) {\n return failed(`model-input store threw reading ${ref.digest}: ${error instanceof Error ? error.message : String(error)}`)\n }\n if (!loaded.succeeded) return loaded\n if (!loaded.value) return failed(`model input ${ref.digest} is not in the store`)\n const actual = await sha256Hex(loaded.value.content)\n if (actual !== ref.digest) return failed(`model input ${ref.digest} content hashes to ${actual}`)\n return { succeeded: true, value: loaded.value }\n}\n\n/** In-memory store. Rejects a blob whose content does not match its digest. */\nexport function createMemoryModelInputStore(): ModelInputStore & { readonly size: number } {\n const blobs = new Map<string, ModelInputBlob>()\n return {\n get size() {\n return blobs.size\n },\n async put(blob) {\n const actual = await sha256Hex(blob.content)\n if (actual !== blob.digest) return failed(`digest ${blob.digest} does not match content (${actual})`)\n if (!blobs.has(blob.digest)) blobs.set(blob.digest, { ...blob })\n return { succeeded: true, value: undefined }\n },\n async get(digest) {\n const blob = blobs.get(digest)\n return { succeeded: true, value: blob ? { ...blob } : null }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,0BAA0B;AACnC,SAAS,eAAe;;;AC3BjB,IAAM,6BAA6B;AAiB1C,IAAM,wBAAwB;AAE9B,IAAM,2BAA2B;AAG1B,IAAM,6BAAiE,OAAO,OAAO;AAAA,EAC1F;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM,uNAAuN,qBAAqB;AAAA,EACpP;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,EACR;AACF,CAAC;AAwBD,IAAM,aAAa,IAAI,IAAY,2BAA2B,IAAI,CAAC,WAAW,OAAO,EAAE,CAAC;AAIjF,SAAS,wBAAwB,UAAoC,CAAC,GAA8B;AACzG,QAAM,OAAO,IAAI,IAAY,QAAQ,QAAQ,CAAC,CAAC;AAC/C,QAAM,UAAU,CAAC,GAAG,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC;AAC5D,MAAI,QAAQ,SAAS,GAAG;AACtB,UAAM,IAAI,MAAM,0DAA0D,QAAQ,KAAK,IAAI,CAAC,EAAE;AAAA,EAChG;AACA,QAAM,QAAQ,QAAQ,iBAAiB,KAAK,KAAK;AACjD,QAAM,OAAO,2BAA2B,OAAO,CAAC,WAAW,CAAC,KAAK,IAAI,OAAO,EAAE,CAAC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/**
|
|
2
|
+
* "What the model saw": content-addressed copies of the exact inputs a turn
|
|
3
|
+
* sent to the model, linked from the turn's execution receipt.
|
|
4
|
+
*
|
|
5
|
+
* A receipt that names a profile revision cannot say what the prompt read once
|
|
6
|
+
* the rendering code has changed. Storing each input by digest answers that
|
|
7
|
+
* permanently: identical prompts across turns share one blob, so a turn adds a
|
|
8
|
+
* small record of digests rather than another copy of the prompt.
|
|
9
|
+
*
|
|
10
|
+
* The store is a port. A product implements it over its own storage (an object
|
|
11
|
+
* bucket, a database table, a vault directory); `createMemoryModelInputStore`
|
|
12
|
+
* is the reference implementation and test double. A digest is the lowercase
|
|
13
|
+
* sha256 hex of the UTF-8 content, the same encoding as
|
|
14
|
+
* `ProfileFingerprint.promptSha`, so a fingerprint already on a receipt
|
|
15
|
+
* resolves to its system-prompt blob directly.
|
|
16
|
+
*/
|
|
17
|
+
import type { RenderedAgentPrompt } from './agent-prompt';
|
|
18
|
+
export declare const MODEL_INPUT_RECORD_SCHEMA = "agent-app.model-input.v1";
|
|
19
|
+
/** What an input was. `workspace-plan` is the canonical JSON of the
|
|
20
|
+
* materialized workspace plan; `turn-context` is per-turn text appended after
|
|
21
|
+
* the system prompt. */
|
|
22
|
+
export type ModelInputKind = 'system-prompt' | 'workspace-plan' | 'turn-context';
|
|
23
|
+
export type ModelInputMediaType = 'text/markdown' | 'application/json' | 'text/plain';
|
|
24
|
+
export interface ModelInputBlob {
|
|
25
|
+
digest: string;
|
|
26
|
+
kind: ModelInputKind;
|
|
27
|
+
mediaType: ModelInputMediaType;
|
|
28
|
+
bytes: number;
|
|
29
|
+
content: string;
|
|
30
|
+
}
|
|
31
|
+
/** A blob without its content: what a record carries. */
|
|
32
|
+
export type ModelInputRef = Omit<ModelInputBlob, 'content'>;
|
|
33
|
+
/** One system-prompt section's identity, from {@link RenderedAgentPrompt}. Two
|
|
34
|
+
* records compared section by section name the section that changed. */
|
|
35
|
+
export interface ModelInputSectionRef {
|
|
36
|
+
id: string;
|
|
37
|
+
title: string;
|
|
38
|
+
bytes: number;
|
|
39
|
+
digest: string;
|
|
40
|
+
}
|
|
41
|
+
/** The record an execution receipt embeds. */
|
|
42
|
+
export interface ModelInputRecord {
|
|
43
|
+
schema: typeof MODEL_INPUT_RECORD_SCHEMA;
|
|
44
|
+
/** sha256 over the record's other fields; equal records have equal digests. */
|
|
45
|
+
digest: string;
|
|
46
|
+
inputs: ModelInputRef[];
|
|
47
|
+
/** Empty when the system prompt was a plain string. */
|
|
48
|
+
sections: ModelInputSectionRef[];
|
|
49
|
+
/** Operating-contract version, when the prompt came from `renderAgentPrompt`. */
|
|
50
|
+
contractVersion: number | null;
|
|
51
|
+
/** ADC plan identity (`hashWorkspacePlan`), matching `ProfileTurnPin.planDigest`. */
|
|
52
|
+
planDigest: string | null;
|
|
53
|
+
model: string | null;
|
|
54
|
+
harness: string | null;
|
|
55
|
+
}
|
|
56
|
+
export type ModelInputOutcome<T> = {
|
|
57
|
+
succeeded: true;
|
|
58
|
+
value: T;
|
|
59
|
+
} | {
|
|
60
|
+
succeeded: false;
|
|
61
|
+
error: string;
|
|
62
|
+
};
|
|
63
|
+
/** Content-addressed blob storage for model inputs. */
|
|
64
|
+
export interface ModelInputStore {
|
|
65
|
+
/** Store a blob. Idempotent: putting an existing digest succeeds. */
|
|
66
|
+
put(blob: ModelInputBlob): Promise<ModelInputOutcome<void>>;
|
|
67
|
+
/** Load a blob; `null` when the digest is unknown. */
|
|
68
|
+
get(digest: string): Promise<ModelInputOutcome<ModelInputBlob | null>>;
|
|
69
|
+
}
|
|
70
|
+
/** Address one input by its content. */
|
|
71
|
+
export declare function modelInputBlob(kind: ModelInputKind, content: string, mediaType?: ModelInputMediaType): Promise<ModelInputBlob>;
|
|
72
|
+
export interface CaptureModelInputInput {
|
|
73
|
+
store: ModelInputStore;
|
|
74
|
+
/** The final system prompt the model received. */
|
|
75
|
+
systemPrompt: string | RenderedAgentPrompt;
|
|
76
|
+
/** Other inputs, such as the canonical workspace-plan JSON. */
|
|
77
|
+
inputs?: ReadonlyArray<{
|
|
78
|
+
kind: ModelInputKind;
|
|
79
|
+
content: string;
|
|
80
|
+
mediaType?: ModelInputMediaType;
|
|
81
|
+
}>;
|
|
82
|
+
planDigest?: string | null;
|
|
83
|
+
model?: string | null;
|
|
84
|
+
harness?: string | null;
|
|
85
|
+
}
|
|
86
|
+
/** Store every input, then build the record a receipt links to. Returns a
|
|
87
|
+
* failure, never a record, when any blob was not stored. */
|
|
88
|
+
export declare function captureModelInput(input: CaptureModelInputInput): Promise<ModelInputOutcome<ModelInputRecord>>;
|
|
89
|
+
/** Load one input back and verify its content still matches its digest. */
|
|
90
|
+
export declare function readModelInput(store: ModelInputStore, ref: Pick<ModelInputRef, 'digest'>): Promise<ModelInputOutcome<ModelInputBlob>>;
|
|
91
|
+
/** In-memory store. Rejects a blob whose content does not match its digest. */
|
|
92
|
+
export declare function createMemoryModelInputStore(): ModelInputStore & {
|
|
93
|
+
readonly size: number;
|
|
94
|
+
};
|