zidane 5.14.4 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/dist/{acp-24uU2WDs.js → acp-Irby04Us.js} +7 -8
  2. package/dist/{acp-24uU2WDs.js.map → acp-Irby04Us.js.map} +1 -1
  3. package/dist/acp-cli.js +7 -7
  4. package/dist/acp.d.ts +2 -3
  5. package/dist/acp.d.ts.map +1 -1
  6. package/dist/acp.js +1 -1
  7. package/dist/{agent-Cch2ayTt.js → agent-DkSmGkDM.js} +10871 -5411
  8. package/dist/agent-DkSmGkDM.js.map +1 -0
  9. package/dist/agent.d.ts +1 -2
  10. package/dist/agent.js +2 -2
  11. package/dist/{anthropic-RGqsJlC8.js → anthropic-CTHsdFG9.js} +46 -6
  12. package/dist/anthropic-CTHsdFG9.js.map +1 -0
  13. package/dist/{auth-C-ms5N2x.js → auth-BDSu_0t3.js} +13 -86
  14. package/dist/auth-BDSu_0t3.js.map +1 -0
  15. package/dist/chat/pure.d.ts +4 -4
  16. package/dist/chat/pure.js +4 -3
  17. package/dist/chat.d.ts +45 -8
  18. package/dist/chat.d.ts.map +1 -1
  19. package/dist/chat.js +9 -6
  20. package/dist/chat.js.map +1 -1
  21. package/dist/completion-core-CXYSVhZo.js +147 -0
  22. package/dist/completion-core-CXYSVhZo.js.map +1 -0
  23. package/dist/{context-breakdown-kO-pDsay.js → context-breakdown-Dzo25N45.js} +2 -23
  24. package/dist/context-breakdown-Dzo25N45.js.map +1 -0
  25. package/dist/contexts/daytona.d.ts +3 -3
  26. package/dist/contexts/daytona.js +1 -1
  27. package/dist/contexts/docker.d.ts +10 -2
  28. package/dist/contexts/docker.d.ts.map +1 -1
  29. package/dist/contexts/docker.js +142 -103
  30. package/dist/contexts/docker.js.map +1 -1
  31. package/dist/contexts/e2b.d.ts +2 -2
  32. package/dist/contexts/e2b.js +1 -1
  33. package/dist/contexts/sandbox.d.ts +1 -1
  34. package/dist/contexts/sandbox.js +4 -1
  35. package/dist/contexts/sandbox.js.map +1 -1
  36. package/dist/{contexts-Lzf5huID.js → contexts-Vone3qQQ.js} +26 -37
  37. package/dist/contexts-Vone3qQQ.js.map +1 -0
  38. package/dist/contexts.d.ts +3 -3
  39. package/dist/contexts.js +1 -1
  40. package/dist/errors.d.ts +1 -2
  41. package/dist/errors.js +1 -1
  42. package/dist/eval.d.ts +1 -1
  43. package/dist/eval.js +3 -3
  44. package/dist/exec-file-size-PXkr-MGA.js +63 -0
  45. package/dist/exec-file-size-PXkr-MGA.js.map +1 -0
  46. package/dist/extensions.d.ts +2 -0
  47. package/dist/extensions.js +2 -0
  48. package/dist/generate-data-WL_yGVL6.js +324 -0
  49. package/dist/generate-data-WL_yGVL6.js.map +1 -0
  50. package/dist/headless.d.ts +1 -1
  51. package/dist/headless.js +15 -10
  52. package/dist/headless.js.map +1 -1
  53. package/dist/index-B8UtiZy7.d.ts +14967 -0
  54. package/dist/index-B8UtiZy7.d.ts.map +1 -0
  55. package/dist/{index-B3ciFUZx.d.ts → index-DsPQbyUn.d.ts} +2 -2
  56. package/dist/index-DsPQbyUn.d.ts.map +1 -0
  57. package/dist/index.d.ts +6 -12
  58. package/dist/index.js +20 -43
  59. package/dist/index.js.map +1 -1
  60. package/dist/{logger-Ktm-lj1s.js → logger-DBX9uYOw.js} +108 -5
  61. package/dist/logger-DBX9uYOw.js.map +1 -0
  62. package/dist/login-DOF8pMVM.js +539 -0
  63. package/dist/login-DOF8pMVM.js.map +1 -0
  64. package/dist/{mcp-Dn5W65Lv.js → mcp-CcvuVXB9.js} +2 -2
  65. package/dist/{mcp-Dn5W65Lv.js.map → mcp-CcvuVXB9.js.map} +1 -1
  66. package/dist/mcp.d.ts +1 -1
  67. package/dist/mcp.js +1 -1
  68. package/dist/{messages-YZQLKaz2.js → messages-CwujiS74.js} +4 -4
  69. package/dist/messages-CwujiS74.js.map +1 -0
  70. package/dist/{openai-compat-0Y7jcncn.js → openai-compat-BvgYGSR1.js} +7 -6
  71. package/dist/{openai-compat-0Y7jcncn.js.map → openai-compat-BvgYGSR1.js.map} +1 -1
  72. package/dist/output/stream-json.d.ts +1 -2
  73. package/dist/output/stream-json.d.ts.map +1 -1
  74. package/dist/output/terminal.d.ts +1 -2
  75. package/dist/output/terminal.d.ts.map +1 -1
  76. package/dist/{glob-DluQFSw1.js → output-cap-kBUHBlnq.js} +50 -2
  77. package/dist/output-cap-kBUHBlnq.js.map +1 -0
  78. package/dist/presets.d.ts +1 -2
  79. package/dist/presets.js +1 -1
  80. package/dist/providers/anthropic.d.ts +2 -2
  81. package/dist/providers/anthropic.js +2 -2
  82. package/dist/providers/arcee.d.ts +1 -1
  83. package/dist/providers/arcee.js +1 -1
  84. package/dist/providers/baseten.d.ts +1 -1
  85. package/dist/providers/baseten.js +1 -1
  86. package/dist/providers/cerebras.d.ts +1 -1
  87. package/dist/providers/cerebras.js +1 -1
  88. package/dist/providers/local.d.ts +1 -1
  89. package/dist/providers/local.js +1 -1
  90. package/dist/providers/openai-compat.d.ts +1 -1
  91. package/dist/providers/openai-compat.js +1 -1
  92. package/dist/providers/openai.d.ts +1 -1
  93. package/dist/providers/openai.js +4 -4
  94. package/dist/providers/openai.js.map +1 -1
  95. package/dist/providers/openrouter.d.ts +1 -1
  96. package/dist/providers/openrouter.js +1 -1
  97. package/dist/providers/xai.d.ts +1 -1
  98. package/dist/providers/xai.js +1 -1
  99. package/dist/{providers-DgmdYGKm.js → providers-z6LDMAr3.js} +3 -3
  100. package/dist/{providers-DgmdYGKm.js.map → providers-z6LDMAr3.js.map} +1 -1
  101. package/dist/providers.d.ts +1 -1
  102. package/dist/providers.js +4 -4
  103. package/dist/{read-state-BymF41Jb.js → read-state-Dq_TXUX1.js} +2 -2
  104. package/dist/{read-state-BymF41Jb.js.map → read-state-Dq_TXUX1.js.map} +1 -1
  105. package/dist/{interpolate-BtIgcCuz.js → resolve-Cr8JSL_O.js} +562 -136
  106. package/dist/resolve-Cr8JSL_O.js.map +1 -0
  107. package/dist/restate.d.ts +2 -2
  108. package/dist/restate.js +2 -2
  109. package/dist/{sandbox-Dgy-m6UF.d.ts → sandbox-CgjG2VvQ.d.ts} +2 -2
  110. package/dist/{sandbox-Dgy-m6UF.d.ts.map → sandbox-CgjG2VvQ.d.ts.map} +1 -1
  111. package/dist/session/sqlite.d.ts +1 -1
  112. package/dist/{session-CqrAFAKJ.js → session-CsdDIPY8.js} +108 -3
  113. package/dist/session-CsdDIPY8.js.map +1 -0
  114. package/dist/session.d.ts +2 -2
  115. package/dist/session.js +3 -3
  116. package/dist/skills-Bsb0rvWI.js +295 -0
  117. package/dist/skills-Bsb0rvWI.js.map +1 -0
  118. package/dist/skills.d.ts +2 -3
  119. package/dist/skills.js +3 -24
  120. package/dist/{errors-CkTvg97v.d.ts → timeout-8vSIRjzl.d.ts} +10 -2
  121. package/dist/timeout-8vSIRjzl.d.ts.map +1 -0
  122. package/dist/{timeout-kGGSXagK.js → timeout-BDetbuN6.js} +59 -2
  123. package/dist/timeout-BDetbuN6.js.map +1 -0
  124. package/dist/tool-formatters-DY0TDb1r.d.ts +378 -0
  125. package/dist/tool-formatters-DY0TDb1r.d.ts.map +1 -0
  126. package/dist/tools/fetch-url.d.ts +1 -1
  127. package/dist/tools/web-search.d.ts +1 -1
  128. package/dist/tools.d.ts +2 -3
  129. package/dist/tools.js +3 -4
  130. package/dist/{transcript-anchors-BHIgMlPq.d.ts → transcript-anchors-Cb-bDbNH.d.ts} +233 -640
  131. package/dist/transcript-anchors-Cb-bDbNH.d.ts.map +1 -0
  132. package/dist/{transcript-anchors-DsoBHg43.js → transcript-anchors-DSRPWjiH.js} +391 -961
  133. package/dist/transcript-anchors-DSRPWjiH.js.map +1 -0
  134. package/dist/tui.d.ts +335 -11
  135. package/dist/tui.d.ts.map +1 -1
  136. package/dist/tui.js +6375 -1892
  137. package/dist/tui.js.map +1 -1
  138. package/dist/{turn-operations-Dw02ZoSQ.d.ts → turn-operations-CgMROLsr.d.ts} +29 -4
  139. package/dist/turn-operations-CgMROLsr.d.ts.map +1 -0
  140. package/dist/{turn-operations-tG0vuBNc.js → turn-operations-Dq9Kx7m2.js} +321 -81
  141. package/dist/turn-operations-Dq9Kx7m2.js.map +1 -0
  142. package/dist/{types-BqdTeBaC.d.ts → types-BDccavwj.d.ts} +42 -1
  143. package/dist/types-BDccavwj.d.ts.map +1 -0
  144. package/dist/{types-CyVGdbia.js → types-BIarq1qE.js} +90 -2
  145. package/dist/types-BIarq1qE.js.map +1 -0
  146. package/dist/types.d.ts +5 -6
  147. package/dist/types.js +1 -1
  148. package/dist/{xai-tPdbAGkq.js → xai-B_e6TOA8.js} +2 -2
  149. package/dist/{xai-tPdbAGkq.js.map → xai-B_e6TOA8.js.map} +1 -1
  150. package/docs/ARCHITECTURE.md +1 -1
  151. package/docs/CHAT.md +7 -6
  152. package/docs/EXECUTION_CONTEXT.md +16 -0
  153. package/docs/EXTENSIONS.md +1063 -0
  154. package/docs/SKILL.md +16 -0
  155. package/docs/TUI.md +10 -3
  156. package/package.json +12 -3
  157. package/dist/agent-Cch2ayTt.js.map +0 -1
  158. package/dist/agent-EFWt6uQ_.d.ts +0 -6914
  159. package/dist/agent-EFWt6uQ_.d.ts.map +0 -1
  160. package/dist/anthropic-RGqsJlC8.js.map +0 -1
  161. package/dist/auth-C-ms5N2x.js.map +0 -1
  162. package/dist/context-breakdown-kO-pDsay.js.map +0 -1
  163. package/dist/contexts-Lzf5huID.js.map +0 -1
  164. package/dist/errors-CkTvg97v.d.ts.map +0 -1
  165. package/dist/glob-DluQFSw1.js.map +0 -1
  166. package/dist/glob-shell-rJMoCIGb.js +0 -21
  167. package/dist/glob-shell-rJMoCIGb.js.map +0 -1
  168. package/dist/index-B3ciFUZx.d.ts.map +0 -1
  169. package/dist/index-BtzE3Uaq.d.ts +0 -2738
  170. package/dist/index-BtzE3Uaq.d.ts.map +0 -1
  171. package/dist/index-tSzOaWNt.d.ts +0 -316
  172. package/dist/index-tSzOaWNt.d.ts.map +0 -1
  173. package/dist/interpolate-BtIgcCuz.js.map +0 -1
  174. package/dist/logger-DGiGf7DW.d.ts +0 -102
  175. package/dist/logger-DGiGf7DW.d.ts.map +0 -1
  176. package/dist/logger-Ktm-lj1s.js.map +0 -1
  177. package/dist/login-CCA-1lgK.js +0 -267
  178. package/dist/login-CCA-1lgK.js.map +0 -1
  179. package/dist/messages-YZQLKaz2.js.map +0 -1
  180. package/dist/policy-DcGlpaNs.d.ts +0 -129
  181. package/dist/policy-DcGlpaNs.d.ts.map +0 -1
  182. package/dist/presets-BQWYMHdd.js +0 -114
  183. package/dist/presets-BQWYMHdd.js.map +0 -1
  184. package/dist/run-summary-DkN8KsHM.d.ts +0 -249
  185. package/dist/run-summary-DkN8KsHM.d.ts.map +0 -1
  186. package/dist/session-CqrAFAKJ.js.map +0 -1
  187. package/dist/shell-quote-BmnhZmdM.js +0 -33
  188. package/dist/shell-quote-BmnhZmdM.js.map +0 -1
  189. package/dist/skills.js.map +0 -1
  190. package/dist/timeout-CpFm0jJ6.d.ts +0 -10
  191. package/dist/timeout-CpFm0jJ6.d.ts.map +0 -1
  192. package/dist/timeout-kGGSXagK.js.map +0 -1
  193. package/dist/tool-formatters-C6iLgc9f.d.ts +0 -1454
  194. package/dist/tool-formatters-C6iLgc9f.d.ts.map +0 -1
  195. package/dist/tools-CCd8e-HT.js +0 -1739
  196. package/dist/tools-CCd8e-HT.js.map +0 -1
  197. package/dist/transcript-anchors-BHIgMlPq.d.ts.map +0 -1
  198. package/dist/transcript-anchors-DsoBHg43.js.map +0 -1
  199. package/dist/turn-operations-Dw02ZoSQ.d.ts.map +0 -1
  200. package/dist/turn-operations-tG0vuBNc.js.map +0 -1
  201. package/dist/types-BqdTeBaC.d.ts.map +0 -1
  202. package/dist/types-CyVGdbia.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-CsdDIPY8.js","names":[],"sources":["../src/session/file-map.ts","../src/session/memory.ts","../src/session/remote.ts","../src/session/index.ts"],"sourcesContent":["/**\n * File-map session store.\n *\n * Wraps a narrow 3-method adapter (`get` / `save` / `delete`) that exchanges a flat\n * map of filename → string content. Useful for embedding zidane sessions inside\n * host-provided session backends that only speak in file maps (not zidane's native\n * `SessionStore` shape).\n *\n * Serialization format:\n * - `turns.jsonl` — one `SessionTurn` per line.\n * - `meta.json` — session metadata (id, agentId, status, runs, metadata, timestamps).\n *\n * JSONL for turns keeps history inspectable with tools like `jq` and resilient to\n * partial corruption — parse up to the first bad line and you still have a valid\n * prefix. Metadata lives in its own file so large turn logs don't bloat the\n * metadata path.\n *\n * Scope: each `createFileMapStore` handles a **single session** — the adapter's\n * file map holds at most one zidane session at a time. This matches how host SDKs\n * scope their session stores per conversation.\n *\n * Divergences from the built-in memory / sqlite stores:\n * - `appendTurns` / `updateStatus` / `updateRun` auto-create a minimal `SessionData`\n * record on first write, instead of silently no-oping when the session hasn't been\n * explicitly `save()`-ed. This matches the host-SDK integration path where\n * `createSession(...)` → `agent.run(...)` directly without an explicit `save()` call.\n * - `updateRun` inserts the run if not found in the cached record (rather than\n * silently dropping). Run records therefore always reach the adapter.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\n/**\n * Host-provided file-map adapter. Three methods exchanging `Record<string, string>`\n * payloads — the whole persistence surface the wrapper needs.\n */\nexport interface FileMapAdapter {\n /** Load the current file map. Returns an empty `files` record when nothing is persisted. */\n get: () => Promise<{ files: Record<string, string> }>\n /** Replace the persisted file map. Full-rewrite semantics. */\n save: (files: Record<string, string>) => Promise<void>\n /** Delete all persisted state. */\n delete: () => Promise<void>\n}\n\nexport interface FileMapStoreOptions {\n /** Filename for the JSONL turns log. Default: `turns.jsonl`. */\n turnsFile?: string\n /** Filename for the metadata JSON. Default: `meta.json`. */\n metaFile?: string\n}\n\ninterface MetaShape {\n id: string\n agentId?: string\n /** Optional — absent on files written before projectRoot persistence. */\n projectRoot?: string\n runs: SessionRun[]\n status: SessionData['status']\n metadata: Record<string, unknown>\n createdAt: number\n updatedAt: number\n}\n\nfunction toMeta(data: SessionData): MetaShape {\n return {\n id: data.id,\n agentId: data.agentId,\n projectRoot: data.projectRoot,\n runs: data.runs,\n status: data.status,\n metadata: data.metadata,\n createdAt: data.createdAt,\n updatedAt: data.updatedAt,\n }\n}\n\nfunction toData(meta: MetaShape, turns: SessionTurn[]): SessionData {\n return {\n id: meta.id,\n agentId: meta.agentId,\n ...(typeof meta.projectRoot === 'string' ? { projectRoot: meta.projectRoot } : {}),\n turns,\n runs: meta.runs,\n status: meta.status,\n metadata: meta.metadata,\n createdAt: meta.createdAt,\n updatedAt: meta.updatedAt,\n }\n}\n\nfunction parseTurnsJsonl(jsonl: string): SessionTurn[] {\n if (!jsonl)\n return []\n const turns: SessionTurn[] = []\n for (const line of jsonl.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed)\n continue\n try {\n turns.push(JSON.parse(trimmed) as SessionTurn)\n }\n catch {\n // Skip malformed lines — preserves the valid prefix on partial corruption.\n }\n }\n return turns\n}\n\nfunction serializeTurnsJsonl(turns: SessionTurn[]): string {\n if (turns.length === 0)\n return ''\n return `${turns.map(t => JSON.stringify(t)).join('\\n')}\\n`\n}\n\n/**\n * Create a single-session `SessionStore` backed by a file-map adapter.\n *\n * @example\n * ```ts\n * const session = await createSession({\n * store: createFileMapStore(hostSessionStore),\n * })\n * ```\n */\nexport function createFileMapStore(\n adapter: FileMapAdapter,\n options: FileMapStoreOptions = {},\n): SessionStore {\n const turnsFile = options.turnsFile ?? 'turns.jsonl'\n const metaFile = options.metaFile ?? 'meta.json'\n\n // Cached view of the persisted session. Populated lazily on first access so the\n // factory itself doesn't do I/O.\n let cached: SessionData | null = null\n let hydrated = false\n // In-flight hydrate memo: concurrent first calls share one adapter.get()\n // instead of racing two reads (the loser's view would clobber the winner's\n // subsequent writes — a lost-update race).\n let hydrating: Promise<void> | null = null\n // Turns salvaged from turns.jsonl when meta.json was present but corrupt.\n // We can't trust the (unparseable) meta for the session id, so we hold the\n // turns aside and re-attach them when the next write establishes an id —\n // the alternative (treating the session as missing) would let that write\n // overwrite an intact turns.jsonl with an empty one.\n let recoveredTurns: SessionTurn[] | null = null\n\n async function hydrate(): Promise<void> {\n if (hydrated)\n return\n if (!hydrating) {\n hydrating = (async () => {\n const { files } = await adapter.get()\n const metaRaw = files[metaFile]\n if (metaRaw) {\n let meta: MetaShape | null = null\n try {\n meta = JSON.parse(metaRaw) as MetaShape\n }\n catch {\n meta = null\n }\n if (meta) {\n cached = toData(meta, parseTurnsJsonl(files[turnsFile] ?? ''))\n }\n else {\n recoveredTurns = parseTurnsJsonl(files[turnsFile] ?? '')\n console.error(`[zidane/file-map] ${metaFile} exists but is not valid JSON — preserving ${recoveredTurns.length} turn(s) from ${turnsFile} for the next write instead of treating the session as missing`)\n }\n }\n hydrated = true\n })().finally(() => {\n hydrating = null\n })\n }\n return hydrating\n }\n\n async function persist(data: SessionData): Promise<void> {\n const meta = toMeta(data)\n await adapter.save({\n [metaFile]: JSON.stringify(meta, null, 2),\n [turnsFile]: serializeTurnsJsonl(data.turns),\n })\n }\n\n // Ensure `cached` exists for `sessionId`, creating a minimal record when first written.\n // Returns false when `cached` already holds a different sessionId (request ignored).\n async function ensureCachedFor(sessionId: string): Promise<boolean> {\n await hydrate()\n if (cached) {\n return cached.id === sessionId\n }\n const now = Date.now()\n cached = {\n id: sessionId,\n // Re-attach turns salvaged from a corrupt-meta hydrate so the next\n // persist() doesn't destroy an intact turns.jsonl.\n turns: recoveredTurns ?? [],\n runs: [],\n status: 'idle',\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }\n recoveredTurns = null\n hydrated = true\n return true\n }\n\n return {\n async load(sessionId: string): Promise<SessionData | null> {\n await hydrate()\n if (!cached || cached.id !== sessionId)\n return null\n return structuredClone(cached)\n },\n\n async save(data: SessionData): Promise<void> {\n cached = structuredClone(data)\n hydrated = true\n await persist(cached)\n },\n\n async delete(sessionId: string): Promise<void> {\n await hydrate()\n if (cached && cached.id !== sessionId)\n return\n cached = null\n await adapter.delete()\n },\n\n async list(filter): Promise<string[]> {\n await hydrate()\n if (!cached)\n return []\n if (filter?.agentId && cached.agentId !== filter.agentId)\n return []\n // file-map stores exactly one session, so the projectRoot filter\n // either keeps it (match / axis off) or drops it entirely.\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null && cached.projectRoot != null)\n return []\n if (typeof v === 'string' && cached.projectRoot !== v)\n return []\n }\n return [cached.id]\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n cached!.turns.push(...structuredClone(turns))\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number): Promise<SessionTurn[]> {\n await hydrate()\n if (!cached || cached.id !== sessionId)\n return []\n const slice = cached.turns.slice(from, limit !== undefined ? from + limit : undefined)\n return structuredClone(slice) as SessionTurn[]\n },\n\n async updateRun(sessionId: string, run: SessionRun): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n const idx = cached!.runs.findIndex(r => r.id === run.id)\n if (idx >= 0)\n cached!.runs[idx] = structuredClone(run)\n else\n cached!.runs.push(structuredClone(run))\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n cached!.status = status\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n }\n}\n","/**\n * In-memory session store.\n * Useful for development and testing. Data is lost when the process exits.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\nexport function createMemoryStore(): SessionStore {\n const sessions = new Map<string, SessionData>()\n\n // Auto-create a minimal record when turns arrive for an unknown id. Mirrors\n // the file-map store: `createSession({store})` + `agent.run()` appends\n // turns without an explicit `save()` first — a get-or-no-op `appendTurns`\n // would silently lose that history. Deliberately scoped to `appendTurns`\n // only: a late `updateRun`/`updateStatus` racing a `delete()` must stay a\n // no-op rather than resurrect a deleted session.\n function ensureSession(sessionId: string): SessionData {\n let data = sessions.get(sessionId)\n if (!data) {\n const now = Date.now()\n data = {\n id: sessionId,\n turns: [],\n runs: [],\n status: 'idle',\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }\n sessions.set(sessionId, data)\n }\n return data\n }\n\n return {\n async load(sessionId: string) {\n const data = sessions.get(sessionId)\n return data ? structuredClone(data) : null\n },\n\n async save(session: SessionData) {\n sessions.set(session.id, structuredClone(session))\n },\n\n async delete(sessionId: string) {\n sessions.delete(sessionId)\n },\n\n async list(filter) {\n let ids = Array.from(sessions.keys())\n if (filter?.agentId) {\n ids = ids.filter(id => sessions.get(id)?.agentId === filter.agentId)\n }\n // `projectRoot` mirrors the SQLite store's tri-state contract:\n // string → only sessions tagged with that root\n // null → only UNTAGGED sessions (legacy / pre-v3 rows)\n // undefined → axis ignored (tagged + untagged both returned)\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null)\n ids = ids.filter(id => sessions.get(id)?.projectRoot == null)\n else if (typeof v === 'string')\n ids = ids.filter(id => sessions.get(id)?.projectRoot === v)\n }\n if (filter?.limit) {\n ids = ids.slice(0, filter.limit)\n }\n return ids\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]) {\n const data = ensureSession(sessionId)\n data.turns.push(...structuredClone(turns))\n data.updatedAt = Date.now()\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number) {\n const data = sessions.get(sessionId)\n if (!data)\n return []\n const sliced = data.turns.slice(from, limit !== undefined ? from + limit : undefined)\n return structuredClone(sliced) as SessionTurn[]\n },\n\n async updateRun(sessionId: string, run: SessionRun) {\n const data = sessions.get(sessionId)\n if (!data)\n return\n // Upsert — see the matching comment in sqlite.ts's\n // `txnUpdateRun` for the failure mode. tl;dr: the agent's\n // `startRun()` only updates in-memory state; the store first\n // sees the run via `updateRun()` at finalize time, so an\n // update-only impl silently drops every new run.\n const idx = data.runs.findIndex(r => r.id === run.id)\n if (idx >= 0)\n data.runs[idx] = structuredClone(run)\n else\n data.runs.push(structuredClone(run))\n data.updatedAt = Date.now()\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']) {\n const data = sessions.get(sessionId)\n if (!data)\n return\n data.status = status\n data.updatedAt = Date.now()\n },\n }\n}\n","/**\n * Remote session store via HTTP API.\n *\n * Expects a REST API with:\n * GET {url}/sessions/{id} -> SessionData | 404\n * PUT {url}/sessions/{id} -> save SessionData\n * DELETE {url}/sessions/{id} -> delete\n * GET {url}/sessions?agentId=&limit=&projectRoot= -> { ids: string[] }\n * `projectRoot=__null__` is the wire encoding for \"untagged only\".\n * POST {url}/sessions/{id}/turns -> append turns\n * GET {url}/sessions/{id}/turns?from=&limit= -> SessionTurn[]\n * PUT {url}/sessions/{id}/runs/{runId} -> update run\n * PATCH {url}/sessions/{id} -> { status }\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\nexport interface RemoteStoreOptions {\n /** Base URL of the session API */\n url: string\n /** Optional headers (e.g. for authentication) */\n headers?: Record<string, string>\n /** Per-request timeout in ms. Default 30s — bounds a hung backend. */\n timeoutMs?: number\n}\n\nconst TRAILING_SLASH = /\\/$/\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport function createRemoteStore(options: RemoteStoreOptions): SessionStore {\n const baseUrl = options.url.replace(TRAILING_SLASH, '')\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const defaultHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...options.headers,\n }\n\n async function request(path: string, init?: RequestInit): Promise<Response> {\n const url = `${baseUrl}${path}`\n // Bound every call so a hung backend can't wedge the caller forever.\n const res = await fetch(url, {\n ...init,\n headers: { ...defaultHeaders, ...init?.headers },\n signal: init?.signal ?? AbortSignal.timeout(timeoutMs),\n })\n return res\n }\n\n /**\n * Parse a JSON response body, rethrowing parse failures with URL/status\n * context so a malformed backend reply produces a diagnosable error\n * instead of an opaque `Unexpected token` from deep in `res.json()`.\n */\n async function parseJson<T>(res: Response, path: string): Promise<T> {\n try {\n return await res.json() as T\n }\n catch (cause) {\n throw new Error(\n `Remote session: malformed JSON from ${path} (${res.status} ${res.statusText})`,\n { cause },\n )\n }\n }\n\n return {\n async load(sessionId: string) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`)\n if (!res.ok) {\n if (res.status === 404)\n return null\n throw new Error(`Remote session load failed: ${res.status} ${res.statusText}`)\n }\n return await parseJson<SessionData>(res, `/sessions/${sessionId}`)\n },\n\n async save(session: SessionData) {\n const res = await request(`/sessions/${encodeURIComponent(session.id)}`, {\n method: 'PUT',\n body: JSON.stringify(session),\n })\n if (!res.ok) {\n throw new Error(`Remote session save failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async delete(sessionId: string) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`, {\n method: 'DELETE',\n })\n if (!res.ok && res.status !== 404) {\n throw new Error(`Remote session delete failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async list(filter) {\n const params = new URLSearchParams()\n if (filter?.agentId)\n params.set('agentId', filter.agentId)\n if (filter?.limit)\n params.set('limit', String(filter.limit))\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null)\n params.set('projectRoot', '__null__')\n else if (typeof v === 'string')\n params.set('projectRoot', v)\n }\n\n const query = params.toString()\n const path = query ? `/sessions?${query}` : '/sessions'\n const res = await request(path)\n\n if (!res.ok) {\n throw new Error(`Remote session list failed: ${res.status} ${res.statusText}`)\n }\n\n const body = await parseJson<{ ids: string[] }>(res, path)\n if (!Array.isArray(body?.ids)) {\n throw new TypeError(`Remote session list: expected { ids: string[] } from ${path}, got ${typeof body?.ids}`)\n }\n return body.ids\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}/turns`, {\n method: 'POST',\n body: JSON.stringify(turns),\n })\n if (!res.ok) {\n throw new Error(`Remote appendTurns failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number) {\n const params = new URLSearchParams()\n if (from)\n params.set('from', String(from))\n if (limit !== undefined)\n params.set('limit', String(limit))\n\n const query = params.toString()\n const path = `/sessions/${encodeURIComponent(sessionId)}/turns${query ? `?${query}` : ''}`\n const res = await request(path)\n\n if (!res.ok) {\n throw new Error(`Remote getTurns failed: ${res.status} ${res.statusText}`)\n }\n\n const turns = await parseJson<SessionTurn[]>(res, path)\n if (!Array.isArray(turns)) {\n throw new TypeError(`Remote getTurns: expected SessionTurn[] from ${path}, got ${typeof turns}`)\n }\n return turns\n },\n\n async updateRun(sessionId: string, run: SessionRun) {\n const res = await request(\n `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(run.id)}`,\n {\n method: 'PUT',\n body: JSON.stringify(run),\n },\n )\n if (!res.ok) {\n throw new Error(`Remote updateRun failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`, {\n method: 'PATCH',\n body: JSON.stringify({ status }),\n })\n if (!res.ok) {\n throw new Error(`Remote updateStatus failed: ${res.status} ${res.statusText}`)\n }\n },\n }\n}\n","/**\n * Session management for agents.\n *\n * A session tracks identity, turn history, and run metadata.\n * Plug in any storage backend by implementing the SessionStore interface,\n * or use one of the built-in stores: memory, sqlite, remote.\n */\n\nimport type { JsonValue, SessionMessage, SessionTurn, TurnUsage } from '../types'\nimport type { ToWireMessagesOptions } from './messages'\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport { Buffer } from 'node:buffer'\nimport { toWireMessages } from './messages'\n\nexport type { SessionContentBlock, SessionMessage, SessionTurn } from '../types'\nexport { createFileMapStore } from './file-map'\n\nconst EXTENSION_SESSION_METADATA_KEY = 'extensions'\nconst EXTENSION_SESSION_ITEM_MAX_BYTES = 16_384\nconst EXTENSION_SESSION_TOTAL_MAX_BYTES = 65_536\nconst DANGEROUS_RECORD_KEYS = new Set(['__proto__', 'prototype', 'constructor'])\nconst extensionSessionStorage = new AsyncLocalStorage<Session>()\n\n/**\n * Run `fn` with `session` bound as the active extension session for the\n * duration of the call (and every async continuation it spawns). Uses\n * `AsyncLocalStorage.run` rather than `enterWith` so concurrent agents in the\n * same process (e.g. the GUI's multi-session host) never observe each other's\n * session through `currentExtensionSession()`.\n */\nexport function withExtensionSession<T>(session: Session | undefined, fn: () => T): T {\n if (!session)\n return fn()\n return extensionSessionStorage.run(session, fn)\n}\n\nexport function currentExtensionSession(): Session | undefined {\n return extensionSessionStorage.getStore()\n}\n\nexport function getExtensionSessionState<T = JsonValue>(\n session: Session | undefined,\n extensionName: string,\n key: string,\n): T | undefined {\n if (!session || !isSafeExtensionStateKey(extensionName) || !isSafeExtensionStateKey(key))\n return undefined\n const root = session.metadata[EXTENSION_SESSION_METADATA_KEY]\n if (!root || typeof root !== 'object' || Array.isArray(root))\n return undefined\n const byExtension = (root as Record<string, unknown>)[extensionName]\n if (!byExtension || typeof byExtension !== 'object' || Array.isArray(byExtension))\n return undefined\n const stored = (byExtension as Record<string, unknown>)[key]\n if (stored === undefined)\n return undefined\n // Hand back a copy so a caller mutating the result can't reach into the live\n // session metadata behind `setMeta`/`save`.\n return jsonClone(stored as JsonValue) as T\n}\n\nexport async function setExtensionSessionState(\n session: Session | undefined,\n extensionName: string,\n key: string,\n value: JsonValue,\n): Promise<void> {\n if (!session)\n return\n assertSafeExtensionStateKey(extensionName, 'extensionName')\n assertSafeExtensionStateKey(key, 'key')\n assertJsonBounded(value, EXTENSION_SESSION_ITEM_MAX_BYTES, `extension session state \"${extensionName}.${key}\"`)\n\n const root = cloneExtensionStateRoot(session.metadata[EXTENSION_SESSION_METADATA_KEY])\n const byExtension = clonePlainRecord(root[extensionName])\n // Deep-copy on write so later mutations to the caller's object don't bleed\n // into persisted state.\n byExtension[key] = jsonClone(value)\n root[extensionName] = byExtension\n assertJsonBounded(root as JsonValue, EXTENSION_SESSION_TOTAL_MAX_BYTES, 'extension session state')\n session.setMeta(EXTENSION_SESSION_METADATA_KEY, root)\n if (session.store)\n await session.save()\n}\n\nexport async function deleteExtensionSessionState(\n session: Session | undefined,\n extensionName: string,\n key: string,\n): Promise<void> {\n if (!session || !isSafeExtensionStateKey(extensionName) || !isSafeExtensionStateKey(key))\n return\n const root = cloneExtensionStateRoot(session.metadata[EXTENSION_SESSION_METADATA_KEY])\n const byExtension = clonePlainRecord(root[extensionName])\n if (!(key in byExtension))\n return\n delete byExtension[key]\n if (Object.keys(byExtension).length > 0)\n root[extensionName] = byExtension\n else\n delete root[extensionName]\n session.setMeta(EXTENSION_SESSION_METADATA_KEY, root)\n if (session.store)\n await session.save()\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SessionRun {\n id: string\n startedAt: number\n endedAt?: number\n prompt: string\n status: 'running' | 'completed' | 'aborted' | 'error'\n turns?: number\n tokensIn?: number\n tokensOut?: number\n error?: string\n /** Per-turn usage breakdown */\n turnUsage?: TurnUsage[]\n /** Total usage across all turns */\n totalUsage?: TurnUsage\n /** Estimated cost in USD */\n cost?: number\n /**\n * The run that spawned this one, when the agent is a subagent sharing its\n * parent's session. Undefined on top-level `agent.run()`. Consumers can walk\n * `runs` by `parentRunId` to reconstruct the subagent tree.\n */\n parentRunId?: string\n /**\n * Zero-based subagent depth. 0 = top-level run, 1 = direct child, …\n * Recorded here so hosts can query/filter by level without walking the tree.\n */\n depth?: number\n /**\n * How this run was initiated when not a plain user prompt. `command` marks\n * a sub-run driven from a `/` command's `ctx.runAgent`; `display` is the\n * short line the transcript shows instead of the full injected prompt\n * (which often embeds bulky material like a diff). Presentation-only —\n * the wire/model payload is unaffected. Absent on normal runs.\n */\n origin?: { kind: 'command', display?: string }\n}\n\nexport interface SessionData {\n id: string\n agentId?: string\n /**\n * Absolute path of the project this session belongs to — typically\n * the git root resolved from `cwd` at creation time, falling back to\n * `cwd` itself when not in a git repo. Set ONCE on creation and never\n * mutated thereafter (the session \"belongs\" to that project forever).\n *\n * Used by the TUI's sessions list to filter rows by current project,\n * so the user only sees conversations relevant to where they are\n * working — without needing one `.{prefix}/` directory per project.\n *\n * `undefined` on pre-tagging legacy sessions; the chat layer treats\n * those as \"untagged\" and hides them unless `Settings.showAllProjects`\n * is on.\n */\n projectRoot?: string\n turns: SessionTurn[]\n runs: SessionRun[]\n status: 'idle' | 'running' | 'completed' | 'error'\n metadata: Record<string, unknown>\n createdAt: number\n updatedAt: number\n}\n\n// ---------------------------------------------------------------------------\n// SessionStore interface (pluggable backend)\n// ---------------------------------------------------------------------------\n\nexport interface SessionStore {\n /** Optional: generate a session ID server-side (e.g. a database-issued UUID). */\n generateSessionId?: () => string | Promise<string>\n\n /**\n * Optional: generate a turn ID server-side for session-managed user turns.\n *\n * Provider-loop assistant and tool-result turns use AgentClock.randomUUID()\n * instead, so durable-execution adapters can keep those IDs replay-stable.\n */\n generateTurnId?: () => string | Promise<string>\n\n /** Load a session by ID. Returns null if not found. */\n load: (sessionId: string) => Promise<SessionData | null>\n\n /** Save a session (create or update, full document). */\n save: (session: SessionData) => Promise<void>\n\n /** Delete a session. */\n delete: (sessionId: string) => Promise<void>\n\n /**\n * List session IDs, optionally filtered. `projectRoot` restricts to\n * sessions whose `SessionData.projectRoot` matches exactly — untagged\n * (legacy) sessions are NOT returned under that filter; pass `null`\n * explicitly to ask for untagged ones, or omit the field to ignore\n * the axis entirely. `agentId` filters by recorded agent; the two\n * conditions AND together when both are set.\n */\n list: (filter?: { agentId?: string, limit?: number, projectRoot?: string | null }) => Promise<string[]>\n\n /** Append new turns to a session (incremental, avoids full re-save). */\n appendTurns: (sessionId: string, turns: SessionTurn[]) => Promise<void>\n\n /** Return a slice of turns for a session. */\n getTurns: (sessionId: string, from?: number, limit?: number) => Promise<SessionTurn[]>\n\n /**\n * Persist a run record (called after completeRun / abortRun / errorRun).\n *\n * **Upsert semantics required.** The agent's run lifecycle calls\n * `session.startRun()` to register a new run in IN-MEMORY state and\n * then `updateRun()` at finalize. The store doesn't see the run any\n * earlier — `appendTurns` is the only intermediate call, and it\n * persists turns but not runs. An update-only implementation would\n * silently drop every newly-created run record at finalize, leaving\n * the on-disk `runs[]` missing entries that the persisted turns\n * reference (which `eventsFromTurns` then mis-classifies via\n * `ancestryOf` → broken depth, broken `child-N` labels, broken\n * `userPrompts` history).\n *\n * Implementations MUST insert when the id doesn't exist and update\n * when it does. The bundled `sqlite` / `memory` / `file-map` stores\n * all follow this contract; remote stores using HTTP PUT get upsert\n * for free via REST semantics.\n */\n updateRun: (sessionId: string, run: SessionRun) => Promise<void>\n\n /** Update the top-level status of a session. */\n updateStatus: (sessionId: string, status: SessionData['status']) => Promise<void>\n\n /**\n * Optional: release backend resources (e.g. close the SQLite handle).\n * Hosts should call this on teardown when present; stores backed by\n * memory or remote HTTP have nothing to release and may omit it.\n */\n close?: () => void\n}\n\n// ---------------------------------------------------------------------------\n// Session (live instance wrapping a SessionData)\n// ---------------------------------------------------------------------------\n\nexport interface Session {\n /** Session ID */\n readonly id: string\n\n /** Agent ID (optional label) */\n readonly agentId?: string\n\n /**\n * Project this session was created under — see {@link SessionData.projectRoot}.\n * Set once on creation; surfaces here for read-only inspection.\n */\n readonly projectRoot?: string\n\n /**\n * Raw persisted turn history — kept pristine for fidelity (the model's\n * reasoning chain stays intact across reloads).\n *\n * **DO NOT pass this directly to a provider request.** Mid-pair\n * persistence (interrupted runs, partial-result writes, compaction\n * boundaries) leaves orphan `tool_use` / `tool_result` blocks here that\n * every provider 400s on (`tool_result must be preceded by a tool_call\n * with the same toolCallId`). The agent's own loop repairs these\n * just-in-time at wire-send time and never writes the repair back to\n * `turns`.\n *\n * For provider requests built outside `agent.run()`, use\n * {@link Session.toMessages} — it applies the same defensive pairing\n * repair and resolves to a guaranteed-safe `SessionMessage[]`.\n */\n readonly turns: SessionTurn[]\n\n /**\n * True when this session has no turns yet.\n *\n * Use this as a first-prompt signal when setting up a run — e.g. writing initial\n * configuration only on fresh sessions. Equivalent to `turns.length === 0`.\n */\n readonly isEmpty: boolean\n\n /** Top-level session status */\n readonly status: SessionData['status']\n\n /** All runs in this session */\n readonly runs: SessionRun[]\n\n /** Arbitrary metadata */\n readonly metadata: Record<string, unknown>\n\n /**\n * Start tracking a new run. `extras.parentRunId` + `extras.depth` are\n * populated by the spawn tool when a child agent shares its parent's\n * session; regular top-level `agent.run()` calls omit them.\n */\n startRun: (runId: string, prompt?: string, extras?: { parentRunId?: string, depth?: number }) => void\n\n /** Mark a run as completed */\n completeRun: (runId: string, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Mark a run as aborted */\n /**\n * Optional `stats` lets the agent backfill the run's token totals when\n * the abort happened *after* the loop accumulated meaningful usage —\n * common when the user presses esc mid-streaming. Without it, the run\n * record reads `0 in / 0 out` on reload regardless of how much was\n * spent before the abort. Same shape as `completeRun`'s stats so the\n * persisted `totalUsage` aggregate stays consistent across paths.\n */\n abortRun: (runId: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Mark a run as errored */\n /** Optional `stats` — same rationale as `abortRun.stats`. */\n errorRun: (runId: string, error: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Append turns to in-memory history AND persist via store.appendTurns (if store present) */\n appendTurns: (turns: SessionTurn[]) => Promise<void>\n\n /** Replace all turns in-memory (does not persist — use save() for that) */\n setTurns: (turns: SessionTurn[]) => void\n\n /**\n * Replace all runs in-memory (does not persist — use save() for that).\n * Mirrors {@link setTurns} for the fork / restore case: callers that\n * bootstrap a session from an externally-derived snapshot (e.g.\n * `onForkTurn` copying parent runs into a child session) need this so\n * the cloned runs land in `data.runs` before the first `save()`.\n * Production agent runs continue to mutate runs via `startRun` /\n * `completeRun` / `updateRun`; this is the bulk-replace escape hatch.\n */\n setRuns: (runs: SessionRun[]) => void\n\n /** Update the session status in memory AND via store.updateStatus (if store present) */\n updateStatus: (status: SessionData['status']) => Promise<void>\n\n /** Persist an updated run record via store.updateRun (if store present) */\n updateRun: (run: SessionRun) => Promise<void>\n\n /** Generate a session-managed turn ID using store.generateTurnId if available, else crypto.randomUUID() */\n generateTurnId: () => string | Promise<string>\n\n /** Set metadata key */\n setMeta: (key: string, value: unknown) => void\n\n /** Persist the full session document to the store */\n save: () => Promise<void>\n\n /**\n * Project the session's persisted turns into wire-ready messages safe to\n * hand to any provider.\n *\n * The canonical answer to \"I need to send these turns to Anthropic /\n * OpenAI from outside `agent.run()`\" (sub-agent classifier, side-channel\n * summarizer, replay worker, …). Runs the same defensive pairing repair\n * the agent loop applies just-in-time at wire-send time\n * ({@link ensureToolResultPairing}), so orphan `tool_use` blocks and\n * dangling `tool_result`s never reach the provider as the 400\n * \"tool_result must be preceded by a tool_call with the same toolCallId\".\n *\n * Pass `provider` to also enforce the user-tail invariant\n * ({@link ensureEndsWithUserMessage}) — required for opus 4.7 / o-series\n * style models that reject assistant-prefill.\n *\n * Pure + idempotent. Resolves content refs only in the returned messages\n * and does NOT mutate `session.turns`. **Do not write the result back via\n * `setTurns` / `appendTurns`** — synthetic placeholders or resolved\n * payloads will contaminate persisted history.\n */\n toMessages: (options?: ToWireMessagesOptions) => Promise<SessionMessage[]>\n\n /** Serialize to SessionData */\n toJSON: () => SessionData\n\n /**\n * The backing store, when one was provided. Exposed so hosts can call\n * its optional `close()` on teardown (e.g. release the SQLite handle).\n */\n readonly store?: SessionStore\n}\n\n// ---------------------------------------------------------------------------\n// createSession\n// ---------------------------------------------------------------------------\n\nexport interface CreateSessionOptions {\n /** Session ID. If omitted and store provides generateSessionId, that is used. */\n id?: string\n /** Agent ID label */\n agentId?: string\n /**\n * Project tag — see {@link SessionData.projectRoot}. Stamped once on\n * creation; ignored when `_data` is set (restoring an existing\n * session preserves whatever was already persisted there). The TUI\n * resolves this from `findGitRoot(cwd) ?? cwd` so sessions started\n * from the same repo (no matter which subdir) share one tag.\n */\n projectRoot?: string\n /** Initial metadata */\n metadata?: Record<string, unknown>\n /** Storage backend (optional, enables save/load) */\n store?: SessionStore\n // @internal: restore from existing data (bypasses id/agentId/metadata options)\n _data?: SessionData\n}\n\n/**\n * Create a new session.\n * Async so stores that generate IDs server-side (e.g. a database) can be supported.\n */\nexport async function createSession(options: CreateSessionOptions = {}): Promise<Session> {\n const store = options.store\n const now = Date.now()\n\n let sessionId = options.id\n if (!sessionId && store?.generateSessionId) {\n sessionId = await store.generateSessionId()\n }\n if (!sessionId) {\n sessionId = generateId()\n }\n\n const data: SessionData = options._data ?? {\n id: sessionId,\n agentId: options.agentId,\n // Stamp the project tag at creation only — restored sessions (the\n // `_data` branch above) keep whatever was already persisted, even\n // if `options.projectRoot` differs. A session's project identity\n // is sticky for its lifetime; loading the same session from a\n // different cwd doesn't re-home it.\n ...(options.projectRoot ? { projectRoot: options.projectRoot } : {}),\n turns: [],\n runs: [],\n status: 'idle',\n metadata: options.metadata ?? {},\n createdAt: now,\n updatedAt: now,\n }\n\n function touch() {\n data.updatedAt = Date.now()\n }\n\n function findRun(runId: string): SessionRun | undefined {\n return data.runs.find(r => r.id === runId)\n }\n\n /**\n * Apply per-run usage stats onto a SessionRun. Shared by `completeRun`,\n * `abortRun`, and `errorRun` so the on-disk shape stays consistent across\n * exit paths — historically only `completeRun` filled these in, and\n * aborted/errored runs rendered `0 in / 0 out` on reload regardless of\n * how much was actually consumed.\n */\n function applyRunStats(run: SessionRun, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n run.turns = stats.turns\n run.tokensIn = stats.tokensIn\n run.tokensOut = stats.tokensOut\n if (stats.turnUsage) {\n run.turnUsage = stats.turnUsage\n const total = stats.turnUsage.reduce((acc, t) => ({\n input: acc.input + t.input,\n output: acc.output + t.output,\n cacheCreation: (acc.cacheCreation ?? 0) + (t.cacheCreation ?? 0),\n cacheRead: (acc.cacheRead ?? 0) + (t.cacheRead ?? 0),\n thinking: (acc.thinking ?? 0) + (t.thinking ?? 0),\n }), { input: 0, output: 0, cacheCreation: 0, cacheRead: 0, thinking: 0 })\n run.totalUsage = {\n input: total.input,\n output: total.output,\n ...(total.cacheCreation ? { cacheCreation: total.cacheCreation } : {}),\n ...(total.cacheRead ? { cacheRead: total.cacheRead } : {}),\n ...(total.thinking ? { thinking: total.thinking } : {}),\n }\n }\n if (stats.cost !== undefined)\n run.cost = stats.cost\n }\n\n const session: Session = {\n ...(store ? { store } : {}),\n get id() { return data.id },\n get agentId() { return data.agentId },\n get projectRoot() { return data.projectRoot },\n get turns() { return data.turns },\n get isEmpty() { return data.turns.length === 0 },\n get status() { return data.status },\n get runs() { return data.runs },\n get metadata() { return data.metadata },\n\n startRun(runId: string, prompt?: string, extras?: { parentRunId?: string, depth?: number }) {\n data.runs.push({\n id: runId,\n startedAt: Date.now(),\n prompt: prompt ?? '',\n status: 'running',\n ...(extras?.parentRunId ? { parentRunId: extras.parentRunId } : {}),\n ...(typeof extras?.depth === 'number' ? { depth: extras.depth } : {}),\n })\n touch()\n },\n\n completeRun(runId: string, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'completed'\n run.endedAt = Date.now()\n applyRunStats(run, stats)\n }\n touch()\n },\n\n abortRun(runId: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'aborted'\n run.endedAt = Date.now()\n // Backfill tokens when available so an aborted run's session\n // ledger reflects actual consumption rather than `0 in / 0 out`.\n if (stats)\n applyRunStats(run, stats)\n }\n touch()\n },\n\n errorRun(runId: string, error: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'error'\n run.endedAt = Date.now()\n run.error = error\n if (stats)\n applyRunStats(run, stats)\n }\n touch()\n },\n\n async appendTurns(turns: SessionTurn[]) {\n data.turns.push(...turns)\n touch()\n if (store) {\n await store.appendTurns(data.id, turns)\n }\n },\n\n setTurns(turns: SessionTurn[]) {\n data.turns = turns\n touch()\n },\n\n setRuns(runs: SessionRun[]) {\n data.runs = runs\n touch()\n },\n\n async updateStatus(status: SessionData['status']) {\n data.status = status\n touch()\n if (store) {\n await store.updateStatus(data.id, status)\n }\n },\n\n async updateRun(run: SessionRun) {\n if (store) {\n await store.updateRun(data.id, run)\n }\n },\n\n generateTurnId() {\n if (store?.generateTurnId) {\n return store.generateTurnId()\n }\n return crypto.randomUUID()\n },\n\n setMeta(key: string, value: unknown) {\n data.metadata[key] = value\n touch()\n },\n\n async save() {\n if (!store) {\n throw new Error('No SessionStore configured. Pass a store to createSession() to enable persistence.')\n }\n await store.save(data)\n },\n\n toMessages(options?: ToWireMessagesOptions) {\n return toWireMessages(data.turns, options)\n },\n\n toJSON() {\n return structuredClone(data)\n },\n }\n\n return session\n}\n\n/**\n * Demote a persisted `'running'` status to `'idle'` (in place) and return the\n * data. A persisted `'running'` is necessarily stale: the run that set it lived\n * in another process (crash, kill -9, power loss) and cannot still be executing\n * in a freshly-loaded session. Call this on the result of a raw `store.load()`\n * so consumers don't render a ghost in-progress state or refuse a new run.\n * `loadSession` applies it automatically; direct `store.load()` callers (e.g.\n * the TUI) should run loaded data through this.\n *\n * Run RECORDS get the same treatment: the agent persists each record at\n * run start with `status: 'running'` (crash durability — see the\n * `SessionStore.updateRun` contract), so a freshly-loaded session may\n * carry `'running'` runs that died with their process. They demote to\n * `'aborted'` so replay renders a truthful \"aborted\" state instead of a\n * perpetually-in-flight run.\n */\nexport function demoteStaleRunningStatus(data: SessionData): SessionData {\n if (data.status === 'running')\n data.status = 'idle'\n for (const run of data.runs) {\n if (run.status === 'running') {\n run.status = 'aborted'\n run.endedAt ??= run.startedAt\n }\n }\n return data\n}\n\n/**\n * Load an existing session from a store.\n */\nexport async function loadSession(store: SessionStore, sessionId: string): Promise<Session | null> {\n const loaded = await store.load(sessionId)\n if (!loaded)\n return null\n\n demoteStaleRunningStatus(loaded)\n\n return createSession({ store, _data: loaded })\n}\n\n// ---------------------------------------------------------------------------\n// Re-export stores\n// ---------------------------------------------------------------------------\n\nexport type { FileMapAdapter, FileMapStoreOptions } from './file-map'\nexport { createMemoryStore } from './memory'\nexport { autoDetectAndConvert, fromAnthropic, fromOpenAI, toAnthropic, toOpenAI, toWireMessages } from './messages'\nexport type { ToWireMessagesOptions } from './messages'\nexport { createRemoteStore } from './remote'\nexport type { RemoteStoreOptions } from './remote'\n\n// NOTE: `createSqliteStore` is intentionally NOT re-exported here. It lives behind\n// the dedicated `zidane/session/sqlite` subpath so that non-Bun consumers don't\n// transitively evaluate `bun:sqlite` when they import from `zidane/session`.\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction generateId(): string {\n return `ses_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`\n}\n\nfunction isSafeExtensionStateKey(key: string): boolean {\n return typeof key === 'string' && key.length > 0 && !DANGEROUS_RECORD_KEYS.has(key)\n}\n\nfunction jsonClone<T extends JsonValue>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nfunction assertSafeExtensionStateKey(key: string, label: string): void {\n if (!isSafeExtensionStateKey(key))\n throw new Error(`Invalid extension session state ${label}.`)\n}\n\nfunction cloneExtensionStateRoot(value: unknown): Record<string, Record<string, JsonValue>> {\n return clonePlainRecord(value) as Record<string, Record<string, JsonValue>>\n}\n\nfunction clonePlainRecord(value: unknown): Record<string, JsonValue> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return {}\n const out: Record<string, JsonValue> = {}\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (!isSafeExtensionStateKey(key))\n continue\n if (isJsonValue(child))\n out[key] = child\n }\n return out\n}\n\nfunction isJsonValue(value: unknown, depth = 0): value is JsonValue {\n if (value === null)\n return true\n if (typeof value === 'string' || typeof value === 'boolean')\n return true\n if (typeof value === 'number')\n return Number.isFinite(value)\n if (typeof value !== 'object')\n return false\n if (depth >= 8)\n return false\n if (Array.isArray(value))\n return value.every(item => isJsonValue(item, depth + 1))\n return Object.entries(value).every(([key, child]) =>\n isSafeExtensionStateKey(key) && isJsonValue(child, depth + 1),\n )\n}\n\nfunction assertJsonBounded(value: JsonValue, maxBytes: number, label: string): void {\n const json = JSON.stringify(value)\n if (json === undefined)\n throw new Error(`${label} must be JSON serializable.`)\n if (Buffer.byteLength(json) > maxBytes)\n throw new Error(`${label} exceeds ${maxBytes} bytes.`)\n}\n"],"mappings":";;;;AAiEA,SAAS,OAAO,MAA8B;CAC5C,OAAO;EACL,IAAI,KAAK;EACT,SAAS,KAAK;EACd,aAAa,KAAK;EAClB,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,UAAU,KAAK;EACf,WAAW,KAAK;EAChB,WAAW,KAAK;CAClB;AACF;AAEA,SAAS,OAAO,MAAiB,OAAmC;CAClE,OAAO;EACL,IAAI,KAAK;EACT,SAAS,KAAK;EACd,GAAI,OAAO,KAAK,gBAAgB,WAAW,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;EAChF;EACA,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,UAAU,KAAK;EACf,WAAW,KAAK;EAChB,WAAW,KAAK;CAClB;AACF;AAEA,SAAS,gBAAgB,OAA8B;CACrD,IAAI,CAAC,OACH,OAAO,CAAC;CACV,MAAM,QAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,MAAM,MAAM,IAAI,GAAG;EACpC,MAAM,UAAU,KAAK,KAAK;EAC1B,IAAI,CAAC,SACH;EACF,IAAI;GACF,MAAM,KAAK,KAAK,MAAM,OAAO,CAAgB;EAC/C,QACM,CAEN;CACF;CACA,OAAO;AACT;AAEA,SAAS,oBAAoB,OAA8B;CACzD,IAAI,MAAM,WAAW,GACnB,OAAO;CACT,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GACX,OAAO;CACT,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,OAAM,SAAQ,YAAY,MAAM,QAAQ,CAAC,CAAC;CACzD,OAAO,OAAO,QAAQ,KAAK,EAAE,OAAO,CAAC,KAAK,WACxC,wBAAwB,GAAG,KAAK,YAAY,OAAO,QAAQ,CAAC,CAC9D;AACF;AAEA,SAAS,kBAAkB,OAAkB,UAAkB,OAAqB;CAClF,MAAM,OAAO,KAAK,UAAU,KAAK;CACjC,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MAAM,GAAG,MAAM,4BAA4B;CACvD,IAAI,OAAO,WAAW,IAAI,IAAI,UAC5B,MAAM,IAAI,MAAM,GAAG,MAAM,WAAW,SAAS,QAAQ;AACzD"}
package/dist/session.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as FileMapAdapter, G as SessionRun, H as CreateSessionOptions, J as demoteStaleRunningStatus, K as SessionStore, Q as createMemoryStore, U as Session, W as SessionData, X as RemoteStoreOptions, Y as loadSession, Z as createRemoteStore, _t as fromOpenAI, bt as toOpenAI, dt as autoDetectAndConvert, et as FileMapStoreOptions, gt as fromAnthropic, lt as ToWireMessagesOptions, mr as SessionTurn, pr as SessionMessage, q as createSession, tt as createFileMapStore, ur as SessionContentBlock, xt as toWireMessages, yt as toAnthropic } from "./agent-EFWt6uQ_.js";
2
- export { CreateSessionOptions, type FileMapAdapter, type FileMapStoreOptions, type RemoteStoreOptions, Session, type SessionContentBlock, SessionData, type SessionMessage, SessionRun, SessionStore, type SessionTurn, type ToWireMessagesOptions, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, demoteStaleRunningStatus, fromAnthropic, fromOpenAI, loadSession, toAnthropic, toOpenAI, toWireMessages };
1
+ import { Af as SessionStore, Bd as SessionMessage, Bf as createRemoteStore, Df as Session, Ef as CreateSessionOptions, Ff as getExtensionSessionState, Hf as FileMapAdapter, If as loadSession, Ld as SessionContentBlock, Lf as setExtensionSessionState, Mf as currentExtensionSession, Nf as deleteExtensionSessionState, Of as SessionData, Pf as demoteStaleRunningStatus, Qf as ToWireMessagesOptions, Rf as withExtensionSession, Uf as FileMapStoreOptions, Vd as SessionTurn, Vf as createMemoryStore, Wf as createFileMapStore, ap as fromAnthropic, cp as toAnthropic, ep as autoDetectAndConvert, jf as createSession, kf as SessionRun, lp as toOpenAI, op as fromOpenAI, up as toWireMessages, zf as RemoteStoreOptions } from "./index-B8UtiZy7.js";
2
+ export { CreateSessionOptions, type FileMapAdapter, type FileMapStoreOptions, type RemoteStoreOptions, Session, type SessionContentBlock, SessionData, type SessionMessage, SessionRun, SessionStore, type SessionTurn, type ToWireMessagesOptions, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
package/dist/session.js CHANGED
@@ -1,3 +1,3 @@
1
- import { h as toWireMessages, i as autoDetectAndConvert, l as fromAnthropic, m as toOpenAI, p as toAnthropic, u as fromOpenAI } from "./messages-YZQLKaz2.js";
2
- import { a as createMemoryStore, i as createRemoteStore, n as demoteStaleRunningStatus, o as createFileMapStore, r as loadSession, t as createSession } from "./session-CqrAFAKJ.js";
3
- export { autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, demoteStaleRunningStatus, fromAnthropic, fromOpenAI, loadSession, toAnthropic, toOpenAI, toWireMessages };
1
+ import { h as toWireMessages, i as autoDetectAndConvert, l as fromAnthropic, m as toOpenAI, p as toAnthropic, u as fromOpenAI } from "./messages-CwujiS74.js";
2
+ import { a as getExtensionSessionState, c as withExtensionSession, d as createFileMapStore, i as demoteStaleRunningStatus, l as createRemoteStore, n as currentExtensionSession, o as loadSession, r as deleteExtensionSessionState, s as setExtensionSessionState, t as createSession, u as createMemoryStore } from "./session-CsdDIPY8.js";
3
+ export { autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
@@ -0,0 +1,295 @@
1
+ import { l as errorMessage } from "./errors-DJUxZg9b.js";
2
+ import { A as validateSkillName, _ as lastLine, b as resolveSubdirRoot, c as parseSkillFile, g as fetchInstallSource, h as defaultWhich, j as projectUserPaths, k as validateSkillForWrite, m as defaultExec, p as InstallSourceError, v as parseInstallSource } from "./resolve-Cr8JSL_O.js";
3
+ import { basename, join, resolve } from "node:path";
4
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ //#region src/skills/install.ts
7
+ var SkillInstallError = class extends InstallSourceError {
8
+ constructor(code, message, candidates) {
9
+ super(code, message, candidates);
10
+ this.name = "SkillInstallError";
11
+ }
12
+ };
13
+ function rethrowAsSkillError(err) {
14
+ if (err instanceof InstallSourceError && !(err instanceof SkillInstallError)) throw new SkillInstallError(err.code, err.message, err.candidates);
15
+ throw err;
16
+ }
17
+ const SKILLS_SH_URL_RE = /^(?:https?:\/\/)?(?:www\.)?skills\.sh\/([\w.-]+)\/([\w.-]+)(?:\/([\w.-]+))?\/?$/;
18
+ /**
19
+ * Parse a raw skill source. Accepts everything the shared grammar does
20
+ * (`owner/repo[#ref][:subdir]`, GitHub URLs, `pkg@version`, …) plus
21
+ * pasted skills.sh catalog URLs — `skills.sh/vercel-labs/agent-skills/
22
+ * react-best-practices` maps to the backing GitHub repo with the third
23
+ * segment as the skill selector.
24
+ */
25
+ function parseSkillInstallSpec(raw) {
26
+ const spec = raw.trim();
27
+ const skillsSh = SKILLS_SH_URL_RE.exec(spec);
28
+ if (skillsSh) return {
29
+ source: {
30
+ kind: "github",
31
+ owner: skillsSh[1],
32
+ repo: skillsSh[2]
33
+ },
34
+ ...skillsSh[3] ? { skill: skillsSh[3] } : {},
35
+ cliSpec: `${skillsSh[1]}/${skillsSh[2]}`
36
+ };
37
+ try {
38
+ return {
39
+ source: parseInstallSource(spec),
40
+ cliSpec: spec
41
+ };
42
+ } catch (err) {
43
+ rethrowAsSkillError(err);
44
+ }
45
+ }
46
+ /**
47
+ * How deep the candidate walk descends. Real-world collections nest
48
+ * skills under category directories (`skills/engineering/tdd/SKILL.md`
49
+ * in mattpocock/skills; `.github/skills/…` elsewhere) — one-level
50
+ * enumeration missed all of them. Four levels covers every observed
51
+ * layout while keeping the walk trivially bounded on the staged tree.
52
+ */
53
+ const CANDIDATE_WALK_MAX_DEPTH = 4;
54
+ /**
55
+ * List installable skills inside a fetched tree.
56
+ *
57
+ * A skill is ANY directory containing a `SKILL.md` — found by a
58
+ * bounded recursive walk (depth {@link CANDIDATE_WALK_MAX_DEPTH}),
59
+ * skipping dot-dirs and `node_modules`, and never descending INTO a
60
+ * skill (its `references/` / `scripts/` subtree ships with it, it
61
+ * doesn't nest further candidates). A root-level `SKILL.md` means
62
+ * "repo IS the skill" and short-circuits, named from the fallback.
63
+ *
64
+ * Candidates carry their root-relative path (`rel`) so same-named
65
+ * skills in different categories stay individually addressable.
66
+ * Sorted by `rel`.
67
+ */
68
+ function listSkillCandidates(dir, fallbackName) {
69
+ if (existsSync(join(dir, "SKILL.md"))) return [{
70
+ name: sanitizeName(fallbackName),
71
+ dir,
72
+ rel: "."
73
+ }];
74
+ const out = [];
75
+ const walk = (current, rel, depth) => {
76
+ if (depth > CANDIDATE_WALK_MAX_DEPTH) return;
77
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
78
+ if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules") continue;
79
+ const childDir = join(current, entry.name);
80
+ const childRel = rel.length === 0 ? entry.name : `${rel}/${entry.name}`;
81
+ if (existsSync(join(childDir, "SKILL.md"))) out.push({
82
+ name: entry.name,
83
+ dir: childDir,
84
+ rel: childRel
85
+ });
86
+ else walk(childDir, childRel, depth + 1);
87
+ }
88
+ };
89
+ walk(dir, "", 1);
90
+ return out.sort((a, b) => a.rel.localeCompare(b.rel));
91
+ }
92
+ /** Human-readable candidate list for error messages — capped, rel-qualified when ambiguous. */
93
+ function describeCandidates(candidates) {
94
+ const nameCounts = /* @__PURE__ */ new Map();
95
+ for (const c of candidates) nameCounts.set(c.name, (nameCounts.get(c.name) ?? 0) + 1);
96
+ const labels = candidates.map((c) => (nameCounts.get(c.name) ?? 0) > 1 ? c.rel : c.name);
97
+ const shown = labels.slice(0, 20);
98
+ const more = labels.length - shown.length;
99
+ return shown.join(", ") + (more > 0 ? `, … and ${more} more` : "");
100
+ }
101
+ /**
102
+ * Validate a staged candidate by PARSING its SKILL.md — the same lenient
103
+ * parser discovery runs, so "installs cleanly" and "discovers cleanly"
104
+ * are the same predicate. Returns the frontmatter name (which wins over
105
+ * the directory-derived candidate name for the target folder).
106
+ */
107
+ async function validateSkillCandidate(candidate) {
108
+ const parsed = await parseSkillFile(join(candidate.dir, "SKILL.md"));
109
+ if (!parsed) throw new SkillInstallError("validate-failed", `${candidate.dir}/SKILL.md is not a valid skill (missing name or description in frontmatter).`);
110
+ const name = parsed.name;
111
+ if (!validateSkillName(name)) throw new SkillInstallError("validate-failed", `Skill name "${name}" is invalid (lowercase alphanumerics + single hyphens, max 64 chars).`);
112
+ return { name };
113
+ }
114
+ /**
115
+ * Install a skill (or one skill out of a multi-skill source).
116
+ *
117
+ * Engine selection: the skills.sh CLI when present on PATH (unless
118
+ * `preferSkillsCli: false`), else the native fetch pipeline. Both accept
119
+ * the same specs; the CLI path additionally understands anything newer
120
+ * their grammar grows, since the spec passes through verbatim.
121
+ */
122
+ async function installSkillFromSpec(opts) {
123
+ const which = (opts.io ?? {}).which ?? defaultWhich;
124
+ const spec = parseSkillInstallSpec(opts.source);
125
+ const skillSelector = opts.skill ?? spec.skill;
126
+ if ((opts.preferSkillsCli ?? true) && which("skills")) return await installViaSkillsCli(spec, skillSelector, opts);
127
+ return await installNatively(spec, skillSelector, opts);
128
+ }
129
+ /**
130
+ * Delegate to the skills.sh CLI. Non-interactive by construction: `-y`
131
+ * skips confirmation prompts, `-g` maps our `user` scope to their
132
+ * global scope (project scope is their default, keyed off cwd). The CLI
133
+ * decides the on-disk layout (`.agents/skills/`), which zidane's
134
+ * discovery already scans.
135
+ */
136
+ async function installViaSkillsCli(spec, skillSelector, opts) {
137
+ const exec = opts.io?.exec ?? defaultExec;
138
+ const args = [
139
+ "add",
140
+ spec.cliSpec,
141
+ "-y"
142
+ ];
143
+ if (skillSelector) args.push("--skill", skillSelector);
144
+ if (opts.scope === "user") args.push("-g");
145
+ opts.onProgress?.(`skills add ${spec.cliSpec}${skillSelector ? ` --skill ${skillSelector}` : ""}…`);
146
+ const res = await exec("skills", args, { cwd: opts.cwd ?? process.cwd() });
147
+ if (!res.ok) throw new SkillInstallError("cli-failed", `skills.sh CLI failed: ${lastLine(res.stderr) || lastLine(res.stdout) || "unknown error"}`);
148
+ return {
149
+ installed: [skillSelector ?? spec.cliSpec],
150
+ engine: "skills-cli"
151
+ };
152
+ }
153
+ async function installNatively(spec, skillSelector, opts) {
154
+ const io = opts.io ?? {};
155
+ const source = spec.source;
156
+ const stage = mkdtempSync(join(tmpdir(), "zidane-skill-install-"));
157
+ try {
158
+ const fetchedInto = join(stage, "fetched");
159
+ mkdirSync(fetchedInto, { recursive: true });
160
+ let provenance;
161
+ try {
162
+ provenance = (await fetchInstallSource(source, fetchedInto, io, opts.onProgress)).provenance;
163
+ } catch (err) {
164
+ rethrowAsSkillError(err);
165
+ }
166
+ let candidateRoot = fetchedInto;
167
+ let fallbackName = source.kind === "github" ? source.repo : source.pkg;
168
+ if (source.kind === "github" && source.subdir) {
169
+ const rooted = resolveSubdirRoot(fetchedInto, source.subdir);
170
+ if (!rooted.ok) {
171
+ if (rooted.reason === "missing") throw new SkillInstallError("no-skill", `"${source.subdir}" is not a directory in ${source.owner}/${source.repo}.`);
172
+ throw new SkillInstallError("invalid-source", `Subdirectory "${source.subdir}" escapes the repository root${rooted.reason === "escape-symlink" ? " through a symlink" : ""}.`);
173
+ }
174
+ candidateRoot = rooted.dir;
175
+ fallbackName = basename(resolve(fetchedInto, source.subdir));
176
+ }
177
+ const candidates = listSkillCandidates(candidateRoot, fallbackName);
178
+ if (candidates.length === 0) throw new SkillInstallError("no-skill", `No skill found in ${opts.source} — no SKILL.md anywhere in the tree (searched ${CANDIDATE_WALK_MAX_DEPTH} levels deep).`);
179
+ let picked;
180
+ if (skillSelector) {
181
+ const matches = candidates.filter((c) => c.name === skillSelector || c.rel === skillSelector);
182
+ if (matches.length === 0) throw new SkillInstallError("no-skill", `No skill named "${skillSelector}" in ${opts.source}. Available: ${describeCandidates(candidates)}`, candidates.map((c) => c.rel));
183
+ if (matches.length > 1) throw new SkillInstallError("multiple-candidates", `"${skillSelector}" is ambiguous in ${opts.source} — pick a path: ${matches.map((c) => c.rel).join(", ")}`, matches.map((c) => c.rel));
184
+ picked = matches[0];
185
+ } else if (candidates.length > 1) throw new SkillInstallError("multiple-candidates", `${opts.source} contains ${candidates.length} skills — pick one: ${describeCandidates(candidates)}`, candidates.map((c) => c.rel));
186
+ else picked = candidates[0];
187
+ const { name } = await validateSkillCandidate(picked);
188
+ const root = scopeRoot(opts);
189
+ const targetDir = join(root, name);
190
+ const backupDir = `${targetDir}.zidane-backup`;
191
+ if (existsSync(targetDir) && !opts.overwrite) throw new SkillInstallError("exists", `Skill "${name}" is already installed at ${targetDir}. Overwrite to replace it.`);
192
+ mkdirSync(root, { recursive: true });
193
+ const hadPrevious = existsSync(targetDir);
194
+ if (hadPrevious) {
195
+ rmSync(backupDir, {
196
+ recursive: true,
197
+ force: true
198
+ });
199
+ renameSync(targetDir, backupDir);
200
+ }
201
+ try {
202
+ cpSync(picked.dir, targetDir, {
203
+ recursive: true,
204
+ dereference: true
205
+ });
206
+ writeProvenance(targetDir, {
207
+ spec: opts.source,
208
+ ...skillSelector ? { skill: skillSelector } : {},
209
+ scope: opts.scope,
210
+ provenance,
211
+ installedAt: Date.now()
212
+ });
213
+ } catch (err) {
214
+ rmSync(targetDir, {
215
+ recursive: true,
216
+ force: true
217
+ });
218
+ if (hadPrevious) renameSync(backupDir, targetDir);
219
+ throw new SkillInstallError("io-failed", `Writing ${targetDir} failed: ${errorMessage(err)}`);
220
+ }
221
+ rmSync(backupDir, {
222
+ recursive: true,
223
+ force: true
224
+ });
225
+ return {
226
+ installed: [name],
227
+ dir: targetDir,
228
+ engine: "native",
229
+ provenance
230
+ };
231
+ } finally {
232
+ rmSync(stage, {
233
+ recursive: true,
234
+ force: true
235
+ });
236
+ }
237
+ }
238
+ /** Provenance sidecar — lets a future update flow replay the recorded spec. */
239
+ const SKILL_PROVENANCE_FILE = ".zidane-install.json";
240
+ function writeProvenance(dir, data) {
241
+ writeFileSync(join(dir, SKILL_PROVENANCE_FILE), `${JSON.stringify(data, null, 2)}\n`);
242
+ }
243
+ /** Read a skill directory's install provenance, `null` for hand-authored skills. */
244
+ function readSkillProvenance(dir) {
245
+ try {
246
+ const raw = JSON.parse(readFileSync(join(dir, SKILL_PROVENANCE_FILE), "utf8"));
247
+ return typeof raw.spec === "string" && raw.spec.length > 0 ? raw : null;
248
+ } catch {
249
+ return null;
250
+ }
251
+ }
252
+ /**
253
+ * Native-install target root: the `<prefix>/skills` flavor of the
254
+ * project/user convention (`~/.zidane/skills`, `<gitRoot>/.zidane/skills`).
255
+ * The `.agents/skills` siblings stay read-only for us — they belong to
256
+ * the cross-agent ecosystem (and the skills.sh CLI writes there).
257
+ */
258
+ function scopeRoot(opts) {
259
+ const root = projectUserPaths({
260
+ subPath: "skills",
261
+ ...opts.cwd ? { cwd: opts.cwd } : {},
262
+ ...opts.home ? { home: opts.home } : {},
263
+ ...opts.prefix ? { prefix: opts.prefix } : {}
264
+ }).find((r) => r.source === opts.scope && r.path.includes(`.${(opts.prefix ?? ".zidane").replace(/^\./, "")}`));
265
+ if (!root) throw new SkillInstallError("io-failed", `No ${opts.scope} skills root resolved.`);
266
+ return root.path;
267
+ }
268
+ function sanitizeName(raw) {
269
+ const cleaned = raw.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-");
270
+ return cleaned.length > 0 ? cleaned : "skill";
271
+ }
272
+ //#endregion
273
+ //#region src/skills/index.ts
274
+ /**
275
+ * Define an inline skill configuration.
276
+ *
277
+ * Strict-validates at author-time — throws if the config would be rejected by
278
+ * `writeSkillToDisk` or the spec. Source defaults to `'inline'`.
279
+ */
280
+ function defineSkill(config) {
281
+ const normalized = {
282
+ ...config,
283
+ source: config.source ?? "inline"
284
+ };
285
+ const result = validateSkillForWrite(normalized);
286
+ if (!result.valid) {
287
+ const summary = result.errors.map((e) => ` - [${e.code}] ${e.message}`).join("\n");
288
+ throw new Error(`Invalid skill "${normalized.name}":\n${summary}`);
289
+ }
290
+ return normalized;
291
+ }
292
+ //#endregion
293
+ export { listSkillCandidates as a, installSkillFromSpec as i, SKILL_PROVENANCE_FILE as n, parseSkillInstallSpec as o, SkillInstallError as r, readSkillProvenance as s, defineSkill as t };
294
+
295
+ //# sourceMappingURL=skills-Bsb0rvWI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skills-Bsb0rvWI.js","names":[],"sources":["../src/skills/install.ts","../src/skills/index.ts"],"sourcesContent":["/**\n * Skill installation — fetch a skill (or a collection of skills) from\n * GitHub / npm / skills.sh and land it under the zidane skills root,\n * where the existing discovery scan picks it up.\n *\n * Built on the shared install layer (`src/install/source.ts`), so the\n * spec grammar, transports, download caps, and subdir containment are\n * byte-identical with the extensions installer. What differs:\n *\n * - **Validation never executes code.** A skill is data: candidates\n * are validated by parsing `SKILL.md` (lenient parser, same one\n * discovery uses) — unlike extensions, whose validation must import\n * the module. Installing a hostile skill can plant instructions,\n * never run a process.\n * - **skills.sh interop, two-way.** The spec grammar accepts pasted\n * `https://skills.sh/<owner>/<repo>[/<skill>]` catalog URLs (mapped\n * to the GitHub repo + a skill selector — skills.sh uses GitHub as\n * its registry). And when the `skills` CLI is on PATH,\n * {@link installSkillFromSpec} delegates to it (`skills add … -y`)\n * so installs land in the user's cross-agent `.agents/skills/`\n * layout and feed the skills.sh lockfile/leaderboard; without the\n * CLI the native fetch path installs the same repos directly.\n * - **Target roots**: `~/.zidane/skills/<name>` (user) or\n * `<gitRoot>/.zidane/skills/<name>` (project) — both already on\n * discovery's default scan paths.\n *\n * Same hardening as extensions: staged `mkdtemp` fetch, physical\n * symlink containment for `:subdir`, folder-safe names, overwrite with\n * backup/rollback, and a provenance file (`.zidane-install.json`) so a\n * future update flow can replay the spec.\n */\n\nimport type { InstallIo, InstallScope, InstallSource } from '../install/source'\nimport { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { basename, join, resolve } from 'node:path'\nimport { projectUserPaths } from '../chat/project-user-paths'\nimport { errorMessage } from '../errors'\nimport { defaultExec, defaultWhich, fetchInstallSource, InstallSourceError, lastLine, parseInstallSource, resolveSubdirRoot } from '../install/source'\nimport { parseSkillFile } from './discovery'\nimport { validateSkillName } from './validate'\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport type SkillInstallErrorCode\n = | 'invalid-source'\n | 'fetch-failed'\n | 'no-skill'\n | 'multiple-candidates'\n | 'validate-failed'\n | 'exists'\n | 'cli-failed'\n | 'io-failed'\n\nexport class SkillInstallError extends InstallSourceError {\n declare readonly code: SkillInstallErrorCode\n constructor(code: SkillInstallErrorCode, message: string, candidates?: readonly string[]) {\n super(code, message, candidates)\n this.name = 'SkillInstallError'\n }\n}\n\nfunction rethrowAsSkillError(err: unknown): never {\n if (err instanceof InstallSourceError && !(err instanceof SkillInstallError))\n throw new SkillInstallError(err.code as SkillInstallErrorCode, err.message, err.candidates)\n throw err\n}\n\n// ---------------------------------------------------------------------------\n// Spec parsing (shared grammar + the skills.sh catalog URL form)\n// ---------------------------------------------------------------------------\n\nconst SKILLS_SH_URL_RE = /^(?:https?:\\/\\/)?(?:www\\.)?skills\\.sh\\/([\\w.-]+)\\/([\\w.-]+)(?:\\/([\\w.-]+))?\\/?$/\n\nexport interface SkillInstallSpec {\n source: InstallSource\n /**\n * Skill name selector for multi-skill sources. From a skills.sh URL's\n * third segment or the caller's explicit pick after a\n * `multiple-candidates` error.\n */\n skill?: string\n /**\n * The spec string to hand the `skills` CLI (its `add` argument).\n * skills.sh URLs pass through verbatim — the CLI understands them —\n * while parsed shorthand re-serializes to `owner/repo`.\n */\n cliSpec: string\n}\n\n/**\n * Parse a raw skill source. Accepts everything the shared grammar does\n * (`owner/repo[#ref][:subdir]`, GitHub URLs, `pkg@version`, …) plus\n * pasted skills.sh catalog URLs — `skills.sh/vercel-labs/agent-skills/\n * react-best-practices` maps to the backing GitHub repo with the third\n * segment as the skill selector.\n */\nexport function parseSkillInstallSpec(raw: string): SkillInstallSpec {\n const spec = raw.trim()\n const skillsSh = SKILLS_SH_URL_RE.exec(spec)\n if (skillsSh) {\n return {\n source: { kind: 'github', owner: skillsSh[1] as string, repo: skillsSh[2] as string },\n ...(skillsSh[3] ? { skill: skillsSh[3] } : {}),\n cliSpec: `${skillsSh[1]}/${skillsSh[2]}`,\n }\n }\n try {\n const source = parseInstallSource(spec)\n return { source, cliSpec: spec }\n }\n catch (err) {\n rethrowAsSkillError(err)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Candidate enumeration + validation (data-only — no code execution)\n// ---------------------------------------------------------------------------\n\nexport interface SkillInstallCandidate {\n /** Directory name candidate (validated against SKILL.md frontmatter later). */\n name: string\n dir: string\n /**\n * Root-relative path (`engineering/tdd`) — the unambiguous selector\n * when the same skill NAME exists in several category directories.\n */\n rel: string\n}\n\n/**\n * How deep the candidate walk descends. Real-world collections nest\n * skills under category directories (`skills/engineering/tdd/SKILL.md`\n * in mattpocock/skills; `.github/skills/…` elsewhere) — one-level\n * enumeration missed all of them. Four levels covers every observed\n * layout while keeping the walk trivially bounded on the staged tree.\n */\nconst CANDIDATE_WALK_MAX_DEPTH = 4\n\n/**\n * List installable skills inside a fetched tree.\n *\n * A skill is ANY directory containing a `SKILL.md` — found by a\n * bounded recursive walk (depth {@link CANDIDATE_WALK_MAX_DEPTH}),\n * skipping dot-dirs and `node_modules`, and never descending INTO a\n * skill (its `references/` / `scripts/` subtree ships with it, it\n * doesn't nest further candidates). A root-level `SKILL.md` means\n * \"repo IS the skill\" and short-circuits, named from the fallback.\n *\n * Candidates carry their root-relative path (`rel`) so same-named\n * skills in different categories stay individually addressable.\n * Sorted by `rel`.\n */\nexport function listSkillCandidates(dir: string, fallbackName: string): SkillInstallCandidate[] {\n if (existsSync(join(dir, 'SKILL.md')))\n return [{ name: sanitizeName(fallbackName), dir, rel: '.' }]\n const out: SkillInstallCandidate[] = []\n const walk = (current: string, rel: string, depth: number): void => {\n if (depth > CANDIDATE_WALK_MAX_DEPTH)\n return\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules')\n continue\n const childDir = join(current, entry.name)\n const childRel = rel.length === 0 ? entry.name : `${rel}/${entry.name}`\n if (existsSync(join(childDir, 'SKILL.md')))\n out.push({ name: entry.name, dir: childDir, rel: childRel })\n else\n walk(childDir, childRel, depth + 1)\n }\n }\n walk(dir, '', 1)\n return out.sort((a, b) => a.rel.localeCompare(b.rel))\n}\n\n/** Human-readable candidate list for error messages — capped, rel-qualified when ambiguous. */\nfunction describeCandidates(candidates: readonly SkillInstallCandidate[]): string {\n const nameCounts = new Map<string, number>()\n for (const c of candidates)\n nameCounts.set(c.name, (nameCounts.get(c.name) ?? 0) + 1)\n const labels = candidates.map(c => ((nameCounts.get(c.name) ?? 0) > 1 ? c.rel : c.name))\n const shown = labels.slice(0, 20)\n const more = labels.length - shown.length\n return shown.join(', ') + (more > 0 ? `, … and ${more} more` : '')\n}\n\n/**\n * Validate a staged candidate by PARSING its SKILL.md — the same lenient\n * parser discovery runs, so \"installs cleanly\" and \"discovers cleanly\"\n * are the same predicate. Returns the frontmatter name (which wins over\n * the directory-derived candidate name for the target folder).\n */\nasync function validateSkillCandidate(candidate: SkillInstallCandidate): Promise<{ name: string }> {\n const parsed = await parseSkillFile(join(candidate.dir, 'SKILL.md'))\n if (!parsed)\n throw new SkillInstallError('validate-failed', `${candidate.dir}/SKILL.md is not a valid skill (missing name or description in frontmatter).`)\n const name = parsed.name\n if (!validateSkillName(name))\n throw new SkillInstallError('validate-failed', `Skill name \"${name}\" is invalid (lowercase alphanumerics + single hyphens, max 64 chars).`)\n return { name }\n}\n\n// ---------------------------------------------------------------------------\n// Install\n// ---------------------------------------------------------------------------\n\nexport interface SkillInstallOptions {\n /** Raw source spec — see {@link parseSkillInstallSpec} for the grammar. */\n source: string\n scope: InstallScope\n /** Pick one skill from a multi-skill source (names from the `multiple-candidates` error). */\n skill?: string\n /** Overwrite an existing install of the same name. */\n overwrite?: boolean\n cwd?: string\n home?: string\n /** Storage prefix (default `.zidane`) — mirrors `ResolvedConfig.prefix`. */\n prefix?: string\n io?: InstallIo\n onProgress?: (message: string) => void\n /**\n * Prefer the skills.sh CLI when `skills` is on PATH (default true).\n * The CLI owns scope + layout decisions (`.agents/skills/`, their\n * lockfile); the native path is the fallback and the forced path in\n * tests. Set false to always install natively.\n */\n preferSkillsCli?: boolean\n}\n\nexport interface SkillInstallResult {\n /** Final skill name(s) installed. The CLI path reports the spec, not names. */\n installed: readonly string[]\n /** Absolute target directory (native path only — the CLI owns its layout). */\n dir?: string\n /** `skills-cli` when delegated to the skills.sh CLI, else `native`. */\n engine: 'skills-cli' | 'native'\n provenance?: string\n}\n\n/**\n * Install a skill (or one skill out of a multi-skill source).\n *\n * Engine selection: the skills.sh CLI when present on PATH (unless\n * `preferSkillsCli: false`), else the native fetch pipeline. Both accept\n * the same specs; the CLI path additionally understands anything newer\n * their grammar grows, since the spec passes through verbatim.\n */\nexport async function installSkillFromSpec(opts: SkillInstallOptions): Promise<SkillInstallResult> {\n const io = opts.io ?? {}\n const which = io.which ?? defaultWhich\n const spec = parseSkillInstallSpec(opts.source)\n const skillSelector = opts.skill ?? spec.skill\n\n if ((opts.preferSkillsCli ?? true) && which('skills'))\n return await installViaSkillsCli(spec, skillSelector, opts)\n\n return await installNatively(spec, skillSelector, opts)\n}\n\n/**\n * Delegate to the skills.sh CLI. Non-interactive by construction: `-y`\n * skips confirmation prompts, `-g` maps our `user` scope to their\n * global scope (project scope is their default, keyed off cwd). The CLI\n * decides the on-disk layout (`.agents/skills/`), which zidane's\n * discovery already scans.\n */\nasync function installViaSkillsCli(\n spec: SkillInstallSpec,\n skillSelector: string | undefined,\n opts: SkillInstallOptions,\n): Promise<SkillInstallResult> {\n const exec = opts.io?.exec ?? defaultExec\n const args = ['add', spec.cliSpec, '-y']\n if (skillSelector)\n args.push('--skill', skillSelector)\n if (opts.scope === 'user')\n args.push('-g')\n opts.onProgress?.(`skills add ${spec.cliSpec}${skillSelector ? ` --skill ${skillSelector}` : ''}…`)\n const res = await exec('skills', args, { cwd: opts.cwd ?? process.cwd() })\n if (!res.ok)\n throw new SkillInstallError('cli-failed', `skills.sh CLI failed: ${lastLine(res.stderr) || lastLine(res.stdout) || 'unknown error'}`)\n return {\n installed: [skillSelector ?? spec.cliSpec],\n engine: 'skills-cli',\n }\n}\n\nasync function installNatively(\n spec: SkillInstallSpec,\n skillSelector: string | undefined,\n opts: SkillInstallOptions,\n): Promise<SkillInstallResult> {\n const io = opts.io ?? {}\n const source = spec.source\n const stage = mkdtempSync(join(tmpdir(), 'zidane-skill-install-'))\n try {\n const fetchedInto = join(stage, 'fetched')\n mkdirSync(fetchedInto, { recursive: true })\n let provenance: string\n try {\n provenance = (await fetchInstallSource(source, fetchedInto, io, opts.onProgress)).provenance\n }\n catch (err) {\n rethrowAsSkillError(err)\n }\n\n // `:subdir` re-roots the search — same physical containment as\n // extensions (hostile symlinks must not walk out of the stage).\n let candidateRoot = fetchedInto\n let fallbackName = source.kind === 'github' ? source.repo : source.pkg\n if (source.kind === 'github' && source.subdir) {\n const rooted = resolveSubdirRoot(fetchedInto, source.subdir)\n if (!rooted.ok) {\n if (rooted.reason === 'missing')\n throw new SkillInstallError('no-skill', `\"${source.subdir}\" is not a directory in ${source.owner}/${source.repo}.`)\n throw new SkillInstallError('invalid-source', `Subdirectory \"${source.subdir}\" escapes the repository root${rooted.reason === 'escape-symlink' ? ' through a symlink' : ''}.`)\n }\n candidateRoot = rooted.dir\n fallbackName = basename(resolve(fetchedInto, source.subdir))\n }\n\n const candidates = listSkillCandidates(candidateRoot, fallbackName)\n if (candidates.length === 0)\n throw new SkillInstallError('no-skill', `No skill found in ${opts.source} — no SKILL.md anywhere in the tree (searched ${CANDIDATE_WALK_MAX_DEPTH} levels deep).`)\n let picked: SkillInstallCandidate\n if (skillSelector) {\n // Selector matches the skill name OR its root-relative path — the\n // path form disambiguates same-named skills in different category\n // directories (`engineering/tdd` vs `personal/tdd`).\n const matches = candidates.filter(c => c.name === skillSelector || c.rel === skillSelector)\n if (matches.length === 0)\n throw new SkillInstallError('no-skill', `No skill named \"${skillSelector}\" in ${opts.source}. Available: ${describeCandidates(candidates)}`, candidates.map(c => c.rel))\n if (matches.length > 1)\n throw new SkillInstallError('multiple-candidates', `\"${skillSelector}\" is ambiguous in ${opts.source} — pick a path: ${matches.map(c => c.rel).join(', ')}`, matches.map(c => c.rel))\n picked = matches[0] as SkillInstallCandidate\n }\n else if (candidates.length > 1) {\n throw new SkillInstallError('multiple-candidates', `${opts.source} contains ${candidates.length} skills — pick one: ${describeCandidates(candidates)}`, candidates.map(c => c.rel))\n }\n else {\n picked = candidates[0] as SkillInstallCandidate\n }\n\n // Frontmatter name wins over the directory-derived candidate name —\n // mirrors \"target folder is named from the VALIDATED definition\".\n const { name } = await validateSkillCandidate(picked)\n\n const root = scopeRoot(opts)\n const targetDir = join(root, name)\n const backupDir = `${targetDir}.zidane-backup`\n if (existsSync(targetDir) && !opts.overwrite)\n throw new SkillInstallError('exists', `Skill \"${name}\" is already installed at ${targetDir}. Overwrite to replace it.`)\n\n mkdirSync(root, { recursive: true })\n const hadPrevious = existsSync(targetDir)\n if (hadPrevious) {\n rmSync(backupDir, { recursive: true, force: true })\n renameSync(targetDir, backupDir)\n }\n try {\n // `dereference` materializes in-tree symlinked files so the install\n // has no dangling links once the stage is deleted.\n cpSync(picked.dir, targetDir, { recursive: true, dereference: true })\n writeProvenance(targetDir, { spec: opts.source, ...(skillSelector ? { skill: skillSelector } : {}), scope: opts.scope, provenance, installedAt: Date.now() })\n }\n catch (err) {\n rmSync(targetDir, { recursive: true, force: true })\n if (hadPrevious)\n renameSync(backupDir, targetDir)\n throw new SkillInstallError('io-failed', `Writing ${targetDir} failed: ${errorMessage(err)}`)\n }\n rmSync(backupDir, { recursive: true, force: true })\n\n return { installed: [name], dir: targetDir, engine: 'native', provenance }\n }\n finally {\n rmSync(stage, { recursive: true, force: true })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Provenance sidecar — lets a future update flow replay the recorded spec. */\nexport const SKILL_PROVENANCE_FILE = '.zidane-install.json'\n\ninterface SkillProvenance {\n spec: string\n skill?: string\n scope: InstallScope\n provenance: string\n installedAt: number\n}\n\nfunction writeProvenance(dir: string, data: SkillProvenance): void {\n writeFileSync(join(dir, SKILL_PROVENANCE_FILE), `${JSON.stringify(data, null, 2)}\\n`)\n}\n\n/** Read a skill directory's install provenance, `null` for hand-authored skills. */\nexport function readSkillProvenance(dir: string): (SkillProvenance & { spec: string }) | null {\n try {\n const raw = JSON.parse(readFileSync(join(dir, SKILL_PROVENANCE_FILE), 'utf8')) as Partial<SkillProvenance>\n return typeof raw.spec === 'string' && raw.spec.length > 0 ? (raw as SkillProvenance) : null\n }\n catch {\n return null\n }\n}\n\n/**\n * Native-install target root: the `<prefix>/skills` flavor of the\n * project/user convention (`~/.zidane/skills`, `<gitRoot>/.zidane/skills`).\n * The `.agents/skills` siblings stay read-only for us — they belong to\n * the cross-agent ecosystem (and the skills.sh CLI writes there).\n */\nfunction scopeRoot(opts: SkillInstallOptions): string {\n const roots = projectUserPaths({\n subPath: 'skills',\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.home ? { home: opts.home } : {}),\n ...(opts.prefix ? { prefix: opts.prefix } : {}),\n })\n const root = roots.find(r => r.source === opts.scope && r.path.includes(`.${(opts.prefix ?? '.zidane').replace(/^\\./, '')}`))\n if (!root)\n throw new SkillInstallError('io-failed', `No ${opts.scope} skills root resolved.`)\n return root.path\n}\n\nfunction sanitizeName(raw: string): string {\n const cleaned = raw.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, '-')\n return cleaned.length > 0 ? cleaned : 'skill'\n}\n","import type { SkillConfig } from './types'\nimport { validateSkillForWrite } from './validate'\n\nexport {\n type ActivationVia,\n type ActiveSkill,\n createSkillActivationState,\n type DeactivationReason,\n type SkillActivationState,\n type SkillActivationStateOptions,\n} from './activation'\nexport {\n IMPLICITLY_ALLOWED_SKILL_TOOLS,\n installAllowedToolsGate,\n} from './allowed-tools'\nexport { buildCatalog } from './catalog'\nexport {\n discoverSkills,\n getDefaultScanPaths,\n inferSource,\n parseFrontmatter,\n parseSkillFile,\n} from './discovery'\nexport type { SourcedScanPath } from './discovery'\nexport {\n installSkillFromSpec,\n listSkillCandidates,\n parseSkillInstallSpec,\n readSkillProvenance,\n SKILL_PROVENANCE_FILE,\n SkillInstallError,\n} from './install'\nexport type {\n SkillInstallCandidate,\n SkillInstallErrorCode,\n SkillInstallOptions,\n SkillInstallResult,\n SkillInstallSpec,\n} from './install'\nexport { interpolateShellCommands, stripShellInterpolations } from './interpolate'\nexport type { InterpolateShellCommandsOptions } from './interpolate'\nexport { resolveSkills } from './resolve'\nexport type {\n ShellInterpolationApproval,\n SkillConfig,\n SkillDiagnostic,\n SkillResource,\n SkillsConfig,\n SkillSource,\n} from './types'\nexport {\n isToolAllowedByUnion,\n matchesAllowedTool,\n parseAllowedToolPattern,\n validateResourcePath,\n validateResourcePathReal,\n validateSkillForWrite,\n validateSkillName,\n} from './validate'\nexport type { SkillValidationIssue, SkillValidationResult } from './validate'\nexport { writeSkillsToDisk, writeSkillToDisk } from './writer'\n\n// ---------------------------------------------------------------------------\n// defineSkill helper\n// ---------------------------------------------------------------------------\n\n/**\n * Define an inline skill configuration.\n *\n * Strict-validates at author-time — throws if the config would be rejected by\n * `writeSkillToDisk` or the spec. Source defaults to `'inline'`.\n */\nexport function defineSkill(config: Omit<SkillConfig, 'source'> & { source?: SkillConfig['source'] }): SkillConfig {\n const normalized: SkillConfig = {\n ...config,\n source: config.source ?? 'inline',\n }\n const result = validateSkillForWrite(normalized)\n if (!result.valid) {\n const summary = result.errors.map(e => ` - [${e.code}] ${e.message}`).join('\\n')\n throw new Error(`Invalid skill \"${normalized.name}\":\\n${summary}`)\n }\n return normalized\n}\n"],"mappings":";;;;;;AAwDA,IAAa,oBAAb,cAAuC,mBAAmB;CAExD,YAAY,MAA6B,SAAiB,YAAgC;EACxF,MAAM,MAAM,SAAS,UAAU;EAC/B,KAAK,OAAO;CACd;AACF;AAEA,SAAS,oBAAoB,KAAqB;CAChD,IAAI,eAAe,sBAAsB,EAAE,eAAe,oBACxD,MAAM,IAAI,kBAAkB,IAAI,MAA+B,IAAI,SAAS,IAAI,UAAU;CAC5F,MAAM;AACR;AAMA,MAAM,mBAAmB;;;;;;;;AAyBzB,SAAgB,sBAAsB,KAA+B;CACnE,MAAM,OAAO,IAAI,KAAK;CACtB,MAAM,WAAW,iBAAiB,KAAK,IAAI;CAC3C,IAAI,UACF,OAAO;EACL,QAAQ;GAAE,MAAM;GAAU,OAAO,SAAS;GAAc,MAAM,SAAS;EAAa;EACpF,GAAI,SAAS,KAAK,EAAE,OAAO,SAAS,GAAG,IAAI,CAAC;EAC5C,SAAS,GAAG,SAAS,GAAG,GAAG,SAAS;CACtC;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AI,YAAY,EAAE,QAAQ,gBAAgB,GAAG,EAAE,QAAQ,YAAY,EAAE,EAAE,QAAQ,UAAU,GAAG;CAC5G,OAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;;;;;;;;;AC3WA,SAAgB,YAAY,QAAuF;CACjH,MAAM,aAA0B;EAC9B,GAAG;EACH,QAAQ,OAAO,UAAU;CAC3B;CACA,MAAM,SAAS,sBAAsB,UAAU;CAC/C,IAAI,CAAC,OAAO,OAAO;EACjB,MAAM,UAAU,OAAO,OAAO,KAAI,MAAK,QAAQ,EAAE,KAAK,IAAI,EAAE,SAAS,EAAE,KAAK,IAAI;EAChF,MAAM,IAAI,MAAM,kBAAkB,WAAW,KAAK,MAAM,SAAS;CACnE;CACA,OAAO;AACT"}
package/dist/skills.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- import { B as SkillSource, I as ShellInterpolationApproval, L as SkillConfig, R as SkillDiagnostic, V as SkillsConfig, d as DeactivationReason, f as SkillActivationState, l as ActivationVia, m as createSkillActivationState, p as SkillActivationStateOptions, u as ActiveSkill, z as SkillResource } from "./agent-EFWt6uQ_.js";
2
- import { C as buildCatalog, S as parseSkillFile, T as installAllowedToolsGate, _ as SourcedScanPath, a as SkillValidationResult, b as inferSource, c as parseAllowedToolPattern, d as validateSkillForWrite, f as validateSkillName, g as stripShellInterpolations, h as interpolateShellCommands, i as SkillValidationIssue, l as validateResourcePath, m as InterpolateShellCommandsOptions, n as writeSkillToDisk, o as isToolAllowedByUnion, p as resolveSkills, r as writeSkillsToDisk, s as matchesAllowedTool, t as defineSkill, u as validateResourcePathReal, v as discoverSkills, w as IMPLICITLY_ALLOWED_SKILL_TOOLS, x as parseFrontmatter, y as getDefaultScanPaths } from "./index-tSzOaWNt.js";
3
- export { type ActivationVia, type ActiveSkill, type DeactivationReason, IMPLICITLY_ALLOWED_SKILL_TOOLS, type InterpolateShellCommandsOptions, type ShellInterpolationApproval, type SkillActivationState, type SkillActivationStateOptions, type SkillConfig, type SkillDiagnostic, type SkillResource, type SkillSource, type SkillValidationIssue, type SkillValidationResult, type SkillsConfig, type SourcedScanPath, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, interpolateShellCommands, isToolAllowedByUnion, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, resolveSkills, stripShellInterpolations, validateResourcePath, validateResourcePathReal, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
1
+ import { $s as ActiveSkill, As as interpolateShellCommands, Bs as listSkillCandidates, Cf as SkillResource, Cs as parseAllowedToolPattern, Ds as validateSkillName, Es as validateSkillForWrite, Fs as SkillInstallErrorCode, Gs as getDefaultScanPaths, Hs as readSkillProvenance, Is as SkillInstallOptions, Js as parseSkillFile, Ks as inferSource, Ls as SkillInstallResult, Ms as SKILL_PROVENANCE_FILE, Ns as SkillInstallCandidate, Os as resolveSkills, Ps as SkillInstallError, Qs as ActivationVia, Rs as SkillInstallSpec, Sf as SkillDiagnostic, Ss as matchesAllowedTool, Tf as SkillsConfig, Ts as validateResourcePathReal, Us as SourcedScanPath, Vs as parseSkillInstallSpec, Ws as discoverSkills, Xs as IMPLICITLY_ALLOWED_SKILL_TOOLS, Ys as buildCatalog, Zs as installAllowedToolsGate, _s as writeSkillToDisk, bf as ShellInterpolationApproval, bs as SkillValidationResult, ec as DeactivationReason, gs as defineSkill, js as stripShellInterpolations, ks as InterpolateShellCommandsOptions, nc as SkillActivationStateOptions, qs as parseFrontmatter, rc as createSkillActivationState, tc as SkillActivationState, vs as writeSkillsToDisk, wf as SkillSource, ws as validateResourcePath, xf as SkillConfig, xs as isToolAllowedByUnion, ys as SkillValidationIssue, zs as installSkillFromSpec } from "./index-B8UtiZy7.js";
2
+ export { type ActivationVia, type ActiveSkill, type DeactivationReason, IMPLICITLY_ALLOWED_SKILL_TOOLS, type InterpolateShellCommandsOptions, SKILL_PROVENANCE_FILE, type ShellInterpolationApproval, type SkillActivationState, type SkillActivationStateOptions, type SkillConfig, type SkillDiagnostic, type SkillInstallCandidate, SkillInstallError, type SkillInstallErrorCode, type SkillInstallOptions, type SkillInstallResult, type SkillInstallSpec, type SkillResource, type SkillSource, type SkillValidationIssue, type SkillValidationResult, type SkillsConfig, type SourcedScanPath, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, installSkillFromSpec, interpolateShellCommands, isToolAllowedByUnion, listSkillCandidates, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, parseSkillInstallSpec, readSkillProvenance, resolveSkills, stripShellInterpolations, validateResourcePath, validateResourcePathReal, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
package/dist/skills.js CHANGED
@@ -1,24 +1,3 @@
1
- import { _ as validateResourcePath, a as writeSkillsToDisk, b as validateSkillName, c as inferSource, d as buildCatalog, f as IMPLICITLY_ALLOWED_SKILL_TOOLS, g as parseAllowedToolPattern, h as matchesAllowedTool, i as writeSkillToDisk, l as parseFrontmatter, m as isToolAllowedByUnion, n as stripShellInterpolations, o as discoverSkills, p as installAllowedToolsGate, r as resolveSkills, s as getDefaultScanPaths, t as interpolateShellCommands, u as parseSkillFile, v as validateResourcePathReal, x as createSkillActivationState, y as validateSkillForWrite } from "./interpolate-BtIgcCuz.js";
2
- //#region src/skills/index.ts
3
- /**
4
- * Define an inline skill configuration.
5
- *
6
- * Strict-validates at author-time — throws if the config would be rejected by
7
- * `writeSkillToDisk` or the spec. Source defaults to `'inline'`.
8
- */
9
- function defineSkill(config) {
10
- const normalized = {
11
- ...config,
12
- source: config.source ?? "inline"
13
- };
14
- const result = validateSkillForWrite(normalized);
15
- if (!result.valid) {
16
- const summary = result.errors.map((e) => ` - [${e.code}] ${e.message}`).join("\n");
17
- throw new Error(`Invalid skill "${normalized.name}":\n${summary}`);
18
- }
19
- return normalized;
20
- }
21
- //#endregion
22
- export { IMPLICITLY_ALLOWED_SKILL_TOOLS, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, interpolateShellCommands, isToolAllowedByUnion, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, resolveSkills, stripShellInterpolations, validateResourcePath, validateResourcePathReal, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
23
-
24
- //# sourceMappingURL=skills.js.map
1
+ import { A as validateSkillName, C as stripShellInterpolations, D as validateResourcePath, E as parseAllowedToolPattern, O as validateResourcePathReal, S as interpolateShellCommands, T as matchesAllowedTool, a as getDefaultScanPaths, c as parseSkillFile, d as installAllowedToolsGate, f as createSkillActivationState, i as discoverSkills, k as validateSkillForWrite, l as buildCatalog, n as writeSkillToDisk, o as inferSource, r as writeSkillsToDisk, s as parseFrontmatter, t as resolveSkills, u as IMPLICITLY_ALLOWED_SKILL_TOOLS, w as isToolAllowedByUnion } from "./resolve-Cr8JSL_O.js";
2
+ import { a as listSkillCandidates, i as installSkillFromSpec, n as SKILL_PROVENANCE_FILE, o as parseSkillInstallSpec, r as SkillInstallError, s as readSkillProvenance, t as defineSkill } from "./skills-Bsb0rvWI.js";
3
+ export { IMPLICITLY_ALLOWED_SKILL_TOOLS, SKILL_PROVENANCE_FILE, SkillInstallError, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, installSkillFromSpec, interpolateShellCommands, isToolAllowedByUnion, listSkillCandidates, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, parseSkillInstallSpec, readSkillProvenance, resolveSkills, stripShellInterpolations, validateResourcePath, validateResourcePathReal, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
@@ -199,5 +199,13 @@ declare function errorMessage(err: unknown): string;
199
199
  */
200
200
  declare function toTypedError(classification: ClassifiedError, provider: string, cause: unknown): AgentContextExceededError | AgentProviderError | AgentAbortedError | AgentToolPairingError;
201
201
  //#endregion
202
- export { AgentToolNotAllowedError as a, ClassifiedError as c, matchesContextExceeded as d, toTypedError as f, AgentProviderError as i, ClassifiedErrorKind as l, AgentBudgetExceededError as n, AgentToolPairingError as o, AgentContextExceededError as r, CONTEXT_EXCEEDED_MESSAGE_PATTERNS as s, AgentAbortedError as t, errorMessage as u };
203
- //# sourceMappingURL=errors-CkTvg97v.d.ts.map
202
+ //#region src/timeout.d.ts
203
+ declare class OperationTimeoutError extends Error {
204
+ readonly code: "operation_timeout";
205
+ readonly timeoutMs: number;
206
+ readonly operation: string;
207
+ constructor(operation: string, timeoutMs: number, message?: string);
208
+ }
209
+ //#endregion
210
+ export { AgentProviderError as a, CONTEXT_EXCEEDED_MESSAGE_PATTERNS as c, errorMessage as d, matchesContextExceeded as f, AgentContextExceededError as i, ClassifiedError as l, AgentAbortedError as n, AgentToolNotAllowedError as o, toTypedError as p, AgentBudgetExceededError as r, AgentToolPairingError as s, OperationTimeoutError as t, ClassifiedErrorKind as u };
211
+ //# sourceMappingURL=timeout-8vSIRjzl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timeout-8vSIRjzl.d.ts","names":[],"sources":["../src/errors.ts","../src/timeout.ts"],"mappings":";;AAYA;;;;AAA+B;AAG/B;;;;;KAHY,mBAAA;;UAGK,eAAA;EACf,IAAA,EAAM,mBAAmB;EAWhB;EATT,YAAA;EAYQ;EAVR,OAAA;;;;;;;EAOA,SAAA;AAAA;AAAA,UAGQ,iBAAA;EAe6B;EAbrC,QAAA;EAakD;EAXlD,YAAA;EAYS;EAVT,KAAA;EAYS;EAVT,SAAA;AAAA;;;;AAYuD;cAL5C,yBAAA,SAAkC,KAAK;EAAA,SACzC,IAAA;EAAA,SACA,QAAA;EAAA,SACA,YAAA;cAEG,OAAA,UAAiB,OAAA,EAAS,iBAAA;AAAA;;;;;cAY3B,kBAAA,SAA2B,KAAK;EAAA,SAClC,IAAA;EAAA,SACA,QAAA;EAAA,SACA,YAAA;EAQ8C;AAYzD;;;;EAZyD,SAF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