@tangle-network/agent-app 0.63.44 → 0.63.45

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.
Files changed (51) hide show
  1. package/dist/{DesignCanvas-VKZ7Y3JU.js → DesignCanvas-Q65UV4D5.js} +3 -2
  2. package/dist/{DesignCanvasEditor-3V53YLLZ.js → DesignCanvasEditor-THEFESEX.js} +3 -2
  3. package/dist/app-auth/index.js +2 -1
  4. package/dist/app-auth/index.js.map +1 -1
  5. package/dist/chat-routes/index.js +9 -7
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/{chunk-ZGGEYYEQ.js → chunk-4E2MUVGL.js} +3 -3
  8. package/dist/chunk-5VE4IDSU.js +75 -0
  9. package/dist/chunk-5VE4IDSU.js.map +1 -0
  10. package/dist/{chunk-CTREXL3O.js → chunk-67CSI5PU.js} +2 -65
  11. package/dist/chunk-67CSI5PU.js.map +1 -0
  12. package/dist/{chunk-DPTNKH22.js → chunk-H6BRJU5M.js} +1 -73
  13. package/dist/chunk-H6BRJU5M.js.map +1 -0
  14. package/dist/chunk-INW4FSID.js +66 -0
  15. package/dist/chunk-INW4FSID.js.map +1 -0
  16. package/dist/{chunk-RZMQ2J5P.js → chunk-L63GYPYY.js} +3 -3
  17. package/dist/{chunk-XTQLZG6M.js → chunk-YQUZQHAD.js} +2 -2
  18. package/dist/design-canvas/index.js +2 -1
  19. package/dist/design-canvas/index.js.map +1 -1
  20. package/dist/design-canvas-react/engine.js +2 -1
  21. package/dist/design-canvas-react/index.js +3 -2
  22. package/dist/design-canvas-react/index.js.map +1 -1
  23. package/dist/design-canvas-react/lazy.js +1 -1
  24. package/dist/platform/index.js +2 -1
  25. package/dist/platform/index.js.map +1 -1
  26. package/dist/public-consultation/index.js +6 -4
  27. package/dist/public-consultation/index.js.map +1 -1
  28. package/dist/sandbox/index.js +7 -5
  29. package/dist/sequences/index.js +2 -1
  30. package/dist/sequences/index.js.map +1 -1
  31. package/dist/skills-placement/box.js +4 -2
  32. package/dist/skills-placement/box.js.map +1 -1
  33. package/dist/vault/store/box-state.d.ts +125 -0
  34. package/dist/vault/store/coordinator.d.ts +9 -1
  35. package/dist/vault/store/index.d.ts +4 -0
  36. package/dist/vault/store/index.js +1227 -4
  37. package/dist/vault/store/index.js.map +1 -1
  38. package/dist/vault/store/sandbox-engine.d.ts +19 -0
  39. package/dist/vault/store/sandbox-hydrate.d.ts +59 -0
  40. package/dist/vault/store/sandbox-reconcile.d.ts +55 -0
  41. package/dist/vault/store/sandbox-sync.d.ts +37 -1
  42. package/dist/vault/store/store.d.ts +10 -1
  43. package/dist/web/index.js +7 -5
  44. package/package.json +1 -1
  45. package/dist/chunk-CTREXL3O.js.map +0 -1
  46. package/dist/chunk-DPTNKH22.js.map +0 -1
  47. /package/dist/{DesignCanvas-VKZ7Y3JU.js.map → DesignCanvas-Q65UV4D5.js.map} +0 -0
  48. /package/dist/{DesignCanvasEditor-3V53YLLZ.js.map → DesignCanvasEditor-THEFESEX.js.map} +0 -0
  49. /package/dist/{chunk-ZGGEYYEQ.js.map → chunk-4E2MUVGL.js.map} +0 -0
  50. /package/dist/{chunk-RZMQ2J5P.js.map → chunk-L63GYPYY.js.map} +0 -0
  51. /package/dist/{chunk-XTQLZG6M.js.map → chunk-YQUZQHAD.js.map} +0 -0
@@ -4,10 +4,12 @@ import {
4
4
  import "../chunk-76MPX7JQ.js";
5
5
  import "../chunk-PV33JZKV.js";
6
6
  import {
7
- shellQuote,
8
7
  writeProfileFilesToBox
9
- } from "../chunk-CTREXL3O.js";
8
+ } from "../chunk-67CSI5PU.js";
10
9
  import "../chunk-ELX5YITO.js";
10
+ import {
11
+ shellQuote
12
+ } from "../chunk-INW4FSID.js";
11
13
  import {
12
14
  sha256Hex
13
15
  } from "../chunk-HY57QRRW.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/skills-placement/box.ts"],"sourcesContent":["/**\n * Delivery of a profile's declared skill corpus onto a running box.\n *\n * The platform materializer is add-or-skip-identical only: it refuses to\n * replace a `SKILL.md` whose content changed and never removes a skill dropped\n * from a later selection. Products edit skill bodies on deploy while boxes live\n * for hours, so this reconcile supplies replace-on-change and prune-on-removal,\n * keyed on a content manifest on the box so an unchanged corpus transfers no\n * bodies. `resolveSkillDir` decides the directory; no path literal lives here.\n *\n * The SDK file API replaces complete files, so identical concurrent reconciles\n * converge without a lock; a concurrent stale delete may return not found.\n */\nimport type { AgentProfileFileMount, AgentProfileResourceRef } from '@tangle-network/agent-interface'\nimport { NotFoundError, type SandboxInstance } from '@tangle-network/sandbox'\nimport type { Harness } from '../harness/index'\nimport type { Outcome } from '../sandbox/outcome'\nimport { writeProfileFilesToBox } from '../sandbox/profile-files'\nimport { shellQuote } from '../sandbox/binary-read'\nimport { resolveSkillDir } from './index'\nimport { sha256Hex } from '../crypto/digest'\n\ninterface DeclaredSkill {\n id: string\n content: string\n}\n\ninterface SkillCorpusManifest {\n schema: string\n hash: string\n ids: string[]\n}\n\nconst SKILL_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\nconst PLACED_CORPORA_LIMIT = 512\n\nexport interface ProfileSkillPlacerConfig {\n /** Manifest schema id written on the box, e.g. `acme-skill-corpus-v1`.\n * Changing it makes every box re-place its corpus once. */\n manifestSchema: string\n /** Home-relative directory holding one manifest per harness, e.g. `~/.tangle/acme-skill-corpora`. */\n manifestDir: string\n /** Resource name prefix for the manifest file mount, e.g. `acme` gives `<harness>-acme-skill-manifest`. */\n manifestName: string\n /**\n * The box filesystem's identity, when the product can read it. With it, a\n * corpus this isolate already placed on the same filesystem skips the\n * on-box manifest read entirely; a replaced filesystem has a new id, so its\n * receipt never matches. Return null when the filesystem is not identified.\n */\n filesystemIncarnation?: (box: SandboxInstance) => string | null\n /**\n * Serialize placement on the box with a `mkdir` lock beside the manifest\n * (30 s wait, a lock older than 2 minutes is reclaimed). Without it, two\n * isolates placing different corpora at once (a rolling deploy) can leave a\n * manifest that names a skill the other one pruned.\n */\n boxLock?: boolean\n}\n\nfunction homeRelative(path: string): string {\n if (!path.startsWith('~/')) throw new Error(`Expected a home-relative path, got ${path}`)\n return path.slice(2)\n}\n\nfunction shellHomePath(path: string): string {\n return `~/${shellQuote(homeRelative(path))}`\n}\n\nasync function acquireBoxLock(box: SandboxInstance, manifestDir: string, lockPath: string): Promise<Outcome<void>> {\n const command = [\n `mkdir -p ${shellHomePath(manifestDir)}`,\n `lock=${shellHomePath(lockPath)}`,\n 'deadline=$(( $(date +%s) + 30 ))',\n 'while ! mkdir \"$lock\" 2>/dev/null; do',\n ' now=$(date +%s)',\n ' if [ -n \"$(find \"$lock\" -maxdepth 0 -mmin +2 -print 2>/dev/null)\" ]; then rm -rf \"$lock\"; continue; fi',\n ' if [ \"$now\" -ge \"$deadline\" ]; then echo \"timed out waiting for skill placement lock\" >&2; exit 42; fi',\n ' sleep 0.1',\n 'done',\n ].join('\\n')\n try {\n const acquired = await box.exec(command)\n if (acquired.exitCode === 0) return { succeeded: true, value: undefined }\n return { succeeded: false, error: new Error(`placeProfileSkillsOnBox: ${acquired.stderr || 'failed to acquire skill placement lock'}`) }\n } catch (error) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: failed to acquire the skill placement lock', { cause: error }) }\n }\n}\n\nasync function releaseBoxLock(box: SandboxInstance, lockPath: string): Promise<Outcome<void>> {\n try {\n const released = await box.exec(`rm -rf ${shellHomePath(lockPath)}`)\n if (released.exitCode === 0) return { succeeded: true, value: undefined }\n return { succeeded: false, error: new Error(`placeProfileSkillsOnBox: failed to release skill placement lock: ${released.stderr}`) }\n } catch (error) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: failed to release the skill placement lock', { cause: error }) }\n }\n}\n\n/** `null` when any ref is not an inline body: a github ref needs async\n * pre-resolution, which the platform materializer also refuses. */\nfunction declaredSkills(refs: readonly AgentProfileResourceRef[]): DeclaredSkill[] | null {\n const skills: DeclaredSkill[] = []\n for (const ref of refs) {\n if (ref.kind !== 'inline') return null\n skills.push({ id: ref.name, content: ref.content })\n }\n return skills\n}\n\nfunction skillFileMounts(root: string, skills: readonly DeclaredSkill[]): AgentProfileFileMount[] {\n return skills.map((skill) => ({\n path: `~/${root}/${skill.id}/SKILL.md`,\n resource: { kind: 'inline' as const, name: skill.id, content: skill.content },\n }))\n}\n\n/**\n * Build the product's skill placer. `placeProfileSkillsOnBox` makes the box's\n * skill directory for a harness match the declared corpus exactly: every\n * declared body present, every previously placed body no longer declared\n * removed. Empty `refs`, or a harness with no skill directory, is a no-op.\n */\nexport function createProfileSkillPlacer(config: ProfileSkillPlacerConfig) {\n const { manifestSchema, manifestDir, manifestName, filesystemIncarnation, boxLock = false } = config\n\n // Corpora this isolate placed or verified, by box, filesystem and harness. Digests only.\n const placedCorpora = new Map<string, string>()\n // A composed corpus is one cached array per harness, so its digest is too.\n const corpusManifests = new WeakMap<readonly AgentProfileResourceRef[], Promise<SkillCorpusManifest>>()\n\n async function skillManifest(skills: readonly DeclaredSkill[]): Promise<SkillCorpusManifest> {\n const normalized = [...skills].sort((a, b) => a.id.localeCompare(b.id))\n return {\n schema: manifestSchema,\n hash: await sha256Hex(JSON.stringify(normalized)),\n ids: normalized.map((skill) => skill.id),\n }\n }\n\n function corpusManifest(refs: readonly AgentProfileResourceRef[], skills: readonly DeclaredSkill[]) {\n let manifest = corpusManifests.get(refs)\n if (!manifest) {\n manifest = skillManifest(skills)\n manifest.catch(() => corpusManifests.delete(refs))\n corpusManifests.set(refs, manifest)\n }\n return manifest\n }\n\n function parseSkillManifest(raw: string): SkillCorpusManifest | null {\n try {\n const value = JSON.parse(raw) as Partial<SkillCorpusManifest>\n if (value.schema !== manifestSchema || typeof value.hash !== 'string') return null\n if (!Array.isArray(value.ids) || value.ids.some((id) => typeof id !== 'string' || !SKILL_ID_RE.test(id))) return null\n return { schema: manifestSchema, hash: value.hash, ids: value.ids }\n } catch {\n return null\n }\n }\n\n function receiptKey(box: SandboxInstance, harness: Harness): string | null {\n const incarnation = filesystemIncarnation?.(box)\n return box.id && incarnation ? `${box.id}\\0${incarnation}\\0${harness}` : null\n }\n\n function recordPlacement(key: string | null, hash: string): void {\n if (!key) return\n if (placedCorpora.size >= PLACED_CORPORA_LIMIT) placedCorpora.clear()\n placedCorpora.set(key, hash)\n }\n\n async function placeSkills(\n box: SandboxInstance,\n harness: Harness,\n root: string,\n skills: readonly DeclaredSkill[],\n expected: SkillCorpusManifest,\n ): Promise<Outcome<void>> {\n const markerPath = `${manifestDir}/${harness}.json`\n let current: SkillCorpusManifest | null = null\n try {\n current = parseSkillManifest(await box.fs.read(homeRelative(markerPath)))\n } catch (err) {\n if (!(err instanceof NotFoundError)) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to read the sandbox skill manifest', { cause: err }),\n }\n }\n }\n if (current?.hash === expected.hash) return { succeeded: true, value: undefined }\n\n const written = await writeProfileFilesToBox(box, skillFileMounts(root, skills))\n if (!written.succeeded) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to write the sandbox skill corpus', { cause: written.error }),\n }\n }\n\n const expectedIds = new Set(expected.ids)\n for (const id of (current?.ids ?? []).filter((id) => !expectedIds.has(id))) {\n try {\n await box.fs.delete(homeRelative(`~/${root}/${id}`), { recursive: true })\n } catch (err) {\n // Another identical reconcile may have removed it first; any other failure stays visible.\n if (err instanceof NotFoundError) continue\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: stale skill cleanup failed', { cause: err }),\n }\n }\n }\n\n const manifestWritten = await writeProfileFilesToBox(box, [{\n path: markerPath,\n resource: { kind: 'inline', name: `${harness}-${manifestName}-skill-manifest`, content: JSON.stringify(expected) },\n }])\n if (!manifestWritten.succeeded) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to write the sandbox skill manifest', { cause: manifestWritten.error }),\n }\n }\n return { succeeded: true, value: undefined }\n }\n\n async function placeProfileSkillsOnBox(\n box: SandboxInstance,\n harness: Harness,\n refs: readonly AgentProfileResourceRef[],\n ): Promise<Outcome<void>> {\n const root = resolveSkillDir(harness)\n if (!root || refs.length === 0) return { succeeded: true, value: undefined }\n\n const skills = declaredSkills(refs)\n if (!skills) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: every declared skill ref must be an inline body') }\n }\n const ids = skills.map((skill) => skill.id)\n if (ids.some((id) => !SKILL_ID_RE.test(id)) || new Set(ids).size !== ids.length) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: skill ids must be unique path-safe slugs') }\n }\n\n let expected: SkillCorpusManifest\n try {\n expected = await corpusManifest(refs, skills)\n } catch (err) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to hash the declared skill corpus', { cause: err }),\n }\n }\n\n const key = receiptKey(box, harness)\n if (key && placedCorpora.get(key) === expected.hash) return { succeeded: true, value: undefined }\n if (!boxLock) {\n const placed = await placeSkills(box, harness, root, skills, expected)\n if (placed.succeeded) recordPlacement(key, expected.hash)\n return placed\n }\n const lockPath = `${manifestDir}/${harness}.json.lock`\n const acquired = await acquireBoxLock(box, manifestDir, lockPath)\n if (!acquired.succeeded) return acquired\n const placed = await placeSkills(box, harness, root, skills, expected)\n const released = await releaseBoxLock(box, lockPath)\n if (placed.succeeded && released.succeeded) recordPlacement(key, expected.hash)\n return released.succeeded ? placed : released\n }\n\n /** Whether two skill declarations carry the same inline corpus. */\n async function sameSkillCorpus(\n left: readonly AgentProfileResourceRef[] | undefined,\n right: readonly AgentProfileResourceRef[],\n ): Promise<boolean> {\n if (!left) return right.length === 0\n if (left === right) return true\n const leftSkills = declaredSkills(left)\n const rightSkills = declaredSkills(right)\n if (!leftSkills || !rightSkills) return false\n const [a, b] = await Promise.all([corpusManifest(left, leftSkills), corpusManifest(right, rightSkills)])\n return a.hash === b.hash\n }\n\n return { placeProfileSkillsOnBox, sameSkillCorpus }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAS,qBAA2C;AAmBpD,IAAM,cAAc;AACpB,IAAM,uBAAuB;AA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,CAAC;AACvG,WAAO,EAAE,SAAS,EAAE;AAAA,EACtB;AAEA,SAAO,EAAE,yBAAyB,gBAAgB;AACpD;","names":["id","placed"]}
1
+ {"version":3,"sources":["../../src/skills-placement/box.ts"],"sourcesContent":["/**\n * Delivery of a profile's declared skill corpus onto a running box.\n *\n * The platform materializer is add-or-skip-identical only: it refuses to\n * replace a `SKILL.md` whose content changed and never removes a skill dropped\n * from a later selection. Products edit skill bodies on deploy while boxes live\n * for hours, so this reconcile supplies replace-on-change and prune-on-removal,\n * keyed on a content manifest on the box so an unchanged corpus transfers no\n * bodies. `resolveSkillDir` decides the directory; no path literal lives here.\n *\n * The SDK file API replaces complete files, so identical concurrent reconciles\n * converge without a lock; a concurrent stale delete may return not found.\n */\nimport type { AgentProfileFileMount, AgentProfileResourceRef } from '@tangle-network/agent-interface'\nimport { NotFoundError, type SandboxInstance } from '@tangle-network/sandbox'\nimport type { Harness } from '../harness/index'\nimport type { Outcome } from '../sandbox/outcome'\nimport { writeProfileFilesToBox } from '../sandbox/profile-files'\nimport { shellQuote } from '../sandbox/binary-read'\nimport { resolveSkillDir } from './index'\nimport { sha256Hex } from '../crypto/digest'\n\ninterface DeclaredSkill {\n id: string\n content: string\n}\n\ninterface SkillCorpusManifest {\n schema: string\n hash: string\n ids: string[]\n}\n\nconst SKILL_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\nconst PLACED_CORPORA_LIMIT = 512\n\nexport interface ProfileSkillPlacerConfig {\n /** Manifest schema id written on the box, e.g. `acme-skill-corpus-v1`.\n * Changing it makes every box re-place its corpus once. */\n manifestSchema: string\n /** Home-relative directory holding one manifest per harness, e.g. `~/.tangle/acme-skill-corpora`. */\n manifestDir: string\n /** Resource name prefix for the manifest file mount, e.g. `acme` gives `<harness>-acme-skill-manifest`. */\n manifestName: string\n /**\n * The box filesystem's identity, when the product can read it. With it, a\n * corpus this isolate already placed on the same filesystem skips the\n * on-box manifest read entirely; a replaced filesystem has a new id, so its\n * receipt never matches. Return null when the filesystem is not identified.\n */\n filesystemIncarnation?: (box: SandboxInstance) => string | null\n /**\n * Serialize placement on the box with a `mkdir` lock beside the manifest\n * (30 s wait, a lock older than 2 minutes is reclaimed). Without it, two\n * isolates placing different corpora at once (a rolling deploy) can leave a\n * manifest that names a skill the other one pruned.\n */\n boxLock?: boolean\n}\n\nfunction homeRelative(path: string): string {\n if (!path.startsWith('~/')) throw new Error(`Expected a home-relative path, got ${path}`)\n return path.slice(2)\n}\n\nfunction shellHomePath(path: string): string {\n return `~/${shellQuote(homeRelative(path))}`\n}\n\nasync function acquireBoxLock(box: SandboxInstance, manifestDir: string, lockPath: string): Promise<Outcome<void>> {\n const command = [\n `mkdir -p ${shellHomePath(manifestDir)}`,\n `lock=${shellHomePath(lockPath)}`,\n 'deadline=$(( $(date +%s) + 30 ))',\n 'while ! mkdir \"$lock\" 2>/dev/null; do',\n ' now=$(date +%s)',\n ' if [ -n \"$(find \"$lock\" -maxdepth 0 -mmin +2 -print 2>/dev/null)\" ]; then rm -rf \"$lock\"; continue; fi',\n ' if [ \"$now\" -ge \"$deadline\" ]; then echo \"timed out waiting for skill placement lock\" >&2; exit 42; fi',\n ' sleep 0.1',\n 'done',\n ].join('\\n')\n try {\n const acquired = await box.exec(command)\n if (acquired.exitCode === 0) return { succeeded: true, value: undefined }\n return { succeeded: false, error: new Error(`placeProfileSkillsOnBox: ${acquired.stderr || 'failed to acquire skill placement lock'}`) }\n } catch (error) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: failed to acquire the skill placement lock', { cause: error }) }\n }\n}\n\nasync function releaseBoxLock(box: SandboxInstance, lockPath: string): Promise<Outcome<void>> {\n try {\n const released = await box.exec(`rm -rf ${shellHomePath(lockPath)}`)\n if (released.exitCode === 0) return { succeeded: true, value: undefined }\n return { succeeded: false, error: new Error(`placeProfileSkillsOnBox: failed to release skill placement lock: ${released.stderr}`) }\n } catch (error) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: failed to release the skill placement lock', { cause: error }) }\n }\n}\n\n/** `null` when any ref is not an inline body: a github ref needs async\n * pre-resolution, which the platform materializer also refuses. */\nfunction declaredSkills(refs: readonly AgentProfileResourceRef[]): DeclaredSkill[] | null {\n const skills: DeclaredSkill[] = []\n for (const ref of refs) {\n if (ref.kind !== 'inline') return null\n skills.push({ id: ref.name, content: ref.content })\n }\n return skills\n}\n\nfunction skillFileMounts(root: string, skills: readonly DeclaredSkill[]): AgentProfileFileMount[] {\n return skills.map((skill) => ({\n path: `~/${root}/${skill.id}/SKILL.md`,\n resource: { kind: 'inline' as const, name: skill.id, content: skill.content },\n }))\n}\n\n/**\n * Build the product's skill placer. `placeProfileSkillsOnBox` makes the box's\n * skill directory for a harness match the declared corpus exactly: every\n * declared body present, every previously placed body no longer declared\n * removed. Empty `refs`, or a harness with no skill directory, is a no-op.\n */\nexport function createProfileSkillPlacer(config: ProfileSkillPlacerConfig) {\n const { manifestSchema, manifestDir, manifestName, filesystemIncarnation, boxLock = false } = config\n\n // Corpora this isolate placed or verified, by box, filesystem and harness. Digests only.\n const placedCorpora = new Map<string, string>()\n // A composed corpus is one cached array per harness, so its digest is too.\n const corpusManifests = new WeakMap<readonly AgentProfileResourceRef[], Promise<SkillCorpusManifest>>()\n\n async function skillManifest(skills: readonly DeclaredSkill[]): Promise<SkillCorpusManifest> {\n const normalized = [...skills].sort((a, b) => a.id.localeCompare(b.id))\n return {\n schema: manifestSchema,\n hash: await sha256Hex(JSON.stringify(normalized)),\n ids: normalized.map((skill) => skill.id),\n }\n }\n\n function corpusManifest(refs: readonly AgentProfileResourceRef[], skills: readonly DeclaredSkill[]) {\n let manifest = corpusManifests.get(refs)\n if (!manifest) {\n manifest = skillManifest(skills)\n manifest.catch(() => corpusManifests.delete(refs))\n corpusManifests.set(refs, manifest)\n }\n return manifest\n }\n\n function parseSkillManifest(raw: string): SkillCorpusManifest | null {\n try {\n const value = JSON.parse(raw) as Partial<SkillCorpusManifest>\n if (value.schema !== manifestSchema || typeof value.hash !== 'string') return null\n if (!Array.isArray(value.ids) || value.ids.some((id) => typeof id !== 'string' || !SKILL_ID_RE.test(id))) return null\n return { schema: manifestSchema, hash: value.hash, ids: value.ids }\n } catch {\n return null\n }\n }\n\n function receiptKey(box: SandboxInstance, harness: Harness): string | null {\n const incarnation = filesystemIncarnation?.(box)\n return box.id && incarnation ? `${box.id}\\0${incarnation}\\0${harness}` : null\n }\n\n function recordPlacement(key: string | null, hash: string): void {\n if (!key) return\n if (placedCorpora.size >= PLACED_CORPORA_LIMIT) placedCorpora.clear()\n placedCorpora.set(key, hash)\n }\n\n async function placeSkills(\n box: SandboxInstance,\n harness: Harness,\n root: string,\n skills: readonly DeclaredSkill[],\n expected: SkillCorpusManifest,\n ): Promise<Outcome<void>> {\n const markerPath = `${manifestDir}/${harness}.json`\n let current: SkillCorpusManifest | null = null\n try {\n current = parseSkillManifest(await box.fs.read(homeRelative(markerPath)))\n } catch (err) {\n if (!(err instanceof NotFoundError)) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to read the sandbox skill manifest', { cause: err }),\n }\n }\n }\n if (current?.hash === expected.hash) return { succeeded: true, value: undefined }\n\n const written = await writeProfileFilesToBox(box, skillFileMounts(root, skills))\n if (!written.succeeded) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to write the sandbox skill corpus', { cause: written.error }),\n }\n }\n\n const expectedIds = new Set(expected.ids)\n for (const id of (current?.ids ?? []).filter((id) => !expectedIds.has(id))) {\n try {\n await box.fs.delete(homeRelative(`~/${root}/${id}`), { recursive: true })\n } catch (err) {\n // Another identical reconcile may have removed it first; any other failure stays visible.\n if (err instanceof NotFoundError) continue\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: stale skill cleanup failed', { cause: err }),\n }\n }\n }\n\n const manifestWritten = await writeProfileFilesToBox(box, [{\n path: markerPath,\n resource: { kind: 'inline', name: `${harness}-${manifestName}-skill-manifest`, content: JSON.stringify(expected) },\n }])\n if (!manifestWritten.succeeded) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to write the sandbox skill manifest', { cause: manifestWritten.error }),\n }\n }\n return { succeeded: true, value: undefined }\n }\n\n async function placeProfileSkillsOnBox(\n box: SandboxInstance,\n harness: Harness,\n refs: readonly AgentProfileResourceRef[],\n ): Promise<Outcome<void>> {\n const root = resolveSkillDir(harness)\n if (!root || refs.length === 0) return { succeeded: true, value: undefined }\n\n const skills = declaredSkills(refs)\n if (!skills) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: every declared skill ref must be an inline body') }\n }\n const ids = skills.map((skill) => skill.id)\n if (ids.some((id) => !SKILL_ID_RE.test(id)) || new Set(ids).size !== ids.length) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: skill ids must be unique path-safe slugs') }\n }\n\n let expected: SkillCorpusManifest\n try {\n expected = await corpusManifest(refs, skills)\n } catch (err) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to hash the declared skill corpus', { cause: err }),\n }\n }\n\n const key = receiptKey(box, harness)\n if (key && placedCorpora.get(key) === expected.hash) return { succeeded: true, value: undefined }\n if (!boxLock) {\n const placed = await placeSkills(box, harness, root, skills, expected)\n if (placed.succeeded) recordPlacement(key, expected.hash)\n return placed\n }\n const lockPath = `${manifestDir}/${harness}.json.lock`\n const acquired = await acquireBoxLock(box, manifestDir, lockPath)\n if (!acquired.succeeded) return acquired\n const placed = await placeSkills(box, harness, root, skills, expected)\n const released = await releaseBoxLock(box, lockPath)\n if (placed.succeeded && released.succeeded) recordPlacement(key, expected.hash)\n return released.succeeded ? placed : released\n }\n\n /** Whether two skill declarations carry the same inline corpus. */\n async function sameSkillCorpus(\n left: readonly AgentProfileResourceRef[] | undefined,\n right: readonly AgentProfileResourceRef[],\n ): Promise<boolean> {\n if (!left) return right.length === 0\n if (left === right) return true\n const leftSkills = declaredSkills(left)\n const rightSkills = declaredSkills(right)\n if (!leftSkills || !rightSkills) return false\n const [a, b] = await Promise.all([corpusManifest(left, leftSkills), corpusManifest(right, rightSkills)])\n return a.hash === b.hash\n }\n\n return { placeProfileSkillsOnBox, sameSkillCorpus }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,SAAS,qBAA2C;AAmBpD,IAAM,cAAc;AACpB,IAAM,uBAAuB;AA0B7B,SAAS,aAAa,MAAsB;AAC1C,MAAI,CAAC,KAAK,WAAW,IAAI,EAAG,OAAM,IAAI,MAAM,sCAAsC,IAAI,EAAE;AACxF,SAAO,KAAK,MAAM,CAAC;AACrB;AAEA,SAAS,cAAc,MAAsB;AAC3C,SAAO,KAAK,WAAW,aAAa,IAAI,CAAC,CAAC;AAC5C;AAEA,eAAe,eAAe,KAAsB,aAAqB,UAA0C;AACjH,QAAM,UAAU;AAAA,IACd,YAAY,cAAc,WAAW,CAAC;AAAA,IACtC,QAAQ,cAAc,QAAQ,CAAC;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACX,MAAI;AACF,UAAM,WAAW,MAAM,IAAI,KAAK,OAAO;AACvC,QAAI,SAAS,aAAa,EAAG,QAAO,EAAE,WAAW,MAAM,OAAO,OAAU;AACxE,WAAO,EAAE,WAAW,OAAO,OAAO,IAAI,MAAM,4BAA4B,SAAS,UAAU,wCAAwC,EAAE,EAAE;AAAA,EACzI,SAAS,OAAO;AACd,WAAO,EAAE,WAAW,OAAO,OAAO,IAAI,MAAM,uEAAuE,EAAE,OAAO,MAAM,CAAC,EAAE;AAAA,EACvI;AACF;AAEA,eAAe,eAAe,KAAsB,UAA0C;AAC5F,MAAI;AACF,UAAM,WAAW,MAAM,IAAI,KAAK,UAAU,cAAc,QAAQ,CAAC,EAAE;AACnE,QAAI,SAAS,aAAa,EAAG,QAAO,EAAE,WAAW,MAAM,OAAO,OAAU;AACxE,WAAO,EAAE,WAAW,OAAO,OAAO,IAAI,MAAM,oEAAoE,SA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aAAa,eAAe,IAAI;AACtC,UAAM,cAAc,eAAe,KAAK;AACxC,QAAI,CAAC,cAAc,CAAC,YAAa,QAAO;AACxC,UAAM,CAAC,GAAG,CAAC,IAAI,MAAM,QAAQ,IAAI,CAAC,eAAe,MAAM,UAAU,GAAG,eAAe,OAAO,WAAW,CAAC,CAAC;AACvG,WAAO,EAAE,SAAS,EAAE;AAAA,EACtB;AAEA,SAAO,EAAE,yBAAyB,gBAAgB;AACpD;","names":["id","placed"]}
@@ -0,0 +1,125 @@
1
+ /**
2
+ * What the workspace Vault coordinator knows about its box's copy of the Vault.
3
+ *
4
+ * Every chat turn used to re-prove that the box holds the Vault: read the
5
+ * baseline, list every head, diff, commit the baseline again, and `test -f`
6
+ * the bootstrap marker. On an unchanged Vault that was about 2 s of GTM's warm
7
+ * path (sandbox.vault.hydration p50 1211 ms, n=943; loss probe 387 ms, n=954;
8
+ * bootstrap 332 ms, n=952; 2026-10-09..11). This record lets a turn skip that
9
+ * work when nothing it would act on has changed.
10
+ *
11
+ * The workspace DO is the only writer of Vault heads (`/vault/mutate`), so it
12
+ * can count them. `generation` moves after every mutation that did not come
13
+ * from the synced box's own reconcile, and `inFlight` is set while one is being
14
+ * applied. A complete hydration records `sync` with the generation it read
15
+ * before it listed the heads; a later turn trusts it only while the generation
16
+ * is the same, no mutation is in flight, and the box is the same sandbox and
17
+ * filesystem incarnation. Anything else, including a failed read of this
18
+ * record, takes the full hydration path.
19
+ *
20
+ * Each record also names the contract it was written under: a sync names the
21
+ * hydration contract, and a bootstrap record names the marker it confirmed. A
22
+ * turn trusts a record only under its own contract, so a release that changes
23
+ * what hydration writes, or bumps the bootstrap marker, reaches every box on
24
+ * its next turn instead of waiting for the box to be recreated.
25
+ */
26
+ export declare const VAULT_BOX_STATE_KEY = "vaultBoxState";
27
+ export declare const VAULT_BOX_STATE_SCHEMA = "vault-box-state-v1";
28
+ /** A mutation in flight longer than this cannot still be running: its request
29
+ * died with the object. Reading the state then moves the generation, so the
30
+ * next hydration records against a value no partial write predates. */
31
+ export declare const VAULT_BOX_MUTATION_STALE_MS: number;
32
+ /** A Vault file that hydration left off the box for its size; the agent reads it through the Vault API. */
33
+ export interface VaultBoxSyncSkip {
34
+ path: string;
35
+ reason: 'too_large';
36
+ detail: string;
37
+ }
38
+ /** A hydration that left more files off the box than this records no sync. */
39
+ export declare const VAULT_BOX_SYNC_MAX_SKIPS = 50;
40
+ /** The box and filesystem whose Vault copy a complete hydration proved current. */
41
+ export interface VaultBoxSync {
42
+ sandboxId: string;
43
+ filesystemIncarnationId: string;
44
+ /** The hydration contract the copy was written under (the sync engine's `contract`). */
45
+ contract: string;
46
+ /** The generation read before that hydration listed the heads. */
47
+ generation: number;
48
+ /** What that hydration left off the box, so a turn that skips hydration still tells the agent. */
49
+ skipped: VaultBoxSyncSkip[];
50
+ syncedAt: string;
51
+ }
52
+ /** The box and filesystem whose product bootstrap marker was confirmed. */
53
+ export interface SandboxBootstrapRecord {
54
+ sandboxId: string;
55
+ filesystemIncarnationId: string;
56
+ /** The bootstrap marker the box confirmed. */
57
+ marker: string;
58
+ at: string;
59
+ }
60
+ export interface StoredVaultBoxState {
61
+ schema: typeof VAULT_BOX_STATE_SCHEMA;
62
+ generation: number;
63
+ inFlight: {
64
+ operationId: string;
65
+ startedAt: number;
66
+ } | null;
67
+ sync: VaultBoxSync | null;
68
+ bootstrap: SandboxBootstrapRecord | null;
69
+ }
70
+ /** What a turn reads. */
71
+ export interface VaultBoxStateView {
72
+ generation: number;
73
+ inFlight: boolean;
74
+ sync: VaultBoxSync | null;
75
+ bootstrap: SandboxBootstrapRecord | null;
76
+ }
77
+ export interface VaultBoxIdentity {
78
+ sandboxId: string;
79
+ filesystemIncarnationId: string;
80
+ }
81
+ /** What a complete hydration asks the coordinator to record. */
82
+ export interface VaultBoxSyncRecord extends VaultBoxIdentity {
83
+ contract: string;
84
+ generation: number;
85
+ skipped: readonly VaultBoxSyncSkip[];
86
+ }
87
+ /** What a confirmed bootstrap asks the coordinator to record. */
88
+ export interface SandboxBootstrapConfirmation extends VaultBoxIdentity {
89
+ marker: string;
90
+ }
91
+ export declare function emptyVaultBoxState(): StoredVaultBoxState;
92
+ /**
93
+ * The stored state, or a fresh one. A value that does not parse starts over at
94
+ * a generation above anything it could have held, so no sync recorded against
95
+ * the unreadable value can match.
96
+ */
97
+ export declare function parseVaultBoxState(value: unknown): StoredVaultBoxState;
98
+ /**
99
+ * Whether a mutation leaves the synced box's copy current without moving the
100
+ * generation: only the reconcile of that same box writes what the box already
101
+ * holds. Every other writer (the app, a tool, another box) moves it.
102
+ */
103
+ export declare function isSyncedBoxWriter(state: StoredVaultBoxState, writer: {
104
+ kind?: unknown;
105
+ id?: unknown;
106
+ } | undefined): boolean;
107
+ export declare function withMutationStarted(state: StoredVaultBoxState, operationId: string, now: number): StoredVaultBoxState;
108
+ /** Runs whether the mutation applied, conflicted or threw: any of them may have reached KV. */
109
+ export declare function withMutationFinished(state: StoredVaultBoxState): StoredVaultBoxState;
110
+ /** A reconcile that left the box and the Vault apart. The generation moves too, so a
111
+ * hydration that started before it cannot record a sync after it. */
112
+ export declare function withSyncInvalidated(state: StoredVaultBoxState): StoredVaultBoxState;
113
+ export declare function withSync(state: StoredVaultBoxState, sync: VaultBoxSync): StoredVaultBoxState;
114
+ export declare function withBootstrap(state: StoredVaultBoxState, bootstrap: SandboxBootstrapRecord): StoredVaultBoxState;
115
+ /** Clears an in-flight marker whose request cannot still be running, moving the generation. */
116
+ export declare function healStaleMutation(state: StoredVaultBoxState, now: number): StoredVaultBoxState | null;
117
+ export declare function viewOfVaultBoxState(state: StoredVaultBoxState): VaultBoxStateView;
118
+ /** Parses a view returned by the coordinator; anything else is unknown (null). */
119
+ export declare function parseVaultBoxStateView(value: unknown): VaultBoxStateView | null;
120
+ /** The skips a sync may carry, or null when the value is not a bounded list of them. */
121
+ export declare function parseVaultBoxSyncSkips(value: unknown): VaultBoxSyncSkip[] | null;
122
+ /** Whether a complete hydration of this exact box, under this contract, saw the Vault as it is now. */
123
+ export declare function vaultBoxInSync(view: VaultBoxStateView | null, box: VaultBoxIdentity, contract: string): boolean;
124
+ /** Whether this exact box's filesystem already holds the product bootstrap this marker names. */
125
+ export declare function sandboxBootstrapRecorded(view: VaultBoxStateView | null, box: VaultBoxIdentity, marker: string): boolean;
@@ -14,7 +14,8 @@
14
14
  */
15
15
  import type { KVStore } from '../../store';
16
16
  import { VaultPathError } from './paths';
17
- import { VaultReadConvergenceError, type VaultHeadState, type VaultMutationPolicy, type VaultMutationRequest, type VaultMutationResult, type VaultVisibilityFence } from './revisions';
17
+ import { VaultReadConvergenceError, type VaultHeadState, type VaultMutationPolicy, type VaultMutationRequest, type VaultMutationResult, type VaultSandboxBaseline, type VaultVisibilityFence } from './revisions';
18
+ import { type StoredVaultBoxState } from './box-state';
18
19
  /** The Durable Object storage calls the coordinator makes; Cloudflare's storage satisfies it. */
19
20
  export interface VaultCoordinatorStorage {
20
21
  get<T>(key: string): Promise<T | undefined>;
@@ -60,5 +61,12 @@ export declare function createVaultCoordinator(options: VaultCoordinatorOptions)
60
61
  handleVaultHeadGet: (request: Request) => Promise<Response>;
61
62
  handleVaultHeadList: (request: Request) => Promise<Response>;
62
63
  handleVaultMutation: (request: Request) => Promise<Response>;
64
+ readVaultSandboxBaseline: (sandboxId: string) => Promise<VaultSandboxBaseline | null>;
65
+ writeVaultSandboxBaseline: (baseline: VaultSandboxBaseline) => Promise<void>;
66
+ handleVaultBaselineGet: (request: Request) => Promise<Response>;
67
+ handleVaultBaselineSet: (request: Request) => Promise<Response>;
68
+ readVaultBoxState: () => Promise<StoredVaultBoxState>;
69
+ updateVaultBoxState: (change: (state: StoredVaultBoxState) => StoredVaultBoxState) => Promise<StoredVaultBoxState>;
70
+ handle: (request: Request) => Promise<Response | null>;
63
71
  };
64
72
  export type VaultCoordinator = ReturnType<typeof createVaultCoordinator>;
@@ -10,3 +10,7 @@ export * from './tree';
10
10
  export * from './store';
11
11
  export * from './coordinator';
12
12
  export * from './sandbox-sync';
13
+ export * from './box-state';
14
+ export * from './sandbox-hydrate';
15
+ export * from './sandbox-reconcile';
16
+ export * from './sandbox-engine';