@theokit/sdk 4.50.0 → 4.51.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 (91) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/{agent-JA4ILE5O.cjs → agent-B2WU3JP6.cjs} +10 -9
  3. package/dist/{agent-JA4ILE5O.cjs.map → agent-B2WU3JP6.cjs.map} +1 -1
  4. package/dist/{agent-GKX5FE5K.js → agent-DI2QQHSJ.js} +9 -8
  5. package/dist/{agent-GKX5FE5K.js.map → agent-DI2QQHSJ.js.map} +1 -1
  6. package/dist/{chunk-3NLOQEJR.js → chunk-34XOCZJO.js} +5 -16
  7. package/dist/chunk-34XOCZJO.js.map +1 -0
  8. package/dist/{chunk-64TJCXY5.cjs → chunk-3G6ZDZ6L.cjs} +5 -5
  9. package/dist/{chunk-64TJCXY5.cjs.map → chunk-3G6ZDZ6L.cjs.map} +1 -1
  10. package/dist/{chunk-JO76RWCA.cjs → chunk-72HEBGWN.cjs} +4 -4
  11. package/dist/{chunk-JO76RWCA.cjs.map → chunk-72HEBGWN.cjs.map} +1 -1
  12. package/dist/{chunk-XARLSCKA.js → chunk-ACHVCIDQ.js} +11 -11
  13. package/dist/chunk-ACHVCIDQ.js.map +1 -0
  14. package/dist/{chunk-RJBHWM6D.js → chunk-E54KDYOE.js} +3 -3
  15. package/dist/{chunk-RJBHWM6D.js.map → chunk-E54KDYOE.js.map} +1 -1
  16. package/dist/{chunk-2S6B5B2A.js → chunk-E7WDXT4X.js} +3 -3
  17. package/dist/{chunk-2S6B5B2A.js.map → chunk-E7WDXT4X.js.map} +1 -1
  18. package/dist/{chunk-TSK4VVBW.cjs → chunk-F7OBYH2X.cjs} +52 -52
  19. package/dist/chunk-F7OBYH2X.cjs.map +1 -0
  20. package/dist/{chunk-6FSQ3CHQ.js → chunk-JGYYNDAZ.js} +5 -6
  21. package/dist/chunk-JGYYNDAZ.js.map +1 -0
  22. package/dist/{chunk-UU7MAO2D.cjs → chunk-OKLYRPKL.cjs} +4 -16
  23. package/dist/chunk-OKLYRPKL.cjs.map +1 -0
  24. package/dist/{chunk-EON4YTR6.js → chunk-R2A3WIJY.js} +3 -3
  25. package/dist/{chunk-EON4YTR6.js.map → chunk-R2A3WIJY.js.map} +1 -1
  26. package/dist/chunk-RIAM53CP.js +22 -0
  27. package/dist/chunk-RIAM53CP.js.map +1 -0
  28. package/dist/{chunk-GH52NOCL.cjs → chunk-RWMNTFHZ.cjs} +9 -9
  29. package/dist/{chunk-GH52NOCL.cjs.map → chunk-RWMNTFHZ.cjs.map} +1 -1
  30. package/dist/{chunk-MZQHVN7C.js → chunk-SEZJGV7C.js} +3 -3
  31. package/dist/{chunk-MZQHVN7C.js.map → chunk-SEZJGV7C.js.map} +1 -1
  32. package/dist/{chunk-FAUKVJCC.cjs → chunk-UQHIEUDY.cjs} +3 -3
  33. package/dist/{chunk-FAUKVJCC.cjs.map → chunk-UQHIEUDY.cjs.map} +1 -1
  34. package/dist/{chunk-UJ7HK7BX.js → chunk-VK7SIDYI.js} +3 -3
  35. package/dist/{chunk-UJ7HK7BX.js.map → chunk-VK7SIDYI.js.map} +1 -1
  36. package/dist/chunk-VKJ7V7EB.cjs +25 -0
  37. package/dist/chunk-VKJ7V7EB.cjs.map +1 -0
  38. package/dist/{chunk-74VVGK7P.cjs → chunk-WUUSAMFC.cjs} +5 -5
  39. package/dist/{chunk-74VVGK7P.cjs.map → chunk-WUUSAMFC.cjs.map} +1 -1
  40. package/dist/{chunk-XA3TSBAH.cjs → chunk-XABN5HY6.cjs} +4 -5
  41. package/dist/chunk-XABN5HY6.cjs.map +1 -0
  42. package/dist/{compact-session-UUCBTBCZ.cjs → compact-session-FKYCJRAK.cjs} +4 -3
  43. package/dist/{compact-session-UUCBTBCZ.cjs.map → compact-session-FKYCJRAK.cjs.map} +1 -1
  44. package/dist/{compact-session-GF2CBKXB.js → compact-session-LF4YOT5S.js} +4 -3
  45. package/dist/{compact-session-GF2CBKXB.js.map → compact-session-LF4YOT5S.js.map} +1 -1
  46. package/dist/context/index.cjs +6 -5
  47. package/dist/context/index.cjs.map +1 -1
  48. package/dist/context/index.js +3 -2
  49. package/dist/context/index.js.map +1 -1
  50. package/dist/cron.cjs +9 -8
  51. package/dist/cron.js +8 -7
  52. package/dist/eval.cjs +8 -7
  53. package/dist/eval.cjs.map +1 -1
  54. package/dist/eval.js +7 -6
  55. package/dist/eval.js.map +1 -1
  56. package/dist/filesystem/index.cjs +6 -5
  57. package/dist/filesystem/index.cjs.map +1 -1
  58. package/dist/filesystem/index.js +2 -1
  59. package/dist/filesystem/index.js.map +1 -1
  60. package/dist/{index-manager-YFFEPISE.cjs → index-manager-34ELCOAP.cjs} +6 -5
  61. package/dist/{index-manager-YFFEPISE.cjs.map → index-manager-34ELCOAP.cjs.map} +1 -1
  62. package/dist/index-manager-OMJVYS2U.js +12 -0
  63. package/dist/{index-manager-X5IPG2JL.js.map → index-manager-OMJVYS2U.js.map} +1 -1
  64. package/dist/index.cjs +127 -35
  65. package/dist/index.cjs.map +1 -1
  66. package/dist/index.d.cts +239 -1
  67. package/dist/index.d.ts +239 -1
  68. package/dist/index.js +98 -13
  69. package/dist/index.js.map +1 -1
  70. package/dist/{inject-session-I3HK3AHB.cjs → inject-session-J7Y6XACY.cjs} +4 -4
  71. package/dist/{inject-session-I3HK3AHB.cjs.map → inject-session-J7Y6XACY.cjs.map} +1 -1
  72. package/dist/{inject-session-NR64GB3T.js → inject-session-MWRJENH4.js} +3 -3
  73. package/dist/{inject-session-NR64GB3T.js.map → inject-session-MWRJENH4.js.map} +1 -1
  74. package/dist/internal/memory/adapters/index.cjs +2 -1
  75. package/dist/internal/memory/adapters/index.js +2 -1
  76. package/dist/internal/security/index.cjs +9 -8
  77. package/dist/internal/security/index.js +2 -1
  78. package/dist/path-safety.cjs +9 -8
  79. package/dist/path-safety.js +2 -1
  80. package/dist/skills.cjs +5 -4
  81. package/dist/skills.js +3 -2
  82. package/dist/workflow.cjs +11 -10
  83. package/dist/workflow.js +3 -2
  84. package/package.json +1 -1
  85. package/dist/chunk-3NLOQEJR.js.map +0 -1
  86. package/dist/chunk-6FSQ3CHQ.js.map +0 -1
  87. package/dist/chunk-TSK4VVBW.cjs.map +0 -1
  88. package/dist/chunk-UU7MAO2D.cjs.map +0 -1
  89. package/dist/chunk-XA3TSBAH.cjs.map +0 -1
  90. package/dist/chunk-XARLSCKA.js.map +0 -1
  91. package/dist/index-manager-X5IPG2JL.js +0 -11
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.51.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 265f51d: Add `evaluateBlastRadius` and `withBlastRadius`: a tool declares the scope it reaches and whether its action is reversible, and the approval layer gates on those rather than on the tool's name.
8
+ - c24a8d8: Add `guardSessionDestruction`, `decideApproval` and `describeCredential`: three rules every agent product rebuilds — refusing to destroy a live session, deciding a tool call by precedence, and reporting a credential's presence without its value.
9
+
10
+ ### Patch Changes
11
+
12
+ - 5c08eb9: Containment guards in `safePathJoin` and `memory_get` now compare paths after symlink resolution, so a link inside the root pointing outside it is refused.
13
+
3
14
  ## 4.50.0
4
15
 
5
16
  ### Minor Changes
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkTSK4VVBW_cjs = require('./chunk-TSK4VVBW.cjs');
4
- require('./chunk-FAUKVJCC.cjs');
3
+ var chunkF7OBYH2X_cjs = require('./chunk-F7OBYH2X.cjs');
4
+ require('./chunk-UQHIEUDY.cjs');
5
5
  require('./chunk-BV2MWEMV.cjs');
6
6
  require('./chunk-KCQUYQ3V.cjs');
7
7
  require('./chunk-BUUUWQMB.cjs');
@@ -10,10 +10,10 @@ require('./chunk-QFFNMJAS.cjs');
10
10
  require('./chunk-4JBHSLQO.cjs');
11
11
  require('./chunk-HLNLYLNN.cjs');
12
12
  require('./chunk-FZ4YMZA3.cjs');
13
- require('./chunk-GH52NOCL.cjs');
13
+ require('./chunk-RWMNTFHZ.cjs');
14
14
  require('./chunk-HECR7KF5.cjs');
15
15
  require('./chunk-BBZYXVLZ.cjs');
16
- require('./chunk-UU7MAO2D.cjs');
16
+ require('./chunk-OKLYRPKL.cjs');
17
17
  require('./chunk-6X2HUT4A.cjs');
18
18
  require('./chunk-7PESI6YD.cjs');
19
19
  require('./chunk-S4Q5OMIK.cjs');
@@ -40,8 +40,9 @@ require('./chunk-VYHJZVL5.cjs');
40
40
  require('./chunk-GLEKLAUW.cjs');
41
41
  require('./chunk-4JRRFRV4.cjs');
42
42
  require('./chunk-C6Y6CWYD.cjs');
43
- require('./chunk-64TJCXY5.cjs');
44
- require('./chunk-XA3TSBAH.cjs');
43
+ require('./chunk-3G6ZDZ6L.cjs');
44
+ require('./chunk-XABN5HY6.cjs');
45
+ require('./chunk-VKJ7V7EB.cjs');
45
46
  require('./chunk-BRHRQOJA.cjs');
46
47
  require('./chunk-YULF6FPB.cjs');
47
48
  require('./chunk-ZHPET3LZ.cjs');
@@ -50,7 +51,7 @@ require('./chunk-ZHPET3LZ.cjs');
50
51
 
51
52
  Object.defineProperty(exports, "Agent", {
52
53
  enumerable: true,
53
- get: function () { return chunkTSK4VVBW_cjs.Agent; }
54
+ get: function () { return chunkF7OBYH2X_cjs.Agent; }
54
55
  });
55
- //# sourceMappingURL=agent-JA4ILE5O.cjs.map
56
- //# sourceMappingURL=agent-JA4ILE5O.cjs.map
56
+ //# sourceMappingURL=agent-B2WU3JP6.cjs.map
57
+ //# sourceMappingURL=agent-B2WU3JP6.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-JA4ILE5O.cjs"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-B2WU3JP6.cjs"}
@@ -1,5 +1,5 @@
1
- export { Agent } from './chunk-XARLSCKA.js';
2
- import './chunk-UJ7HK7BX.js';
1
+ export { Agent } from './chunk-ACHVCIDQ.js';
2
+ import './chunk-VK7SIDYI.js';
3
3
  import './chunk-2SFBB54R.js';
4
4
  import './chunk-GNMPCZNN.js';
5
5
  import './chunk-K2BQQ445.js';
@@ -8,10 +8,10 @@ import './chunk-TDDRPFO3.js';
8
8
  import './chunk-4QEC4CCS.js';
9
9
  import './chunk-F4RUADRC.js';
10
10
  import './chunk-ZTEAJAE6.js';
11
- import './chunk-RJBHWM6D.js';
11
+ import './chunk-E54KDYOE.js';
12
12
  import './chunk-J5RW43IR.js';
13
13
  import './chunk-AM2CNBKE.js';
14
- import './chunk-3NLOQEJR.js';
14
+ import './chunk-34XOCZJO.js';
15
15
  import './chunk-ZS6SLELQ.js';
16
16
  import './chunk-LLE7HPRI.js';
17
17
  import './chunk-SNKY3C2L.js';
@@ -38,10 +38,11 @@ import './chunk-X2FR4OIT.js';
38
38
  import './chunk-Z6N6SDNR.js';
39
39
  import './chunk-L4JFQCG4.js';
40
40
  import './chunk-5NBUH3NO.js';
41
- import './chunk-2S6B5B2A.js';
42
- import './chunk-6FSQ3CHQ.js';
41
+ import './chunk-E7WDXT4X.js';
42
+ import './chunk-JGYYNDAZ.js';
43
+ import './chunk-RIAM53CP.js';
43
44
  import './chunk-OLLOUAUJ.js';
44
45
  import './chunk-MRKSSN36.js';
45
46
  import './chunk-PBML2FHN.js';
46
- //# sourceMappingURL=agent-GKX5FE5K.js.map
47
- //# sourceMappingURL=agent-GKX5FE5K.js.map
47
+ //# sourceMappingURL=agent-DI2QQHSJ.js.map
48
+ //# sourceMappingURL=agent-DI2QQHSJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-GKX5FE5K.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent-DI2QQHSJ.js"}
@@ -1,8 +1,8 @@
1
1
  import { findGitRoot, DEFAULT_DISCOVERY_SPECS, walkUpForFile, walkUpForGlob } from './chunk-4NAKHID5.js';
2
+ import { insideRoot } from './chunk-RIAM53CP.js';
2
3
  import { homedir } from 'os';
3
- import { relative, isAbsolute, dirname, resolve, join } from 'path';
4
+ import { dirname, relative, resolve, join, isAbsolute } from 'path';
4
5
  import { readFile } from 'fs/promises';
5
- import { realpathSync } from 'fs';
6
6
  import { z } from 'zod';
7
7
 
8
8
  var HEAD_RATIO = 0.7;
@@ -51,17 +51,6 @@ function emitTruncationCounter(source) {
51
51
  } catch {
52
52
  }
53
53
  }
54
- function realOrResolved(path) {
55
- try {
56
- return realpathSync(path);
57
- } catch {
58
- return path;
59
- }
60
- }
61
- function insideRoot(target, root) {
62
- const rel = relative(realOrResolved(root), realOrResolved(target));
63
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
64
- }
65
54
 
66
55
  // src/internal/runtime/context/context-import-resolver.ts
67
56
  var IMPORT_RE = /^@(\S+)\s*$/gm;
@@ -339,6 +328,6 @@ async function loadPlainMarkdownSource(spec, path, id, opts, gitRoot) {
339
328
  };
340
329
  }
341
330
 
342
- export { DEFAULT_MAX_BYTES_PER_FILE, insideRoot, parseRules, resolveImports, runDiscovery, shouldActivateRule, truncateWithMarker };
343
- //# sourceMappingURL=chunk-3NLOQEJR.js.map
344
- //# sourceMappingURL=chunk-3NLOQEJR.js.map
331
+ export { DEFAULT_MAX_BYTES_PER_FILE, parseRules, resolveImports, runDiscovery, shouldActivateRule, truncateWithMarker };
332
+ //# sourceMappingURL=chunk-34XOCZJO.js.map
333
+ //# sourceMappingURL=chunk-34XOCZJO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/context/context-loaders.ts","../src/internal/runtime/context/context-import-resolver.ts","../src/internal/runtime/context/context-glob.ts","../src/internal/runtime/context/context-yaml-lite.ts","../src/internal/runtime/context/context-rules-frontmatter.ts","../src/internal/runtime/context/context-mdc-parser.ts","../src/internal/runtime/context/context-discovery-runner.ts"],"names":["resolvePath","z","dirname","readFile"],"mappings":";;;;;;;AAaA,IAAM,UAAA,GAAa,GAAA;AACnB,IAAM,UAAA,GAAa,GAAA;AACnB,IAAM,MAAA,GAAS,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AA,IAAY,CAAC,EAAA,KACnD,kBAAA,CAAmB,IAAI,IAAA,CAAK,YAAA,IAAgB,EAAE;AAAA,GAChD;AACF;AAEA,eAAe,uBAAA,CACb,IAAA,EACA,IAAA,EACA,EAAA,EACA,MACA,OAAA,EACuC;AACvC,EAAA,MAAM,MAAA,GAAS,MAAM,iBAAA,CAAkB,IAAA,EAAM,EAAE,eAAA,EAAiB,IAAA,CAAK,iBAAiB,CAAA;AACtF,EAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AACjC,EAAA,IAAI,UAAU,MAAA,CAAO,OAAA;AACrB,EAAA,IAAI,KAAK,aAAA,EAAe;AACtB,IAAA,OAAA,GAAU,MAAM,cAAA,CAAe,OAAA,EAAS,IAAA,EAAM;AAAA,MAC5C,OAAA,kBAAS,IAAI,GAAA,CAAI,CAAC,IAAI,CAAC,CAAA;AAAA,MACvB,KAAA,EAAO,CAAA;AAAA,MACP,iBAAiB,IAAA,CAAK,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAKtB,WAAA,EAAa,IAAA,CAAK,UAAA,IAAc,OAAA,IAAW,IAAA,CAAK;AAAA,KACjD,CAAA;AAAA,EACH;AACA,EAAA,OAAO;AAAA,IACL,EAAA;AAAA,IACA,MAAA,EAAQ,IAAA;AAAA,IACR,OAAA;AAAA,IACA,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,WAAW,MAAA,CAAO;AAAA,GACpB;AACF","file":"chunk-34XOCZJO.js","sourcesContent":["/**\n * Context file loaders + truncation (T1.2, ADRs D154 / D155 / D159).\n *\n * Reads context source files from disk, applies the per-file size cap\n * with 70%/20% head/tail truncation, and emits the\n * `context_files_truncated` telemetry counter when the cap fires.\n * Pure (no I/O) for `truncateWithMarker` — testable in isolation.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\n\nconst HEAD_RATIO = 0.7;\nconst TAIL_RATIO = 0.2;\nconst MARKER = \"\\n\\n…[truncated by theokit]\\n\\n\";\n\n/** Default per-file cap (40k chars ≈ 10k tokens). D155. */\nexport const DEFAULT_MAX_BYTES_PER_FILE = 40_000;\n\nexport interface LoadedSource {\n /** Absolute path the content came from. */\n readonly source: string;\n readonly content: string;\n readonly originalBytes: number;\n readonly truncated: boolean;\n}\n\nexport interface TruncateResult {\n readonly truncated: boolean;\n readonly finalContent: string;\n}\n\n/**\n * Cap `content` at `max` characters with 70%/20% head/tail truncation\n * and an explicit marker. Pure — no I/O, no telemetry.\n *\n * EC-C: when `max <= MARKER.length`, skip the marker entirely and\n * return a head-only slice. Without this guard, `budget = max -\n * MARKER.length` would go negative and `content.slice(-tailBytes)`\n * would slice from the END of the string rather than truncating.\n *\n * EC-H: codepoint integrity — `String.slice()` operates on UTF-16\n * code units, which can split surrogate pairs. We accept that\n * trailing/leading replacement chars (U+FFFD) may appear at boundaries.\n * Modern LLMs tolerate them; byte-exact safety would require Buffer\n * slicing + TextDecoder with `fatal: true` retry, which adds complexity\n * without value.\n *\n * @public\n */\nexport function truncateWithMarker(content: string, max: number): TruncateResult {\n if (content.length <= max) {\n return { truncated: false, finalContent: content };\n }\n // EC-C: max too small to fit even the marker — return head-only slice.\n if (max <= MARKER.length) {\n return { truncated: true, finalContent: content.slice(0, max) };\n }\n const budget = max - MARKER.length;\n const headBytes = Math.floor(budget * (HEAD_RATIO / (HEAD_RATIO + TAIL_RATIO)));\n const tailBytes = budget - headBytes;\n return {\n truncated: true,\n finalContent: content.slice(0, headBytes) + MARKER + content.slice(-tailBytes),\n };\n}\n\n/**\n * Read a file from disk and apply the per-file cap. Emits telemetry\n * counter when truncation fires.\n *\n * EC-G: file deleted between discovery and read (FS race) → returns\n * `undefined`, never throws.\n *\n * @internal\n */\nexport async function loadPlainMarkdown(\n absPath: string,\n opts: { maxBytesPerFile?: number } = {},\n): Promise<LoadedSource | undefined> {\n const max = opts.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;\n let content: string;\n try {\n content = await readFile(absPath, \"utf8\");\n } catch {\n // EC-G: ENOENT / EACCES / etc → caller treats as missing.\n return undefined;\n }\n const { truncated, finalContent } = truncateWithMarker(content, max);\n if (truncated) {\n emitTruncationCounter(absPath);\n }\n return {\n source: absPath,\n content: finalContent,\n originalBytes: content.length,\n truncated,\n };\n}\n\n/**\n * EC-L: telemetry no-op when OTel is not imported. We import the tracer\n * lazily and use `safeCall` so the lookup never throws and never pulls\n * OTel into the import graph for users without `@opentelemetry/api`\n * installed.\n *\n * @internal\n */\nfunction emitTruncationCounter(source: string): void {\n // Lazy resolution via globalThis avoids static import of telemetry/tracer.\n // Tests can spy via the same path; production users without OTel see no-op.\n const tracer = (\n globalThis as { __theokit_tracer?: { inc?: (k: string, attrs: unknown) => void } }\n ).__theokit_tracer;\n if (tracer?.inc === undefined) return;\n try {\n tracer.inc(\"context_files_truncated\", { file: source });\n } catch {\n // Telemetry must never break the loader.\n }\n}\n","/**\n * `@path/to/file` import resolver (T2.1, ADR D156).\n *\n * Anthropic/Gemini convention: lines that are EXACTLY `@path` get\n * replaced with the imported file's content, recursively (5-hop cap),\n * with cycle detection. Inline `see @x.md, also @y.md` references are\n * NOT resolved (EC-Q — own-line only, mirrors Anthropic's actual\n * behavior).\n *\n * EC-D fix: every imported file is itself capped at `maxBytesPerFile`\n * via `loadPlainMarkdown` BEFORE concatenation. Prevents a CLAUDE.md\n * with 5 imports of 30k each from ballooning to 150k of imported\n * content before the outer cap fires.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, resolve as resolvePath } from \"node:path\";\n\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { insideRoot } from \"./path-containment.js\";\n\n/** EC-Q: line-anchored. `@path` must be alone on its line. */\nconst IMPORT_RE = /^@(\\S+)\\s*$/gm;\nconst MAX_HOPS = 5;\n\nexport interface ResolveImportsOptions {\n /** Absolute paths already resolved (cycle detection). */\n readonly visited: Set<string>;\n /** Current recursion depth — caps at MAX_HOPS. */\n readonly depth: number;\n /** Per-import file cap (EC-D). Forwarded to loadPlainMarkdown. */\n readonly maxBytesPerFile: number;\n /**\n * The directory an import may not escape. When set, a target resolving outside it is\n * refused and replaced with a placeholder.\n *\n * The file carrying the import is REPOSITORY-CONTROLLED — `CLAUDE.md` and `GEMINI.md`\n * are the two default specs with `followImports: true`, and both are found by\n * `git-root-walk` inside the tree the agent was pointed at. Without a root, a cloned\n * repository could name `@~/.ssh/id_rsa` or any absolute path and have its contents\n * inlined into the system prompt, and from there sent to the model provider. The\n * traversal guard that already existed (`isSafePattern`) guards the discovery PATTERN,\n * not the import TARGET, so it never saw this.\n *\n * OPTIONAL, so a caller outside the discovery path keeps the previous behaviour rather\n * than breaking on an upgrade. `runDiscovery` always supplies `gitRoot ?? cwd` — the\n * same value it already uses to keep absolute paths out of `<source name=\"\">`.\n */\n readonly projectRoot?: string;\n}\n\n/**\n * Resolve `@path` directives in `content`. Each match is replaced with\n * the imported file content (already cap-truncated per EC-D), and\n * recursion continues on the resolved content until MAX_HOPS or cycle.\n *\n * Failure modes (placeholders, never throws):\n * - file not found → `[@import not found: <path>]`\n * - cycle detected → `[@import cycle detected: <path>]`\n * - depth exceeded → trailing `\\n\\n…[@import depth limit 5 reached]\\n\\n`\n *\n * @internal\n */\nexport async function resolveImports(\n content: string,\n basePath: string,\n opts: ResolveImportsOptions,\n): Promise<string> {\n if (opts.depth >= MAX_HOPS) {\n return `${content}\\n\\n…[@import depth limit ${MAX_HOPS} reached]\\n\\n`;\n }\n const baseDir = dirname(basePath);\n return replaceAsync(content, IMPORT_RE, async (raw) => {\n const absolute = resolveImportPath(raw, baseDir);\n // Containment BEFORE the read. Reporting the refusal after loading the file would\n // already have put the bytes in memory, and the placeholder names the path the author\n // wrote rather than the resolved one — echoing `/home/<user>/.ssh/id_rsa` back into the\n // prompt would leak the layout of the machine to the same untrusted document.\n if (opts.projectRoot !== undefined && !insideRoot(absolute, opts.projectRoot)) {\n return `[@import outside the project root, refused: ${raw}]`;\n }\n if (opts.visited.has(absolute)) {\n return `[@import cycle detected: ${raw}]`;\n }\n opts.visited.add(absolute);\n const loaded = await loadPlainMarkdown(absolute, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) {\n return `[@import not found: ${raw}]`;\n }\n // Recurse with same visited set + incremented depth. `projectRoot` is FORWARDED: an\n // imported file is repository-controlled too, so a root that applied only at depth 0\n // would be escapable in one extra hop.\n return resolveImports(loaded.content, absolute, {\n visited: opts.visited,\n depth: opts.depth + 1,\n maxBytesPerFile: opts.maxBytesPerFile,\n ...(opts.projectRoot === undefined ? {} : { projectRoot: opts.projectRoot }),\n });\n });\n}\n\nfunction resolveImportPath(raw: string, baseDir: string): string {\n if (raw.startsWith(\"~/\")) {\n return resolvePath(join(homedir(), raw.slice(2)));\n }\n if (isAbsolute(raw)) {\n return resolvePath(raw);\n }\n return resolvePath(join(baseDir, raw));\n}\n\n/**\n * Async equivalent of `String.prototype.replace` — sequential. Returns\n * `content` with every `re` match replaced by `await replacer(match)`.\n *\n * @internal\n */\nasync function replaceAsync(\n content: string,\n re: RegExp,\n replacer: (raw: string) => Promise<string>,\n): Promise<string> {\n const matches: Array<{ match: string; raw: string; index: number }> = [];\n // Reset lastIndex; clone the regex to avoid stateful traps.\n const localRe = new RegExp(re.source, re.flags);\n let m: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex loop\n while ((m = localRe.exec(content)) !== null) {\n matches.push({ match: m[0], raw: m[1] ?? \"\", index: m.index });\n if (m.index === localRe.lastIndex) localRe.lastIndex += 1;\n }\n if (matches.length === 0) return content;\n let result = \"\";\n let cursor = 0;\n for (const entry of matches) {\n result += content.slice(cursor, entry.index);\n result += await replacer(entry.raw);\n cursor = entry.index + entry.match.length;\n }\n result += content.slice(cursor);\n return result;\n}\n","/**\n * Shared glob → RegExp compiler for context discovery (extracted from the\n * MDC parser so the `.cursor/rules/*.mdc` and `.theokit/rules/*.md` parsers\n * share ONE implementation — DRY, no new dependency).\n *\n * Supports `**` (any depth), `*` (single path segment, no `/`), `?` (single\n * non-separator char). Sufficient for the patterns Cursor and Claude Code\n * themselves recommend.\n *\n * @internal\n */\nexport function globToRegex(glob: string): RegExp {\n // Support **/ (zero-or-more path segments), ** (any depth), * (single\n // segment), ? (single non-separator char). `**/` collapses so `src/**/*.ts`\n // matches `src/foo.ts` AND `src/a/b/foo.ts` — the semantics Cursor and Claude\n // Code document (\"src/**/* → all files under src/\"). `*` and `?` never cross a\n // `/` (strict glob segment semantics). Escape other regex metas.\n const compiled = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*\\//g, \"::GLOBSTAR_SLASH::\")\n .replace(/\\*\\*/g, \"::GLOBSTAR::\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/::GLOBSTAR_SLASH::/g, \"(?:.*/)?\")\n .replace(/::GLOBSTAR::/g, \".*\");\n return new RegExp(`^${compiled}$`);\n}\n\n/**\n * True when any of `patterns` glob-matches any of `paths`. Central helper so\n * both rule parsers agree on activation semantics.\n *\n * @internal\n */\nexport function anyGlobMatches(\n patterns: ReadonlyArray<string>,\n paths: ReadonlyArray<string>,\n): boolean {\n if (patterns.length === 0 || paths.length === 0) return false;\n const res = patterns.map(globToRegex);\n return paths.some((p) => res.some((re) => re.test(p)));\n}\n","/**\n * Minimal YAML-subset frontmatter parsing shared by the `.cursor/rules/*.mdc`\n * and `.theokit/rules/*.md` parsers (extracted for DRY — one parser, one set\n * of edge-case behaviours, no new dependency).\n *\n * Handles `key: value` lines (string scalars, booleans, integers) and `key:`\n * followed by indented `- item` arrays or inline `[a, b]` arrays. Sufficient\n * for the small, fixed frontmatter field sets these rule files use. Throws on\n * a truly malformed line (no colon).\n *\n * NOTE — distinct from the sibling `yaml-frontmatter.ts` `parseSimpleYaml` on\n * purpose: that one parses INLINE arrays only (`key: [a, b]`), whereas rule\n * files (`.cursor/rules/*.mdc`, `.theokit/rules/*.md`) use MULTI-LINE `- item`\n * lists (`paths:` / `globs:`), which this parser adds. Unifying onto the inline\n * parser would drop multi-line list support; unifying the other way would touch\n * the skills/subagents/persistence loaders that depend on the inline one. The\n * two intentionally coexist until a shared parser handles both shapes.\n *\n * @internal\n */\n\nconst FRONTMATTER_RE = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/;\n\nexport interface FrontmatterSplit {\n /** Raw YAML block between the `---` fences, or undefined when absent. */\n readonly yaml: string | undefined;\n /** The markdown body after the frontmatter (or the whole content). */\n readonly body: string;\n}\n\n/**\n * Split `---`-fenced frontmatter from the body. When no frontmatter fence is\n * present, `yaml` is undefined and `body` is the whole content.\n *\n * @internal\n */\nexport function splitFrontmatter(content: string): FrontmatterSplit {\n const m = FRONTMATTER_RE.exec(content);\n if (m === null) return { yaml: undefined, body: content };\n return { yaml: m[1] ?? \"\", body: m[2] ?? \"\" };\n}\n\n/**\n * Parse the minimal YAML subset. Throws on a line without a colon (malformed).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: YAML-subset parser handles scalars + multi-line arrays + inline arrays in a single pass; extracting helpers fragments the line-state machine.\nexport function parseSimpleYaml(yaml: string): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const lines = yaml.split(/\\r?\\n/);\n let i = 0;\n while (i < lines.length) {\n const line = lines[i];\n i += 1;\n if (line === undefined) continue;\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n const colon = trimmed.indexOf(\":\");\n if (colon === -1) throw new Error(`Invalid YAML line: ${trimmed}`);\n const key = trimmed.slice(0, colon).trim();\n const rest = trimmed.slice(colon + 1).trim();\n if (rest === \"\") {\n // Possible array; collect indented `- item` lines.\n const items: string[] = [];\n while (i < lines.length) {\n const next = lines[i];\n if (next === undefined) break;\n const nextTrim = next.trim();\n if (nextTrim.startsWith(\"- \")) {\n items.push(parseScalar(nextTrim.slice(2).trim()) as string);\n i += 1;\n } else if (nextTrim === \"\") {\n i += 1;\n } else {\n break;\n }\n }\n out[key] = items;\n } else if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n // Inline array `globs: [\"**/*.ts\", \"**/*.tsx\"]`\n const inner = rest.slice(1, -1).trim();\n out[key] =\n inner === \"\"\n ? []\n : inner.split(\",\").map((s) => parseScalar(s.trim().replace(/^[\"']|[\"']$/g, \"\")));\n } else {\n out[key] = parseScalar(rest);\n }\n }\n return out;\n}\n\nfunction parseScalar(s: string): string | boolean | number {\n if (s === \"true\") return true;\n if (s === \"false\") return false;\n if (/^-?\\d+$/.test(s)) return parseInt(s, 10);\n // Strip surrounding quotes if present.\n return s.replace(/^[\"']|[\"']$/g, \"\");\n}\n","/**\n * Parser for `.theokit/rules/*.md` — theokit-native path-scoped rules,\n * mirroring Claude Code's `.claude/rules/`.\n *\n * Frontmatter fields:\n * - `paths` — glob-pattern array (Claude Code parity: `.claude/rules` uses `paths:`).\n * - `globs` — glob-pattern array (Cursor-compatible alias; unioned with `paths`).\n * - `alwaysApply` — activate unconditionally (no scope needed).\n * - `enabled` — set `false` to disable the rule entirely (wins over everything).\n * - `description` — human note; not used for activation in v1.\n *\n * Activation (`shouldActivateRule`):\n * - `enabled: false` → never activates.\n * - `alwaysApply: true` → always activates.\n * - otherwise → activates iff a `paths`/`globs` pattern matches an in-scope\n * file (the caller's `agent.send(..., { contextPaths })`). With no in-scope\n * files, a scoped rule stays dormant (parity with Cursor `.mdc`).\n *\n * A file with no `---` frontmatter is treated as an unconditional rule\n * (`alwaysApply: true`). Malformed YAML → `undefined` (caller drops + counts).\n *\n * Glob + YAML subset are shared with the MDC parser (DRY, no new dependency).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for `.theokit/rules/*.md` files. @internal */\nexport const RulesFrontmatterSchema = z.object({\n description: z.string().optional(),\n paths: z.array(z.string()).optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n enabled: z.boolean().optional(),\n});\n\nexport type RulesFrontmatter = z.infer<typeof RulesFrontmatterSchema>;\n\nexport interface RulesParseResult {\n readonly frontmatter: RulesFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.theokit/rules/*.md` content into frontmatter + body. No frontmatter\n * fence → unconditional rule. Malformed YAML → `undefined`.\n *\n * @internal\n */\nexport function parseRules(content: string): RulesParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = RulesFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether a rule activates given the in-scope files. `paths` and\n * `globs` are unioned; both are glob patterns matched against the caller's\n * declared scope.\n *\n * @internal\n */\nexport function shouldActivateRule(\n fm: RulesFrontmatter,\n inScopePaths: ReadonlyArray<string>,\n): boolean {\n if (fm.enabled === false) return false;\n if (fm.alwaysApply === true) return true;\n const patterns = [...(fm.paths ?? []), ...(fm.globs ?? [])];\n if (patterns.length === 0) return false;\n return anyGlobMatches(patterns, inScopePaths);\n}\n","/**\n * MDC (Markdown Cursor) parser for `.cursor/rules/*.mdc` (T3.1, ADR D154).\n *\n * Parses YAML frontmatter with `description` / `globs` / `alwaysApply`\n * fields. Honors activation per Cursor's docs:\n * - `alwaysApply: true` → activates unconditionally.\n * - `alwaysApply: false` + matching glob in `touchedFiles` → activates.\n * - `alwaysApply: false` + no glob match → skipped.\n *\n * **EC-I (v1 semantic):** at `agent.send()` time, `touchedFiles` is empty\n * UNLESS the caller passes `contextPaths` (the in-scope file set). When\n * `contextPaths` is provided, per-glob activation fires; otherwise only\n * `alwaysApply: true` rules activate. Description-based \"agent requested\"\n * classification is out of scope.\n *\n * Glob matching + the YAML subset are shared with the `.theokit/rules/*.md`\n * parser via `context-glob.ts` / `context-yaml-lite.ts` (DRY, no new dep).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for MDC files. @internal */\nexport const McdFrontmatterSchema = z.object({\n description: z.string().optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n});\n\nexport type McdFrontmatter = z.infer<typeof McdFrontmatterSchema>;\n\nexport interface McdParseResult {\n readonly frontmatter: McdFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.mdc` content. Returns frontmatter + body. EC-18: when the\n * file has no `---` frontmatter, returns `frontmatter: {alwaysApply:\n * true}` so the body is treated as an unconditional rule.\n *\n * On YAML parse error, returns `undefined` and the caller emits a\n * telemetry counter (EC-21).\n *\n * @internal\n */\nexport function parseMdc(content: string): McdParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n // EC-18: no frontmatter — treat as alwaysApply\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = McdFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether an MDC rule activates given the currently-touched\n * files. EC-I: empty `touchedFiles` → only `alwaysApply: true`\n * activates.\n *\n * @internal\n */\nexport function shouldActivate(fm: McdFrontmatter, touchedFiles: ReadonlyArray<string>): boolean {\n if (fm.alwaysApply === true) return true;\n if (fm.globs === undefined || fm.globs.length === 0) return false;\n return anyGlobMatches(fm.globs, touchedFiles);\n}\n","/**\n * Multi-format context discovery runner (T5.1, ADRs D150-D156).\n *\n * Walks `DEFAULT_DISCOVERY_SPECS` (or caller override), loads each\n * spec via the appropriate parser, applies `@import` resolution where\n * declared, and returns a flat list of `AggregatorSource[]` ready for\n * the aggregate cap.\n *\n * **EC-E privacy fix:** source disambiguation uses\n * `relative(gitRoot ?? cwd, ...)` — NEVER absolute paths in\n * `<source name=\"\">`.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, relative } from \"node:path\";\n\nimport type { AggregatorSource } from \"./context-aggregator.js\";\nimport {\n DEFAULT_DISCOVERY_SPECS,\n type DiscoverySpec,\n findGitRoot,\n walkUpForFile,\n walkUpForGlob,\n} from \"./context-discovery.js\";\nimport { resolveImports } from \"./context-import-resolver.js\";\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { parseMdc, shouldActivate } from \"./context-mdc-parser.js\";\nimport { parseRules, shouldActivateRule } from \"./context-rules-frontmatter.js\";\n\nexport interface DiscoveryRunnerOptions {\n /** Workspace root passed to all discovery scopes. */\n readonly cwd: string;\n /** Per-file truncation cap (D155). */\n readonly maxBytesPerFile: number;\n /** Optional override of the default registry. */\n readonly specs?: ReadonlyArray<DiscoverySpec>;\n /** Cursor MDC: file paths the LLM has touched this turn (EC-I: empty at send-time). */\n readonly touchedFiles?: ReadonlyArray<string>;\n /** When true, skip `theokit-context` spec — caller already handles the legacy path. */\n readonly skipLegacyTheokitContext?: boolean;\n /**\n * The root an `@import` may not escape. Defaults to `gitRoot ?? cwd` — the same value\n * this runner already uses to keep absolute paths out of `<source name=\"\">`.\n *\n * Present so an embedder with a trust boundary narrower than the repository can declare\n * it. Absent, the repository IS the boundary, which is the honest default for a document\n * discovered by walking the repository.\n */\n readonly importRoot?: string;\n}\n\n/**\n * Run discovery + loading across all specs. Returns sources ready for\n * the aggregator (priority + content fields populated).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-spec dispatch ladder + cross-spec dedup is a flat orchestrator; splitting would obscure the priority-merge invariant.\nexport async function runDiscovery(opts: DiscoveryRunnerOptions): Promise<AggregatorSource[]> {\n const gitRoot = findGitRoot(opts.cwd);\n const specs = opts.specs ?? DEFAULT_DISCOVERY_SPECS;\n const out: AggregatorSource[] = [];\n const seenReal = new Set<string>();\n\n for (const spec of specs) {\n if (opts.skipLegacyTheokitContext && spec.id === \"theokit-context\") continue;\n const paths = await resolvePathsForSpec(spec, opts.cwd, gitRoot);\n for (const path of paths) {\n if (seenReal.has(path)) continue;\n seenReal.add(path);\n const source = await loadOneSource(spec, path, opts, gitRoot);\n if (source !== undefined) out.push(source);\n }\n }\n return out;\n}\n\nasync function resolvePathsForSpec(\n spec: DiscoverySpec,\n cwd: string,\n gitRoot: string | undefined,\n): Promise<string[]> {\n if (spec.scope === \"cwd-only\") {\n return walkUpForFile(cwd, spec.pattern, cwd);\n }\n if (spec.scope === \"git-root-walk\") {\n return walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);\n }\n // globbed\n return walkUpForGlob(cwd, spec.pattern);\n}\n\nasync function loadOneSource(\n spec: DiscoverySpec,\n path: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n // EC-E privacy: name uses relative-to-git-root for disambiguation;\n // NEVER absolute paths in the public `<source name=\"\">` attribute.\n // For cwd-only specs (THEO.md), no disambiguation is needed because\n // the scope can only ever match a single file.\n const relPath = relative(gitRoot ?? opts.cwd, dirname(path));\n const needsSuffix = spec.scope !== \"cwd-only\" && relPath !== \"\" && relPath !== \".\";\n const id = needsSuffix ? `${spec.id}@${relPath}` : spec.id;\n\n if (spec.parser === \"mdc\") {\n return loadMdcSource(spec, path, id, opts);\n }\n if (spec.parser === \"rules-frontmatter\") {\n return loadRulesSource(spec, path, id, opts);\n }\n if (spec.parser === \"frontmatter-zod\") {\n // Legacy `.theokit/context/*.md` — handled by `loadContextConfig` in\n // `context-manager.ts` for backward compat. We skip here unless caller\n // explicitly wants us to load it (currently always skipped).\n return undefined;\n }\n // plain-markdown\n return loadPlainMarkdownSource(spec, path, id, opts, gitRoot);\n}\n\n/**\n * Shared read → parse → activation-gate → source pipeline for the frontmatter\n * discovery parsers (mdc, rules). Binds the parser + the activation predicate so\n * the mdc and rules loaders differ only in those two, not in the surrounding\n * read/guard/shape boilerplate (DRY).\n */\nasync function loadParsedSource<F>(\n spec: DiscoverySpec,\n path: string,\n id: string,\n parse: (raw: string) => { frontmatter: F; body: string } | undefined,\n isActive: (frontmatter: F) => boolean,\n): Promise<AggregatorSource | undefined> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n return undefined;\n }\n const parsed = parse(raw);\n if (parsed === undefined || !isActive(parsed.frontmatter)) return undefined;\n return { id, source: path, content: parsed.body, priority: spec.priority, truncated: false };\n}\n\nfunction loadMdcSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseMdc, (fm) =>\n shouldActivate(fm, opts.touchedFiles ?? []),\n );\n}\n\nfunction loadRulesSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseRules, (fm) =>\n shouldActivateRule(fm, opts.touchedFiles ?? []),\n );\n}\n\nasync function loadPlainMarkdownSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n const loaded = await loadPlainMarkdown(path, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) return undefined;\n let content = loaded.content;\n if (spec.followImports) {\n content = await resolveImports(content, path, {\n visited: new Set([path]),\n depth: 0,\n maxBytesPerFile: opts.maxBytesPerFile,\n // The document carrying the import is repository-controlled, so the repository is the\n // boundary it may not cross. Without this, `CLAUDE.md` / `GEMINI.md` — the two specs\n // with `followImports: true` — could name any absolute or `~/` path and have it\n // inlined into the system prompt.\n projectRoot: opts.importRoot ?? gitRoot ?? opts.cwd,\n });\n }\n return {\n id,\n source: path,\n content,\n priority: spec.priority,\n truncated: loaded.truncated,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkXA3TSBAH_cjs = require('./chunk-XA3TSBAH.cjs');
3
+ var chunkXABN5HY6_cjs = require('./chunk-XABN5HY6.cjs');
4
4
  var chunkBRHRQOJA_cjs = require('./chunk-BRHRQOJA.cjs');
5
5
  var chunkYULF6FPB_cjs = require('./chunk-YULF6FPB.cjs');
6
6
  var promises = require('fs/promises');
@@ -90,8 +90,8 @@ async function discoverSkills(dir, options) {
90
90
  if (!entry.isDirectory()) continue;
91
91
  let skillDir;
92
92
  try {
93
- skillDir = chunkXA3TSBAH_cjs.safePathJoin(dir, entry.name);
94
- chunkXA3TSBAH_cjs.assertNoSymlinkEscape(skillDir, dir);
93
+ skillDir = chunkXABN5HY6_cjs.safePathJoin(dir, entry.name);
94
+ chunkXABN5HY6_cjs.assertNoSymlinkEscape(skillDir, dir);
95
95
  } catch {
96
96
  continue;
97
97
  }
@@ -150,5 +150,5 @@ exports.buildSkillsBlock = buildSkillsBlock;
150
150
  exports.discoverSkills = discoverSkills;
151
151
  exports.escapeBlockBody = escapeBlockBody;
152
152
  exports.stripSkillFrontmatter = stripSkillFrontmatter;
153
- //# sourceMappingURL=chunk-64TJCXY5.cjs.map
154
- //# sourceMappingURL=chunk-64TJCXY5.cjs.map
153
+ //# sourceMappingURL=chunk-3G6ZDZ6L.cjs.map
154
+ //# sourceMappingURL=chunk-3G6ZDZ6L.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/runtime/skills/skill-frontmatter.ts","../src/internal/runtime/skills/discover-skills.ts","../src/internal/runtime/system-prompt/escape.ts","../src/internal/runtime/skills/skills-block.ts"],"names":["ConfigurationError","parseSimpleYaml","readWorkspaceDir","safePathJoin","assertNoSymlinkEscape","join","readFile"],"mappings":";;;;;;;;;AAMA,SAAS,SAAS,CAAA,EAAqD;AACrE,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AACrC;AAGA,SAAS,eAAe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,MAAM,KAAA;AAAA,EACR;AACF;;;ACtIO,IAAM,eAAA,GAAkB,CAAC,CAAA,KAC9B,CAAA,CAAE,QAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,MAAM,CAAA,CAAE,OAAA,CAAQ,MAAM,MAAM;;;ACO9D,SAAS,iBACd,MAAA,EACoB;AACpB,EAAA,IAAI,MAAA,CAAO,MAAA,KAAW,CAAA,EAAG,OAAO,MAAA;AAChC,EAAA,MAAM,QAAQ,MAAA,CAAO,GAAA;AAAA,IACnB,CAAC,KAAA,KAAU,CAAA,IAAA,EAAO,eAAA,CAAgB,KAAA,CAAM,IAAI,CAAC,CAAA,EAAA,EAAK,eAAA,CAAgB,KAAA,CAAM,WAAW,CAAC,CAAA;AAAA,GACtF;AACA,EAAA,OAAO,CAAA;AAAA,EAAa,KAAA,CAAM,IAAA,CAAK,IAAI,CAAC;AAAA,SAAA,CAAA;AACtC","file":"chunk-64TJCXY5.cjs","sourcesContent":["import { ConfigurationError } from \"../../../errors.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\n\ntype StringFields = Record<string, string | undefined>;\n\n/** Narrow a FrontmatterValue to string; non-strings + undefined → undefined. */\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n/** Coerce parser output to legacy string-only shape (skill schema is all-string). */\nfunction toStringFields(raw: Record<string, FrontmatterValue | undefined>): StringFields {\n const out: StringFields = {};\n for (const [k, v] of Object.entries(raw)) out[k] = asString(v);\n return out;\n}\n\n/**\n * Strict skill frontmatter schema (ADR D10).\n *\n * Required: `name`, `description`.\n * Optional: `category`, `dependencies` (comma-separated string in the\n * simple-YAML dialect — parsed to `string[]`).\n *\n * Unknown fields are ignored (forward-compat). Malformed YAML or missing\n * required fields surface as `ConfigurationError` with one of the typed\n * codes below.\n *\n * @internal\n */\nexport interface SkillFrontmatter {\n name: string;\n description: string;\n category?: string;\n dependencies?: string[];\n}\n\n/**\n * Parse a SKILL.md file body into validated frontmatter.\n *\n * @throws ConfigurationError(code: \"missing_frontmatter\") — no `---` block at file head.\n * @throws ConfigurationError(code: \"schema_invalid\") — YAML malformed OR required field missing.\n *\n * @internal\n */\nexport function parseSkillFrontmatter(raw: string, fallbackName: string): SkillFrontmatter {\n const fields = extractAndParseFrontmatter(raw, fallbackName);\n const name = resolveName(fields, fallbackName);\n ensureRequiredFields(fields, name);\n return buildFrontmatter(fields, name);\n}\n\n/**\n * SE20 — return a SKILL.md's BODY (everything after the frontmatter block), trimmed.\n * When there is no frontmatter block, the whole file is the body. Reuses the same\n * frontmatter regex as {@link parseSkillFrontmatter} (DRY).\n */\nexport function stripSkillFrontmatter(raw: string): string {\n const match = /^---\\s*\\n[\\s\\S]*?\\n---\\s*\\n/.exec(raw);\n return (match === null ? raw : raw.slice(match[0].length)).trim();\n}\n\nfunction extractAndParseFrontmatter(raw: string, fallbackName: string): StringFields {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Skill ${fallbackName} is missing frontmatter`, {\n code: \"missing_frontmatter\",\n });\n }\n const frontmatter = match[1] ?? \"\";\n // EC-5: guard against syntactically invalid frontmatter so the loader\n // surfaces schema_invalid rather than crashing.\n try {\n return toStringFields(parseSimpleYaml(frontmatter));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new ConfigurationError(\n `Skill ${fallbackName} has malformed YAML frontmatter: ${detail}`,\n { code: \"schema_invalid\", cause },\n );\n }\n}\n\nfunction resolveName(fields: StringFields, fallbackName: string): string {\n if (hasContent(fields.name)) return fields.name;\n if (hasContent(fallbackName)) return fallbackName;\n throw new ConfigurationError(\"Skill at unknown path is missing required field: name\", {\n code: \"schema_invalid\",\n });\n}\n\nfunction ensureRequiredFields(fields: StringFields, name: string): void {\n if (!hasContent(fields.description)) {\n throw new ConfigurationError(`Skill ${name} is missing required field: description`, {\n code: \"schema_invalid\",\n });\n }\n}\n\nfunction buildFrontmatter(fields: StringFields, name: string): SkillFrontmatter {\n const description = fields.description;\n if (description === undefined) {\n // ensureRequiredFields already threw; this is unreachable but satisfies TS\n throw new ConfigurationError(`Skill ${name} missing description`, { code: \"schema_invalid\" });\n }\n const result: SkillFrontmatter = { name, description };\n if (hasContent(fields.category)) result.category = fields.category;\n const deps = parseDependencies(fields.dependencies);\n if (deps !== undefined) result.dependencies = deps;\n return result;\n}\n\nfunction parseDependencies(raw: string | undefined): string[] | undefined {\n if (!hasContent(raw)) return undefined;\n const deps = (raw as string)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return deps.length > 0 ? deps : undefined;\n}\n\nfunction hasContent(value: string | undefined): value is string {\n return value !== undefined && value.trim().length > 0;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { assertNoSymlinkEscape, safePathJoin } from \"../../security/path-guard.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { parseSkillFrontmatter } from \"./skill-frontmatter.js\";\n\n/**\n * A discovered skill's metadata. The skill BODY is never included — only the\n * strict frontmatter fields plus the resolved `source` path.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport interface Skill {\n name: string;\n description: string;\n /** Absolute path to the discovered `SKILL.md`. */\n source: string;\n category?: string;\n dependencies?: string[];\n}\n\n/**\n * Information passed to `onInvalidSkill` when a `SKILL.md` is present but its\n * frontmatter is malformed (missing required field or invalid YAML).\n *\n * @public\n */\nexport interface InvalidSkillInfo {\n /** The skill directory name (used as the fallback skill name). */\n name: string;\n /** Absolute path to the offending `SKILL.md`. */\n source: string;\n /** Typed reason: `missing_frontmatter` or `schema_invalid`. */\n code: string;\n message: string;\n}\n\n/**\n * Options for {@link discoverSkills}.\n *\n * @public\n */\nexport interface DiscoverSkillsOptions {\n /**\n * Called once per directory that contains a `SKILL.md` with malformed\n * frontmatter. The skill is excluded from the result; discovery continues\n * (strict-frontmatter ADR / EC-5). A directory WITHOUT a `SKILL.md` is NOT a\n * malformed skill and does not trigger this callback.\n *\n * Default: no-op (a library primitive must not write to the consumer's\n * stderr by default).\n */\n onInvalidSkill?: (info: InvalidSkillInfo) => void;\n}\n\n/**\n * Discover `SKILL.md` skills under an arbitrary directory.\n *\n * For each immediate subdirectory `<dir>/<name>/` containing a `SKILL.md`, the\n * file's strict YAML frontmatter is parsed (`name`/`description` required;\n * `category`/`dependencies` optional). Malformed skills are skipped (optionally\n * reported via {@link DiscoverSkillsOptions.onInvalidSkill}); a subdirectory\n * whose realpath escapes `dir` (via symlink) is skipped (symlink-escape guard,\n * reusing `@theokit/sdk/path-safety`).\n *\n * NEVER throws: a missing, unreadable, or non-directory `dir` yields `[]`.\n *\n * Discovery order follows the filesystem `readdir` order (OS-dependent). Sort\n * the result before {@link buildSkillsBlock} if a stable block order matters.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport async function discoverSkills(\n dir: string,\n options?: DiscoverSkillsOptions,\n): Promise<Skill[]> {\n let entries: Awaited<ReturnType<typeof readWorkspaceDir>>;\n try {\n entries = await readWorkspaceDir(dir, \"skills_read_error\", \"skills directory\");\n } catch {\n // never-throw contract: unreadable / not-a-directory → no skills (EC-1)\n return [];\n }\n\n const skills: Skill[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n let skillDir: string;\n try {\n skillDir = safePathJoin(dir, entry.name);\n assertNoSymlinkEscape(skillDir, dir);\n } catch {\n continue;\n }\n const skillPath = join(skillDir, \"SKILL.md\");\n let raw: string;\n try {\n raw = await readFile(skillPath, \"utf8\");\n } catch {\n // no SKILL.md in this subdir → not a skill, not an error (EC-2)\n continue;\n }\n const skill = tryParseSkill(raw, entry.name, skillPath, options);\n if (skill !== undefined) skills.push(skill);\n }\n return skills;\n}\n\nfunction tryParseSkill(\n raw: string,\n fallbackName: string,\n source: string,\n options: DiscoverSkillsOptions | undefined,\n): Skill | undefined {\n try {\n const frontmatter = parseSkillFrontmatter(raw, fallbackName);\n const skill: Skill = {\n name: frontmatter.name,\n description: frontmatter.description,\n source,\n };\n if (frontmatter.category !== undefined) skill.category = frontmatter.category;\n if (frontmatter.dependencies !== undefined) skill.dependencies = frontmatter.dependencies;\n return skill;\n } catch (cause) {\n if (cause instanceof ConfigurationError) {\n options?.onInvalidSkill?.({\n name: fallbackName,\n source,\n code: cause.code ?? \"unknown\",\n message: cause.message,\n });\n return undefined;\n }\n throw cause;\n }\n}\n","/**\n * Block-body XML escape (ADR D9 — prompt-injection defence).\n *\n * Order matters: `&` MUST be escaped first so subsequent `<`/`>` replacements\n * do not double-encode the `&` characters they introduce.\n *\n * @internal\n */\nexport const escapeBlockBody = (s: string): string =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n","import { escapeBlockBody } from \"../system-prompt/escape.js\";\n\n/**\n * Render the `<skills>` system-prompt block from a skill list.\n *\n * Input is the structural subset `{ name, description }` — the skill BODY is\n * NOT in the type, so it cannot leak into the prompt. Both fields are passed\n * through `escapeBlockBody` to neutralise prompt-injection vectors hidden in\n * user-controlled SKILL.md frontmatter (injection-escape ADR).\n *\n * Returns `undefined` for an empty list so the caller can omit the block.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport function buildSkillsBlock(\n skills: ReadonlyArray<{ name: string; description: string }>,\n): string | undefined {\n if (skills.length === 0) return undefined;\n const lines = skills.map(\n (skill) => ` - ${escapeBlockBody(skill.name)}: ${escapeBlockBody(skill.description)}`,\n );\n return `<skills>\\n${lines.join(\"\\n\")}\\n</skills>`;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/runtime/skills/skill-frontmatter.ts","../src/internal/runtime/skills/discover-skills.ts","../src/internal/runtime/system-prompt/escape.ts","../src/internal/runtime/skills/skills-block.ts"],"names":["ConfigurationError","parseSimpleYaml","readWorkspaceDir","safePathJoin","assertNoS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AAA,QACN,MAAA;AAAA,QACA,IAAA,EAAM,MAAM,IAAA,IAAQ,SAAA;AAAA,QACpB,SAAS,KAAA,CAAM;AAAA,OAChB,CAAA;AACD,MAAA,OAAO,MAAA;AAAA,IACT;AACA,IAAA,MAAM,KAAA;AAAA,EACR;AACF;;;ACtIO,IAAM,eAAA,GAAkB,CAAC,CAAA,KAC9B,CAAA,CAAE,QAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,MAAM,CAAA,CAAE,OAAA,CAAQ,MAAM,MAAM;;;ACO9D,SAAS,iBACd,MAAA,EACoB;AACpB,EAAA,IAAI,MAAA,CAAO,MAAA,KAAW,CAAA,EAAG,OAAO,MAAA;AAChC,EAAA,MAAM,QAAQ,MAAA,CAAO,GAAA;AAAA,IACnB,CAAC,KAAA,KAAU,CAAA,IAAA,EAAO,eAAA,CAAgB,KAAA,CAAM,IAAI,CAAC,CAAA,EAAA,EAAK,eAAA,CAAgB,KAAA,CAAM,WAAW,CAAC,CAAA;AAAA,GACtF;AACA,EAAA,OAAO,CAAA;AAAA,EAAa,KAAA,CAAM,IAAA,CAAK,IAAI,CAAC;AAAA,SAAA,CAAA;AACtC","file":"chunk-3G6ZDZ6L.cjs","sourcesContent":["import { ConfigurationError } from \"../../../errors.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\n\ntype StringFields = Record<string, string | undefined>;\n\n/** Narrow a FrontmatterValue to string; non-strings + undefined → undefined. */\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n/** Coerce parser output to legacy string-only shape (skill schema is all-string). */\nfunction toStringFields(raw: Record<string, FrontmatterValue | undefined>): StringFields {\n const out: StringFields = {};\n for (const [k, v] of Object.entries(raw)) out[k] = asString(v);\n return out;\n}\n\n/**\n * Strict skill frontmatter schema (ADR D10).\n *\n * Required: `name`, `description`.\n * Optional: `category`, `dependencies` (comma-separated string in the\n * simple-YAML dialect — parsed to `string[]`).\n *\n * Unknown fields are ignored (forward-compat). Malformed YAML or missing\n * required fields surface as `ConfigurationError` with one of the typed\n * codes below.\n *\n * @internal\n */\nexport interface SkillFrontmatter {\n name: string;\n description: string;\n category?: string;\n dependencies?: string[];\n}\n\n/**\n * Parse a SKILL.md file body into validated frontmatter.\n *\n * @throws ConfigurationError(code: \"missing_frontmatter\") — no `---` block at file head.\n * @throws ConfigurationError(code: \"schema_invalid\") — YAML malformed OR required field missing.\n *\n * @internal\n */\nexport function parseSkillFrontmatter(raw: string, fallbackName: string): SkillFrontmatter {\n const fields = extractAndParseFrontmatter(raw, fallbackName);\n const name = resolveName(fields, fallbackName);\n ensureRequiredFields(fields, name);\n return buildFrontmatter(fields, name);\n}\n\n/**\n * SE20 — return a SKILL.md's BODY (everything after the frontmatter block), trimmed.\n * When there is no frontmatter block, the whole file is the body. Reuses the same\n * frontmatter regex as {@link parseSkillFrontmatter} (DRY).\n */\nexport function stripSkillFrontmatter(raw: string): string {\n const match = /^---\\s*\\n[\\s\\S]*?\\n---\\s*\\n/.exec(raw);\n return (match === null ? raw : raw.slice(match[0].length)).trim();\n}\n\nfunction extractAndParseFrontmatter(raw: string, fallbackName: string): StringFields {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Skill ${fallbackName} is missing frontmatter`, {\n code: \"missing_frontmatter\",\n });\n }\n const frontmatter = match[1] ?? \"\";\n // EC-5: guard against syntactically invalid frontmatter so the loader\n // surfaces schema_invalid rather than crashing.\n try {\n return toStringFields(parseSimpleYaml(frontmatter));\n } catch (cause) {\n const detail = cause instanceof Error ? cause.message : String(cause);\n throw new ConfigurationError(\n `Skill ${fallbackName} has malformed YAML frontmatter: ${detail}`,\n { code: \"schema_invalid\", cause },\n );\n }\n}\n\nfunction resolveName(fields: StringFields, fallbackName: string): string {\n if (hasContent(fields.name)) return fields.name;\n if (hasContent(fallbackName)) return fallbackName;\n throw new ConfigurationError(\"Skill at unknown path is missing required field: name\", {\n code: \"schema_invalid\",\n });\n}\n\nfunction ensureRequiredFields(fields: StringFields, name: string): void {\n if (!hasContent(fields.description)) {\n throw new ConfigurationError(`Skill ${name} is missing required field: description`, {\n code: \"schema_invalid\",\n });\n }\n}\n\nfunction buildFrontmatter(fields: StringFields, name: string): SkillFrontmatter {\n const description = fields.description;\n if (description === undefined) {\n // ensureRequiredFields already threw; this is unreachable but satisfies TS\n throw new ConfigurationError(`Skill ${name} missing description`, { code: \"schema_invalid\" });\n }\n const result: SkillFrontmatter = { name, description };\n if (hasContent(fields.category)) result.category = fields.category;\n const deps = parseDependencies(fields.dependencies);\n if (deps !== undefined) result.dependencies = deps;\n return result;\n}\n\nfunction parseDependencies(raw: string | undefined): string[] | undefined {\n if (!hasContent(raw)) return undefined;\n const deps = (raw as string)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return deps.length > 0 ? deps : undefined;\n}\n\nfunction hasContent(value: string | undefined): value is string {\n return value !== undefined && value.trim().length > 0;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { assertNoSymlinkEscape, safePathJoin } from \"../../security/path-guard.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { parseSkillFrontmatter } from \"./skill-frontmatter.js\";\n\n/**\n * A discovered skill's metadata. The skill BODY is never included — only the\n * strict frontmatter fields plus the resolved `source` path.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport interface Skill {\n name: string;\n description: string;\n /** Absolute path to the discovered `SKILL.md`. */\n source: string;\n category?: string;\n dependencies?: string[];\n}\n\n/**\n * Information passed to `onInvalidSkill` when a `SKILL.md` is present but its\n * frontmatter is malformed (missing required field or invalid YAML).\n *\n * @public\n */\nexport interface InvalidSkillInfo {\n /** The skill directory name (used as the fallback skill name). */\n name: string;\n /** Absolute path to the offending `SKILL.md`. */\n source: string;\n /** Typed reason: `missing_frontmatter` or `schema_invalid`. */\n code: string;\n message: string;\n}\n\n/**\n * Options for {@link discoverSkills}.\n *\n * @public\n */\nexport interface DiscoverSkillsOptions {\n /**\n * Called once per directory that contains a `SKILL.md` with malformed\n * frontmatter. The skill is excluded from the result; discovery continues\n * (strict-frontmatter ADR / EC-5). A directory WITHOUT a `SKILL.md` is NOT a\n * malformed skill and does not trigger this callback.\n *\n * Default: no-op (a library primitive must not write to the consumer's\n * stderr by default).\n */\n onInvalidSkill?: (info: InvalidSkillInfo) => void;\n}\n\n/**\n * Discover `SKILL.md` skills under an arbitrary directory.\n *\n * For each immediate subdirectory `<dir>/<name>/` containing a `SKILL.md`, the\n * file's strict YAML frontmatter is parsed (`name`/`description` required;\n * `category`/`dependencies` optional). Malformed skills are skipped (optionally\n * reported via {@link DiscoverSkillsOptions.onInvalidSkill}); a subdirectory\n * whose realpath escapes `dir` (via symlink) is skipped (symlink-escape guard,\n * reusing `@theokit/sdk/path-safety`).\n *\n * NEVER throws: a missing, unreadable, or non-directory `dir` yields `[]`.\n *\n * Discovery order follows the filesystem `readdir` order (OS-dependent). Sort\n * the result before {@link buildSkillsBlock} if a stable block order matters.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport async function discoverSkills(\n dir: string,\n options?: DiscoverSkillsOptions,\n): Promise<Skill[]> {\n let entries: Awaited<ReturnType<typeof readWorkspaceDir>>;\n try {\n entries = await readWorkspaceDir(dir, \"skills_read_error\", \"skills directory\");\n } catch {\n // never-throw contract: unreadable / not-a-directory → no skills (EC-1)\n return [];\n }\n\n const skills: Skill[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n let skillDir: string;\n try {\n skillDir = safePathJoin(dir, entry.name);\n assertNoSymlinkEscape(skillDir, dir);\n } catch {\n continue;\n }\n const skillPath = join(skillDir, \"SKILL.md\");\n let raw: string;\n try {\n raw = await readFile(skillPath, \"utf8\");\n } catch {\n // no SKILL.md in this subdir → not a skill, not an error (EC-2)\n continue;\n }\n const skill = tryParseSkill(raw, entry.name, skillPath, options);\n if (skill !== undefined) skills.push(skill);\n }\n return skills;\n}\n\nfunction tryParseSkill(\n raw: string,\n fallbackName: string,\n source: string,\n options: DiscoverSkillsOptions | undefined,\n): Skill | undefined {\n try {\n const frontmatter = parseSkillFrontmatter(raw, fallbackName);\n const skill: Skill = {\n name: frontmatter.name,\n description: frontmatter.description,\n source,\n };\n if (frontmatter.category !== undefined) skill.category = frontmatter.category;\n if (frontmatter.dependencies !== undefined) skill.dependencies = frontmatter.dependencies;\n return skill;\n } catch (cause) {\n if (cause instanceof ConfigurationError) {\n options?.onInvalidSkill?.({\n name: fallbackName,\n source,\n code: cause.code ?? \"unknown\",\n message: cause.message,\n });\n return undefined;\n }\n throw cause;\n }\n}\n","/**\n * Block-body XML escape (ADR D9 — prompt-injection defence).\n *\n * Order matters: `&` MUST be escaped first so subsequent `<`/`>` replacements\n * do not double-encode the `&` characters they introduce.\n *\n * @internal\n */\nexport const escapeBlockBody = (s: string): string =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n","import { escapeBlockBody } from \"../system-prompt/escape.js\";\n\n/**\n * Render the `<skills>` system-prompt block from a skill list.\n *\n * Input is the structural subset `{ name, description }` — the skill BODY is\n * NOT in the type, so it cannot leak into the prompt. Both fields are passed\n * through `escapeBlockBody` to neutralise prompt-injection vectors hidden in\n * user-controlled SKILL.md frontmatter (injection-escape ADR).\n *\n * Returns `undefined` for an empty list so the caller can omit the block.\n *\n * Public via `@theokit/sdk/skills`.\n *\n * @public\n */\nexport function buildSkillsBlock(\n skills: ReadonlyArray<{ name: string; description: string }>,\n): string | undefined {\n if (skills.length === 0) return undefined;\n const lines = skills.map(\n (skill) => ` - ${escapeBlockBody(skill.name)}: ${escapeBlockBody(skill.description)}`,\n );\n return `<skills>\\n${lines.join(\"\\n\")}\\n</skills>`;\n}\n"]}
@@ -3,7 +3,7 @@
3
3
  var chunkRBQYHEZD_cjs = require('./chunk-RBQYHEZD.cjs');
4
4
  var chunkPNVDQL5Y_cjs = require('./chunk-PNVDQL5Y.cjs');
5
5
  var chunkWJVHMTKB_cjs = require('./chunk-WJVHMTKB.cjs');
6
- var chunkXA3TSBAH_cjs = require('./chunk-XA3TSBAH.cjs');
6
+ var chunkXABN5HY6_cjs = require('./chunk-XABN5HY6.cjs');
7
7
  var zod = require('zod');
8
8
 
9
9
  // src/internal/workflow/event-stream.ts
@@ -388,7 +388,7 @@ function workflowAsTool(workflow, spec) {
388
388
  };
389
389
  }
390
390
  function validateStepId(id) {
391
- chunkXA3TSBAH_cjs.sanitizeIdentifier(id, { maxLen: 64 });
391
+ chunkXABN5HY6_cjs.sanitizeIdentifier(id, { maxLen: 64 });
392
392
  }
393
393
  function mintShortId() {
394
394
  return globalThis.crypto.randomUUID().replace(/-/g, "").slice(0, 8);
@@ -420,5 +420,5 @@ exports.cloneWorkflow = cloneWorkflow;
420
420
  exports.fn = fn;
421
421
  exports.workflowAsTool = workflowAsTool;
422
422
  exports.workflowStep = workflowStep;
423
- //# sourceMappingURL=chunk-JO76RWCA.cjs.map
424
- //# sourceMappingURL=chunk-JO76RWCA.cjs.map
423
+ //# sourceMappingURL=chunk-72HEBGWN.cjs.map
424
+ //# sourceMappingURL=chunk-72HEBGWN.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/workflow/event-stream.ts","../src/workflow.ts"],"names":["z","PersistenceSchema","WorkflowNestedError","toJsonSchema","sanitizeIdentifier","WorkflowDuplicateStepIdError"],"mappings":";;;;;;;;;AAgBO,SAAS,iBAAA,GAAyC;AACvD,EAAA,MAAM,SAA0B,EAAC;AACjC,EAAA,MAAM,UAA6D,EAAC;AACpE,EAAA,IAAI,KAAA,GAAQ,KAAA;AAEZ,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,KAAK,KAAA,EAA4B;AAC/B,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,MAAM,M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CAAC,CAAA;AAClE,EAAA,OAAO,EAAC;AACV;AAEA,SAAS,mBAAA,CAAoB,OAA4B,IAAA,EAAyB;AAChF,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,IAAI,IAAA,CAAK,IAAI,CAAA,CAAE,EAAE,GAAG,MAAM,IAAIC,8CAAA,CAA6B,CAAA,CAAE,EAAE,CAAA;AAC/D,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,EAAE,CAAA;AACb,IAAA,KAAA,MAAW,MAAA,IAAU,aAAA,CAAc,CAAC,CAAA,EAAG;AACrC,MAAA,mBAAA,CAAoB,QAAQ,IAAI,CAAA;AAAA,IAClC;AAAA,EACF;AACF","file":"chunk-JO76RWCA.cjs","sourcesContent":["/**\n * SE28 — a minimal pushable async iterator for `Workflow.stream()`. The executor\n * pushes {@link WorkflowEvent}s as steps run; the consumer drains them via\n * `for await`. Buffers events emitted before the consumer is ready; `end()`\n * closes the iterator so a pending/next `next()` resolves `done: true`.\n *\n * @internal\n */\n\nimport type { WorkflowEvent } from \"../../types/workflow.js\";\n\nexport interface PushableEventStream extends AsyncIterableIterator<WorkflowEvent> {\n push(event: WorkflowEvent): void;\n end(): void;\n}\n\nexport function createEventStream(): PushableEventStream {\n const buffer: WorkflowEvent[] = [];\n const waiters: Array<(r: IteratorResult<WorkflowEvent>) => void> = [];\n let ended = false;\n\n const stream: PushableEventStream = {\n push(event: WorkflowEvent): void {\n if (ended) return;\n const waiter = waiters.shift();\n if (waiter !== undefined) waiter({ value: event, done: false });\n else buffer.push(event);\n },\n end(): void {\n if (ended) return;\n ended = true;\n for (const waiter of waiters.splice(0)) waiter({ value: undefined, done: true });\n },\n next(): Promise<IteratorResult<WorkflowEvent>> {\n const buffered = buffer.shift();\n if (buffered !== undefined) return Promise.resolve({ value: buffered, done: false });\n if (ended) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => waiters.push(resolve));\n },\n // `for await` calls return() on break/throw — close early so events stop\n // buffering in memory for a consumer that stopped iterating.\n return(): Promise<IteratorResult<WorkflowEvent>> {\n stream.end();\n buffer.length = 0;\n return Promise.resolve({ value: undefined, done: true });\n },\n [Symbol.asyncIterator](): PushableEventStream {\n return stream;\n },\n };\n return stream;\n}\n","/**\n * Public `Workflow` class — declarative multi-step orchestration over\n * `Agent.send`, `Handoff`, `Agent.batch` and friends (Adoption Roadmap #5;\n * ADRs D230-D248).\n *\n * Usage:\n *\n * import { Agent } from \"@theokit/sdk\";\n * import { Workflow, fn, agentStep } from \"@theokit/sdk/workflow\";\n *\n * const classifier = await Agent.create({ ... });\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (input: { id: string }) => {\n * if (!input.id) throw new Error(\"missing id\");\n * return input;\n * }))\n * .then(agentStep(\"classify\", classifier, (i) => `Classify: ${JSON.stringify(i)}`))\n * .commit();\n *\n * const run = await wf.run({ id: \"x\" });\n * console.log(run.status, run.output);\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { PersistenceSchema } from \"./internal/persistence/persistence-schema.js\";\nimport { sanitizeIdentifier } from \"./internal/security/path-guard.js\";\nimport { createEventStream } from \"./internal/workflow/event-stream.js\";\nimport { toJsonSchema } from \"./internal/zod/to-json-schema.js\";\nimport type { CustomTool, SDKAgent } from \"./types/agent.js\";\nimport type { MessageOrigin } from \"./types/run.js\";\nimport type {\n AgentStep,\n BranchStep,\n DowhileStep,\n FnStep,\n ForeachStep,\n ParallelStep,\n RetryPolicy,\n SleepStep,\n Step,\n StepContext,\n SuspendStep,\n WorkflowDescription,\n WorkflowEvent,\n WorkflowOptions,\n WorkflowResumeOptions,\n WorkflowRun,\n WorkflowRunOptions,\n WorkflowStepDescription,\n WorkflowStream,\n} from \"./types/workflow.js\";\nimport { WorkflowDuplicateStepIdError, WorkflowNestedError } from \"./types/workflow.js\";\n\n/* ─── Zod validation schemas ─── */\n\nconst RetryPolicySchema = z.object({\n // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].\n maxAttempts: z\n .number()\n .int(\"retry.maxAttempts must be integer\")\n .min(1, \"retry.maxAttempts must be >= 1\")\n .max(20, \"retry.maxAttempts must be <= 20\"),\n initialBackoffMs: z.number().int().min(0).optional(),\n backoffCoefficient: z.number().min(1).optional(),\n maximumBackoffMs: z.number().int().min(0).optional(),\n nonRetryableErrors: z.array(z.string()).optional(),\n});\n\nconst WorkflowOptionsSchema = z.object({\n name: z.string().min(1).max(128),\n persistence: PersistenceSchema,\n // SE27 — declared so a future `new WorkflowBuilder(parsed)` refactor cannot\n // silently drop them (create() passes the ORIGINAL options today, but the\n // schema is also the documentation of the shape).\n inputSchema: z.custom<ZodType>().optional(),\n outputSchema: z.custom<ZodType>().optional(),\n});\n\n/* ─── Builder ─── */\n\nexport class WorkflowBuilder<TInput = unknown, TOutput = unknown> {\n private readonly _steps: Step[] = [];\n private _committed = false;\n\n /** @internal */\n constructor(private readonly options: WorkflowOptions) {}\n\n /** @internal — only the executor reads this. */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: D233 locks the a peer framework-style `.then(step)` builder DSL. The method is fluent, never awaited.\n then<TO = unknown>(step: Step): WorkflowBuilder<TInput, TO> {\n this.assertNotCommitted();\n validateStepId(step.id);\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, TO>;\n }\n\n parallel(\n branches: ReadonlyArray<ReadonlyArray<Step>>,\n opts?: { id?: string; concurrency?: number; errorPolicy?: \"fail-fast\" | \"collect\" },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `parallel_${this._steps.length}`;\n validateStepId(id);\n for (const branch of branches) {\n for (const inner of branch) validateStepId(inner.id);\n }\n const step: ParallelStep = {\n kind: \"parallel\",\n id,\n branches,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(opts?.errorPolicy !== undefined ? { errorPolicy: opts.errorPolicy } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n branch(\n predicates: BranchStep[\"predicates\"],\n opts?: { id?: string; fallback?: ReadonlyArray<Step> },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `branch_${this._steps.length}`;\n validateStepId(id);\n const step: BranchStep = {\n kind: \"branch\",\n id,\n predicates,\n ...(opts?.fallback !== undefined ? { fallback: opts.fallback } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n foreach(\n iterableFrom: string,\n step: Step,\n opts?: { id?: string; concurrency?: number },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `foreach_${this._steps.length}`;\n validateStepId(id);\n validateStepId(iterableFrom);\n validateStepId(step.id);\n const node: ForeachStep = {\n kind: \"foreach\",\n id,\n iterableFrom,\n step,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n dowhile(\n step: Step,\n condFn: DowhileStep[\"condFn\"],\n opts?: { id?: string; maxIterations?: number },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `dowhile_${this._steps.length}`;\n validateStepId(id);\n validateStepId(step.id);\n const node: DowhileStep = {\n kind: \"dowhile\",\n id,\n step,\n condFn,\n ...(opts?.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n sleep(durationMs: number, id?: string): WorkflowBuilder<TInput, TOutput> {\n this.assertNotCommitted();\n const stepId = id ?? `sleep_${this._steps.length}`;\n validateStepId(stepId);\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);\n }\n const step: SleepStep = { kind: \"sleep\", id: stepId, durationMs };\n this._steps.push(step);\n return this;\n }\n\n suspend(opts?: { id?: string; payloadSchema?: ZodType }): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `suspend_${this._steps.length}`;\n validateStepId(id);\n const step: SuspendStep = {\n kind: \"suspend\",\n id,\n ...(opts?.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n commit(): Workflow<TInput, TOutput> {\n this.assertNotCommitted();\n this.validateUniqueIds();\n this._committed = true;\n // EC-5 absorbed: mint unique workflowId so single-flight lock is per-instance\n const workflowId = `wf-${mintShortId()}`;\n return new Workflow<TInput, TOutput>({ ...this.options, workflowId }, [...this._steps]);\n }\n\n private validateUniqueIds(): void {\n const seen = new Set<string>();\n walkStepsValidating(this._steps, seen);\n }\n\n private assertNotCommitted(): void {\n if (this._committed) {\n throw new Error(\"Workflow already committed; create a fresh Workflow.create(...) call.\");\n }\n }\n}\n\n/* ─── Workflow class ─── */\n\n/**\n * theokit#161 — project one step to its reflectable shape, recursing into the variants that nest.\n *\n * `parallel` branches are FLATTENED: the grouping is a scheduling detail (which steps may run\n * concurrently), not shape a reader of the workflow needs, and preserving it would put a second,\n * branch-shaped level into a type whose whole purpose is to be renderable.\n */\nfunction describeStep(step: Step): WorkflowStepDescription {\n const base = { id: step.id, kind: step.kind } as const;\n if (step.kind === \"parallel\") {\n return { ...base, steps: step.branches.flat().map(describeStep) };\n }\n if (step.kind === \"branch\") {\n const fromPredicates = step.predicates.flatMap(([, steps]) => steps.map(describeStep));\n const fromFallback = (step.fallback ?? []).map(describeStep);\n return { ...base, steps: [...fromPredicates, ...fromFallback] };\n }\n if (step.kind === \"foreach\" || step.kind === \"dowhile\") {\n return { ...base, steps: [describeStep(step.step)] };\n }\n return base;\n}\n\nexport class Workflow<TInput = unknown, TOutput = unknown> {\n /** @internal */\n constructor(\n private readonly _options: WorkflowOptions,\n private readonly _steps: ReadonlyArray<Step>,\n ) {}\n\n /** @internal — only the executor reads these. */\n get __options(): WorkflowOptions {\n return this._options;\n }\n /** @internal */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n /**\n * Construct a workflow builder. Validate options via Zod and return a\n * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the\n * immutable `Workflow`.\n */\n static create<TI = unknown, TO = unknown>(options: WorkflowOptions): WorkflowBuilder<TI, TO> {\n WorkflowOptionsSchema.parse(options);\n return new WorkflowBuilder<TI, TO>(options);\n }\n\n /**\n * theokit#161 — describe this workflow's shape, for a reflection surface.\n *\n * Returns `{ name, steps }`, each step carrying its `id` and `kind`, recursing into `parallel`,\n * `branch`, `foreach` and `dowhile`. Every executable a step holds — predicates, conditions,\n * agents, prompt templates — is omitted: it cannot cross a process boundary and says nothing about\n * shape.\n *\n * There is deliberately no `Workflow.list()`. A workflow is a value the caller constructs and\n * holds, so the caller already knows which ones exist; a registry would add process-global state\n * nothing releases in order to re-answer a question the host can answer itself. A reflection\n * endpoint maps over its own workflows and calls this.\n *\n * @public\n */\n describe(): WorkflowDescription {\n return {\n name: this._options.name,\n steps: this._steps.map(describeStep),\n };\n }\n\n /**\n * Run this workflow with the given input. Returns a populated\n * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via\n * `run.status === \"failed\"`.\n */\n async run(input: TInput, opts?: WorkflowRunOptions): Promise<WorkflowRun<TOutput>> {\n // Lazy import to keep the public façade lean.\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n const result = await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, opts);\n // T3.4: opt-in Task wrapping (ADRs D363, D374). Workflows are\n // observable via Task.list/get/subscribe; the underlying run is\n // already terminal here (executor returned), so the Task just\n // records the outcome for inspection.\n if (opts?.task !== undefined) {\n const { submit: taskSubmit } = await import(\"./internal/task/registry.js\");\n const taskOpts = opts.task === true ? {} : opts.task;\n const id = taskOpts.id ?? `wf-${result.id}`;\n await taskSubmit({\n kind: \"workflow\",\n work: async (ctx) => {\n ctx.emit({ status: result.status, runId: result.id });\n return { status: result.status, runId: result.id, output: result.output };\n },\n id,\n meta: {\n workflowName: this._options.name,\n runId: result.id,\n status: result.status,\n ...(taskOpts.meta ?? {}),\n },\n allowReservedPrefix: true,\n });\n }\n return result;\n }\n\n /**\n * SE28 — run the workflow and STREAM step-level events as they happen. Returns\n * an async iterator of {@link WorkflowEvent}s (`step_started` / `step_completed`\n * / `step_failed` / `workflow_suspended` / `workflow_completed`, top-level\n * steps) plus a `result` promise resolving to the same terminal\n * {@link WorkflowRun} `run()` returns. Iterate for progress; await `result` for\n * the outcome. The stream ends when the run terminates.\n *\n * `result` is the AUTHORITATIVE terminal status. Not every terminal state has a\n * closing event: a step failure emits `step_failed`, but an `outputSchema`\n * rejection (SE27) or an abort ends the stream WITHOUT `workflow_completed` —\n * always `await result` to read the final `status`. Consuming order is free:\n * awaiting `result` without draining, or draining without awaiting `result`,\n * both work (breaking out of `for await` stops the buffering early).\n */\n stream(input: TInput, opts?: WorkflowRunOptions): WorkflowStream<TOutput> {\n const queue = createEventStream();\n const result = (async (): Promise<WorkflowRun<TOutput>> => {\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n try {\n return await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, {\n ...opts,\n onStepEvent: (event: WorkflowEvent) => queue.push(event),\n } as WorkflowRunOptions);\n } finally {\n queue.end(); // authoritative terminal is `result`; close the stream\n }\n })();\n return Object.assign(queue, { result });\n }\n\n /**\n * Resume a suspended workflow from its snapshot. Throws\n * `WorkflowSnapshotNotFoundError` if `runId` is unknown.\n */\n static async resume<TO = unknown>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n const { resumeWorkflow } = await import(\"./internal/workflow/executor.js\");\n return resumeWorkflow<TO>(opts);\n }\n}\n\n/* ─── Helper factory functions ─── */\n\n/**\n * Build a `FnStep`. `id` must match `^[a-z0-9][a-z0-9_-]*$`.\n */\nexport function fn<I = unknown, O = unknown>(\n id: string,\n step: (input: I, ctx: StepContext) => Promise<O> | O,\n opts?: { inputSchema?: ZodType; outputSchema?: ZodType; retry?: RetryPolicy },\n): FnStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"fn\",\n id,\n fn: step as FnStep[\"fn\"],\n ...(opts?.inputSchema !== undefined ? { inputSchema: opts.inputSchema } : {}),\n ...(opts?.outputSchema !== undefined ? { outputSchema: opts.outputSchema } : {}),\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/**\n * Build an `AgentStep`. The `promptTemplate` can be a static string or a\n * function that receives the input and returns the prompt.\n */\nexport function agentStep(\n id: string,\n agent: SDKAgent,\n promptTemplate: string | ((input: unknown) => string),\n opts?: { retry?: RetryPolicy; origin?: MessageOrigin },\n): AgentStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"agent\",\n id,\n agent,\n promptTemplate,\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n // SE3 — carry the turn's provenance down to `agent.send()` (metadata-only).\n ...(opts?.origin !== undefined ? { origin: opts.origin } : {}),\n };\n}\n\n/**\n * SE30 — use a committed {@link Workflow} as a step inside another workflow.\n * Wraps the child as an `FnStep` (opaque — the child runs in its OWN executor\n * with its own id-space, so nested step-ids never collide with the parent's).\n * The child's output becomes the step output. A non-`completed` child fails the\n * parent step with a typed {@link WorkflowNestedError}: nested `suspended` is NOT\n * resumable in v1 (resume continues AFTER the step — the child would be skipped;\n * use a top-level suspend). See ADR 0010.\n *\n * @public\n */\nexport function workflowStep<TI = unknown, TO = unknown>(\n child: Workflow<TI, TO>,\n opts?: { id?: string },\n): FnStep {\n const id = opts?.id ?? `workflow_${child.__options.name}`;\n validateStepId(id);\n return {\n kind: \"fn\",\n id,\n fn: async (input: unknown, ctx: StepContext): Promise<unknown> => {\n const run = await child.run(input as TI, { signal: ctx.signal });\n if (run.status === \"completed\") return run.output;\n throw new WorkflowNestedError(id, child.__options.name, run.status, run.error);\n },\n };\n}\n\n/**\n * SE30 — clone a committed workflow under a new id/name. The clone runs\n * independently (its own single-flight lock + observability identity) with the\n * same committed steps. Mirrors a peer framework's `cloneWorkflow`.\n *\n * @public\n */\nexport function cloneWorkflow<TI = unknown, TO = unknown>(\n wf: Workflow<TI, TO>,\n opts: { id: string },\n): Workflow<TI, TO> {\n return new Workflow<TI, TO>(\n { ...wf.__options, name: opts.id, workflowId: `wf-${mintShortId()}` },\n [...wf.__steps],\n );\n}\n\n/* ─── Test seam re-export ─── */\n\nexport { __resetSnapshotStoresForTests } from \"./internal/workflow/snapshot-store.js\";\n\n/* ─── Re-exports for ergonomics (errors + all public types). After the\n sub-path extraction `@theokit/sdk/workflow` is the single import site,\n so type aliases must surface here (previously they reached consumers\n via `types/index.ts:25 export type * from \"./workflow.js\"`, which the\n extraction removes). ─── */\n\nexport type * from \"./types/workflow.js\";\nexport {\n WorkflowAlreadyRunningError,\n WorkflowCompensateNotImplementedError,\n WorkflowDuplicateStepIdError,\n WorkflowInputError,\n WorkflowMaxIterationsExceededError,\n WorkflowNestedError,\n WorkflowNotSerializableError,\n WorkflowOutputError,\n WorkflowParallelError,\n WorkflowResumeStepNotFoundError,\n WorkflowSnapshotNotFoundError,\n WorkflowStateError,\n} from \"./types/workflow.js\";\n\n/* ─── SE19 — workflowAsTool (expose a Workflow as an agent tool) ─── */\n\n/**\n * Raised by a {@link workflowAsTool} tool when the wrapped workflow run does not\n * reach `status: \"completed\"` (a step failed, the run was cancelled/suspended).\n * The dispatch converts it to a `tool_result(isError)`.\n *\n * @public\n */\nexport class WorkflowToolError extends Error {\n readonly code = \"workflow_tool_failed\" as const;\n constructor(\n readonly toolName: string,\n readonly workflowStatus: string,\n readonly workflowError?: { name: string; message: string },\n ) {\n super(\n `workflowAsTool(\"${toolName}\"): workflow ${workflowStatus}${\n workflowError ? `: ${workflowError.message}` : \"\"\n }`,\n );\n this.name = \"WorkflowToolError\";\n }\n}\n\n/** Spec for {@link workflowAsTool}. `inputSchema` is the workflow's input shape (Zod). */\nexport interface WorkflowAsToolSpec<T extends ZodType> {\n /** Tool name surfaced to the LLM. Same constraints as a `CustomTool.name`. */\n name: string;\n /** Description surfaced to the LLM — when the agent should trigger the workflow. */\n description: string;\n /** Zod schema for the workflow's input (a `Workflow` carries no top-level schema). */\n inputSchema: T;\n}\n\n/**\n * SE19 — expose a {@link Workflow} as an agent {@link CustomTool}, completing the\n * \"X as tools\" trio (tools; agents-as-tools via `defineSubAgent`; workflows-as-tools).\n * The handler validates the model's args against `spec.inputSchema`, runs the\n * workflow, and returns its output (a string as-is, else JSON). A run that does not\n * reach `status: \"completed\"` raises a typed {@link WorkflowToolError} (workflow\n * step errors do NOT throw — they surface via `run.status === \"failed\"`).\n *\n * Accepts any `{ run }`-shaped workflow (structural), so it never imports the\n * `Workflow` class directly.\n *\n * @public\n */\nexport function workflowAsTool<T extends ZodType, TOutput = unknown>(\n workflow: { run: (input: z.infer<T>) => Promise<WorkflowRun<TOutput>> },\n spec: WorkflowAsToolSpec<T>,\n): CustomTool {\n const inputSchema = toJsonSchema(spec.inputSchema, { unrepresentable: \"any\" });\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (rawInput: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(rawInput) as z.infer<T>;\n const run = await workflow.run(parsed);\n if (run.status !== \"completed\") {\n throw new WorkflowToolError(spec.name, run.status, run.error);\n }\n const output = run.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n },\n };\n}\n\n/* ─── Internal helpers ─── */\n\nfunction validateStepId(id: string): void {\n // Reuses D81 grammar: ^[a-z0-9][a-z0-9_-]*$\n sanitizeIdentifier(id, { maxLen: 64 });\n}\n\nfunction mintShortId(): string {\n return globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8);\n}\n\nfunction nestedStepsOf(s: Step): ReadonlyArray<ReadonlyArray<Step>> {\n if (s.kind === \"parallel\") return s.branches;\n if (s.kind === \"branch\") {\n const groups = s.predicates.map(([, branch]) => branch);\n return s.fallback !== undefined ? [...groups, s.fallback] : groups;\n }\n if (s.kind === \"foreach\" || s.kind === \"dowhile\") return [[s.step]];\n return [];\n}\n\nfunction walkStepsValidating(steps: ReadonlyArray<Step>, seen: Set<string>): void {\n for (const s of steps) {\n if (seen.has(s.id)) throw new WorkflowDuplicateStepIdError(s.id);\n seen.add(s.id);\n for (const nested of nestedStepsOf(s)) {\n walkStepsValidating(nested, seen);\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/workflow/event-stream.ts","../src/workflow.ts"],"names":["z","PersistenceSchema","WorkflowNestedError","toJsonSchema","sanitizeIdentifier","WorkflowDuplicateStepIdError"],"mappings":";;;;;;;;;AAgBO,SAAS,iBAAA,GAAyC;AACvD,EAAA,MAAM,SAA0B,EAAC;AACjC,EAAA,MAAM,UAA6D,EAAC;AACpE,EAAA,IAAI,KAAA,GAAQ,KAAA;AAEZ,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,KAAK,KAAA,EAA4B;AAC/B,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,MAAM,MAAA,GAAS,QAAQ,KAAA,EAAM;AAC7B,MAAA,IAAI,MAAA,KAAW,QAAW,MAAA,CAAO,EAAE,OAAO,KAAA,EAAO,IAAA,EAAM,OAAO,CAAA;AAAA,WACzD,MAAA,CAAO,KAAK,KAAK,CAAA;AAAA,IACxB,CAAA;AAAA,IACA,GAAA,GAAY;AACV,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,KAAA,GAAQ,IAAA;AACR,MAAA,KAAA,MAAW,MAAA,IAAU,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,EAAG,MAAA,CAAO,EAAE,KAAA,EAAO,MAAA,EAAW,IAAA,EAAM,IAAA,EAAM,CAAA;AAAA,IACjF,CAAA;AAAA,IACA,IAAA,GAA+C;AAC7C,MAAA,MAAM,QAAA,GA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iterator for `Workflow.stream()`. The executor\n * pushes {@link WorkflowEvent}s as steps run; the consumer drains them via\n * `for await`. Buffers events emitted before the consumer is ready; `end()`\n * closes the iterator so a pending/next `next()` resolves `done: true`.\n *\n * @internal\n */\n\nimport type { WorkflowEvent } from \"../../types/workflow.js\";\n\nexport interface PushableEventStream extends AsyncIterableIterator<WorkflowEvent> {\n push(event: WorkflowEvent): void;\n end(): void;\n}\n\nexport function createEventStream(): PushableEventStream {\n const buffer: WorkflowEvent[] = [];\n const waiters: Array<(r: IteratorResult<WorkflowEvent>) => void> = [];\n let ended = false;\n\n const stream: PushableEventStream = {\n push(event: WorkflowEvent): void {\n if (ended) return;\n const waiter = waiters.shift();\n if (waiter !== undefined) waiter({ value: event, done: false });\n else buffer.push(event);\n },\n end(): void {\n if (ended) return;\n ended = true;\n for (const waiter of waiters.splice(0)) waiter({ value: undefined, done: true });\n },\n next(): Promise<IteratorResult<WorkflowEvent>> {\n const buffered = buffer.shift();\n if (buffered !== undefined) return Promise.resolve({ value: buffered, done: false });\n if (ended) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => waiters.push(resolve));\n },\n // `for await` calls return() on break/throw — close early so events stop\n // buffering in memory for a consumer that stopped iterating.\n return(): Promise<IteratorResult<WorkflowEvent>> {\n stream.end();\n buffer.length = 0;\n return Promise.resolve({ value: undefined, done: true });\n },\n [Symbol.asyncIterator](): PushableEventStream {\n return stream;\n },\n };\n return stream;\n}\n","/**\n * Public `Workflow` class — declarative multi-step orchestration over\n * `Agent.send`, `Handoff`, `Agent.batch` and friends (Adoption Roadmap #5;\n * ADRs D230-D248).\n *\n * Usage:\n *\n * import { Agent } from \"@theokit/sdk\";\n * import { Workflow, fn, agentStep } from \"@theokit/sdk/workflow\";\n *\n * const classifier = await Agent.create({ ... });\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (input: { id: string }) => {\n * if (!input.id) throw new Error(\"missing id\");\n * return input;\n * }))\n * .then(agentStep(\"classify\", classifier, (i) => `Classify: ${JSON.stringify(i)}`))\n * .commit();\n *\n * const run = await wf.run({ id: \"x\" });\n * console.log(run.status, run.output);\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { PersistenceSchema } from \"./internal/persistence/persistence-schema.js\";\nimport { sanitizeIdentifier } from \"./internal/security/path-guard.js\";\nimport { createEventStream } from \"./internal/workflow/event-stream.js\";\nimport { toJsonSchema } from \"./internal/zod/to-json-schema.js\";\nimport type { CustomTool, SDKAgent } from \"./types/agent.js\";\nimport type { MessageOrigin } from \"./types/run.js\";\nimport type {\n AgentStep,\n BranchStep,\n DowhileStep,\n FnStep,\n ForeachStep,\n ParallelStep,\n RetryPolicy,\n SleepStep,\n Step,\n StepContext,\n SuspendStep,\n WorkflowDescription,\n WorkflowEvent,\n WorkflowOptions,\n WorkflowResumeOptions,\n WorkflowRun,\n WorkflowRunOptions,\n WorkflowStepDescription,\n WorkflowStream,\n} from \"./types/workflow.js\";\nimport { WorkflowDuplicateStepIdError, WorkflowNestedError } from \"./types/workflow.js\";\n\n/* ─── Zod validation schemas ─── */\n\nconst RetryPolicySchema = z.object({\n // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].\n maxAttempts: z\n .number()\n .int(\"retry.maxAttempts must be integer\")\n .min(1, \"retry.maxAttempts must be >= 1\")\n .max(20, \"retry.maxAttempts must be <= 20\"),\n initialBackoffMs: z.number().int().min(0).optional(),\n backoffCoefficient: z.number().min(1).optional(),\n maximumBackoffMs: z.number().int().min(0).optional(),\n nonRetryableErrors: z.array(z.string()).optional(),\n});\n\nconst WorkflowOptionsSchema = z.object({\n name: z.string().min(1).max(128),\n persistence: PersistenceSchema,\n // SE27 — declared so a future `new WorkflowBuilder(parsed)` refactor cannot\n // silently drop them (create() passes the ORIGINAL options today, but the\n // schema is also the documentation of the shape).\n inputSchema: z.custom<ZodType>().optional(),\n outputSchema: z.custom<ZodType>().optional(),\n});\n\n/* ─── Builder ─── */\n\nexport class WorkflowBuilder<TInput = unknown, TOutput = unknown> {\n private readonly _steps: Step[] = [];\n private _committed = false;\n\n /** @internal */\n constructor(private readonly options: WorkflowOptions) {}\n\n /** @internal — only the executor reads this. */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: D233 locks the a peer framework-style `.then(step)` builder DSL. The method is fluent, never awaited.\n then<TO = unknown>(step: Step): WorkflowBuilder<TInput, TO> {\n this.assertNotCommitted();\n validateStepId(step.id);\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, TO>;\n }\n\n parallel(\n branches: ReadonlyArray<ReadonlyArray<Step>>,\n opts?: { id?: string; concurrency?: number; errorPolicy?: \"fail-fast\" | \"collect\" },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `parallel_${this._steps.length}`;\n validateStepId(id);\n for (const branch of branches) {\n for (const inner of branch) validateStepId(inner.id);\n }\n const step: ParallelStep = {\n kind: \"parallel\",\n id,\n branches,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(opts?.errorPolicy !== undefined ? { errorPolicy: opts.errorPolicy } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n branch(\n predicates: BranchStep[\"predicates\"],\n opts?: { id?: string; fallback?: ReadonlyArray<Step> },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `branch_${this._steps.length}`;\n validateStepId(id);\n const step: BranchStep = {\n kind: \"branch\",\n id,\n predicates,\n ...(opts?.fallback !== undefined ? { fallback: opts.fallback } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n foreach(\n iterableFrom: string,\n step: Step,\n opts?: { id?: string; concurrency?: number },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `foreach_${this._steps.length}`;\n validateStepId(id);\n validateStepId(iterableFrom);\n validateStepId(step.id);\n const node: ForeachStep = {\n kind: \"foreach\",\n id,\n iterableFrom,\n step,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n dowhile(\n step: Step,\n condFn: DowhileStep[\"condFn\"],\n opts?: { id?: string; maxIterations?: number },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `dowhile_${this._steps.length}`;\n validateStepId(id);\n validateStepId(step.id);\n const node: DowhileStep = {\n kind: \"dowhile\",\n id,\n step,\n condFn,\n ...(opts?.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n sleep(durationMs: number, id?: string): WorkflowBuilder<TInput, TOutput> {\n this.assertNotCommitted();\n const stepId = id ?? `sleep_${this._steps.length}`;\n validateStepId(stepId);\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);\n }\n const step: SleepStep = { kind: \"sleep\", id: stepId, durationMs };\n this._steps.push(step);\n return this;\n }\n\n suspend(opts?: { id?: string; payloadSchema?: ZodType }): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `suspend_${this._steps.length}`;\n validateStepId(id);\n const step: SuspendStep = {\n kind: \"suspend\",\n id,\n ...(opts?.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n commit(): Workflow<TInput, TOutput> {\n this.assertNotCommitted();\n this.validateUniqueIds();\n this._committed = true;\n // EC-5 absorbed: mint unique workflowId so single-flight lock is per-instance\n const workflowId = `wf-${mintShortId()}`;\n return new Workflow<TInput, TOutput>({ ...this.options, workflowId }, [...this._steps]);\n }\n\n private validateUniqueIds(): void {\n const seen = new Set<string>();\n walkStepsValidating(this._steps, seen);\n }\n\n private assertNotCommitted(): void {\n if (this._committed) {\n throw new Error(\"Workflow already committed; create a fresh Workflow.create(...) call.\");\n }\n }\n}\n\n/* ─── Workflow class ─── */\n\n/**\n * theokit#161 — project one step to its reflectable shape, recursing into the variants that nest.\n *\n * `parallel` branches are FLATTENED: the grouping is a scheduling detail (which steps may run\n * concurrently), not shape a reader of the workflow needs, and preserving it would put a second,\n * branch-shaped level into a type whose whole purpose is to be renderable.\n */\nfunction describeStep(step: Step): WorkflowStepDescription {\n const base = { id: step.id, kind: step.kind } as const;\n if (step.kind === \"parallel\") {\n return { ...base, steps: step.branches.flat().map(describeStep) };\n }\n if (step.kind === \"branch\") {\n const fromPredicates = step.predicates.flatMap(([, steps]) => steps.map(describeStep));\n const fromFallback = (step.fallback ?? []).map(describeStep);\n return { ...base, steps: [...fromPredicates, ...fromFallback] };\n }\n if (step.kind === \"foreach\" || step.kind === \"dowhile\") {\n return { ...base, steps: [describeStep(step.step)] };\n }\n return base;\n}\n\nexport class Workflow<TInput = unknown, TOutput = unknown> {\n /** @internal */\n constructor(\n private readonly _options: WorkflowOptions,\n private readonly _steps: ReadonlyArray<Step>,\n ) {}\n\n /** @internal — only the executor reads these. */\n get __options(): WorkflowOptions {\n return this._options;\n }\n /** @internal */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n /**\n * Construct a workflow builder. Validate options via Zod and return a\n * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the\n * immutable `Workflow`.\n */\n static create<TI = unknown, TO = unknown>(options: WorkflowOptions): WorkflowBuilder<TI, TO> {\n WorkflowOptionsSchema.parse(options);\n return new WorkflowBuilder<TI, TO>(options);\n }\n\n /**\n * theokit#161 — describe this workflow's shape, for a reflection surface.\n *\n * Returns `{ name, steps }`, each step carrying its `id` and `kind`, recursing into `parallel`,\n * `branch`, `foreach` and `dowhile`. Every executable a step holds — predicates, conditions,\n * agents, prompt templates — is omitted: it cannot cross a process boundary and says nothing about\n * shape.\n *\n * There is deliberately no `Workflow.list()`. A workflow is a value the caller constructs and\n * holds, so the caller already knows which ones exist; a registry would add process-global state\n * nothing releases in order to re-answer a question the host can answer itself. A reflection\n * endpoint maps over its own workflows and calls this.\n *\n * @public\n */\n describe(): WorkflowDescription {\n return {\n name: this._options.name,\n steps: this._steps.map(describeStep),\n };\n }\n\n /**\n * Run this workflow with the given input. Returns a populated\n * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via\n * `run.status === \"failed\"`.\n */\n async run(input: TInput, opts?: WorkflowRunOptions): Promise<WorkflowRun<TOutput>> {\n // Lazy import to keep the public façade lean.\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n const result = await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, opts);\n // T3.4: opt-in Task wrapping (ADRs D363, D374). Workflows are\n // observable via Task.list/get/subscribe; the underlying run is\n // already terminal here (executor returned), so the Task just\n // records the outcome for inspection.\n if (opts?.task !== undefined) {\n const { submit: taskSubmit } = await import(\"./internal/task/registry.js\");\n const taskOpts = opts.task === true ? {} : opts.task;\n const id = taskOpts.id ?? `wf-${result.id}`;\n await taskSubmit({\n kind: \"workflow\",\n work: async (ctx) => {\n ctx.emit({ status: result.status, runId: result.id });\n return { status: result.status, runId: result.id, output: result.output };\n },\n id,\n meta: {\n workflowName: this._options.name,\n runId: result.id,\n status: result.status,\n ...(taskOpts.meta ?? {}),\n },\n allowReservedPrefix: true,\n });\n }\n return result;\n }\n\n /**\n * SE28 — run the workflow and STREAM step-level events as they happen. Returns\n * an async iterator of {@link WorkflowEvent}s (`step_started` / `step_completed`\n * / `step_failed` / `workflow_suspended` / `workflow_completed`, top-level\n * steps) plus a `result` promise resolving to the same terminal\n * {@link WorkflowRun} `run()` returns. Iterate for progress; await `result` for\n * the outcome. The stream ends when the run terminates.\n *\n * `result` is the AUTHORITATIVE terminal status. Not every terminal state has a\n * closing event: a step failure emits `step_failed`, but an `outputSchema`\n * rejection (SE27) or an abort ends the stream WITHOUT `workflow_completed` —\n * always `await result` to read the final `status`. Consuming order is free:\n * awaiting `result` without draining, or draining without awaiting `result`,\n * both work (breaking out of `for await` stops the buffering early).\n */\n stream(input: TInput, opts?: WorkflowRunOptions): WorkflowStream<TOutput> {\n const queue = createEventStream();\n const result = (async (): Promise<WorkflowRun<TOutput>> => {\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n try {\n return await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, {\n ...opts,\n onStepEvent: (event: WorkflowEvent) => queue.push(event),\n } as WorkflowRunOptions);\n } finally {\n queue.end(); // authoritative terminal is `result`; close the stream\n }\n })();\n return Object.assign(queue, { result });\n }\n\n /**\n * Resume a suspended workflow from its snapshot. Throws\n * `WorkflowSnapshotNotFoundError` if `runId` is unknown.\n */\n static async resume<TO = unknown>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n const { resumeWorkflow } = await import(\"./internal/workflow/executor.js\");\n return resumeWorkflow<TO>(opts);\n }\n}\n\n/* ─── Helper factory functions ─── */\n\n/**\n * Build a `FnStep`. `id` must match `^[a-z0-9][a-z0-9_-]*$`.\n */\nexport function fn<I = unknown, O = unknown>(\n id: string,\n step: (input: I, ctx: StepContext) => Promise<O> | O,\n opts?: { inputSchema?: ZodType; outputSchema?: ZodType; retry?: RetryPolicy },\n): FnStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"fn\",\n id,\n fn: step as FnStep[\"fn\"],\n ...(opts?.inputSchema !== undefined ? { inputSchema: opts.inputSchema } : {}),\n ...(opts?.outputSchema !== undefined ? { outputSchema: opts.outputSchema } : {}),\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/**\n * Build an `AgentStep`. The `promptTemplate` can be a static string or a\n * function that receives the input and returns the prompt.\n */\nexport function agentStep(\n id: string,\n agent: SDKAgent,\n promptTemplate: string | ((input: unknown) => string),\n opts?: { retry?: RetryPolicy; origin?: MessageOrigin },\n): AgentStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"agent\",\n id,\n agent,\n promptTemplate,\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n // SE3 — carry the turn's provenance down to `agent.send()` (metadata-only).\n ...(opts?.origin !== undefined ? { origin: opts.origin } : {}),\n };\n}\n\n/**\n * SE30 — use a committed {@link Workflow} as a step inside another workflow.\n * Wraps the child as an `FnStep` (opaque — the child runs in its OWN executor\n * with its own id-space, so nested step-ids never collide with the parent's).\n * The child's output becomes the step output. A non-`completed` child fails the\n * parent step with a typed {@link WorkflowNestedError}: nested `suspended` is NOT\n * resumable in v1 (resume continues AFTER the step — the child would be skipped;\n * use a top-level suspend). See ADR 0010.\n *\n * @public\n */\nexport function workflowStep<TI = unknown, TO = unknown>(\n child: Workflow<TI, TO>,\n opts?: { id?: string },\n): FnStep {\n const id = opts?.id ?? `workflow_${child.__options.name}`;\n validateStepId(id);\n return {\n kind: \"fn\",\n id,\n fn: async (input: unknown, ctx: StepContext): Promise<unknown> => {\n const run = await child.run(input as TI, { signal: ctx.signal });\n if (run.status === \"completed\") return run.output;\n throw new WorkflowNestedError(id, child.__options.name, run.status, run.error);\n },\n };\n}\n\n/**\n * SE30 — clone a committed workflow under a new id/name. The clone runs\n * independently (its own single-flight lock + observability identity) with the\n * same committed steps. Mirrors a peer framework's `cloneWorkflow`.\n *\n * @public\n */\nexport function cloneWorkflow<TI = unknown, TO = unknown>(\n wf: Workflow<TI, TO>,\n opts: { id: string },\n): Workflow<TI, TO> {\n return new Workflow<TI, TO>(\n { ...wf.__options, name: opts.id, workflowId: `wf-${mintShortId()}` },\n [...wf.__steps],\n );\n}\n\n/* ─── Test seam re-export ─── */\n\nexport { __resetSnapshotStoresForTests } from \"./internal/workflow/snapshot-store.js\";\n\n/* ─── Re-exports for ergonomics (errors + all public types). After the\n sub-path extraction `@theokit/sdk/workflow` is the single import site,\n so type aliases must surface here (previously they reached consumers\n via `types/index.ts:25 export type * from \"./workflow.js\"`, which the\n extraction removes). ─── */\n\nexport type * from \"./types/workflow.js\";\nexport {\n WorkflowAlreadyRunningError,\n WorkflowCompensateNotImplementedError,\n WorkflowDuplicateStepIdError,\n WorkflowInputError,\n WorkflowMaxIterationsExceededError,\n WorkflowNestedError,\n WorkflowNotSerializableError,\n WorkflowOutputError,\n WorkflowParallelError,\n WorkflowResumeStepNotFoundError,\n WorkflowSnapshotNotFoundError,\n WorkflowStateError,\n} from \"./types/workflow.js\";\n\n/* ─── SE19 — workflowAsTool (expose a Workflow as an agent tool) ─── */\n\n/**\n * Raised by a {@link workflowAsTool} tool when the wrapped workflow run does not\n * reach `status: \"completed\"` (a step failed, the run was cancelled/suspended).\n * The dispatch converts it to a `tool_result(isError)`.\n *\n * @public\n */\nexport class WorkflowToolError extends Error {\n readonly code = \"workflow_tool_failed\" as const;\n constructor(\n readonly toolName: string,\n readonly workflowStatus: string,\n readonly workflowError?: { name: string; message: string },\n ) {\n super(\n `workflowAsTool(\"${toolName}\"): workflow ${workflowStatus}${\n workflowError ? `: ${workflowError.message}` : \"\"\n }`,\n );\n this.name = \"WorkflowToolError\";\n }\n}\n\n/** Spec for {@link workflowAsTool}. `inputSchema` is the workflow's input shape (Zod). */\nexport interface WorkflowAsToolSpec<T extends ZodType> {\n /** Tool name surfaced to the LLM. Same constraints as a `CustomTool.name`. */\n name: string;\n /** Description surfaced to the LLM — when the agent should trigger the workflow. */\n description: string;\n /** Zod schema for the workflow's input (a `Workflow` carries no top-level schema). */\n inputSchema: T;\n}\n\n/**\n * SE19 — expose a {@link Workflow} as an agent {@link CustomTool}, completing the\n * \"X as tools\" trio (tools; agents-as-tools via `defineSubAgent`; workflows-as-tools).\n * The handler validates the model's args against `spec.inputSchema`, runs the\n * workflow, and returns its output (a string as-is, else JSON). A run that does not\n * reach `status: \"completed\"` raises a typed {@link WorkflowToolError} (workflow\n * step errors do NOT throw — they surface via `run.status === \"failed\"`).\n *\n * Accepts any `{ run }`-shaped workflow (structural), so it never imports the\n * `Workflow` class directly.\n *\n * @public\n */\nexport function workflowAsTool<T extends ZodType, TOutput = unknown>(\n workflow: { run: (input: z.infer<T>) => Promise<WorkflowRun<TOutput>> },\n spec: WorkflowAsToolSpec<T>,\n): CustomTool {\n const inputSchema = toJsonSchema(spec.inputSchema, { unrepresentable: \"any\" });\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (rawInput: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(rawInput) as z.infer<T>;\n const run = await workflow.run(parsed);\n if (run.status !== \"completed\") {\n throw new WorkflowToolError(spec.name, run.status, run.error);\n }\n const output = run.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n },\n };\n}\n\n/* ─── Internal helpers ─── */\n\nfunction validateStepId(id: string): void {\n // Reuses D81 grammar: ^[a-z0-9][a-z0-9_-]*$\n sanitizeIdentifier(id, { maxLen: 64 });\n}\n\nfunction mintShortId(): string {\n return globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8);\n}\n\nfunction nestedStepsOf(s: Step): ReadonlyArray<ReadonlyArray<Step>> {\n if (s.kind === \"parallel\") return s.branches;\n if (s.kind === \"branch\") {\n const groups = s.predicates.map(([, branch]) => branch);\n return s.fallback !== undefined ? [...groups, s.fallback] : groups;\n }\n if (s.kind === \"foreach\" || s.kind === \"dowhile\") return [[s.step]];\n return [];\n}\n\nfunction walkStepsValidating(steps: ReadonlyArray<Step>, seen: Set<string>): void {\n for (const s of steps) {\n if (seen.has(s.id)) throw new WorkflowDuplicateStepIdError(s.id);\n seen.add(s.id);\n for (const nested of nestedStepsOf(s)) {\n walkStepsValidating(nested, seen);\n }\n }\n}\n"]}