@theokit/sdk 4.28.0 → 4.30.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 (90) hide show
  1. package/dist/agent-7YUGJJTU.js +41 -0
  2. package/dist/agent-7YUGJJTU.js.map +1 -0
  3. package/dist/{cron-BN6JJlDw.d.ts → agent-Bzg2_uGr.d.cts} +56 -577
  4. package/dist/{cron-CoQREV_k.d.cts → agent-Ekv8y7_c.d.ts} +56 -577
  5. package/dist/agent-LD76RI74.cjs +50 -0
  6. package/dist/agent-LD76RI74.cjs.map +1 -0
  7. package/dist/{chunk-AKSBP7OO.js → chunk-5IB2UKSN.js} +5 -41
  8. package/dist/chunk-5IB2UKSN.js.map +1 -0
  9. package/dist/{chunk-PF5Y5BHG.js → chunk-5YCAR23S.js} +3 -3
  10. package/dist/{chunk-PF5Y5BHG.js.map → chunk-5YCAR23S.js.map} +1 -1
  11. package/dist/chunk-BNIFFFH3.js +129 -0
  12. package/dist/chunk-BNIFFFH3.js.map +1 -0
  13. package/dist/{chunk-LSLPF6OI.cjs → chunk-DHLZIMP6.cjs} +5 -43
  14. package/dist/chunk-DHLZIMP6.cjs.map +1 -0
  15. package/dist/chunk-FKCC2MED.js +43 -0
  16. package/dist/chunk-FKCC2MED.js.map +1 -0
  17. package/dist/{chunk-PN53WGEI.cjs → chunk-GWMQ5CS3.cjs} +633 -741
  18. package/dist/chunk-GWMQ5CS3.cjs.map +1 -0
  19. package/dist/{chunk-QUTUJ6P6.cjs → chunk-HK7ZHSAX.cjs} +25 -16
  20. package/dist/chunk-HK7ZHSAX.cjs.map +1 -0
  21. package/dist/{chunk-XW6RXVGB.js → chunk-ISZ3MBUD.js} +610 -718
  22. package/dist/chunk-ISZ3MBUD.js.map +1 -0
  23. package/dist/{chunk-MQLCZ4HJ.cjs → chunk-JLMXKTBX.cjs} +4 -4
  24. package/dist/{chunk-MQLCZ4HJ.cjs.map → chunk-JLMXKTBX.cjs.map} +1 -1
  25. package/dist/chunk-LALRCFSN.cjs +46 -0
  26. package/dist/chunk-LALRCFSN.cjs.map +1 -0
  27. package/dist/{chunk-I53QDJVI.cjs → chunk-NG6B2PMA.cjs} +5 -5
  28. package/dist/{chunk-I53QDJVI.cjs.map → chunk-NG6B2PMA.cjs.map} +1 -1
  29. package/dist/{chunk-DUK5WMKJ.js → chunk-R6ZP6KNB.js} +25 -16
  30. package/dist/chunk-R6ZP6KNB.js.map +1 -0
  31. package/dist/chunk-RZQ6E5YZ.cjs +131 -0
  32. package/dist/chunk-RZQ6E5YZ.cjs.map +1 -0
  33. package/dist/{chunk-G6GO6BXD.js → chunk-XAUBQMQU.js} +3 -3
  34. package/dist/{chunk-G6GO6BXD.js.map → chunk-XAUBQMQU.js.map} +1 -1
  35. package/dist/compact-session-OO2GD76G.js +1 -1
  36. package/dist/compact-session-OO7NVWPB.cjs +1 -1
  37. package/dist/cron-CjzvXGT2.d.cts +579 -0
  38. package/dist/cron-D0Z29gI-.d.ts +579 -0
  39. package/dist/cron.cjs +13 -11
  40. package/dist/cron.d.cts +2 -1
  41. package/dist/cron.d.ts +2 -1
  42. package/dist/cron.js +12 -10
  43. package/dist/eval.cjs +17 -15
  44. package/dist/eval.cjs.map +1 -1
  45. package/dist/eval.js +13 -11
  46. package/dist/eval.js.map +1 -1
  47. package/dist/{index-manager-CB6I7XFQ.cjs → index-manager-H7HUMW52.cjs} +5 -5
  48. package/dist/{index-manager-CB6I7XFQ.cjs.map → index-manager-H7HUMW52.cjs.map} +1 -1
  49. package/dist/{index-manager-L27Q3QAC.js → index-manager-P7ZUX2RG.js} +4 -4
  50. package/dist/{index-manager-L27Q3QAC.js.map → index-manager-P7ZUX2RG.js.map} +1 -1
  51. package/dist/index.cjs +65 -44
  52. package/dist/index.cjs.map +1 -1
  53. package/dist/index.d.cts +18 -4
  54. package/dist/index.d.ts +18 -4
  55. package/dist/index.js +41 -20
  56. package/dist/index.js.map +1 -1
  57. package/dist/internal/persistence/index.cjs +10 -10
  58. package/dist/internal/persistence/index.js +2 -2
  59. package/dist/internal/persistence/jsonl.d.cts +7 -0
  60. package/dist/internal/persistence/jsonl.d.ts +7 -0
  61. package/dist/internal/persistence/session-writer.d.cts +56 -0
  62. package/dist/internal/persistence/session-writer.d.ts +56 -0
  63. package/dist/internal/persistence/transcript-ops.d.cts +71 -0
  64. package/dist/internal/persistence/transcript-ops.d.ts +71 -0
  65. package/dist/internal/plugins/types.d.cts +1 -1
  66. package/dist/internal/plugins/types.d.ts +1 -1
  67. package/dist/persistence.cjs +115 -12
  68. package/dist/persistence.cjs.map +1 -1
  69. package/dist/persistence.d.cts +2 -0
  70. package/dist/persistence.d.ts +2 -0
  71. package/dist/persistence.js +105 -3
  72. package/dist/persistence.js.map +1 -1
  73. package/dist/skills.cjs +4 -3
  74. package/dist/skills.js +2 -1
  75. package/dist/subagents-loader.cjs +19 -0
  76. package/dist/subagents-loader.cjs.map +1 -0
  77. package/dist/subagents-loader.d.cts +39 -0
  78. package/dist/subagents-loader.d.ts +39 -0
  79. package/dist/subagents-loader.js +16 -0
  80. package/dist/subagents-loader.js.map +1 -0
  81. package/dist/types/plugin.d.ts +32 -0
  82. package/dist/workflow.cjs +1 -1
  83. package/dist/workflow.js +1 -1
  84. package/package.json +12 -2
  85. package/dist/chunk-AKSBP7OO.js.map +0 -1
  86. package/dist/chunk-DUK5WMKJ.js.map +0 -1
  87. package/dist/chunk-LSLPF6OI.cjs.map +0 -1
  88. package/dist/chunk-PN53WGEI.cjs.map +0 -1
  89. package/dist/chunk-QUTUJ6P6.cjs.map +0 -1
  90. package/dist/chunk-XW6RXVGB.js.map +0 -1
@@ -1,11 +1,113 @@
1
- export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds } from './chunk-DUK5WMKJ.js';
1
+ export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds } from './chunk-R6ZP6KNB.js';
2
2
  export { PersistenceSchema } from './chunk-CAH3G4IS.js';
3
- export { applyWalWithFallback, isCorruptionError, openSqliteResilient, sanitizeFts5Query } from './chunk-77FOZCOT.js';
4
3
  export { withFileLock } from './chunk-HZQEDNF6.js';
4
+ export { applyWalWithFallback, isCorruptionError, openSqliteResilient, sanitizeFts5Query } from './chunk-77FOZCOT.js';
5
5
  export { withCwdMutex } from './chunk-2XLKLVVR.js';
6
6
  export { encodeProjectDir, transcriptPath } from './chunk-ZZWTY3RX.js';
7
7
  export { atomicWriteJson, atomicWriteText, replaceFileAtomic } from './chunk-S2BBRVQX.js';
8
- import './chunk-WLKFWQSJ.js';
8
+ import { TheokitAgentError } from './chunk-WLKFWQSJ.js';
9
9
  import './chunk-JTFYYKDT.js';
10
+ import { openSync, closeSync, rmSync, readFileSync, writeSync, statSync, readSync } from 'fs';
11
+
12
+ var SessionBusyError = class extends TheokitAgentError {
13
+ constructor(sessionPath) {
14
+ super(
15
+ `another process is already writing this session: ${sessionPath}. Fork it to a new id instead of appending \u2014 two writers interleave lines into a sequence that parses but is not what either process wrote.`,
16
+ { code: "session_busy", isRetryable: false }
17
+ );
18
+ this.sessionPath = sessionPath;
19
+ }
20
+ sessionPath;
21
+ name = "SessionBusyError";
22
+ };
23
+ async function acquireSessionWriter(sessionPath) {
24
+ const lockPath = `${sessionPath}.lock`;
25
+ let fd;
26
+ try {
27
+ fd = openSync(lockPath, "wx");
28
+ } catch (err) {
29
+ if (err.code === "EEXIST") {
30
+ throw new SessionBusyError(sessionPath);
31
+ }
32
+ throw err;
33
+ }
34
+ closeSync(fd);
35
+ let released = false;
36
+ return {
37
+ sessionPath,
38
+ release: async () => {
39
+ if (released) return;
40
+ released = true;
41
+ rmSync(lockPath, { force: true });
42
+ }
43
+ };
44
+ }
45
+ var LiveSessionError = class extends TheokitAgentError {
46
+ constructor(path) {
47
+ super(
48
+ `refusing to write over a live session transcript: ${path}. Fork to a new id instead \u2014 the live pointer, the most recent transcript and any active registry entry are never overwritten (audit-trail rotation, M60).`,
49
+ { code: "live_session_protected", isRetryable: false }
50
+ );
51
+ this.path = path;
52
+ }
53
+ path;
54
+ name = "LiveSessionError";
55
+ };
56
+ function forkTranscript(src, dst, options = {}) {
57
+ for (const live of options.liveSessionPaths ?? []) {
58
+ if (live === dst) throw new LiveSessionError(dst);
59
+ }
60
+ const lines = readFileSync(src, "utf8").split("\n").filter((l) => l.trim().length > 0);
61
+ const kept = options.beforeRecordIndex === void 0 ? lines : lines.slice(0, options.beforeRecordIndex);
62
+ const body = kept.length > 0 ? `${kept.join("\n")}
63
+ ` : "";
64
+ const fd = openSync(dst, "wx");
65
+ try {
66
+ writeSync(fd, body);
67
+ } finally {
68
+ closeSync(fd);
69
+ }
70
+ }
71
+ var TAIL_CHUNK = 64 * 1024;
72
+ function lerCaudaBruta(path, want) {
73
+ const size = statSync(path).size;
74
+ const fd = openSync(path, "r");
75
+ let bytesRead = 0;
76
+ let tail = "";
77
+ let pos = size;
78
+ try {
79
+ while (pos > 0) {
80
+ const len = Math.min(TAIL_CHUNK, pos);
81
+ pos -= len;
82
+ const buf = Buffer.alloc(len);
83
+ readSync(fd, buf, 0, len, pos);
84
+ bytesRead += len;
85
+ tail = buf.toString("utf8") + tail;
86
+ if (naoVazias(tail).length > want) break;
87
+ }
88
+ } finally {
89
+ closeSync(fd);
90
+ }
91
+ const linhas = naoVazias(tail);
92
+ return { linhas: pos > 0 ? linhas.slice(1) : linhas, bytesRead };
93
+ }
94
+ function naoVazias(texto) {
95
+ return texto.split("\n").filter((l) => l.trim().length > 0);
96
+ }
97
+ function readJsonlTail(path, options = {}) {
98
+ const want = options.maxRecords ?? Number.POSITIVE_INFINITY;
99
+ const { linhas, bytesRead } = lerCaudaBruta(path, want);
100
+ let sel = linhas;
101
+ if (options.sinceMarker !== void 0) {
102
+ const marcador = options.sinceMarker;
103
+ const idx = sel.findLastIndex((l) => l.includes(marcador));
104
+ if (idx >= 0) sel = sel.slice(idx + 1);
105
+ }
106
+ if (Number.isFinite(want)) sel = sel.slice(-want);
107
+ const out = sel.map((l) => JSON.parse(l));
108
+ return options._stats === true ? Object.assign(out, { bytesRead }) : out;
109
+ }
110
+
111
+ export { LiveSessionError, SessionBusyError, acquireSessionWriter, forkTranscript, readJsonlTail };
10
112
  //# sourceMappingURL=persistence.js.map
11
113
  //# sourceMappingURL=persistence.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"persistence.js"}
1
+ {"version":3,"sources":["../src/internal/persistence/session-writer.ts","../src/internal/persistence/transcript-ops.ts"],"names":["openSync","closeSync"],"mappings":";;;;;;;;;;;AA0CO,IAAM,gBAAA,GAAN,cAA+B,iBAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAeA,eAAsB,qBAAqB,WAAA,EAAkD;AAC3F,EAAA,MAAM,QAAA,GAAW,GAAG,WAAW,CAAA,KAAA,CAAA;AAC/B,EAAA,IAAI,EAAA;AACJ,EAAA,IAAI;AACF,IAAA,EAAA,GAAK,QAAA,CAAS,UAAU,IAAI,CAAA;AAAA,EAC9B,SAAS,GAAA,EAAK;AACZ,IAAA,IAAK,GAAA,CAA8B,SAAS,QAAA,EAAU;AACpD,MAAA,MAAM,IAAI,iBAAiB,WAAW,CAAA;AAAA,IACxC;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACA,EAAA,SAAA,CAAU,EAAE,CAAA;AAEZ,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,SAAS,YAA2B;AAClC,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAA,CAAO,QAAA,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IAAA,EAAK,CAAE,MAAA,GAAS,CAAC,CAAA;AAC5D;AASO,SAAS,aAAA,CACd,IAAA,EACA,OAAA,GAAgC,EAAC,EAC5B;AACL,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,UAAA,IAAc,MAAA,CAAO,iBAAA;AAC1C,EAAA,MAAM,EAAE,MAAA,EAAQ,SAAA,EAAU,GAAI,aAAA,CAAc,MAAM,IAAI,CAAA;AAEtD,EAAA,IAAI,GAAA,GAAM,MAAA;AACV,EAAA,IAAI,OAAA,CAAQ,gBAAgB,MAAA,EAAW;AACrC,IAAA,MAAM,WAAW,OAAA,CAAQ,WAAA;AACzB,IAAA,MAAM,GAAA,GAAM,IAAI,aAAA,CAAc,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,QAAQ,CAAC,CAAA;AACzD,IAAA,IAAI,OAAO,CAAA,EAAG,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,MAAM,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,MAAA,CAAO,SAAS,IAAI,CAAA,QAAS,GAAA,CAAI,KAAA,CAAM,CAAC,IAAI,CAAA;AAEhD,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,CAAC,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAM,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.js","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport { closeSync, openSync, rmSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n const lockPath = `${sessionPath}.lock`;\n let fd: number;\n try {\n fd = openSync(lockPath, \"wx\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n throw new SessionBusyError(sessionPath);\n }\n throw err;\n }\n closeSync(fd);\n\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n };\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee.\n const fd = openSync(dst, \"wx\");\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Lê chunks de trás para frente até acumular linhas completas suficientes.\n *\n * Extraído de `readJsonlTail` porque o laço de leitura e a seleção de registros são duas\n * responsabilidades — e juntas passavam do teto de complexidade. A primeira linha do buffer pode\n * estar cortada ao meio quando a leitura parou antes do início do arquivo; por isso ela é descartada.\n */\nfunction lerCaudaBruta(path: string, want: number): { linhas: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (naoVazias(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const linhas = naoVazias(tail);\n return { linhas: pos > 0 ? linhas.slice(1) : linhas, bytesRead };\n}\n\n/** Linhas com conteúdo, na ordem do arquivo. */\nfunction naoVazias(texto: string): string[] {\n return texto.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { linhas, bytesRead } = lerCaudaBruta(path, want);\n\n let sel = linhas;\n if (options.sinceMarker !== undefined) {\n const marcador = options.sinceMarker;\n const idx = sel.findLastIndex((l) => l.includes(marcador));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
package/dist/skills.cjs CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunkLSLPF6OI_cjs = require('./chunk-LSLPF6OI.cjs');
3
+ var chunkDHLZIMP6_cjs = require('./chunk-DHLZIMP6.cjs');
4
4
  require('./chunk-KIO7QFIV.cjs');
5
+ require('./chunk-LALRCFSN.cjs');
5
6
  require('./chunk-A44COQJJ.cjs');
6
7
  require('./chunk-BEURCLDV.cjs');
7
8
 
@@ -9,11 +10,11 @@ require('./chunk-BEURCLDV.cjs');
9
10
 
10
11
  Object.defineProperty(exports, "buildSkillsBlock", {
11
12
  enumerable: true,
12
- get: function () { return chunkLSLPF6OI_cjs.buildSkillsBlock; }
13
+ get: function () { return chunkDHLZIMP6_cjs.buildSkillsBlock; }
13
14
  });
14
15
  Object.defineProperty(exports, "discoverSkills", {
15
16
  enumerable: true,
16
- get: function () { return chunkLSLPF6OI_cjs.discoverSkills; }
17
+ get: function () { return chunkDHLZIMP6_cjs.discoverSkills; }
17
18
  });
18
19
  //# sourceMappingURL=skills.cjs.map
19
20
  //# sourceMappingURL=skills.cjs.map
package/dist/skills.js CHANGED
@@ -1,5 +1,6 @@
1
- export { buildSkillsBlock, discoverSkills } from './chunk-AKSBP7OO.js';
1
+ export { buildSkillsBlock, discoverSkills } from './chunk-5IB2UKSN.js';
2
2
  import './chunk-POQT2OIF.js';
3
+ import './chunk-FKCC2MED.js';
3
4
  import './chunk-WLKFWQSJ.js';
4
5
  import './chunk-JTFYYKDT.js';
5
6
  //# sourceMappingURL=skills.js.map
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+
3
+ var chunkRZQ6E5YZ_cjs = require('./chunk-RZQ6E5YZ.cjs');
4
+ require('./chunk-LALRCFSN.cjs');
5
+ require('./chunk-A44COQJJ.cjs');
6
+ require('./chunk-BEURCLDV.cjs');
7
+
8
+ // src/subagents-loader.ts
9
+ async function discoverSubagents(cwd) {
10
+ return chunkRZQ6E5YZ_cjs.loadSubagents(cwd, true, void 0);
11
+ }
12
+ async function loadSubagentDefinition(name, cwd) {
13
+ return (await discoverSubagents(cwd))[name];
14
+ }
15
+
16
+ exports.discoverSubagents = discoverSubagents;
17
+ exports.loadSubagentDefinition = loadSubagentDefinition;
18
+ //# sourceMappingURL=subagents-loader.cjs.map
19
+ //# sourceMappingURL=subagents-loader.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/subagents-loader.ts"],"names":["loadSubagents"],"mappings":";;;;;;;;AA4BA,eAAsB,kBAAkB,GAAA,EAAuD;AAC7F,EAAA,OAAOA,+BAAA,CAAc,GAAA,EAAK,IAAA,EAAM,MAAS,CAAA;AAC3C;AAQA,eAAsB,sBAAA,CACpB,MACA,GAAA,EACsC;AACtC,EAAA,OAAA,CAAQ,MAAM,iBAAA,CAAkB,GAAG,CAAA,EAAG,IAAI,CAAA;AAC5C","file":"subagents-loader.cjs","sourcesContent":["/**\n * M81 — `.theokit/agents` discovery, exposed so a consumer can read the on-disk subagent\n * definitions with one import instead of hand-rolling a second parser.\n *\n * ## Why this file exists\n *\n * `src/skills.ts` already exposed `discoverSkills` for the sibling domain. Subagents had the same\n * loader — `internal/runtime/skills/subagents-loader.ts` — with no public door. A consumer behind\n * the layer boundary (the agent-builder never imports `@theokit/sdk*` directly) could not reach it,\n * so re-implementing was the only legal option. It re-implemented, and then wrote a test whose only\n * job was to watch the two parsers for drift. That test is the cleanest possible evidence that the\n * duplication should not exist.\n *\n * ## What crosses is the PARSED config\n *\n * The return is `AgentDefinition` — already interpreted — never the `.md` text or the frontmatter\n * shape. Exporting the file format would freeze an internal detail as public API; exporting the\n * parsed value leaves the format free to change.\n */\n\nimport { loadSubagents } from \"./internal/runtime/skills/subagents-loader.js\";\nimport type { AgentDefinition } from \"./types/agent.js\";\n\n/**\n * Discover the subagents defined under `<cwd>/.theokit/agents/*.md`.\n *\n * An absent directory yields `{}` — a project without subagents is the common case, not an error.\n */\nexport async function discoverSubagents(cwd: string): Promise<Record<string, AgentDefinition>> {\n return loadSubagents(cwd, true, undefined);\n}\n\n/**\n * Load ONE subagent definition by name, or `undefined` when it is not defined on disk.\n *\n * A thin selector over {@link discoverSubagents} rather than a second reader: one parser is the\n * whole point of this module.\n */\nexport async function loadSubagentDefinition(\n name: string,\n cwd: string,\n): Promise<AgentDefinition | undefined> {\n return (await discoverSubagents(cwd))[name];\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import { a as AgentDefinition } from './agent-Bzg2_uGr.cjs';
2
+ import './run-OJbGyweZ.cjs';
3
+ import 'zod';
4
+
5
+ /**
6
+ * M81 — `.theokit/agents` discovery, exposed so a consumer can read the on-disk subagent
7
+ * definitions with one import instead of hand-rolling a second parser.
8
+ *
9
+ * ## Why this file exists
10
+ *
11
+ * `src/skills.ts` already exposed `discoverSkills` for the sibling domain. Subagents had the same
12
+ * loader — `internal/runtime/skills/subagents-loader.ts` — with no public door. A consumer behind
13
+ * the layer boundary (the agent-builder never imports `@theokit/sdk*` directly) could not reach it,
14
+ * so re-implementing was the only legal option. It re-implemented, and then wrote a test whose only
15
+ * job was to watch the two parsers for drift. That test is the cleanest possible evidence that the
16
+ * duplication should not exist.
17
+ *
18
+ * ## What crosses is the PARSED config
19
+ *
20
+ * The return is `AgentDefinition` — already interpreted — never the `.md` text or the frontmatter
21
+ * shape. Exporting the file format would freeze an internal detail as public API; exporting the
22
+ * parsed value leaves the format free to change.
23
+ */
24
+
25
+ /**
26
+ * Discover the subagents defined under `<cwd>/.theokit/agents/*.md`.
27
+ *
28
+ * An absent directory yields `{}` — a project without subagents is the common case, not an error.
29
+ */
30
+ declare function discoverSubagents(cwd: string): Promise<Record<string, AgentDefinition>>;
31
+ /**
32
+ * Load ONE subagent definition by name, or `undefined` when it is not defined on disk.
33
+ *
34
+ * A thin selector over {@link discoverSubagents} rather than a second reader: one parser is the
35
+ * whole point of this module.
36
+ */
37
+ declare function loadSubagentDefinition(name: string, cwd: string): Promise<AgentDefinition | undefined>;
38
+
39
+ export { discoverSubagents, loadSubagentDefinition };
@@ -0,0 +1,39 @@
1
+ import { a as AgentDefinition } from './agent-Ekv8y7_c.js';
2
+ import './run-OJbGyweZ.js';
3
+ import 'zod';
4
+
5
+ /**
6
+ * M81 — `.theokit/agents` discovery, exposed so a consumer can read the on-disk subagent
7
+ * definitions with one import instead of hand-rolling a second parser.
8
+ *
9
+ * ## Why this file exists
10
+ *
11
+ * `src/skills.ts` already exposed `discoverSkills` for the sibling domain. Subagents had the same
12
+ * loader — `internal/runtime/skills/subagents-loader.ts` — with no public door. A consumer behind
13
+ * the layer boundary (the agent-builder never imports `@theokit/sdk*` directly) could not reach it,
14
+ * so re-implementing was the only legal option. It re-implemented, and then wrote a test whose only
15
+ * job was to watch the two parsers for drift. That test is the cleanest possible evidence that the
16
+ * duplication should not exist.
17
+ *
18
+ * ## What crosses is the PARSED config
19
+ *
20
+ * The return is `AgentDefinition` — already interpreted — never the `.md` text or the frontmatter
21
+ * shape. Exporting the file format would freeze an internal detail as public API; exporting the
22
+ * parsed value leaves the format free to change.
23
+ */
24
+
25
+ /**
26
+ * Discover the subagents defined under `<cwd>/.theokit/agents/*.md`.
27
+ *
28
+ * An absent directory yields `{}` — a project without subagents is the common case, not an error.
29
+ */
30
+ declare function discoverSubagents(cwd: string): Promise<Record<string, AgentDefinition>>;
31
+ /**
32
+ * Load ONE subagent definition by name, or `undefined` when it is not defined on disk.
33
+ *
34
+ * A thin selector over {@link discoverSubagents} rather than a second reader: one parser is the
35
+ * whole point of this module.
36
+ */
37
+ declare function loadSubagentDefinition(name: string, cwd: string): Promise<AgentDefinition | undefined>;
38
+
39
+ export { discoverSubagents, loadSubagentDefinition };
@@ -0,0 +1,16 @@
1
+ import { loadSubagents } from './chunk-BNIFFFH3.js';
2
+ import './chunk-FKCC2MED.js';
3
+ import './chunk-WLKFWQSJ.js';
4
+ import './chunk-JTFYYKDT.js';
5
+
6
+ // src/subagents-loader.ts
7
+ async function discoverSubagents(cwd) {
8
+ return loadSubagents(cwd, true, void 0);
9
+ }
10
+ async function loadSubagentDefinition(name, cwd) {
11
+ return (await discoverSubagents(cwd))[name];
12
+ }
13
+
14
+ export { discoverSubagents, loadSubagentDefinition };
15
+ //# sourceMappingURL=subagents-loader.js.map
16
+ //# sourceMappingURL=subagents-loader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/subagents-loader.ts"],"names":[],"mappings":";;;;;;AA4BA,eAAsB,kBAAkB,GAAA,EAAuD;AAC7F,EAAA,OAAO,aAAA,CAAc,GAAA,EAAK,IAAA,EAAM,MAAS,CAAA;AAC3C;AAQA,eAAsB,sBAAA,CACpB,MACA,GAAA,EACsC;AACtC,EAAA,OAAA,CAAQ,MAAM,iBAAA,CAAkB,GAAG,CAAA,EAAG,IAAI,CAAA;AAC5C","file":"subagents-loader.js","sourcesContent":["/**\n * M81 — `.theokit/agents` discovery, exposed so a consumer can read the on-disk subagent\n * definitions with one import instead of hand-rolling a second parser.\n *\n * ## Why this file exists\n *\n * `src/skills.ts` already exposed `discoverSkills` for the sibling domain. Subagents had the same\n * loader — `internal/runtime/skills/subagents-loader.ts` — with no public door. A consumer behind\n * the layer boundary (the agent-builder never imports `@theokit/sdk*` directly) could not reach it,\n * so re-implementing was the only legal option. It re-implemented, and then wrote a test whose only\n * job was to watch the two parsers for drift. That test is the cleanest possible evidence that the\n * duplication should not exist.\n *\n * ## What crosses is the PARSED config\n *\n * The return is `AgentDefinition` — already interpreted — never the `.md` text or the frontmatter\n * shape. Exporting the file format would freeze an internal detail as public API; exporting the\n * parsed value leaves the format free to change.\n */\n\nimport { loadSubagents } from \"./internal/runtime/skills/subagents-loader.js\";\nimport type { AgentDefinition } from \"./types/agent.js\";\n\n/**\n * Discover the subagents defined under `<cwd>/.theokit/agents/*.md`.\n *\n * An absent directory yields `{}` — a project without subagents is the common case, not an error.\n */\nexport async function discoverSubagents(cwd: string): Promise<Record<string, AgentDefinition>> {\n return loadSubagents(cwd, true, undefined);\n}\n\n/**\n * Load ONE subagent definition by name, or `undefined` when it is not defined on disk.\n *\n * A thin selector over {@link discoverSubagents} rather than a second reader: one parser is the\n * whole point of this module.\n */\nexport async function loadSubagentDefinition(\n name: string,\n cwd: string,\n): Promise<AgentDefinition | undefined> {\n return (await discoverSubagents(cwd))[name];\n}\n"]}
@@ -77,6 +77,38 @@ export interface TransformContext {
77
77
  agentId: string;
78
78
  runId: string;
79
79
  }
80
+ /**
81
+ * M82 — one tool call of the turn, as seen by `transform_tool_result`. `id` is the correlation key
82
+ * back into the batch: it equals the `toolUseId` of the matching `tool_result` part.
83
+ *
84
+ * @public
85
+ */
86
+ export interface ToolCallSummary {
87
+ id: string;
88
+ name: string;
89
+ args: Record<string, unknown>;
90
+ }
91
+ /**
92
+ * M82 — context for `transform_tool_result`, the only tool-stage hook whose return value the SDK
93
+ * actually applies (`#runTransform` folds it; `#runFireAndForget` discards `post_tool_call`'s).
94
+ *
95
+ * Before M82 this seam knew only `{agentId, runId}`, so a hook could transform results but could not
96
+ * tell WHICH tool produced which one. A policy scoped to a tool name — the common case — therefore
97
+ * had to live on `post_tool_call`, whose return is discarded, and silently degraded to observation.
98
+ *
99
+ * `toolCalls` is PLURAL because the seam is batch-shaped: `dispatchTools` runs every tool call of the
100
+ * turn and the hook receives all results together. A singular `name` would have to lie in any
101
+ * multi-tool turn. Correlate with `LlmToolResultPart.toolUseId === ToolCallSummary.id`.
102
+ *
103
+ * Kept separate from {@link TransformContext} on purpose: that type is shared with
104
+ * `transform_llm_output`, which has no tool call at all, and an optional field there would be
105
+ * permanently `undefined` for half its consumers.
106
+ *
107
+ * @public
108
+ */
109
+ export interface ToolResultTransformContext extends TransformContext {
110
+ toolCalls: readonly ToolCallSummary[];
111
+ }
80
112
  /**
81
113
  * Context passed to `pre_user_send` hook handlers (ADR D145).
82
114
  *
package/dist/workflow.cjs CHANGED
@@ -4,8 +4,8 @@ var chunkZ2OC3UIW_cjs = require('./chunk-Z2OC3UIW.cjs');
4
4
  var chunkBWT67BI4_cjs = require('./chunk-BWT67BI4.cjs');
5
5
  require('./chunk-PNVDQL5Y.cjs');
6
6
  require('./chunk-WJVHMTKB.cjs');
7
- require('./chunk-KIO7QFIV.cjs');
8
7
  require('./chunk-TIZ4TS5V.cjs');
8
+ require('./chunk-KIO7QFIV.cjs');
9
9
  require('./chunk-A44COQJJ.cjs');
10
10
  require('./chunk-BEURCLDV.cjs');
11
11
 
package/dist/workflow.js CHANGED
@@ -2,8 +2,8 @@ export { Workflow, WorkflowBuilder, WorkflowToolError, agentStep, cloneWorkflow,
2
2
  export { WorkflowAlreadyRunningError, WorkflowCompensateNotImplementedError, WorkflowDuplicateStepIdError, WorkflowInputError, WorkflowMaxIterationsExceededError, WorkflowNestedError, WorkflowNotSerializableError, WorkflowOutputError, WorkflowParallelError, WorkflowResumeStepNotFoundError, WorkflowSnapshotNotFoundError, WorkflowStateError, __resetSnapshotStoresForTests } from './chunk-UVNG67DG.js';
3
3
  import './chunk-CAH3G4IS.js';
4
4
  import './chunk-4VPXM6UU.js';
5
- import './chunk-POQT2OIF.js';
6
5
  import './chunk-S2BBRVQX.js';
6
+ import './chunk-POQT2OIF.js';
7
7
  import './chunk-WLKFWQSJ.js';
8
8
  import './chunk-JTFYYKDT.js';
9
9
  //# sourceMappingURL=workflow.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/sdk",
3
- "version": "4.28.0",
3
+ "version": "4.30.0",
4
4
  "description": "TypeScript SDK for the Theo agent harness — same surface, local or cloud.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/usetheodev/theokit-sdk#readme",
@@ -298,7 +298,17 @@
298
298
  "default": "./dist/interactive/index.cjs"
299
299
  }
300
300
  },
301
- "./package.json": "./package.json"
301
+ "./package.json": "./package.json",
302
+ "./subagents-loader": {
303
+ "import": {
304
+ "types": "./dist/subagents-loader.d.ts",
305
+ "default": "./dist/subagents-loader.js"
306
+ },
307
+ "require": {
308
+ "types": "./dist/subagents-loader.d.cts",
309
+ "default": "./dist/subagents-loader.cjs"
310
+ }
311
+ }
302
312
  },
303
313
  "files": [
304
314
  "dist",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/runtime/config/workspace-dir.ts","../src/internal/runtime/context/yaml-frontmatter.ts","../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":[],"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{ readdir } from \"node:fs/promises\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\n\n/**\n * Entry returned by `readWorkspaceDir`. Mirrors the subset of\n * `fs.Dirent` the file-based loaders use.\n */\nexport interface WorkspaceDirEntry {\n name: string;\n isDirectory(): boolean;\n isFile(): boolean;\n}\n\n/**\n * Read a workspace subdirectory and return its entries. When the directory\n * does not exist (`ENOENT`), returns an empty array — the file-based loaders\n * (skills, plugins, agents) treat a missing directory as \"no entries\"\n * rather than an error.\n *\n * Any other I/O failure is wrapped as `ConfigurationError` so callers can\n * surface a stable error code.\n *\n * @internal\n */\nexport async function readWorkspaceDir(\n root: string,\n errorCode: string,\n describe: string,\n): Promise<WorkspaceDirEntry[]> {\n try {\n return (await readdir(root, { withFileTypes: true })) as WorkspaceDirEntry[];\n } catch (cause) {\n const err = cause as NodeJS.ErrnoException;\n if (err.code === \"ENOENT\") return [];\n throw new ConfigurationError(`Failed to read ${describe}: ${root}`, {\n code: errorCode,\n cause,\n });\n }\n}\n","/**\n * Tiny YAML-frontmatter parser shared by the file-based loaders (skills,\n * subagents, hooks, context, plugins). Supports four scalar shapes:\n *\n * key: bar → \"bar\" (string)\n * key: 42 → 42 (number)\n * key: true → true (boolean)\n * key: [a, b, c] → [\"a\",\"b\",\"c\"](string[])\n * key: → undefined (caller's Zod default kicks in)\n *\n * Limitations (intentional — keep parser tiny, no dep):\n * - No nested objects (use flat keys like `providerId` not `provider.id`).\n * - No quoted strings — `match: \"1\"` becomes the literal 3-char string `\"1\"`.\n * - List values cannot contain a literal comma inside an element; the\n * `tags: [a,b, c]` splitter is greedy on `,`. Use multi-line lists or\n * reword if you need this.\n *\n * @internal\n */\n\nexport type FrontmatterValue = string | number | boolean | string[];\n\nexport function parseSimpleYaml(text: string): Record<string, FrontmatterValue | undefined> {\n const fields: Record<string, FrontmatterValue | undefined> = {};\n for (const line of text.split(/\\r?\\n/)) {\n const colonIndex = line.indexOf(\":\");\n if (colonIndex === -1) continue;\n const key = line.slice(0, colonIndex).trim();\n if (key.length === 0) continue;\n const raw = line.slice(colonIndex + 1).trim();\n fields[key] = coerce(raw);\n }\n return fields;\n}\n\nfunction coerce(raw: string): FrontmatterValue | undefined {\n // EC-3: empty value → undefined so Zod `.optional().default(...)` applies.\n if (raw.length === 0) return undefined;\n if (raw.startsWith(\"[\") && raw.endsWith(\"]\")) {\n return raw\n .slice(1, -1)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n if (raw === \"true\" || raw === \"false\") return raw === \"true\";\n const n = Number(raw);\n if (Number.isFinite(n) && raw === String(n)) return n;\n return raw;\n}\n","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 +0,0 @@
1
- {"version":3,"sources":["../src/internal/persistence/jsonl.ts"],"names":[],"mappings":";;;;AAoBO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACzC,WAAA,CACE,SACS,IAAA,EACT;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFJ,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGT,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AAAA,EACd;AAAA,EAJW,IAAA;AAKb;AAEA,SAAS,cAAc,KAAA,EAAkD;AACvE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAA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AuB,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,GAAA;AACT;AAUO,SAAS,WAAA,CAAY,MAAc,MAAA,EAAuB;AAC/D,EAAA,SAAA,CAAU,QAAQ,IAAI,CAAA,EAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC5C,EAAA,cAAA,CAAe,IAAA,EAAM,CAAA,EAAG,IAAA,CAAK,SAAA,CAAU,MAAM,CAAC;AAAA,CAAI,CAAA;AACpD;AAYO,SAAS,YAAA,CACd,MACA,KAAA,EACa;AACb,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI;AACF,IAAA,IAAA,GAAO,YAAA,CAAa,MAAM,MAAM,CAAA;AAAA,EAClC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,KAAA,MAAW,OAAA,IAAW,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA,EAAG;AAEtC,IAAA,MAAM,MAAA,GAAS,kBAAA,CAAmB,OAAA,CAAQ,IAAA,EAAM,CAAA;AAChD,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,IAAA,IAAI,OAAO,QAAQ,QAAA,IAAY,GAAA,CAAI,SAAS,CAAA,EAAG,IAAA,CAAK,IAAI,GAAG,CAAA;AAAA,EAC7D;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-DUK5WMKJ.js","sourcesContent":["/**\n * Durable JSONL primitives shared by the eval harness (M6).\n *\n * - `loadJsonl` — generic dataset reader (split/trim/skip-blank/parse) with a\n * line-numbered {@link JsonlParseError}. The dataset SCHEMA is the caller's\n * concern via `map` (M6 ADR D3) — this module owns only the parse.\n * - `appendJsonl` / `readJsonlIds` — crash-durable, resumable batch persistence\n * (M6 ADR D1): each record is appended as one whole `\\n`-terminated line the\n * instant it is produced, and a re-run resumes by skipping already-keyed rows.\n *\n * referencia: knowledge-base/references/theocode-eval/lib/swebench-dataset.ts:82\n * (parseJsonl + line-N error) and swebench-batch.ts:113,205 (resume + per-line\n * flush).\n *\n * @internal\n */\nimport { appendFileSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\n/** Raised when a JSONL line is not valid JSON or is not a JSON object. Carries the 1-based line number. */\nexport class JsonlParseError extends Error {\n constructor(\n message: string,\n readonly line: number,\n ) {\n super(message);\n this.name = \"JsonlParseError\";\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Parse a single trimmed line to a plain object, or `undefined` if blank / invalid / non-object. */\nfunction tryParseObjectLine(line: string): Record<string, unknown> | undefined {\n if (line.length === 0) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n return isPlainObject(parsed) ? parsed : undefined;\n}\n\n/**\n * Parse a JSONL file into rows. Blank lines are skipped. A malformed or\n * non-object line throws {@link JsonlParseError} naming the 1-based line. When\n * `map` is provided, each raw object is mapped to the typed row (the SWE-bench\n * schema lives in the caller's `map`, per M6 ADR D3).\n */\nexport function loadJsonl<T = Record<string, unknown>>(\n path: string,\n opts: { map?: (raw: Record<string, unknown>, lineNumber: number) => T } = {},\n): T[] {\n const text = readFileSync(path, \"utf8\");\n const out: T[] = [];\n let lineNumber = 0;\n for (const rawLine of text.split(\"\\n\")) {\n lineNumber += 1;\n const line = rawLine.trim();\n if (line.length === 0) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n throw new JsonlParseError(`line ${lineNumber}: invalid JSON`, lineNumber);\n }\n if (!isPlainObject(parsed)) {\n throw new JsonlParseError(`line ${lineNumber}: not a JSON object`, lineNumber);\n }\n out.push(opts.map ? opts.map(parsed, lineNumber) : (parsed as unknown as T));\n }\n return out;\n}\n\n/**\n * Append one record as a whole `\\n`-terminated JSON line. Creates the parent dir\n * if missing. `appendFileSync` is synchronous, so within a single Node process\n * the event loop serializes writes and each call writes its line atomically —\n * interleave-safe for the bounded-concurrency batch runner.\n *\n * referencia: swebench-batch.ts:192 (mkdir-before-append), :205 (per-line flush).\n */\nexport function appendJsonl(path: string, record: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n appendFileSync(path, `${JSON.stringify(record)}\\n`);\n}\n\n/**\n * Read the set of keys from an existing JSONL file for which `keyFn(parsed)`\n * returns a non-empty string. Used to resume a crashed batch by skipping rows\n * already persisted with a successful result. A trailing partial line from an\n * interrupted append is tolerated (skipped, not thrown), and a missing file\n * yields an empty set.\n *\n * referencia: swebench-batch.ts:113 (readDoneIds), :129 (success-only),\n * :131 (tolerate partial line).\n */\nexport function readJsonlIds(\n path: string,\n keyFn: (parsed: Record<string, unknown>) => string | undefined,\n): Set<string> {\n const done = new Set<string>();\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return done; // no file yet → nothing done\n }\n for (const rawLine of text.split(\"\\n\")) {\n // A trailing partial line from an interrupted run parses to undefined → skipped.\n const parsed = tryParseObjectLine(rawLine.trim());\n if (parsed === undefined) continue;\n const key = keyFn(parsed);\n if (typeof key === \"string\" && key.length > 0) done.add(key);\n }\n return done;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/runtime/config/workspace-dir.ts","../src/internal/runtime/context/yaml-frontmatter.ts","../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":["readdir","ConfigurationError","safePathJoin","assertNoSymlinkEscape","join","readFile"],"mappings":";;;;;;;AAyBA,eAAsB,gBAAA,CACpB,IAAA,EACA,SAAA,EACA,QAAA,EAC8B;AAC9B,EAAA,IAAI;AACF,IAAA,OAAQ,MAAMA,gBAAA,CAAQ,IAAA,EAAM,EAAE,aAAA,EAAe,MAAM,CAAA;AAAA,EACrD,SAAS,KAAA,EAAO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QAAA;AACrE,IAAA,IAAI,WAAA,CAAY,YAAA,KAAiB,KAAA,CAAA,EAAW,KAAA,CAAM,eAAe,WAAA,CAAY,YAAA;AAC7E,IAAA,OAAO,KAAA;AAAA,EACT,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,iBAAiBJ,oCAAA,EAAoB;AACvC,MAAA,OAAA,EAAS,cAAA,GAAiB;AAAA,QACxB,IAAA,EAAM,YAAA;AAAA,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-LSLPF6OI.cjs","sourcesContent":["import { readdir } from \"node:fs/promises\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\n\n/**\n * Entry returned by `readWorkspaceDir`. Mirrors the subset of\n * `fs.Dirent` the file-based loaders use.\n */\nexport interface WorkspaceDirEntry {\n name: string;\n isDirectory(): boolean;\n isFile(): boolean;\n}\n\n/**\n * Read a workspace subdirectory and return its entries. When the directory\n * does not exist (`ENOENT`), returns an empty array — the file-based loaders\n * (skills, plugins, agents) treat a missing directory as \"no entries\"\n * rather than an error.\n *\n * Any other I/O failure is wrapped as `ConfigurationError` so callers can\n * surface a stable error code.\n *\n * @internal\n */\nexport async function readWorkspaceDir(\n root: string,\n errorCode: string,\n describe: string,\n): Promise<WorkspaceDirEntry[]> {\n try {\n return (await readdir(root, { withFileTypes: true })) as WorkspaceDirEntry[];\n } catch (cause) {\n const err = cause as NodeJS.ErrnoException;\n if (err.code === \"ENOENT\") return [];\n throw new ConfigurationError(`Failed to read ${describe}: ${root}`, {\n code: errorCode,\n cause,\n });\n }\n}\n","/**\n * Tiny YAML-frontmatter parser shared by the file-based loaders (skills,\n * subagents, hooks, context, plugins). Supports four scalar shapes:\n *\n * key: bar → \"bar\" (string)\n * key: 42 → 42 (number)\n * key: true → true (boolean)\n * key: [a, b, c] → [\"a\",\"b\",\"c\"](string[])\n * key: → undefined (caller's Zod default kicks in)\n *\n * Limitations (intentional — keep parser tiny, no dep):\n * - No nested objects (use flat keys like `providerId` not `provider.id`).\n * - No quoted strings — `match: \"1\"` becomes the literal 3-char string `\"1\"`.\n * - List values cannot contain a literal comma inside an element; the\n * `tags: [a,b, c]` splitter is greedy on `,`. Use multi-line lists or\n * reword if you need this.\n *\n * @internal\n */\n\nexport type FrontmatterValue = string | number | boolean | string[];\n\nexport function parseSimpleYaml(text: string): Record<string, FrontmatterValue | undefined> {\n const fields: Record<string, FrontmatterValue | undefined> = {};\n for (const line of text.split(/\\r?\\n/)) {\n const colonIndex = line.indexOf(\":\");\n if (colonIndex === -1) continue;\n const key = line.slice(0, colonIndex).trim();\n if (key.length === 0) continue;\n const raw = line.slice(colonIndex + 1).trim();\n fields[key] = coerce(raw);\n }\n return fields;\n}\n\nfunction coerce(raw: string): FrontmatterValue | undefined {\n // EC-3: empty value → undefined so Zod `.optional().default(...)` applies.\n if (raw.length === 0) return undefined;\n if (raw.startsWith(\"[\") && raw.endsWith(\"]\")) {\n return raw\n .slice(1, -1)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n if (raw === \"true\" || raw === \"false\") return raw === \"true\";\n const n = Number(raw);\n if (Number.isFinite(n) && raw === String(n)) return n;\n return raw;\n}\n","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"]}