@tangle-network/agent-app 0.43.48 → 0.43.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,12 +2,68 @@ import "./chunk-UAKFCMWK.js";
2
2
  import {
3
3
  checkThemeContract
4
4
  } from "./chunk-NYATNLRK.js";
5
+ import {
6
+ CANVAS_ELEMENT_KINDS,
7
+ CANVAS_MCP_TOOLS,
8
+ CANVAS_MCP_TOOL_NAMES,
9
+ DEFAULT_DESIGN_CANVAS_MCP_DESCRIPTION,
10
+ SCENE_OPERATION_TYPES,
11
+ applyBindingsToDocument,
12
+ buildDesignCanvasMcpServerEntry,
13
+ createDesignCanvasMcpHandler,
14
+ findCanvasMcpTool,
15
+ instantiateTemplate,
16
+ listTemplateSlots,
17
+ validateBindings
18
+ } from "./chunk-WFMUDX5J.js";
5
19
  import {
6
20
  darkTheme,
7
21
  lightTheme,
8
22
  themeColor,
9
23
  themeToCssVars
10
24
  } from "./chunk-47C6PJCW.js";
25
+ import {
26
+ CHANNEL_PRESETS,
27
+ EXPORT_PRESETS,
28
+ SCENE_ELEMENT_KINDS,
29
+ SCENE_SCHEMA_VERSION,
30
+ SIZE_PRESETS,
31
+ applySceneOperation,
32
+ applySceneOperations,
33
+ assertColor,
34
+ assertFinite,
35
+ assertPositiveFinite,
36
+ assertSceneMediaSrc,
37
+ bleedAwareExportBounds,
38
+ bleedAwareExportRect,
39
+ boundsIntersect,
40
+ collectSlots,
41
+ createEmptyDocument,
42
+ createPage,
43
+ elementAabb,
44
+ elementExtent,
45
+ estimateTextHeight,
46
+ findElement,
47
+ findPreset,
48
+ matchPreset,
49
+ requireChannelPreset,
50
+ requireElement,
51
+ requirePage,
52
+ scaleForPreset,
53
+ scalePageForChannelPreset,
54
+ storeApplyScenePlan,
55
+ validateSceneOperation,
56
+ validateSceneOperations,
57
+ validateSlotValue
58
+ } from "./chunk-M2EBUDZ7.js";
59
+ import {
60
+ DEFAULT_REDACTION_PATTERNS,
61
+ buildRedactedDocument,
62
+ detectSpans,
63
+ maskSpans,
64
+ redactForIngestion,
65
+ revealSpan
66
+ } from "./chunk-5RMIUJDI.js";
11
67
  import {
12
68
  buildFlowTrace,
13
69
  childSpanContext,
@@ -85,68 +141,12 @@ import {
85
141
  snapshotFrame,
86
142
  trackIntervals
87
143
  } from "./chunk-ZYBWGSAZ.js";
88
- import {
89
- CANVAS_ELEMENT_KINDS,
90
- CANVAS_MCP_TOOLS,
91
- CANVAS_MCP_TOOL_NAMES,
92
- DEFAULT_DESIGN_CANVAS_MCP_DESCRIPTION,
93
- SCENE_OPERATION_TYPES,
94
- applyBindingsToDocument,
95
- buildDesignCanvasMcpServerEntry,
96
- createDesignCanvasMcpHandler,
97
- findCanvasMcpTool,
98
- instantiateTemplate,
99
- listTemplateSlots,
100
- validateBindings
101
- } from "./chunk-WFMUDX5J.js";
102
- import {
103
- CHANNEL_PRESETS,
104
- EXPORT_PRESETS,
105
- SCENE_ELEMENT_KINDS,
106
- SCENE_SCHEMA_VERSION,
107
- SIZE_PRESETS,
108
- applySceneOperation,
109
- applySceneOperations,
110
- assertColor,
111
- assertFinite,
112
- assertPositiveFinite,
113
- assertSceneMediaSrc,
114
- bleedAwareExportBounds,
115
- bleedAwareExportRect,
116
- boundsIntersect,
117
- collectSlots,
118
- createEmptyDocument,
119
- createPage,
120
- elementAabb,
121
- elementExtent,
122
- estimateTextHeight,
123
- findElement,
124
- findPreset,
125
- matchPreset,
126
- requireChannelPreset,
127
- requireElement,
128
- requirePage,
129
- scaleForPreset,
130
- scalePageForChannelPreset,
131
- storeApplyScenePlan,
132
- validateSceneOperation,
133
- validateSceneOperations,
134
- validateSlotValue
135
- } from "./chunk-M2EBUDZ7.js";
136
144
  import {
137
145
  composeMissionFlowTrace,
138
146
  delegationActivityToFlowSpans,
139
147
  loopTraceEventsToFlowSpans,
140
148
  stepActivityFlowTrace
141
149
  } from "./chunk-2QI7XV2T.js";
142
- import {
143
- DEFAULT_REDACTION_PATTERNS,
144
- buildRedactedDocument,
145
- detectSpans,
146
- maskSpans,
147
- redactForIngestion,
148
- revealSpan
149
- } from "./chunk-5RMIUJDI.js";
150
150
  import {
151
151
  HubExecClient,
152
152
  invokeIntegrationHub,
@@ -217,7 +217,18 @@ import {
217
217
  createPresetToolHandlers,
218
218
  createPresetWorkspaceKeyManager,
219
219
  createPresetWorkspaceKeyStore
220
- } from "./chunk-UHXQ3KNX.js";
220
+ } from "./chunk-54GSK2KK.js";
221
+ import {
222
+ createFieldCrypto,
223
+ decodeHexKey,
224
+ decryptAesGcm,
225
+ decryptBytes,
226
+ decryptWithKey,
227
+ deriveKey,
228
+ encryptAesGcm,
229
+ encryptBytes,
230
+ encryptWithKey
231
+ } from "./chunk-TA5Q4I2K.js";
221
232
  import {
222
233
  createPlatformBalanceManager,
223
234
  createTcloudKeyProvisioner,
@@ -243,6 +254,17 @@ import {
243
254
  ChatStoreInputError,
244
255
  threadTitleFromMessage
245
256
  } from "./chunk-5EQCITY3.js";
257
+ import {
258
+ addSecurityHeaders,
259
+ assertMediaUrl,
260
+ checkRateLimit,
261
+ clearCookieHeader,
262
+ extractRequestContext,
263
+ parseJsonObjectBody,
264
+ readCookieValue,
265
+ requireString,
266
+ serializeCookie
267
+ } from "./chunk-HFC4BTWJ.js";
246
268
  import {
247
269
  TURN_EVENTS_MIGRATION_SQL,
248
270
  TURN_STATUS_SCOPE_MIGRATION_SQL,
@@ -265,17 +287,6 @@ import {
265
287
  respondToSessionInteraction,
266
288
  validateInteractionAnswerBody
267
289
  } from "./chunk-6KVH5SP5.js";
268
- import {
269
- addSecurityHeaders,
270
- assertMediaUrl,
271
- checkRateLimit,
272
- clearCookieHeader,
273
- extractRequestContext,
274
- parseJsonObjectBody,
275
- readCookieValue,
276
- requireString,
277
- serializeCookie
278
- } from "./chunk-HFC4BTWJ.js";
279
290
  import {
280
291
  DEFAULT_ATTACHMENT_PROMPT_HEADER,
281
292
  attachmentInputToPart,
@@ -350,17 +361,6 @@ import {
350
361
  planRevisionKey,
351
362
  planToPersistedPart
352
363
  } from "./chunk-SIXYZ2FB.js";
353
- import {
354
- createFieldCrypto,
355
- decodeHexKey,
356
- decryptAesGcm,
357
- decryptBytes,
358
- decryptWithKey,
359
- deriveKey,
360
- encryptAesGcm,
361
- encryptBytes,
362
- encryptWithKey
363
- } from "./chunk-TA5Q4I2K.js";
364
364
  import {
365
365
  createKnowledgeLoop,
366
366
  createReviewerDecider,
@@ -426,7 +426,7 @@ import {
426
426
  verifySandboxTerminalToken,
427
427
  verifyTerminalProxyToken,
428
428
  writeProfileFilesToBox
429
- } from "./chunk-5RJNEEO2.js";
429
+ } from "./chunk-HRJJH3RX.js";
430
430
  import {
431
431
  DEFAULT_HARNESS,
432
432
  KNOWN_HARNESSES,
@@ -438,7 +438,7 @@ import {
438
438
  resolveSessionHarness,
439
439
  snapHarnessToModel,
440
440
  snapModelToHarness
441
- } from "./chunk-E7QYOOON.js";
441
+ } from "./chunk-MCJSS6SM.js";
442
442
  import {
443
443
  createCapabilityToken,
444
444
  createExpiringCapabilityToken,
@@ -7,9 +7,9 @@ import {
7
7
  createPresetToolHandlers,
8
8
  createPresetWorkspaceKeyManager,
9
9
  createPresetWorkspaceKeyStore
10
- } from "../chunk-UHXQ3KNX.js";
11
- import "../chunk-G3HCU7TA.js";
10
+ } from "../chunk-54GSK2KK.js";
12
11
  import "../chunk-TA5Q4I2K.js";
12
+ import "../chunk-G3HCU7TA.js";
13
13
  export {
14
14
  PRESET_MIGRATION_SQL,
15
15
  PRESET_TABLES,
@@ -1,8 +1,8 @@
1
- import { AgentProfileFileMount, AgentProfileMcpServer, AgentProfile } from '@tangle-network/sandbox';
1
+ import { AgentProfileFileMount, AgentProfileResourceRef, AgentProfileMcpServer, AgentProfile } from '@tangle-network/sandbox';
2
2
  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
- export { ComposeShellResourcesInput, CorpusEntry, CorpusLoadResult, GlobModules, LoadCorpusOptions, composeShellResources, corpusSkills, loadMarkdownCorpus, registrySkills, skillMountPath } from '../skills/index.js';
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
 
7
7
  /**
8
8
  * Profile composer + evolvable-section seam for agent products.
@@ -61,6 +61,17 @@ interface ProfileChannels {
61
61
  userSkills?: UserSkill[];
62
62
  /** Final skip filter applied to the composed mount list by mount `path`. */
63
63
  filesPredicate?: (mount: AgentProfileFileMount) => boolean;
64
+ /** Typed `resources.skills` channel — refs the platform materializer places
65
+ * at the harness-native skill dir (see {@link skillRefs} and
66
+ * `@tangle-network/agent-app/skills-placement`'s `composeSkillsForHarness`).
67
+ * The successor to path-baked mounts: `registry`/`userSkills` above mount
68
+ * files at the hardcoded claude-code path via {@link skillMountPath};
69
+ * `skillRefs` instead rides the provider-neutral `resources.skills` field
70
+ * the platform resolves per harness. */
71
+ skillRefs?: AgentProfileResourceRef[];
72
+ /** Tier passed to {@link registrySkills} for the `registry` channel.
73
+ * Previously hardcoded `'free'`; default unchanged. */
74
+ registryTier?: string;
64
75
  }
65
76
  /** A per-user / per-workspace skill: an id and an inline `SKILL.md` body. The
66
77
  * user-facing analogue of a registry {@link SkillEntry} with no tier gate —
@@ -1,10 +1,19 @@
1
1
  import {
2
+ assertSkillDeliveryDisjoint,
2
3
  composeShellResources,
4
+ composeSkills,
3
5
  corpusSkills,
4
6
  loadMarkdownCorpus,
7
+ mergeComposedSkills,
8
+ parseCorpusSkills,
9
+ parseSkillFrontmatter,
5
10
  registrySkills,
6
- skillMountPath
7
- } from "../chunk-KOG473C4.js";
11
+ renderInlineSkills,
12
+ renderSkillIndex,
13
+ skillEntryFromMarkdown,
14
+ skillMountPath,
15
+ skillRefs
16
+ } from "../chunk-NBSBRZ6F.js";
8
17
 
9
18
  // src/profile/index.ts
10
19
  import { mergeAgentProfiles } from "@tangle-network/sandbox";
@@ -53,7 +62,7 @@ function composeAgentProfile(base, channels = {}, overlay = {}, budget = {}) {
53
62
  skills: channels.skills,
54
63
  knowledge: channels.knowledge,
55
64
  evolvable: channels.evolvable,
56
- registry: channels.registry ? registrySkills(channels.registry) : void 0,
65
+ registry: channels.registry ? registrySkills(channels.registry, channels.registryTier ?? "free") : void 0,
57
66
  predicate: channels.filesPredicate
58
67
  };
59
68
  const channelFiles = composeShellResources(shellInput);
@@ -67,7 +76,10 @@ function composeAgentProfile(base, channels = {}, overlay = {}, budget = {}) {
67
76
  ...overlay.name ? { name: overlay.name } : {},
68
77
  ...Object.keys(promptOverlay).length > 0 ? { prompt: promptOverlay } : {},
69
78
  ...overlay.mcp ? { mcp: overlay.mcp } : {},
70
- resources: { files }
79
+ resources: {
80
+ files,
81
+ ...channels.skillRefs && channels.skillRefs.length > 0 ? { skills: channels.skillRefs } : {}
82
+ }
71
83
  };
72
84
  const merged = mergeAgentProfiles(base, overlayProfile);
73
85
  if (!merged)
@@ -95,16 +107,25 @@ function makeEvolvableSection(input) {
95
107
  }
96
108
  export {
97
109
  DEFAULT_MAX_SYSTEM_PROMPT_BYTES,
110
+ assertSkillDeliveryDisjoint,
98
111
  assertSystemPromptWithinBudget,
99
112
  composeAgentProfile,
100
113
  composeShellResources,
114
+ composeSkills,
101
115
  corpusSkills,
102
116
  largestPromptSections,
103
117
  loadMarkdownCorpus,
104
118
  makeEvolvableSection,
119
+ mergeComposedSkills,
120
+ parseCorpusSkills,
121
+ parseSkillFrontmatter,
105
122
  profile,
106
123
  registrySkills,
124
+ renderInlineSkills,
125
+ renderSkillIndex,
126
+ skillEntryFromMarkdown,
107
127
  skillMountPath,
128
+ skillRefs,
108
129
  stripComments,
109
130
  userSkillMounts
110
131
  };
@@ -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} 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}\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}\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 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 `Trim the prompt, move content to skills/knowledge mounts, or raise maxSystemPromptBytes deliberately.`\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 ? registrySkills(channels.registry) : 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: { files },\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 composeShellResources,\n corpusSkills,\n loadMarkdownCorpus,\n registrySkills,\n skillMountPath,\n} from '../skills/index'\nexport type {\n ComposeShellResourcesInput,\n CorpusEntry,\n CorpusLoadResult,\n GlobModules,\n LoadCorpusOptions,\n SkillEntry,\n} from '../skills/index'\n"],"mappings":";;;;;;;;;AAyCA,SAAS,0BAA0B;AACnC,SAAS,eAAe;AAwEjB,IAAM,kCAAkC;AAgBxC,SAAS,sBACd,QACA,MAAM,GACmC;AACzC,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,WAAoD,CAAC;AAC3D,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,QAAM,QAAQ,CAAC,QAAgB;AAC7B,UAAM,OAAO,OAAO,MAAM,OAAO,GAAG;AACpC,QAAI,KAAK,KAAK,EAAG,UAAS,KAAK,EAAE,OAAO,OAAO,QAAQ,OAAO,IAAI,EAAE,WAAW,CAAC;AAAA,EAClF;AACA,QAAM,YAAY;AAClB,aAAW,SAAS,OAAO,SAAS,SAAS,GAAG;AAC9C,UAAM,MAAM,KAAK;AACjB,aAAS,MAAM,CAAC,KAAK,IAAI,KAAK,KAAK;AACnC,YAAQ,MAAM;AAAA,EAChB;AACA,QAAM,OAAO,MAAM;AACnB,SAAO,SAAS,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG;AAChE;AAOO,SAAS,+BACd,cACA,SAA+B,CAAC,GAC1B;AACN,QAAM,MAAM,OAAO,wBAAwB;AAC3C,QAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,YAAY,EAAE;AACrD,MAAI,SAAS,IAAK;AAClB,QAAM,WAAW,sBAAsB,YAAY,EAChD,IAAI,CAAC,MAAM,IAAI,EAAE,KAAK,MAAM,EAAE,KAAK,IAAI,EACvC,KAAK,IAA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,IAAI,EAAE,QAAQ,cAAc,IAAI,CAAC;AAAA,IACzE,GAAI,QAAQ,MAAM,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC;AAAA,IAC1C,WAAW,EAAE,MAAM;AAAA,EACrB;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'\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}\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 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 `Trim the prompt, move content to skills/knowledge mounts, or raise maxSystemPromptBytes deliberately.`\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'\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0CA,SAAS,0BAA0B;AACnC,SAAS,eAAe;AAmFjB,IAAM,kCAAkC;AAgBxC,SAAS,sBACd,QACA,MAAM,GACmC;AACzC,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,WAAoD,CAAC;AAC3D,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,QAAM,QAAQ,CAAC,QAAgB;AAC7B,UAAM,OAAO,OAAO,MAAM,OAAO,GAAG;AACpC,QAAI,KAAK,KAAK,EAAG,UAAS,KAAK,EAAE,OAAO,OAAO,QAAQ,OAAO,IAAI,EAAE,WAAW,CAAC;AAAA,EAClF;AACA,QAAM,YAAY;AAClB,aAAW,SAAS,OAAO,SAAS,SAAS,GAAG;AAC9C,UAAM,MAAM,KAAK;AACjB,aAAS,MAAM,CAAC,KAAK,IAAI,KAAK,KAAK;AACnC,YAAQ,MAAM;AAAA,EAChB;AACA,QAAM,OAAO,MAAM;AACnB,SAAO,SAAS,KAAK,CAAC,GAA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AoB,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"]}
@@ -32,7 +32,8 @@
32
32
  * `@tangle-network/agent-app/skills` subpath loads the corpus and returns file
33
33
  * mounts (`AgentProfileFileMount[]`); the PRODUCT renders any `## Skills` text
34
34
  * section and folds it into `base` before calling this assembler. This module
35
- * never renders a skills heading.
35
+ * never renders a skills heading — `@tangle-network/agent-app/skills`'s
36
+ * `renderInlineSkills`/`renderSkillIndex` are the source of that section text.
36
37
  */
37
38
  /** Inputs to {@link assembleSystemPrompt}. */
38
39
  interface AssembleSystemPromptInput {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/prompt/index.ts"],"sourcesContent":["/**\n * System-prompt assembler for agent products.\n *\n * Every agent product composes its system prompt the same way: a base profile\n * prompt (the operator persona + tools block + any skills section the consumer\n * already rendered), an always-on operating directive, then an ordered list of\n * optional per-turn context sections (known-context, board, approval history,\n * learned-style, pending questions, the active artifact). The ORDERING and the\n * whitespace contract are identical across products; only the section BODIES are\n * domain. This module owns the ordering and the joins; the product injects every\n * body as an already-rendered string through the `sections` array.\n *\n * Whitespace contract (preserves the join/concat/trim algebra of the per-product\n * pre-lift composers — a product adopting this asserts byte-for-byte parity in\n * its own suite):\n * - base is emitted verbatim, with no leading/trailing normalization.\n * - directive is appended after base with a single `\\n\\n` join.\n * - each section in `sections` is appended with NO separator: a section is\n * either '' (absent — contributes nothing) or already carries its own\n * leading `\\n\\n` (and its `## ` heading). The assembler concatenates them\n * unconditionally, which is why the conditional-prefix-or-empty contract\n * lives in the product's section renderers, not here.\n * - `trim` (default false) applies a final `.trim()` to the whole result.\n * Branches that historically trimmed pass `trim: true`; branches that did\n * not (e.g. the new-workspace paths) leave it false, preserving that\n * asymmetry rather than silently changing trailing whitespace.\n *\n * Pure string composition: no SDK runtime symbol, no node builtins, no glob.\n * The base profile prompt and the skills-section insertion point both live\n * INSIDE the product-built `base` string — the assembler never reaches into an\n * AgentProfile and never loads a corpus. The sibling\n * `@tangle-network/agent-app/skills` subpath loads the corpus and returns file\n * mounts (`AgentProfileFileMount[]`); the PRODUCT renders any `## Skills` text\n * section and folds it into `base` before calling this assembler. This module\n * never renders a skills heading.\n */\n\n/** Inputs to {@link assembleSystemPrompt}. */\nexport interface AssembleSystemPromptInput {\n /** The product's already-composed base block: persona/system prompt + tools\n * block + (optionally) the rendered skills section. The product is\n * responsible for resolving its profile system prompt and failing loud if it\n * is absent — an empty base reaches this assembler only as a programmer\n * error, which it rejects (see {@link AssembleResult}). */\n base: string\n /** The always-on operating directive, placed immediately after base with a\n * `\\n\\n` join. Pass '' to omit it (the join is then suppressed). */\n directive?: string\n /** Ordered per-turn context sections, each already rendered by the product to\n * either '' (absent) or a `\\n\\n## …`-prefixed string. Concatenated in order\n * with no added separator. */\n sections?: string[]\n /** Apply a final `.trim()` to the composed result. Default false — set true\n * only on branches whose pre-lift output was trimmed. */\n trim?: boolean\n}\n\n/** Typed outcome of {@link assembleSystemPrompt}. `succeeded: false` is returned\n * for a programmer error (an empty base) rather than emitting a roleless\n * prompt — callers MUST inspect `succeeded` before using `prompt`. */\nexport type AssembleResult =\n | { succeeded: true; prompt: string }\n | { succeeded: false; error: string }\n\n/** True when a string is empty or whitespace-only. */\nfunction isBlank(value: string): boolean {\n return value.trim().length === 0\n}\n\n/**\n * Assemble a system prompt from a base block, an operating directive, and an\n * ordered list of pre-rendered context sections.\n *\n * Returns a typed outcome: an empty/blank `base` is a defect (an agent with no\n * persona/system prompt), so it fails loud instead of silently producing a\n * prompt with no role. The product resolves and validates its profile prompt\n * upstream; this is the last-line guard at the seam.\n */\nexport function assembleSystemPrompt(input: AssembleSystemPromptInput): AssembleResult {\n const { base, directive = '', sections = [], trim = false } = input\n\n if (isBlank(base)) {\n return {\n succeeded: false,\n error: 'assembleSystemPrompt: base is empty — a system prompt with no persona/base block is a defect, not a default',\n }\n }\n\n let prompt = directive.length > 0 ? `${base}\\n\\n${directive}` : base\n for (const section of sections) prompt += section\n\n return { succeeded: true, prompt: trim ? prompt.trim() : prompt }\n}"],"mappings":";AAiEA,SAAS,QAAQ,OAAwB;AACvC,SAAO,MAAM,KAAK,EAAE,WAAW;AACjC;AAWO,SAAS,qBAAqB,OAAkD;AACrF,QAAM,EAAE,MAAM,YAAY,IAAI,WAAW,CAAC,GAAG,OAAO,MAAM,IAAI;AAE9D,MAAI,QAAQ,IAAI,GAAG;AACjB,WAAO;AAAA,MACL,WAAW;AAAA,MACX,OAAO;AAAA,IACT;AAAA,EACF;AAEA,MAAI,SAAS,UAAU,SAAS,IAAI,GAAG,IAAI;AAAA;AAAA,EAAO,SAAS,KAAK;AAChE,aAAW,WAAW,SAAU,WAAU;AAE1C,SAAO,EAAE,WAAW,MAAM,QAAQ,OAAO,OAAO,KAAK,IAAI,OAAO;AAClE;","names":[]}
1
+ {"version":3,"sources":["../../src/prompt/index.ts"],"sourcesContent":["/**\n * System-prompt assembler for agent products.\n *\n * Every agent product composes its system prompt the same way: a base profile\n * prompt (the operator persona + tools block + any skills section the consumer\n * already rendered), an always-on operating directive, then an ordered list of\n * optional per-turn context sections (known-context, board, approval history,\n * learned-style, pending questions, the active artifact). The ORDERING and the\n * whitespace contract are identical across products; only the section BODIES are\n * domain. This module owns the ordering and the joins; the product injects every\n * body as an already-rendered string through the `sections` array.\n *\n * Whitespace contract (preserves the join/concat/trim algebra of the per-product\n * pre-lift composers — a product adopting this asserts byte-for-byte parity in\n * its own suite):\n * - base is emitted verbatim, with no leading/trailing normalization.\n * - directive is appended after base with a single `\\n\\n` join.\n * - each section in `sections` is appended with NO separator: a section is\n * either '' (absent — contributes nothing) or already carries its own\n * leading `\\n\\n` (and its `## ` heading). The assembler concatenates them\n * unconditionally, which is why the conditional-prefix-or-empty contract\n * lives in the product's section renderers, not here.\n * - `trim` (default false) applies a final `.trim()` to the whole result.\n * Branches that historically trimmed pass `trim: true`; branches that did\n * not (e.g. the new-workspace paths) leave it false, preserving that\n * asymmetry rather than silently changing trailing whitespace.\n *\n * Pure string composition: no SDK runtime symbol, no node builtins, no glob.\n * The base profile prompt and the skills-section insertion point both live\n * INSIDE the product-built `base` string — the assembler never reaches into an\n * AgentProfile and never loads a corpus. The sibling\n * `@tangle-network/agent-app/skills` subpath loads the corpus and returns file\n * mounts (`AgentProfileFileMount[]`); the PRODUCT renders any `## Skills` text\n * section and folds it into `base` before calling this assembler. This module\n * never renders a skills heading — `@tangle-network/agent-app/skills`'s\n * `renderInlineSkills`/`renderSkillIndex` are the source of that section text.\n */\n\n/** Inputs to {@link assembleSystemPrompt}. */\nexport interface AssembleSystemPromptInput {\n /** The product's already-composed base block: persona/system prompt + tools\n * block + (optionally) the rendered skills section. The product is\n * responsible for resolving its profile system prompt and failing loud if it\n * is absent — an empty base reaches this assembler only as a programmer\n * error, which it rejects (see {@link AssembleResult}). */\n base: string\n /** The always-on operating directive, placed immediately after base with a\n * `\\n\\n` join. Pass '' to omit it (the join is then suppressed). */\n directive?: string\n /** Ordered per-turn context sections, each already rendered by the product to\n * either '' (absent) or a `\\n\\n## …`-prefixed string. Concatenated in order\n * with no added separator. */\n sections?: string[]\n /** Apply a final `.trim()` to the composed result. Default false — set true\n * only on branches whose pre-lift output was trimmed. */\n trim?: boolean\n}\n\n/** Typed outcome of {@link assembleSystemPrompt}. `succeeded: false` is returned\n * for a programmer error (an empty base) rather than emitting a roleless\n * prompt — callers MUST inspect `succeeded` before using `prompt`. */\nexport type AssembleResult =\n | { succeeded: true; prompt: string }\n | { succeeded: false; error: string }\n\n/** True when a string is empty or whitespace-only. */\nfunction isBlank(value: string): boolean {\n return value.trim().length === 0\n}\n\n/**\n * Assemble a system prompt from a base block, an operating directive, and an\n * ordered list of pre-rendered context sections.\n *\n * Returns a typed outcome: an empty/blank `base` is a defect (an agent with no\n * persona/system prompt), so it fails loud instead of silently producing a\n * prompt with no role. The product resolves and validates its profile prompt\n * upstream; this is the last-line guard at the seam.\n */\nexport function assembleSystemPrompt(input: AssembleSystemPromptInput): AssembleResult {\n const { base, directive = '', sections = [], trim = false } = input\n\n if (isBlank(base)) {\n return {\n succeeded: false,\n error: 'assembleSystemPrompt: base is empty — a system prompt with no persona/base block is a defect, not a default',\n }\n }\n\n let prompt = directive.length > 0 ? `${base}\\n\\n${directive}` : base\n for (const section of sections) prompt += section\n\n return { succeeded: true, prompt: trim ? prompt.trim() : prompt }\n}"],"mappings":";AAkEA,SAAS,QAAQ,OAAwB;AACvC,SAAO,MAAM,KAAK,EAAE,WAAW;AACjC;AAWO,SAAS,qBAAqB,OAAkD;AACrF,QAAM,EAAE,MAAM,YAAY,IAAI,WAAW,CAAC,GAAG,OAAO,MAAM,IAAI;AAE9D,MAAI,QAAQ,IAAI,GAAG;AACjB,WAAO;AAAA,MACL,WAAW;AAAA,MACX,OAAO;AAAA,IACT;AAAA,EACF;AAEA,MAAI,SAAS,UAAU,SAAS,IAAI,GAAG,IAAI;AAAA;AAAA,EAAO,SAAS,KAAK;AAChE,aAAW,WAAW,SAAU,WAAU;AAE1C,SAAO,EAAE,WAAW,MAAM,QAAQ,OAAO,OAAO,KAAK,IAAI,OAAO;AAClE;","names":[]}
package/dist/run/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  KNOWN_HARNESSES
3
- } from "../chunk-E7QYOOON.js";
3
+ } from "../chunk-MCJSS6SM.js";
4
4
 
5
5
  // src/run/index.ts
6
6
  var ROUTER_HARNESS = "router";
@@ -58,8 +58,8 @@ import {
58
58
  verifySandboxTerminalToken,
59
59
  verifyTerminalProxyToken,
60
60
  writeProfileFilesToBox
61
- } from "../chunk-5RJNEEO2.js";
62
- import "../chunk-E7QYOOON.js";
61
+ } from "../chunk-HRJJH3RX.js";
62
+ import "../chunk-MCJSS6SM.js";
63
63
  import "../chunk-PJC4NXPA.js";
64
64
  import "../chunk-7EVZUIHW.js";
65
65
  import "../chunk-S5SRJJQG.js";