@tangle-network/agent-app 0.60.229 → 0.60.231

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/skills-placement/index.ts"],"sourcesContent":["/**\n * Harness-native skill directory resolution — the one place agent-app binds\n * to the platform's authoritative per-harness skill-dir map.\n *\n * `../skills` renders skill CONTENT (parse, tier-filter, `inline`/`mounted`\n * delivery) but deliberately stops short of naming WHICH cwd path a `mounted`\n * skill lands at on a given harness — that mapping is owned by the platform\n * materializer (`@tangle-network/agent-profile-materialize`'s\n * `skillDirForHarness`), not by app-shell. This subpath exists so no product\n * — and no other agent-app module — ever writes a skill path literal\n * (`~/.claude/skills/...`, `.opencode/skills`, ...) of its own; it bridges\n * agent-app's `Harness` taxonomy onto the platform's `HarnessId` and asks the\n * platform for the answer.\n *\n * Requires the OPTIONAL peer `@tangle-network/agent-profile-materialize`.\n * Products that don't install it simply don't import this subpath — every\n * other agent-app skills surface (`../skills`, `ProfileChannels.skillRefs`)\n * works without it, falling back to `inline` delivery.\n */\n\nimport {\n defineInlineResource,\n type AgentProfile,\n type AgentProfileFileMount,\n} from '@tangle-network/agent-interface'\nimport { KNOWN_HARNESSES, type Harness } from '../harness/index'\nimport { skillDirForHarness, type HarnessId } from '@tangle-network/agent-profile-materialize'\nimport { composeSkills, renderInlineSkills, type ComposedSkills, type SkillEntry } from '../skills/index'\n\n/** agent-app `Harness` -> platform `HarnessId`, identity-mapped for exactly\n * the harnesses the platform map covers. Harnesses absent here (`amp`,\n * `factory-droids`, `forge`, `acp`, `cursor`, `cli-base`) resolve to `null` —\n * {@link composeSkillsForHarness} refuses by default rather than silently\n * delivering `inline`; a caller that genuinely needs `inline` on one of\n * these opts in explicitly (`onNoSkillDir: 'inline'`). `cursor`'s adapter\n * supports `resources.skills` bespokely but isn't in the platform map yet;\n * treating it as unbridged is the safe posture until the map covers it,\n * rather than guessing its cwd skill dir here. */\nconst HARNESS_BRIDGE: Partial<Record<Harness, HarnessId>> = {\n opencode: 'opencode',\n 'claude-code': 'claude-code',\n nanoclaw: 'nanoclaw',\n 'kimi-code': 'kimi-code',\n codex: 'codex',\n pi: 'pi',\n prime: 'prime',\n hermes: 'hermes',\n openclaw: 'openclaw',\n}\n\n/** Resolve the cwd-relative skill dir `resources.skills` refs materialize\n * into on `harness` — via the platform's `skillDirForHarness`. `null` when\n * `harness` isn't bridged (see {@link HARNESS_BRIDGE}) or when the platform\n * itself has no cwd skill primitive for it (e.g. `hermes`, user-dir-only). */\nexport function resolveSkillDir(harness: Harness): string | null {\n const bridged = HARNESS_BRIDGE[harness]\n if (!bridged) return null\n return skillDirForHarness(bridged)\n}\n\n/** Filter `harnesses` down to those with no mounted skill dir (deduped,\n * first-seen order preserved) — the set that must fall back to `inline`\n * delivery, or that a caller should warn about before offering \"mounted\"\n * install UX. */\nexport function unsupportedSkillHarnesses(harnesses: Iterable<Harness>): Harness[] {\n const seen = new Set<Harness>()\n const out: Harness[] = []\n for (const harness of harnesses) {\n if (resolveSkillDir(harness) !== null) continue\n if (seen.has(harness)) continue\n seen.add(harness)\n out.push(harness)\n }\n return out\n}\n\n/** Inputs to {@link composeSkillsForHarness}. */\nexport interface ComposeSkillsForHarnessInput {\n skills: SkillEntry[]\n harness: Harness\n tier?: string\n heading?: string\n /**\n * What to do when `harness` has no native skill-mount directory (see\n * {@link resolveSkillDir}). Default `'throw'`: refuse rather than silently\n * inlining every skill BODY into the system prompt. Pass `'inline'` only as\n * a deliberate, auditable opt-in — the caller has decided every skill must\n * reach this harness even though it will be concatenated into the prompt.\n */\n onNoSkillDir?: 'throw' | 'inline'\n}\n\n/** `KNOWN_HARNESSES` filtered to those the platform materializer can mount\n * skill files onto natively (a non-null {@link resolveSkillDir}). Computed\n * fresh rather than cached — the platform map can grow without a release\n * here. Used only to build the actionable error in\n * {@link composeSkillsForHarness}; not exported because it duplicates\n * {@link unsupportedSkillHarnesses}'s complement and callers should reach\n * for that instead when they need the harness list at runtime. */\nfunction nativeSkillMountHarnesses(): Harness[] {\n return KNOWN_HARNESSES.filter((harness) => resolveSkillDir(harness) !== null)\n}\n\n/**\n * Compose {@link ComposedSkills} for `harness`.\n *\n * `mounted` delivery is the standard path: whenever the platform names a cwd\n * skill dir for `harness`, skills ride the typed `resources.skills` channel\n * and the platform materializer writes each one to that directory as a real\n * file — the agent reads it on demand with its own file tools.\n *\n * `inline` delivery — every skill BODY rendered straight into the system\n * prompt — is a NARROW fallback for harnesses with no native skill dir, never\n * a co-equal mode. An `AgentProfile` is a RECIPE that materializes into a\n * sandbox, not a prompt template: skill bodies belong in a file mount, and\n * `prompt.systemPrompt` should carry only what the agent must obey without a\n * tool call (identity, tool-call contract, safety rules, output format) plus\n * a short index of what's mounted. Concatenating skill bodies into the prompt\n * degrades the model toward empty answers once it grows large enough — one\n * product reproduced a 151,882-byte prompt exactly this way, from an\n * unnoticed inline fallback.\n *\n * Because of that, `onNoSkillDir` defaults to `'throw'`: a harness with no\n * skill dir refuses instead of silently inlining. The thrown error names the\n * harness, the skill count, the byte size that would have been inlined, and\n * the harnesses that DO support native mounting. Pass `onNoSkillDir:\n * 'inline'` only as a deliberate, auditable opt-in when every skill genuinely\n * must reach this harness regardless of prompt cost.\n *\n * The one function a product calls instead of hand-checking `resolveSkillDir`\n * and branching between {@link composeSkills}'s two modes itself.\n */\nexport function composeSkillsForHarness(input: ComposeSkillsForHarnessInput): ComposedSkills {\n const { skills, harness, tier, heading, onNoSkillDir = 'throw' } = input\n const skillDir = resolveSkillDir(harness)\n if (skillDir) return composeSkills({ skills, mode: 'mounted', skillDir, tier, heading })\n if (onNoSkillDir === 'inline') return composeSkills({ skills, mode: 'inline', tier, heading })\n\n const relevant = tier ? skills.filter((s) => s.tier === tier) : skills\n const promptSection = renderInlineSkills({ skills, tier, heading })\n const bytes = new TextEncoder().encode(promptSection).byteLength\n const mountable = nativeSkillMountHarnesses()\n throw new Error(\n `composeSkillsForHarness: \"${harness}\" has no native skill-mount directory. ` +\n `Inlining ${relevant.length} skill(s) (${bytes} bytes) into its system prompt would silently ` +\n `convert mounted skills into prompt text — a 151,882-byte prompt shipped this way once, and ` +\n `oversized prompts degrade toward empty answers. Mount the skills instead: pick a harness with ` +\n `native skill support (${mountable.join(', ')}), or pass onNoSkillDir: 'inline' to opt in ` +\n `explicitly and accept the inlined bytes.`,\n )\n}\n\nexport type { ComposedSkills, SkillEntry } from '../skills/index'\n\n/** A file that rides BESIDE a skill entry (kit sources, references, pinned\n * requirements — anything the SKILL.md tells the agent to read or run).\n * `path` is skill-dir-relative (`kit/iso-kit.mjs`, `references/x.md`). */\nexport interface SkillSupportFile {\n path: string\n content: string\n}\n\n/** Inline file mounts placing a skill's support files beside its entry on\n * `harness`: `<skillDir>/<skillId>/<path>`. Empty when the harness has no\n * cwd skill dir — the same posture as `resources.skills` itself (the\n * platform skips skills there too), so nothing orphan lands in a workspace\n * a harness will never read.\n *\n * This is the placement primitive for kit-carrying skills (vendored\n * executable kits, reference trees). A growing program belongs in THESE\n * mounts — never in an env var: runtimeSecrets values are capped (8192\n * chars on the sandbox SDK) and a skill tree outgrew that cap in production\n * once, taking every isolated turn down with a secret-provider refusal. */\nexport function skillSupportFileMounts(\n harness: Harness,\n skillId: string,\n files: readonly SkillSupportFile[],\n): AgentProfileFileMount[] {\n const skillDir = resolveSkillDir(harness)\n if (!skillDir || files.length === 0) return []\n return files.map((file) => ({\n path: `${skillDir}/${skillId}/${file.path}`,\n resource: defineInlineResource(`${skillId}/${file.path}`, file.content),\n }))\n}\n\n/** Attach a skill's support files to `profile` for `harness`, idempotently.\n *\n * Replacement is by EXACT CONTENT under the skill's own subtree (any path\n * ending `/<skillId>/<path>` whose bytes match a support file of THIS call):\n * re-deriving the same profile for another harness replaces this skill's\n * own mounts wherever they previously pointed, while pack-declared files\n * with similar paths stay untouched. With no skill dir the skill's own\n * mounts are dropped (and nothing added) — mirroring how the platform\n * treats the skill entry itself on that harness. */\nexport function withSkillSupportFiles<\n P extends { resources?: AgentProfile['resources'] },\n>(profile: P, harness: Harness, skillId: string, files: readonly SkillSupportFile[]): P {\n const hasSkillDir = resolveSkillDir(harness) !== null\n const desired = skillSupportFileMounts(harness, skillId, files)\n const desiredByPath = new Map(\n desired.map((mount) => [mount.path, mount.resource] as const),\n )\n const byRelPath = new Map(files.map((file) => [file.path, file.content] as const))\n const suffix = `/${skillId}/`\n const relUnderSkill = (path: string): string | null => {\n const at = path.lastIndexOf(suffix)\n return at < 0 ? null : path.slice(at + suffix.length)\n }\n // \"Ours\" = a mount under THIS skill's subtree whose bytes match a support\n // file of this call. It is STALE when the harness has no skill dir (there\n // is nowhere to place it — mirroring how the platform skips the skill\n // entry itself) or when this call would place it at a different path\n // (re-derivation for another harness). Exact-content identity only: a\n // foreign mount at one of our paths keeps the location (pack-declared\n // files win at their declared paths), and a mount already identical to\n // what we would add is kept as-is, so re-deriving for the SAME harness\n // returns the profile unchanged.\n const isStaleOurs = (mount: AgentProfileFileMount): boolean => {\n if (mount.resource.kind !== 'inline') return false\n const rel = relUnderSkill(mount.path)\n if (rel === null || byRelPath.get(rel) !== mount.resource.content) return false\n const desiredHere = desiredByPath.get(mount.path)\n return (\n !hasSkillDir ||\n desiredHere === undefined ||\n desiredHere.kind !== 'inline' ||\n desiredHere.content !== mount.resource.content\n )\n }\n const existing = profile.resources?.files ?? []\n const retained = existing.filter((mount) => !isStaleOurs(mount))\n const taken = new Set(retained.map((mount) => mount.path))\n const additions = desired.filter((mount) => !taken.has(mount.path))\n if (retained.length === existing.length && additions.length === 0) return profile\n return {\n ...profile,\n resources: { ...(profile.resources ?? {}), files: [...retained, ...additions] },\n }\n}\n"],"mappings":";;;;;;;;;;;AAoBA;AAAA,EACE;AAAA,OAGK;AAEP,SAAS,0BAA0C;AAYnD,IAAM,iBAAsD;AAAA,EAC1D,UAAU;AAAA,EACV,eAAe;AAAA,EACf,UAAU;AAAA,EACV,aAAa;AAAA,EACb,OAAO;AAAA,EACP,IAAI;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,SAAS,IAAI,CAAC,UAAU,MAAM,IAAI,CAAC;AACzD,QAAM,YAAY,QAAQ,OAAO,CAAC,UAAU,CAAC,MAAM,IAAI,MAAM,IAAI,CAAC;AAClE,MAAI,SAAS,WAAW,SAAS,UAAU,UAAU,WAAW,EAAG,QAAO;AAC1E,SAAO;AAAA,IACL,GAAG;AAAA,IACH,WAAW,EAAE,GAAI,QAAQ,aAAa,CAAC,GAAI,OAAO,CAAC,GAAG,UAAU,GAAG,SAAS,EAAE;AAAA,EAChF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/skills-placement/index.ts"],"sourcesContent":["/**\n * Harness-native skill directory resolution — the one place agent-app binds\n * to the platform's authoritative per-harness skill-dir map.\n *\n * `../skills` renders skill CONTENT (parse, tier-filter, `inline`/`mounted`\n * delivery) but deliberately stops short of naming WHICH cwd path a `mounted`\n * skill lands at on a given harness — that mapping is owned by the platform\n * materializer (`@tangle-network/agent-profile-materialize`'s\n * `skillDirForHarness`), not by app-shell. This subpath exists so no product\n * — and no other agent-app module — ever writes a skill path literal\n * (`~/.claude/skills/...`, `.opencode/skills`, ...) of its own; it bridges\n * agent-app's `Harness` taxonomy onto the platform's `HarnessId` and asks the\n * platform for the answer.\n *\n * Requires the OPTIONAL peer `@tangle-network/agent-profile-materialize`.\n * Products that don't install it simply don't import this subpath — every\n * other agent-app skills surface (`../skills`, `ProfileChannels.skillRefs`)\n * works without it, falling back to `inline` delivery.\n */\n\nimport {\n defineInlineResource,\n type AgentProfile,\n type AgentProfileFileMount,\n} from '@tangle-network/agent-interface'\nimport { KNOWN_HARNESSES, type Harness } from '../harness/index'\nimport { skillDirForHarness, type HarnessId } from '@tangle-network/agent-profile-materialize'\nimport { composeSkills, renderInlineSkills, type ComposedSkills, type SkillEntry } from '../skills/index'\n\n/** agent-app `Harness` -> platform `HarnessId`, identity-mapped for exactly\n * the harnesses the platform map covers. Harnesses absent here (`amp`,\n * `factory-droids`, `forge`, `acp`, `cursor`, `cli-base`) resolve to `null` —\n * {@link composeSkillsForHarness} refuses by default rather than silently\n * delivering `inline`; a caller that genuinely needs `inline` on one of\n * these opts in explicitly (`onNoSkillDir: 'inline'`). `cursor`'s adapter\n * supports `resources.skills` bespokely but isn't in the platform map yet;\n * treating it as unbridged is the safe posture until the map covers it,\n * rather than guessing its cwd skill dir here. */\nconst HARNESS_BRIDGE: Partial<Record<Harness, HarnessId>> = {\n opencode: 'opencode',\n 'claude-code': 'claude-code',\n nanoclaw: 'nanoclaw',\n 'kimi-code': 'kimi-code',\n codex: 'codex',\n pi: 'pi',\n prime: 'prime',\n hermes: 'hermes',\n openclaw: 'openclaw',\n}\n\n/** Resolve the cwd-relative skill dir `resources.skills` refs materialize\n * into on `harness` — via the platform's `skillDirForHarness`. `null` when\n * `harness` isn't bridged (see {@link HARNESS_BRIDGE}) or when the platform\n * itself has no cwd skill primitive for it (e.g. `hermes`, user-dir-only). */\nexport function resolveSkillDir(harness: Harness): string | null {\n const bridged = HARNESS_BRIDGE[harness]\n if (!bridged) return null\n return skillDirForHarness(bridged)\n}\n\n/** Filter `harnesses` down to those with no mounted skill dir (deduped,\n * first-seen order preserved) — the set that must fall back to `inline`\n * delivery, or that a caller should warn about before offering \"mounted\"\n * install UX. */\nexport function unsupportedSkillHarnesses(harnesses: Iterable<Harness>): Harness[] {\n const seen = new Set<Harness>()\n const out: Harness[] = []\n for (const harness of harnesses) {\n if (resolveSkillDir(harness) !== null) continue\n if (seen.has(harness)) continue\n seen.add(harness)\n out.push(harness)\n }\n return out\n}\n\n/** Inputs to {@link composeSkillsForHarness}. */\nexport interface ComposeSkillsForHarnessInput {\n skills: SkillEntry[]\n harness: Harness\n tier?: string\n heading?: string\n /**\n * What to do when `harness` has no native skill-mount directory (see\n * {@link resolveSkillDir}). Default `'throw'`: refuse rather than silently\n * inlining every skill BODY into the system prompt. Pass `'inline'` only as\n * a deliberate, auditable opt-in — the caller has decided every skill must\n * reach this harness even though it will be concatenated into the prompt.\n */\n onNoSkillDir?: 'throw' | 'inline'\n}\n\n/** `KNOWN_HARNESSES` filtered to those the platform materializer can mount\n * skill files onto natively (a non-null {@link resolveSkillDir}). Computed\n * fresh rather than cached — the platform map can grow without a release\n * here. Used only to build the actionable error in\n * {@link composeSkillsForHarness}; not exported because it duplicates\n * {@link unsupportedSkillHarnesses}'s complement and callers should reach\n * for that instead when they need the harness list at runtime. */\nfunction nativeSkillMountHarnesses(): Harness[] {\n return KNOWN_HARNESSES.filter((harness) => resolveSkillDir(harness) !== null)\n}\n\n/**\n * Compose {@link ComposedSkills} for `harness`.\n *\n * `mounted` delivery is the standard path: whenever the platform names a cwd\n * skill dir for `harness`, skills ride the typed `resources.skills` channel\n * and the platform materializer writes each one to that directory as a real\n * file — the agent reads it on demand with its own file tools.\n *\n * `inline` delivery — every skill BODY rendered straight into the system\n * prompt — is a NARROW fallback for harnesses with no native skill dir, never\n * a co-equal mode. An `AgentProfile` is a RECIPE that materializes into a\n * sandbox, not a prompt template: skill bodies belong in a file mount, and\n * `prompt.systemPrompt` should carry only what the agent must obey without a\n * tool call (identity, tool-call contract, safety rules, output format) plus\n * a short index of what's mounted. Concatenating skill bodies into the prompt\n * degrades the model toward empty answers once it grows large enough — one\n * product reproduced a 151,882-byte prompt exactly this way, from an\n * unnoticed inline fallback.\n *\n * Because of that, `onNoSkillDir` defaults to `'throw'`: a harness with no\n * skill dir refuses instead of silently inlining. The thrown error names the\n * harness, the skill count, the byte size that would have been inlined, and\n * the harnesses that DO support native mounting. Pass `onNoSkillDir:\n * 'inline'` only as a deliberate, auditable opt-in when every skill genuinely\n * must reach this harness regardless of prompt cost.\n *\n * The one function a product calls instead of hand-checking `resolveSkillDir`\n * and branching between {@link composeSkills}'s two modes itself.\n */\nexport function composeSkillsForHarness(input: ComposeSkillsForHarnessInput): ComposedSkills {\n const { skills, harness, tier, heading, onNoSkillDir = 'throw' } = input\n const skillDir = resolveSkillDir(harness)\n if (skillDir) return composeSkills({ skills, mode: 'mounted', skillDir, tier, heading })\n if (onNoSkillDir === 'inline') return composeSkills({ skills, mode: 'inline', tier, heading })\n\n const relevant = tier ? skills.filter((s) => s.tier === tier) : skills\n const promptSection = renderInlineSkills({ skills, tier, heading })\n const bytes = new TextEncoder().encode(promptSection).byteLength\n const mountable = nativeSkillMountHarnesses()\n throw new Error(\n `composeSkillsForHarness: \"${harness}\" has no native skill-mount directory. ` +\n `Inlining ${relevant.length} skill(s) (${bytes} bytes) into its system prompt would silently ` +\n `convert mounted skills into prompt text — a 151,882-byte prompt shipped this way once, and ` +\n `oversized prompts degrade toward empty answers. Mount the skills instead: pick a harness with ` +\n `native skill support (${mountable.join(', ')}), or pass onNoSkillDir: 'inline' to opt in ` +\n `explicitly and accept the inlined bytes.`,\n )\n}\n\nexport type { ComposedSkills, SkillEntry } from '../skills/index'\n\n/** A file that rides BESIDE a skill entry (kit sources, references, pinned\n * requirements — anything the SKILL.md tells the agent to read or run).\n * `path` is skill-dir-relative (`kit/iso-kit.mjs`, `references/x.md`). */\nexport interface SkillSupportFile {\n path: string\n content: string\n}\n\n/** Optional naming and reconciliation policies for skill support files. */\nexport interface SkillSupportFileOptions {\n /** Resource name for newly created mounts. Defaults to `<skillId>/<path>`. */\n resourceName?: (file: SkillSupportFile) => string\n /**\n * `retain` (default) keeps identical mounts at their desired paths.\n * `replace` removes owned mounts and appends canonical mounts in file order.\n * Foreign mounts always keep their paths. On a supported harness, if they\n * occupy every desired path, `replace` leaves the original profile unchanged.\n */\n reconcileExisting?: 'retain' | 'replace'\n}\n\n/** Inline file mounts placing a skill's support files beside its entry on\n * `harness`: `<skillDir>/<skillId>/<path>`. Empty when the harness has no\n * cwd skill dir — the same posture as `resources.skills` itself (the\n * platform skips skills there too), so nothing orphan lands in a workspace\n * a harness will never read.\n *\n * This is the placement primitive for kit-carrying skills (vendored\n * executable kits, reference trees). A growing program belongs in THESE\n * mounts — never in an env var: runtimeSecrets values are capped (8192\n * chars on the sandbox SDK) and a skill tree outgrew that cap in production\n * once, taking every isolated turn down with a secret-provider refusal. */\nexport function skillSupportFileMounts(\n harness: Harness,\n skillId: string,\n files: readonly SkillSupportFile[],\n options: Pick<SkillSupportFileOptions, 'resourceName'> = {},\n): AgentProfileFileMount[] {\n const skillDir = resolveSkillDir(harness)\n if (!skillDir || files.length === 0) return []\n return files.map((file) => ({\n path: `${skillDir}/${skillId}/${file.path}`,\n resource: defineInlineResource(\n options.resourceName ? options.resourceName(file) : `${skillId}/${file.path}`,\n file.content,\n ),\n }))\n}\n\n/** Attach a skill's support files to `profile` for `harness`, idempotently.\n *\n * Replacement is by EXACT CONTENT under the skill's own subtree (any path\n * ending `/<skillId>/<path>` whose bytes match a support file of THIS call):\n * re-deriving the same profile for another harness replaces this skill's\n * own mounts wherever they previously pointed, while pack-declared files\n * with similar paths stay untouched. With no skill dir the skill's own\n * mounts are dropped (and nothing added) — mirroring how the platform\n * treats the skill entry itself on that harness. `options` can customize\n * new resource names and opt into replacing owned mounts in file order. */\nexport function withSkillSupportFiles<\n P extends { resources?: AgentProfile['resources'] },\n>(\n profile: P,\n harness: Harness,\n skillId: string,\n files: readonly SkillSupportFile[],\n options: SkillSupportFileOptions = {},\n): P {\n const hasSkillDir = resolveSkillDir(harness) !== null\n const desired = skillSupportFileMounts(harness, skillId, files, options)\n const desiredByPath = new Map(\n desired.map((mount) => [mount.path, mount.resource] as const),\n )\n const byRelPath = new Map(files.map((file) => [file.path, file.content] as const))\n const suffix = `/${skillId}/`\n const relUnderSkill = (path: string): string | null => {\n const at = path.lastIndexOf(suffix)\n return at < 0 ? null : path.slice(at + suffix.length)\n }\n // \"Ours\" = a mount under THIS skill's subtree whose bytes match a support\n // file of this call. It is STALE when the harness has no skill dir (there\n // is nowhere to place it — mirroring how the platform skips the skill\n // entry itself) or when this call would place it at a different path\n // (re-derivation for another harness). Exact-content identity only: a\n // foreign mount at one of our paths keeps the location (pack-declared\n // files win at their declared paths). By default an identical mount is\n // kept as-is; the replace policy regenerates owned mounts in file order.\n const shouldDropMount = (mount: AgentProfileFileMount): boolean => {\n if (mount.resource.kind !== 'inline') return false\n const rel = relUnderSkill(mount.path)\n if (rel === null || byRelPath.get(rel) !== mount.resource.content) return false\n if (options.reconcileExisting === 'replace') return true\n const desiredHere = desiredByPath.get(mount.path)\n return (\n !hasSkillDir ||\n desiredHere === undefined ||\n desiredHere.kind !== 'inline' ||\n desiredHere.content !== mount.resource.content\n )\n }\n const existing = profile.resources?.files ?? []\n const retained = existing.filter((mount) => !shouldDropMount(mount))\n const taken = new Set(retained.map((mount) => mount.path))\n const additions = desired.filter((mount) => !taken.has(mount.path))\n // Preserve the replace policy's no-op when foreign mounts occupy every\n // destination; without a skill dir, owned mounts are still removed.\n if (additions.length === 0 && (\n retained.length === existing.length ||\n (hasSkillDir && options.reconcileExisting === 'replace')\n )) return profile\n return {\n ...profile,\n resources: { ...(profile.resources ?? {}), files: [...retained, ...additions] },\n }\n}\n"],"mappings":";;;;;;;;;;;AAoBA;AAAA,EACE;AAAA,OAGK;AAEP,SAAS,0BAA0C;AAYnD,IAAM,iBAAsD;AAAA,EAC1D,UAAU;AAAA,EACV,eAAe;AAAA,EACf,UAAU;AAAA,EACV,aAAa;AAAA,EACb,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,UAAU;AACZ;AAMO,SAAS,gBAAgB,SAAiC;AAC/D,QAAM,UAAU,eAAe,OAAO;AACtC,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,mBAAmB,OAAO;AACnC;AAMO,SAAS,0BAA0B,WAAyC;AACjF,QAAM,OAAO,oBAAI,IAAa;AAC9B,QAAM,MAAiB,CAAC;AACxB,aAAW,WAAW,WAAW;AAC/B,QAAI,gBAAgB,OAAO,MAAM,KAAM;AACvC,QAAI,KAAK,IAAI,OAAO,EAAG;AACvB,SAAK,IAAI,OAAO;AAChB,QAAI,KAAK,OAAO;AAAA,EAClB;AACA,SAAO;AACT;AAyBA,SAAS,4BAAuC;AAC9C,SAAO,gBAAgB,OAA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@@ -0,0 +1,5 @@
1
+ import { type AppToolDefinition } from '../tools/registry';
2
+ import type { WorkProductService } from './service';
3
+ import { type WorkProductToolConfig } from './tool-config';
4
+ /** Register the incremental evidence and exception writes that accumulate a draft. */
5
+ export declare function buildDraftEmissionTools(config: WorkProductToolConfig, service: WorkProductService): AppToolDefinition[];
@@ -0,0 +1,19 @@
1
+ import type { AppToolContext } from '../tools/types';
2
+ import type { WorkProductOutcome, WorkProductService } from './service';
3
+ import { type WorkProductToolConfig } from './tool-config';
4
+ import type { WorkProductRecord } from './types';
5
+ /** Unwrap a guarded outcome, retrying ONCE on a lost race (the single
6
+ * serialized turn owner makes real contention rare; one re-read-and-retry
7
+ * absorbs the benign case). A deterministic rejection maps to a correctable
8
+ * `ToolInputError` so the model learns exactly why. */
9
+ export declare function unwrap<T>(run: () => Promise<WorkProductOutcome<T>>, code: string): Promise<T>;
10
+ export declare function requireScopeKey(args: Record<string, unknown>): string;
11
+ export declare function requireBatch(args: Record<string, unknown>, field: string): unknown[];
12
+ /**
13
+ * Resolve the scope's open draft row, creating or reopening as needed:
14
+ * an open `draft`/`blocked` row resumes; a `changes_requested` row reopens as
15
+ * the correction draft (version +1); a `ready` row refuses — the package is
16
+ * awaiting review and must receive a verdict first; otherwise a fresh draft
17
+ * is created at `last reviewed version + 1` with dispatch-stamped provenance.
18
+ */
19
+ export declare function resolveDraft(service: WorkProductService, config: WorkProductToolConfig, scopeKey: string, ctx: AppToolContext): Promise<WorkProductRecord>;
@@ -0,0 +1,160 @@
1
+ import type { AppToolContext } from '../tools/types';
2
+ import { type ConfusableTargetGroup } from './claim-support';
3
+ import type { WorkProductToolConfig } from './tool-config';
4
+ import type { EvidenceEntry } from './types';
5
+ /**
6
+ * Resolve every entry's quote against the document it names — the one place
7
+ * lineage text is decided.
8
+ *
9
+ * Two citation forms, and the asymmetry between them is the point:
10
+ *
11
+ * - `locator.span` — the model names `[start, end)` into text it just read
12
+ * and the PLATFORM slices the quote out of the source bytes. There is no
13
+ * retyping step, so a fabricated quote is not rejected, it is impossible.
14
+ * The slice REPLACES any quote the model also sent (the document is the
15
+ * authority, not the model's transcription of it) and the resolved text
16
+ * goes back in the tool result, so the model sees what was stored.
17
+ * - `locator.quote` alone — the legacy free-text form, still verified
18
+ * character-for-character. Kept because evidence written before spans
19
+ * existed, and sources reached through paths that cannot offer offsets,
20
+ * must stay expressible; a product does not lose lineage by upgrading.
21
+ *
22
+ * Entries are MUTATED in place with the resolved quote and its server-set
23
+ * `quoteBasis`, then persisted — so what a reviewer reads is what the platform
24
+ * proved, not what the model typed.
25
+ *
26
+ * Source texts are read once per distinct `sourceRef` in the batch — a
27
+ * 50-entry batch citing three documents is three reads, not fifty.
28
+ *
29
+ * Without `readSourceText` the product has given the shell no way to see its
30
+ * documents: free-text quotes go unchecked (as before — inventing a weaker
31
+ * check would report unverified lineage as verified), and a span is a LOUD
32
+ * refusal rather than a silently dropped locator, because a span the platform
33
+ * cannot slice is a wiring bug in the product, not a model mistake.
34
+ */
35
+ export declare function resolveEvidenceQuotes(config: WorkProductToolConfig, entries: readonly EvidenceEntry[], ctx: AppToolContext): Promise<void>;
36
+ /**
37
+ * Refuse any entry whose anchored text does not carry the figure it claims.
38
+ *
39
+ * This runs AFTER `resolveEvidenceQuotes`, on the text the platform decided,
40
+ * and it is deliberately independent of how that text was anchored. `find`
41
+ * makes a mis-addressed citation unlikely — the platform locates the line — but
42
+ * `span` still accepts offsets a caller computed, and this is what "accepted
43
+ * only when they independently verify" means concretely: the slice has to
44
+ * contain the value.
45
+ *
46
+ * Row `7256ef49` is the case. Four span citations, every quote a real slice of
47
+ * the right document, every one ~200 characters above the figure it claimed.
48
+ * `resolveEvidenceQuotes` passed all four; nothing else here would have caught
49
+ * them; a reviewer would have read four authoritative-looking citations
50
+ * supporting nothing.
51
+ *
52
+ * Rejection is a `ToolInputError` so it folds back to the model mid-turn, the
53
+ * same posture a non-occurring quote already gets, and the message names both
54
+ * ways out — cite the value, or drop the locator because the figure was
55
+ * computed. An unsatisfiable gate does not stop a bad submit, it selects for
56
+ * one, so naming the second exit is load-bearing rather than politeness.
57
+ */
58
+ export declare function assertClaimsSupported(config: WorkProductToolConfig, entries: readonly EvidenceEntry[]): void;
59
+ /**
60
+ * Refuse any entry whose cited line belongs to a sibling target.
61
+ *
62
+ * The fifth degree of freedom, and the one the four gates before it pass by
63
+ * construction: `quote_verification` proves the text is in the document,
64
+ * `claim_support` proves the text carries the claimed figure, and neither
65
+ * asks whether the figure belongs on THIS line. Row `95105c8a` shipped
66
+ * `evidence_coverage 6/6`, `claim_support 19/19`, `quote_verification 19/19`
67
+ * with `line_3a` (qualified dividends) pointing at the ordinary-dividends line
68
+ * and `line_3b` pointing at the qualified one.
69
+ *
70
+ * The product supplies which targets are confusable and what their lines say;
71
+ * the shell only compares. Refusal requires the document to positively name a
72
+ * sibling, so silence passes — see `./claim-support` for why that asymmetry is
73
+ * load-bearing rather than lenient.
74
+ */
75
+ export declare function assertTargetsNotCrossed(config: WorkProductToolConfig, entries: readonly EvidenceEntry[]): void;
76
+ /** Re-verify every persisted quote at submit time. The upsert gate stops new
77
+ * fabrication; this stops a package whose evidence was written BEFORE the
78
+ * gate existed (or under a since-corrected document) from reaching a
79
+ * reviewer. Entries with no quote are neither verified nor failures — they
80
+ * are lineage with no click target, counted separately so the recorded check
81
+ * states how much of the package is quote-backed.
82
+ *
83
+ * A span-anchored entry is re-checked by RE-SLICING the current document and
84
+ * comparing to the stored text, not by substring search. The difference
85
+ * matters exactly when a source has been replaced since the citation was
86
+ * written: a substring search would still pass if the sentence survived
87
+ * anywhere in the new file, while the reviewer's click target has silently
88
+ * moved. Re-slicing says the offsets still select the same characters. */
89
+ export declare function summarizeQuoteVerification(config: WorkProductToolConfig, evidence: readonly EvidenceEntry[], ctx: AppToolContext): Promise<{
90
+ verified: number;
91
+ spanAnchored: number;
92
+ withoutQuote: number;
93
+ failed: string[];
94
+ } | undefined>;
95
+ /**
96
+ * Re-run claim support over every PERSISTED entry at submit time.
97
+ *
98
+ * Unlike `summarizeQuoteVerification` this needs no `readSourceText`: the
99
+ * question is whether the stored quote carries the stored claim, and both are
100
+ * on the row. So it runs for every product, including one that cannot read its
101
+ * sources back — and it is the check that catches a package whose evidence was
102
+ * written before this gate existed. Row `7256ef49` is exactly that package.
103
+ */
104
+ export declare function summarizeClaimSupport(evidence: readonly EvidenceEntry[]): {
105
+ supported: number;
106
+ checkable: number;
107
+ unsupported: string[];
108
+ };
109
+ /**
110
+ * Re-run target correctness over every PERSISTED entry at submit time — the
111
+ * check that catches a package whose evidence was written before this gate
112
+ * existed. Like `summarizeClaimSupport` it reads only the row (the stored quote
113
+ * and the stored target), so it runs for every product.
114
+ */
115
+ export declare function summarizeTargetCorrectness(evidence: readonly EvidenceEntry[], groups: readonly ConfusableTargetGroup[], targetOf: (entry: EvidenceEntry) => string): {
116
+ correct: number;
117
+ checkable: number;
118
+ crossed: {
119
+ id: string;
120
+ detail: string;
121
+ }[];
122
+ };
123
+ /**
124
+ * Run artifact agreement over every PERSISTED entry against the artifact being
125
+ * submitted — the ONLY place it runs, and the "only" is load-bearing.
126
+ *
127
+ * The obvious second placement is the upsert, for the early feedback, and it
128
+ * makes the gate unsatisfiable on the one path that needs it most. A
129
+ * `changes_requested` row keeps the artifact the reviewer REJECTED, and an
130
+ * agent correcting a crossed package has exactly one order available to it:
131
+ * fix the evidence, then submit the corrected artifact, because the artifact
132
+ * is only settable at submit. Comparing the incoming citation to that stale
133
+ * artifact refuses precisely the correction being asked for —
134
+ *
135
+ * artifact (rejected): line_3a = 2204.18, line_3b = 1955.02
136
+ * agent re-emits: line_3a <- 1955.02 <- the fix
137
+ * stale comparison: "1955.02 is line_3b's value" -> refused, forever
138
+ *
139
+ * so the package can never be repaired. Same failure mode as a coverage gate
140
+ * demanding lineage for a computed value, removed for the same reason: an
141
+ * unsatisfiable rule does not stop bad work, it selects for invented work.
142
+ * Here both halves are current and either can be corrected during the turn.
143
+ *
144
+ * Nothing is lost by waiting. Row `95105c8a` is caught here and could only ever
145
+ * have been caught here — its crossed evidence was written turns before there
146
+ * was an artifact to compare it to.
147
+ *
148
+ * Only a real CONTRADICTION is refused: the claim asserts a figure the same
149
+ * artifact reports on another target. A component of an aggregate is not one
150
+ * (row `a68b1943` evidences a 189,750.00 wage line with two W-2s of 128,450.00
151
+ * and 61,300.00, and must keep doing so).
152
+ */
153
+ export declare function summarizeArtifactAgreement(evidence: readonly EvidenceEntry[], fieldValues: ReadonlyMap<string, string>, targetOf: (entry: EvidenceEntry) => string): {
154
+ agreeing: number;
155
+ checkable: number;
156
+ contradicting: {
157
+ id: string;
158
+ detail: string;
159
+ }[];
160
+ };
@@ -431,6 +431,60 @@ function workProductTrustInputs(records, verdictsFor) {
431
431
  return items;
432
432
  }
433
433
 
434
+ // src/work-product/tool-config.ts
435
+ var MAX_WORK_PRODUCT_BATCH = 50;
436
+ var EVIDENCE_COVERAGE_CHECK = "evidence_coverage";
437
+ var QUOTE_VERIFICATION_CHECK = "quote_verification";
438
+ var CLAIM_SUPPORT_CHECK = "claim_support";
439
+ var TARGET_CORRECTNESS_CHECK = "target_correctness";
440
+ var ARTIFACT_AGREEMENT_CHECK = "artifact_agreement";
441
+
442
+ // src/work-product/draft-tool-context.ts
443
+ async function unwrap(run, code) {
444
+ let outcome = await run();
445
+ if (!outcome.succeeded && outcome.conflict) outcome = await run();
446
+ if (!outcome.succeeded) throw new ToolInputError(code, outcome.error, outcome.conflict ? 409 : 400);
447
+ return outcome.value;
448
+ }
449
+ function requireScopeKey(args) {
450
+ const scopeKey = typeof args.scopeKey === "string" ? args.scopeKey.trim() : "";
451
+ if (!scopeKey) throw new ToolInputError("missing_scope_key", "scopeKey is required \u2014 the engagement key this work product belongs to.");
452
+ return scopeKey;
453
+ }
454
+ function requireBatch(args, field) {
455
+ const raw = args[field];
456
+ if (!Array.isArray(raw) || raw.length === 0) {
457
+ throw new ToolInputError("missing_entries", `${field} must be a non-empty array.`);
458
+ }
459
+ if (raw.length > MAX_WORK_PRODUCT_BATCH) {
460
+ throw new ToolInputError("batch_too_large", `${field} accepts at most ${MAX_WORK_PRODUCT_BATCH} entries per call \u2014 send smaller batches.`);
461
+ }
462
+ return raw;
463
+ }
464
+ async function resolveDraft(service, config, scopeKey, ctx) {
465
+ const open = await service.openDraft(ctx.workspaceId, scopeKey);
466
+ if (open) return open;
467
+ const awaitingReview = await service.awaitingReview(ctx.workspaceId, scopeKey);
468
+ if (awaitingReview) {
469
+ throw new ToolInputError(
470
+ "awaiting_review",
471
+ `Work product for ${scopeKey} (v${awaitingReview.version}) is awaiting review \u2014 no further emission until a reviewer verdict.`,
472
+ 409
473
+ );
474
+ }
475
+ const awaitingCorrection = await service.awaitingCorrection(ctx.workspaceId, scopeKey);
476
+ if (awaitingCorrection) {
477
+ return unwrap(() => service.reopen(awaitingCorrection.id), "reopen_failed");
478
+ }
479
+ return service.create({
480
+ workspaceId: ctx.workspaceId,
481
+ threadId: ctx.threadId,
482
+ scopeKey,
483
+ version: await service.nextVersion(ctx.workspaceId, scopeKey),
484
+ provenance: stampProvenance(config.provenance(ctx), config.now)
485
+ });
486
+ }
487
+
434
488
  // src/work-product/quote.ts
435
489
  var WHITESPACE = /[\s\p{Zs}\u2028\u2029\u200b-\u200d\ufeff]+/gu;
436
490
  var DASHES = /[\u2010-\u2015\u2212\ufe58\ufe63\uff0d]/gu;
@@ -518,57 +572,7 @@ function sliceSourceSpan(sourceText, span) {
518
572
  return { ok: true, quote };
519
573
  }
520
574
 
521
- // src/work-product/tools.ts
522
- var MAX_WORK_PRODUCT_BATCH = 50;
523
- var EVIDENCE_COVERAGE_CHECK = "evidence_coverage";
524
- var QUOTE_VERIFICATION_CHECK = "quote_verification";
525
- var CLAIM_SUPPORT_CHECK = "claim_support";
526
- var TARGET_CORRECTNESS_CHECK = "target_correctness";
527
- var ARTIFACT_AGREEMENT_CHECK = "artifact_agreement";
528
- async function unwrap(run, code) {
529
- let outcome = await run();
530
- if (!outcome.succeeded && outcome.conflict) outcome = await run();
531
- if (!outcome.succeeded) throw new ToolInputError(code, outcome.error, outcome.conflict ? 409 : 400);
532
- return outcome.value;
533
- }
534
- function requireScopeKey(args) {
535
- const scopeKey = typeof args.scopeKey === "string" ? args.scopeKey.trim() : "";
536
- if (!scopeKey) throw new ToolInputError("missing_scope_key", "scopeKey is required \u2014 the engagement key this work product belongs to.");
537
- return scopeKey;
538
- }
539
- function requireBatch(args, field) {
540
- const raw = args[field];
541
- if (!Array.isArray(raw) || raw.length === 0) {
542
- throw new ToolInputError("missing_entries", `${field} must be a non-empty array.`);
543
- }
544
- if (raw.length > MAX_WORK_PRODUCT_BATCH) {
545
- throw new ToolInputError("batch_too_large", `${field} accepts at most ${MAX_WORK_PRODUCT_BATCH} entries per call \u2014 send smaller batches.`);
546
- }
547
- return raw;
548
- }
549
- async function resolveDraft(service, config, scopeKey, ctx) {
550
- const open = await service.openDraft(ctx.workspaceId, scopeKey);
551
- if (open) return open;
552
- const awaitingReview = await service.awaitingReview(ctx.workspaceId, scopeKey);
553
- if (awaitingReview) {
554
- throw new ToolInputError(
555
- "awaiting_review",
556
- `Work product for ${scopeKey} (v${awaitingReview.version}) is awaiting review \u2014 no further emission until a reviewer verdict.`,
557
- 409
558
- );
559
- }
560
- const awaitingCorrection = await service.awaitingCorrection(ctx.workspaceId, scopeKey);
561
- if (awaitingCorrection) {
562
- return unwrap(() => service.reopen(awaitingCorrection.id), "reopen_failed");
563
- }
564
- return service.create({
565
- workspaceId: ctx.workspaceId,
566
- threadId: ctx.threadId,
567
- scopeKey,
568
- version: await service.nextVersion(ctx.workspaceId, scopeKey),
569
- provenance: stampProvenance(config.provenance(ctx), config.now)
570
- });
571
- }
575
+ // src/work-product/evidence-verification.ts
572
576
  function spanErrorDetail(failure) {
573
577
  switch (failure.reason) {
574
578
  case "not_integer":
@@ -788,12 +792,9 @@ function summarizeArtifactAgreement(evidence, fieldValues, targetOf) {
788
792
  }
789
793
  return { agreeing, checkable, contradicting };
790
794
  }
791
- function buildWorkProductTools(config) {
792
- const service = createWorkProductService({
793
- store: config.store,
794
- ...config.now ? { now: config.now } : {},
795
- ...config.generateId ? { generateId: config.generateId } : {}
796
- });
795
+
796
+ // src/work-product/draft-emission-tools.ts
797
+ function buildDraftEmissionTools(config, service) {
797
798
  const canResolveTextLocators = config.readSourceText !== void 0;
798
799
  const locatorProperties = {
799
800
  page: { type: "number" },
@@ -950,7 +951,12 @@ function buildWorkProductTools(config) {
950
951
  };
951
952
  }
952
953
  });
953
- const submitWorkProduct = defineAppTool({
954
+ return [upsertEvidence, flagException];
955
+ }
956
+
957
+ // src/work-product/submission-tool.ts
958
+ function buildSubmissionTool(config, service) {
959
+ return defineAppTool({
954
960
  name: "submit_work_product",
955
961
  description: "Submit the finished work product for professional review \u2014 the terminal call after evidence and exceptions are recorded. Refused while a blocking exception is unresolved, or when a material target lacks evidence. Include your own quality checks in `checks`.",
956
962
  parameters: {
@@ -1144,7 +1150,16 @@ function buildWorkProductTools(config) {
1144
1150
  };
1145
1151
  }
1146
1152
  });
1147
- return [upsertEvidence, flagException, submitWorkProduct];
1153
+ }
1154
+
1155
+ // src/work-product/tools.ts
1156
+ function buildWorkProductTools(config) {
1157
+ const service = createWorkProductService({
1158
+ store: config.store,
1159
+ ...config.now ? { now: config.now } : {},
1160
+ ...config.generateId ? { generateId: config.generateId } : {}
1161
+ });
1162
+ return [...buildDraftEmissionTools(config, service), buildSubmissionTool(config, service)];
1148
1163
  }
1149
1164
 
1150
1165
  // src/work-product/route.ts