@theokit/sdk 5.4.0 → 5.6.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.
- package/CHANGELOG.md +642 -0
- package/dist/{agent-AUVD4TI4.cjs → agent-47NS6ZVL.cjs} +13 -13
- package/dist/{agent-AUVD4TI4.cjs.map → agent-47NS6ZVL.cjs.map} +1 -1
- package/dist/{agent-C1Efo7PI.d.cts → agent-82d_DrCL.d.cts} +33 -2
- package/dist/{agent-Bmy2G_ml.d.ts → agent-G6g-uwcB.d.ts} +33 -2
- package/dist/{agent-MNINE73R.js → agent-JJZM2VIK.js} +12 -12
- package/dist/{agent-MNINE73R.js.map → agent-JJZM2VIK.js.map} +1 -1
- package/dist/{chunk-IKBLU7ZS.js → chunk-2UXQASTX.js} +232 -32
- package/dist/chunk-2UXQASTX.js.map +1 -0
- package/dist/{chunk-VPK6PHIE.cjs → chunk-52FDUJSV.cjs} +8 -8
- package/dist/{chunk-VPK6PHIE.cjs.map → chunk-52FDUJSV.cjs.map} +1 -1
- package/dist/{chunk-2XRAWOZZ.js → chunk-5NELQ6LB.js} +65 -3
- package/dist/chunk-5NELQ6LB.js.map +1 -0
- package/dist/{chunk-3FDU5JFE.cjs → chunk-7IZKTQ5G.cjs} +35 -7
- package/dist/chunk-7IZKTQ5G.cjs.map +1 -0
- package/dist/{chunk-7SZAV6QG.js → chunk-7MMTZBTT.js} +3 -3
- package/dist/{chunk-7SZAV6QG.js.map → chunk-7MMTZBTT.js.map} +1 -1
- package/dist/{chunk-SADXXGWU.js → chunk-BZ3YMAMP.js} +3 -3
- package/dist/{chunk-NQTNSHSB.cjs.map → chunk-BZ3YMAMP.js.map} +1 -1
- package/dist/{chunk-LX7SEXOQ.js → chunk-CA5VUAP3.js} +25 -7
- package/dist/chunk-CA5VUAP3.js.map +1 -0
- package/dist/{chunk-IU5N5224.cjs → chunk-EIOMN5VA.cjs} +8 -8
- package/dist/chunk-EIOMN5VA.cjs.map +1 -0
- package/dist/{chunk-KWGSBZ2Q.js → chunk-FPIY5CLV.js} +3 -3
- package/dist/{chunk-KWGSBZ2Q.js.map → chunk-FPIY5CLV.js.map} +1 -1
- package/dist/{chunk-UALC6Q3J.cjs → chunk-GCHZMH42.cjs} +290 -88
- package/dist/chunk-GCHZMH42.cjs.map +1 -0
- package/dist/{chunk-NQTNSHSB.cjs → chunk-GFFBXSQT.cjs} +5 -5
- package/dist/chunk-GFFBXSQT.cjs.map +1 -0
- package/dist/{chunk-J6KZE2ZQ.cjs → chunk-HG4UN4MN.cjs} +4 -4
- package/dist/{chunk-J6KZE2ZQ.cjs.map → chunk-HG4UN4MN.cjs.map} +1 -1
- package/dist/{chunk-N6OOOYFZ.js → chunk-HUDNLFY4.js} +4 -4
- package/dist/chunk-HUDNLFY4.js.map +1 -0
- package/dist/{chunk-LOHMT36V.cjs → chunk-LD6HASA5.cjs} +65 -2
- package/dist/chunk-LD6HASA5.cjs.map +1 -0
- package/dist/{chunk-QATRS7JD.cjs → chunk-MYJGWS2J.cjs} +26 -8
- package/dist/chunk-MYJGWS2J.cjs.map +1 -0
- package/dist/{chunk-XD3FS5OI.js → chunk-N2KAIZ5D.js} +34 -7
- package/dist/chunk-N2KAIZ5D.js.map +1 -0
- package/dist/{chunk-HW7SEELD.cjs → chunk-QRVS2PRE.cjs} +31 -8
- package/dist/chunk-QRVS2PRE.cjs.map +1 -0
- package/dist/{chunk-AYA65JA5.cjs → chunk-RWPLWMCZ.cjs} +25 -9
- package/dist/chunk-RWPLWMCZ.cjs.map +1 -0
- package/dist/{chunk-WS5ULCL4.js → chunk-STGSMJMJ.js} +3 -3
- package/dist/{chunk-WS5ULCL4.js.map → chunk-STGSMJMJ.js.map} +1 -1
- package/dist/{chunk-O7L7M42F.js → chunk-T3ZDEYTJ.js} +21 -5
- package/dist/chunk-T3ZDEYTJ.js.map +1 -0
- package/dist/{chunk-43YXGD3P.cjs → chunk-TY56BKSK.cjs} +8 -4
- package/dist/chunk-TY56BKSK.cjs.map +1 -0
- package/dist/chunk-UOLBAPDM.js +66 -0
- package/dist/chunk-UOLBAPDM.js.map +1 -0
- package/dist/{chunk-Z2JFX372.cjs → chunk-VUHXC74Q.cjs} +15 -15
- package/dist/{chunk-Z2JFX372.cjs.map → chunk-VUHXC74Q.cjs.map} +1 -1
- package/dist/{chunk-NSLHPAC7.js → chunk-X7EUUHXU.js} +6 -5
- package/dist/chunk-X7EUUHXU.js.map +1 -0
- package/dist/context/index.cjs +7 -7
- package/dist/context/index.js +3 -3
- package/dist/{context-4AIK26QB.cjs → context-HR4KMXMA.cjs} +7 -7
- package/dist/{context-4AIK26QB.cjs.map → context-HR4KMXMA.cjs.map} +1 -1
- package/dist/context-J5BJ3LBS.js +6 -0
- package/dist/{context-EGM6CHXD.js.map → context-J5BJ3LBS.js.map} +1 -1
- package/dist/{cron-DSMdlhyF.d.cts → cron-DWv69ZSD.d.cts} +1 -1
- package/dist/{cron-Dcdrdv_T.d.ts → cron-GynWtAax.d.ts} +1 -1
- package/dist/cron.cjs +12 -12
- package/dist/cron.d.cts +2 -2
- package/dist/cron.d.ts +2 -2
- package/dist/cron.js +11 -11
- package/dist/eval.cjs +11 -11
- package/dist/eval.js +10 -10
- package/dist/{index-manager-W7FDMGEG.js → index-manager-27WLNQEE.js} +5 -5
- package/dist/{index-manager-W7FDMGEG.js.map → index-manager-27WLNQEE.js.map} +1 -1
- package/dist/{index-manager-3UNPYH34.cjs → index-manager-BBHDKMQS.cjs} +6 -6
- package/dist/{index-manager-3UNPYH34.cjs.map → index-manager-BBHDKMQS.cjs.map} +1 -1
- package/dist/index.cjs +274 -40
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +168 -5
- package/dist/index.d.ts +168 -5
- package/dist/index.js +246 -23
- package/dist/index.js.map +1 -1
- package/dist/internal/memory/storage/index.cjs +32 -32
- package/dist/internal/memory/storage/index.js +3 -3
- package/dist/internal/memory/storage/memory-root.d.cts +27 -0
- package/dist/internal/memory/storage/memory-root.d.ts +27 -0
- package/dist/internal/persistence/index.cjs +4 -4
- package/dist/internal/persistence/index.js +1 -1
- package/dist/internal/runtime/compat/foreign-config-sources.d.ts +17 -4
- package/dist/internal/runtime/compat/managed-settings.d.ts +80 -0
- package/dist/internal/runtime/context/context-discovery-runner.d.ts +14 -0
- package/dist/internal/runtime/context/context-discovery.d.ts +37 -0
- package/dist/internal/runtime/context/context-manager.d.ts +21 -1
- package/dist/internal/runtime/context/yaml-frontmatter.d.ts +6 -3
- package/dist/internal/runtime/hooks/hooks-executor.d.ts +23 -1
- package/dist/internal/runtime/hooks/hooks-source.d.ts +46 -1
- package/dist/internal/runtime/skills/discover-skills.d.ts +4 -0
- package/dist/project.cjs +3 -3
- package/dist/project.js +1 -1
- package/dist/skills.cjs +5 -5
- package/dist/skills.js +2 -2
- package/dist/subagents-loader-CJFYQQU2.js +7 -0
- package/dist/{subagents-loader-AIVDQ2D5.js.map → subagents-loader-CJFYQQU2.js.map} +1 -1
- package/dist/subagents-loader-MOO7DC4E.cjs +16 -0
- package/dist/{subagents-loader-DN4LETGL.cjs.map → subagents-loader-MOO7DC4E.cjs.map} +1 -1
- package/dist/subagents-loader.cjs +4 -4
- package/dist/subagents-loader.d.cts +1 -1
- package/dist/subagents-loader.d.ts +1 -1
- package/dist/subagents-loader.js +3 -3
- package/dist/types/agent.d.ts +6 -1
- package/dist/types/hooks.d.ts +22 -0
- package/docs/error-codes.md +20 -18
- package/docs/harness-capability-map.md +9 -1
- package/package.json +1 -1
- package/dist/chunk-2XRAWOZZ.js.map +0 -1
- package/dist/chunk-3FDU5JFE.cjs.map +0 -1
- package/dist/chunk-43YXGD3P.cjs.map +0 -1
- package/dist/chunk-AYA65JA5.cjs.map +0 -1
- package/dist/chunk-HW7SEELD.cjs.map +0 -1
- package/dist/chunk-IKBLU7ZS.js.map +0 -1
- package/dist/chunk-IU5N5224.cjs.map +0 -1
- package/dist/chunk-JNAA4G4H.js +0 -43
- package/dist/chunk-JNAA4G4H.js.map +0 -1
- package/dist/chunk-LOHMT36V.cjs.map +0 -1
- package/dist/chunk-LX7SEXOQ.js.map +0 -1
- package/dist/chunk-N6OOOYFZ.js.map +0 -1
- package/dist/chunk-NSLHPAC7.js.map +0 -1
- package/dist/chunk-O7L7M42F.js.map +0 -1
- package/dist/chunk-QATRS7JD.cjs.map +0 -1
- package/dist/chunk-SADXXGWU.js.map +0 -1
- package/dist/chunk-UALC6Q3J.cjs.map +0 -1
- package/dist/chunk-XD3FS5OI.js.map +0 -1
- package/dist/context-EGM6CHXD.js +0 -6
- package/dist/subagents-loader-AIVDQ2D5.js +0 -7
- package/dist/subagents-loader-DN4LETGL.cjs +0 -16
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/config/workspace-dir.ts","../src/internal/runtime/context/yaml-frontmatter.ts"],"names":["readdir","ConfigurationError"],"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;AACd,IAAA,MAAM,GAAA,GAAM,KAAA;AACZ,IAAA,IAAI,GAAA,CAAI,IAAA,KAAS,QAAA,EAAU,OAAO,EAAC;AACnC,IAAA,MAAM,IAAIC,oCAAA,CAAmB,CAAA,eAAA,EAAkB,QAAQ,CAAA,EAAA,EAAK,IAAI,CAAA,CAAA,EAAI;AAAA,MAClE,IAAA,EAAM,SAAA;AAAA,MACN;AAAA,KACD,CAAA;AAAA,EACH;AACF;;;ACfO,SAAS,gBAAgB,IAAA,EAA4D;AAC1F,EAAA,MAAM,SAAuD,EAAC;AAC9D,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,OAAO,CAAA;AAChC,EAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,MAA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,IAAK,CAAA,EAAG;AAC/B,IAAA,MAAM,IAAA,GAAA,CAAQ,KAAA,CAAM,CAAC,CAAA,IAAK,IAAI,IAAA,EAAK;AACnC,IAAA,IAAI,IAAA,KAAS,EAAA,IAAM,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG;AACzC,IAAA,IAAI,CAAC,IAAA,CAAK,UAAA,CAAW,IAAI,CAAA,EAAG;AAC5B,IAAA,KAAA,CAAM,KAAK,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,CAAE,MAAM,CAAA;AAAA,EACjC;AACA,EAAA,OAAO,EAAE,KAAA,EAAO,GAAA,EAAK,CAAA,EAAE;AACzB;AAEA,SAAS,OAAO,GAAA,EAA2C;AAEzD,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,CAAA,EAAG,OAAO,MAAA;AAC7B,EAAA,IAAI,IAAI,UAAA,CAAW,GAAG,KAAK,GAAA,CAAI,QAAA,CAAS,GAAG,CAAA,EAAG;AAC5C,IAAA,OAAO,GAAA,CACJ,MAAM,CAAA,EAAG,EAAE,EACX,KAAA,CAAM,GAAG,EACT,GAAA,CAAI,CAAC,MAAM,CAAA,CAAE,IAAA,EAAM,CAAA,CACnB,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,CAAC,CAAA;AAAA,EAC/B;AACA,EAAA,IAAI,GAAA,KAAQ,MAAA,IAAU,GAAA,KAAQ,OAAA,SAAgB,GAAA,KAAQ,MAAA;AACtD,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,IAAI,MAAA,CAAO,SAAS,CAAC,CAAA,IAAK,QAAQ,MAAA,CAAO,CAAC,GAAG,OAAO,CAAA;AACpD,EAAA,OAAO,GAAA;AACT","file":"chunk-QRVS2PRE.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 * - a → [\"a\",\"b\"] (block list, when `- ` items follow a bare key)\n * - b\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 * - Inline list values cannot contain a literal comma inside an element; the\n * `tags: [a,b, c]` splitter is greedy on `,`. Use the block form above or\n * reword if you need this — and note that the block form was, for a while,\n * what this line recommended and the parser could not read.\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 const lines = text.split(/\\r?\\n/);\n for (let i = 0; i < lines.length; i += 1) {\n const entry = splitEntry(lines[i] ?? \"\");\n if (entry === undefined) continue;\n const { key, raw } = entry;\n\n // `key:` with nothing after it may open a block list. Collect first, then decide: items found →\n // a list; none → `undefined`, which is the long-standing meaning of a bare key and what a\n // caller's Zod default relies on.\n const block = raw.length === 0 ? collectBlockList(lines, i + 1) : undefined;\n if (block !== undefined && block.items.length > 0) {\n fields[key] = block.items;\n // `end` is the first line that is NOT part of this list, and the loop's own `i += 1` steps\n // past it — so stop one short, or the key after a block list is swallowed.\n i = block.end - 1;\n continue;\n }\n\n fields[key] = coerce(raw);\n }\n return fields;\n}\n\n/**\n * Split one line into its key and its raw value, or report that it carries neither.\n *\n * A line with no `:` is not an entry (a `- item` continuation is the case that matters here), and\n * neither is one whose key is blank. Both were `continue`s inside the loop; they are the same\n * question — \"is this line an entry?\" — and asking it in one place is what keeps the loop under the\n * repository's cognitive-complexity limit.\n */\nfunction splitEntry(line: string): { key: string; raw: string } | undefined {\n const colonIndex = line.indexOf(\":\");\n if (colonIndex === -1) return undefined;\n const key = line.slice(0, colonIndex).trim();\n if (key.length === 0) return undefined;\n return { key, raw: line.slice(colonIndex + 1).trim() };\n}\n\n/**\n * Read the `- item` lines that follow a bare `key:`, and report where they stop.\n *\n * Line-oriented parsing skipped these outright — a `- item` has no colon — so the key coerced to\n * `undefined` and the values went nowhere. A reader saw the key on disk and found no behaviour,\n * with nothing to grep for. The docblock above made it sharper by advising \"use multi-line lists\"\n * for a limitation of the inline form; multi-line was the one shape this parser could not read.\n *\n * Extracted rather than inlined because inlining it put `parseSimpleYaml` at a cognitive complexity\n * of 24 against a limit of 10 — measured, not assumed: the pre-change function raised no such\n * diagnostic on the same file path.\n *\n * Blank and `#` lines do not end a list; anything else does. `end` is the index of that first\n * non-item line, so the caller resumes there rather than re-reading what it consumed.\n */\nfunction collectBlockList(lines: string[], start: number): { items: string[]; end: number } {\n const items: string[] = [];\n let j = start;\n for (; j < lines.length; j += 1) {\n const next = (lines[j] ?? \"\").trim();\n if (next === \"\" || next.startsWith(\"#\")) continue;\n if (!next.startsWith(\"- \")) break;\n items.push(next.slice(2).trim());\n }\n return { items, end: j };\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"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkTY56BKSK_cjs = require('./chunk-TY56BKSK.cjs');
|
|
4
|
+
var chunkQRVS2PRE_cjs = require('./chunk-QRVS2PRE.cjs');
|
|
5
5
|
var chunkJ7J7J2GN_cjs = require('./chunk-J7J7J2GN.cjs');
|
|
6
6
|
var chunk6LHQPOMI_cjs = require('./chunk-6LHQPOMI.cjs');
|
|
7
7
|
var promises = require('fs/promises');
|
|
@@ -9,7 +9,7 @@ var path = require('path');
|
|
|
9
9
|
|
|
10
10
|
async function pluginBundleDirs(cwd, compatSources = []) {
|
|
11
11
|
const dirs = [];
|
|
12
|
-
for (const root of
|
|
12
|
+
for (const root of chunkTY56BKSK_cjs.pluginBundleRoots(cwd, compatSources)) {
|
|
13
13
|
let entries;
|
|
14
14
|
try {
|
|
15
15
|
entries = await promises.readdir(root, { withFileTypes: true });
|
|
@@ -41,7 +41,7 @@ async function loadSubagents(cwd, settingSourcesIncludeProject, inline, compatSo
|
|
|
41
41
|
}
|
|
42
42
|
async function readProjectSubagents(cwd, compatSources) {
|
|
43
43
|
const subagents = {};
|
|
44
|
-
for (const configRoot of
|
|
44
|
+
for (const configRoot of chunkTY56BKSK_cjs.projectConfigRoots(cwd, compatSources, "subagents")) {
|
|
45
45
|
await readSubagentsFrom(path.join(configRoot, "agents"), subagents);
|
|
46
46
|
}
|
|
47
47
|
for (const bundle of await pluginBundleDirs(cwd, compatSources)) {
|
|
@@ -50,7 +50,7 @@ async function readProjectSubagents(cwd, compatSources) {
|
|
|
50
50
|
return subagents;
|
|
51
51
|
}
|
|
52
52
|
async function readSubagentsFrom(root, subagents) {
|
|
53
|
-
const entries = await
|
|
53
|
+
const entries = await chunkQRVS2PRE_cjs.readWorkspaceDir(root, "subagents_read_error", "subagents directory");
|
|
54
54
|
for (const entry of entries) {
|
|
55
55
|
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
|
|
56
56
|
const path$1 = path.join(root, entry.name);
|
|
@@ -96,12 +96,28 @@ function parseSubagentMarkdown(raw, filename) {
|
|
|
96
96
|
const name = asString(fields.name) ?? filename.replace(/\.md$/, "");
|
|
97
97
|
return { name, definition };
|
|
98
98
|
}
|
|
99
|
+
var KNOWN_CLAUDE_CODE_FIELDS = /* @__PURE__ */ new Set([
|
|
100
|
+
"disallowedTools",
|
|
101
|
+
"permissionMode",
|
|
102
|
+
"maxTurns",
|
|
103
|
+
"skills",
|
|
104
|
+
"memory",
|
|
105
|
+
"background",
|
|
106
|
+
"effort",
|
|
107
|
+
"isolation",
|
|
108
|
+
"initialPrompt",
|
|
109
|
+
"hooks",
|
|
110
|
+
"experimental",
|
|
111
|
+
"mcpServers"
|
|
112
|
+
]);
|
|
99
113
|
function rejectUnknownFields(fields, filename) {
|
|
100
114
|
for (const key of Object.keys(fields)) {
|
|
101
115
|
if (INERT_CLAUDE_CODE_FIELDS.has(key)) continue;
|
|
102
116
|
if (!ACCEPTED_FIELDS.has(key)) {
|
|
117
|
+
const siblings = [...KNOWN_CLAUDE_CODE_FIELDS].filter((f) => f !== key);
|
|
118
|
+
const origin = KNOWN_CLAUDE_CODE_FIELDS.has(key) ? ` \u2014 "${key}" is a Claude Code subagent field that this runtime does not support. The same applies to: ${siblings.join(", ")}. Removing them one at a time will meet each in turn; the tree is written for another runtime` : "";
|
|
103
119
|
throw new chunkJ7J7J2GN_cjs.ConfigurationError(
|
|
104
|
-
`Subagent ${filename}: unknown frontmatter field "${key}" (accepted: ${[...ACCEPTED_FIELDS].join(", ")})`,
|
|
120
|
+
`Subagent ${filename}: unknown frontmatter field "${key}" (accepted: ${[...ACCEPTED_FIELDS].join(", ")})${origin}`,
|
|
105
121
|
{ code: "subagent_unknown_field" }
|
|
106
122
|
);
|
|
107
123
|
}
|
|
@@ -163,10 +179,10 @@ function splitFrontmatter(raw, filename) {
|
|
|
163
179
|
return { frontmatter: match[1] ?? "", body: (match[2] ?? "").trim() };
|
|
164
180
|
}
|
|
165
181
|
function parseFrontmatterFields(frontmatter) {
|
|
166
|
-
return
|
|
182
|
+
return chunkQRVS2PRE_cjs.parseSimpleYaml(frontmatter);
|
|
167
183
|
}
|
|
168
184
|
|
|
169
185
|
exports.loadSubagents = loadSubagents;
|
|
170
186
|
exports.pluginBundleDirs = pluginBundleDirs;
|
|
171
|
-
//# sourceMappingURL=chunk-
|
|
172
|
-
//# sourceMappingURL=chunk-
|
|
187
|
+
//# sourceMappingURL=chunk-RWPLWMCZ.cjs.map
|
|
188
|
+
//# sourceMappingURL=chunk-RWPLWMCZ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/plugin-loader/plugin-bundles.ts","../src/internal/runtime/skills/subagents-loader.ts"],"names":["pluginBundleRoots","readdir","join","projectConfigRoots","readWorkspaceDir","path","readFile","diag","ConfigurationError","parseSimpleYaml"],"mappings":";;;;;;;;;AAyBA,eAAsB,gBAAA,CACpB,GAAA,EAEA,aAAA,GAAoD,EAAC,EAClC;AACnB,EAAA,MAAM,OAAiB,EAAC;AACxB,EAAA,KAAA,MAAW,IAAA,IAAQA,mCAAA,CAAkB,GAAA,EAAK,aAAa,CAAA,EAAG;AACxD,IAAA,IAAI,OAAA;AACJ,IAAA,IAAI;AACF,MAAA,OAAA,GAAU,MAAMC,gBAAA,CAAQ,IAAA,EAAM,EAAE,aAAA,EAAe,MAAM,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,MAAM,OAAA,CAAQ,CAAC,GAAG,OAAO,CAAA,CAAE,IAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,EAAM,CAAA,CAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,CAAC,CAAA;AAC9E,EAAA,IAAI,OAAO,MAAM,QAAA,EAAU;AACzB,IAAA,OAAO,EACJ,KAAA,CAAM,QAAQ,CAAA,CACd,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,EAAM,EACnB,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,CAAC,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,EAAC;AACV;AAGA,SAAS,eAAe,GAAA,EAAsB;AAC5C,EAAA,OAAO,WAAA,CAAY,KAAK,GAAG,CAAA;AAC7B;AAEA,SAAS,gBAAA,CAAiB,KAAa,QAAA,EAAyD;AAC9F,EAAA,MAAM,KAAA,GAAQ,yCAAA,CAA0C,IAAA,CAAK,GAAG,CAAA;AAChE,EAAA,IAAI,UAAU,IAAA,EAAM;AAClB,IAAA,MAAM,IAAIA,oCAAA,CAAmB,CAAA,SAAA,EAAY,QAAQ,CAAA,uBAAA,CAAA,EAA2B;AAAA,MAC1E,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,OAAO,EAAE,WAAA,EAAa,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA,EAAI,IAAA,EAAA,CAAO,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA,EAAI,IAAA,EAAK,EAAE;AACtE;AAEA,SAAS,uBAAuB,WAAA,EAAmE;AAIjG,EAAA,OAAOC,kCAAgB,WAAW,CAAA;AACpC","file":"chunk-RWPLWMCZ.cjs","sourcesContent":["/**\n * Locating the plugin bundles a project carries.\n *\n * Shared by the skills and subagents loaders, which both need the same answer to \"which folders in\n * this project are plugins\" and would otherwise each grow their own copy of the directory walk.\n *\n * @internal\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pluginBundleRoots } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\n\n/**\n * Every plugin folder under the project's plugin roots.\n *\n * Returns the FOLDERS, not their contents — what a bundle contributes (`skills/`, `agents/`) is the\n * caller's business, and a loader that also knew the layout would have to change whenever the other\n * one did.\n *\n * A missing root is not an error: most projects carry no plugins, and treating their absence as a\n * failure would make \"none installed\" indistinguishable from \"the directory could not be read\".\n */\nexport async function pluginBundleDirs(\n cwd: string,\n /** Declared foreign dialects (#524). Empty reads `.theokit/plugins` only. */\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<string[]> {\n const dirs: string[] = [];\n for (const root of pluginBundleRoots(cwd, compatSources)) {\n let entries: Dirent[];\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (entry.isDirectory()) dirs.push(join(root, entry.name));\n }\n }\n return dirs;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport type { AgentDefinition } from \"../../../types/agent.js\";\nimport type { ModelSelection } from \"../../../types/agent-prims.js\";\nimport { diag } from \"../../diagnostics.js\";\nimport { projectConfigRoots } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\nimport { pluginBundleDirs } from \"../plugin-loader/plugin-bundles.js\";\n\n/**\n * Load file-based subagents from `.theokit/agents/*.md` and merge with\n * inline definitions. Inline overrides file-based on name conflict.\n *\n * Each markdown file has YAML frontmatter (description + optional model)\n * and a body that becomes the subagent prompt.\n *\n * @internal\n */\nexport async function loadSubagents(\n cwd: string,\n settingSourcesIncludeProject: boolean,\n inline: Record<string, AgentDefinition> | undefined,\n /** Declared foreign dialects (#524). Empty reads `.theokit/` only. */\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<Record<string, AgentDefinition>> {\n const result: Record<string, AgentDefinition> = {};\n if (settingSourcesIncludeProject) {\n const projectAgents = await readProjectSubagents(cwd, compatSources);\n for (const [name, definition] of Object.entries(projectAgents)) {\n result[name] = definition;\n }\n }\n if (inline !== undefined) {\n for (const [name, definition] of Object.entries(inline)) {\n result[name] = definition;\n }\n }\n return result;\n}\n\n/**\n * Read agent declarations from every project config root (`.theokit`, then `.claude`).\n *\n * FIRST occurrence of a name wins, which is what makes `projectConfigRoots`' order a contract rather\n * than a detail: a project declaring the same agent in both means the explicit namespace.\n */\nasync function readProjectSubagents(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[],\n): Promise<Record<string, AgentDefinition>> {\n const subagents: Record<string, AgentDefinition> = {};\n for (const configRoot of projectConfigRoots(cwd, compatSources, \"subagents\")) {\n await readSubagentsFrom(join(configRoot, \"agents\"), subagents);\n }\n // A Claude Code plugin is a BUNDLE, and its `agents/` is what it exists to contribute. Read after\n // the project's own, so a project can shadow an agent a plugin ships without editing the plugin.\n for (const bundle of await pluginBundleDirs(cwd, compatSources)) {\n await readSubagentsFrom(join(bundle, \"agents\"), subagents);\n }\n return subagents;\n}\n\nasync function readSubagentsFrom(\n root: string,\n subagents: Record<string, AgentDefinition>,\n): Promise<void> {\n const entries = await readWorkspaceDir(root, \"subagents_read_error\", \"subagents directory\");\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const path = join(root, entry.name);\n const raw = await readFile(path, \"utf8\");\n // A markdown file with NO frontmatter is not an agent declaration — a directory of agents\n // written for the Claude Code CLI conventionally carries documentation beside them, and\n // `.claude/agents/README.md` exists in this repository. Throwing on it made ONE such file stop\n // every agent in the directory from loading.\n //\n // Skipped with a warn rather than in silence, and ONLY for the no-frontmatter case: a file that\n // HAS frontmatter and gets it wrong is a broken agent and still fails loudly, which is what\n // keeps a typo'd `sandbox` from returning as a silent gate through this door.\n if (!hasFrontmatter(raw)) {\n diag(`[theokit-sdk] ${entry.name} has no frontmatter — not an agent declaration, skipping`);\n continue;\n }\n const definition = parseSubagentMarkdown(raw, entry.name);\n if (subagents[definition.name] === undefined) {\n // `path` is computed above to read the file and was then dropped. Keeping it is the whole\n // visibility fix (#524): without it a listing cannot say which root an agent came from.\n subagents[definition.name] = { ...definition.definition, source: path };\n }\n }\n}\n\n// The frontmatter keys a disk subagent may declare. Any other key is a typed load\n// error rather than a silent drop — a dropped `sandbox` an operator wrote believing\n// it confines the child is exactly the silent-gate failure class this guards against.\nconst ACCEPTED_FIELDS = new Set([\n \"name\",\n \"description\",\n \"model\",\n \"tools\",\n \"reasoning_effort\",\n \"mcp\",\n \"sandbox\",\n]);\n\n// Fields the Claude Code CLI writes that carry NO behaviour for this runtime. Accepted and ignored,\n// so an agent authored for the CLI loads here unchanged — measured 2026-08-26 across the 59 agent\n// files on one machine, where `color` appeared in 38 of them and made every one of those a\n// `subagent_unknown_field` load error.\n//\n// Named explicitly instead of loosening the check above, because that check's reason is sound: a\n// dropped `sandbox` an operator wrote believing it confines the child is a silent gate. A field that\n// COULD change behaviour must still fail loudly. This set is the difference between \"we know this\n// one and it does nothing\" and \"we have never heard of this\" — two facts a bare allow-everything\n// would collapse into one.\n//\n// Anything added here needs the same justification: inert for THIS runtime, not merely unfamiliar.\nconst INERT_CLAUDE_CODE_FIELDS = new Set([\n /** The CLI's label colour for the agent. Presentation only. */\n \"color\",\n]);\n\nfunction parseSubagentMarkdown(\n raw: string,\n filename: string,\n): { name: string; definition: AgentDefinition } {\n const { frontmatter, body } = splitFrontmatter(raw, filename);\n const fields = parseFrontmatterFields(frontmatter);\n rejectUnknownFields(fields, filename);\n rejectMcp(fields, filename);\n\n const definition: AgentDefinition = {\n description: asString(fields.description) ?? \"\",\n prompt: body,\n };\n const model = resolveModel(fields, filename);\n if (model !== undefined) definition.model = model;\n const tools = toStringList(fields.tools);\n if (tools.length > 0) definition.tools = tools;\n const sandbox = resolveSandbox(fields, filename);\n if (sandbox !== undefined) definition.sandbox = sandbox;\n\n const name = asString(fields.name) ?? filename.replace(/\\.md$/, \"\");\n return { name, definition };\n}\n\n/**\n * Frontmatter keys that Claude Code documents for a subagent and this runtime does not accept.\n *\n * Not an allow-list — every one of these still fails the load. It exists so the FAILURE can say\n * which kind of unknown it met. A user migrating a `.claude/agents/` tree used to learn one key per\n * round trip: fix `memory`, meet `permissionMode`, fix that, meet `maxTurns` — with nothing saying\n * the set was finite or that the tree was simply written for another runtime.\n *\n * The distinction this file already draws for `INERT_CLAUDE_CODE_FIELDS` is the same one: \"the\n * difference between 'we know this one and it does nothing' and 'we have never heard of this' — two\n * facts a bare allow-everything would collapse into one.\" This is the third fact beside them —\n * \"another runtime's field\" — and it changes only the message, never the verdict.\n */\nconst KNOWN_CLAUDE_CODE_FIELDS = new Set([\n \"disallowedTools\",\n \"permissionMode\",\n \"maxTurns\",\n \"skills\",\n \"memory\",\n \"background\",\n \"effort\",\n \"isolation\",\n \"initialPrompt\",\n \"hooks\",\n \"experimental\",\n \"mcpServers\",\n]);\n\nfunction rejectUnknownFields(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): void {\n for (const key of Object.keys(fields)) {\n if (INERT_CLAUDE_CODE_FIELDS.has(key)) continue;\n if (!ACCEPTED_FIELDS.has(key)) {\n const siblings = [...KNOWN_CLAUDE_CODE_FIELDS].filter((f) => f !== key);\n const origin = KNOWN_CLAUDE_CODE_FIELDS.has(key)\n ? ` — \"${key}\" is a Claude Code subagent field that this runtime does not support. ` +\n `The same applies to: ${siblings.join(\", \")}. Removing them one at a time will meet each ` +\n `in turn; the tree is written for another runtime`\n : \"\";\n throw new ConfigurationError(\n `Subagent ${filename}: unknown frontmatter field \"${key}\" (accepted: ${[...ACCEPTED_FIELDS].join(\", \")})${origin}`,\n { code: \"subagent_unknown_field\" },\n );\n }\n }\n}\n\n// mcp: a known field, but not yet honored on the LOCAL delegation path. The frontmatter YAML can only\n// express server NAMES (parseSimpleYaml has no nested-object support), while a child's `Agent.create`\n// needs `mcpServers` as a Record<name, config>; resolving names→config per-subagent in local delegation\n// is its own follow-up. Rather than silently drop it (the M26/M32 silent-gate class), it is a typed load\n// error that names the field and points at the alternative.\nfunction rejectMcp(fields: Record<string, FrontmatterValue | undefined>, filename: string): void {\n if (fields.mcp !== undefined) {\n throw new ConfigurationError(\n `Subagent ${filename}: per-subagent \"mcp\" is not yet supported on the local delegation path; declare MCP servers in .theokit/mcp.json (or the parent) instead`,\n { code: \"subagent_mcp_unsupported_local\" },\n );\n }\n}\n\n// model + reasoning_effort — effort rides inside `model.params[thinking]`, so it requires a concrete\n// model id to attach to (a child inheriting the parent's model cannot carry the parent's provider-\n// specific effort param safely).\nfunction resolveModel(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): ModelSelection | \"inherit\" | undefined {\n const modelId = asString(fields.model);\n const effort = asString(fields.reasoning_effort);\n // reasoning_effort rides in model.params[thinking], so it needs a CONCRETE model id to attach to.\n // Neither an absent model NOR `model: inherit` can carry it (the inherited id is unknown at load), so\n // both are typed errors rather than a silently-dropped effort — the silent-gate class this guards.\n if (effort !== undefined && (modelId === undefined || modelId === \"inherit\")) {\n throw new ConfigurationError(\n `Subagent ${filename}: reasoning_effort requires a concrete model (effort is a model parameter; an absent model or \"inherit\" cannot carry it)`,\n { code: \"subagent_reasoning_effort_without_model\" },\n );\n }\n if (modelId === undefined) return undefined;\n if (modelId === \"inherit\") return \"inherit\";\n return effort !== undefined\n ? { id: modelId, params: [{ id: \"thinking\", value: effort }] }\n : { id: modelId };\n}\n\n// sandbox: boolean only. A granular mode string (read-only/…) is unsupported by the SDK runtime and is\n// a typed error rather than a silent coercion to a boolean.\nfunction resolveSandbox(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): boolean | undefined {\n if (fields.sandbox === undefined) return undefined;\n if (typeof fields.sandbox !== \"boolean\") {\n throw new ConfigurationError(\n `Subagent ${filename}: sandbox must be a boolean (got \"${String(fields.sandbox)}\"); granular sandbox modes are not supported by the runtime`,\n { code: \"subagent_sandbox_not_boolean\" },\n );\n }\n return fields.sandbox;\n}\n\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n if (typeof v !== \"string\") return undefined;\n // parseSimpleYaml does not strip quotes (documented), and `model`/`reasoning_effort` are fields users\n // habitually quote (`model: \"openai/gpt-4o\"`). Strip a single matching surrounding quote pair so a\n // quoted id/effort does not slip past validation and fail only at the provider.\n const m = /^([\"'])(.*)\\1$/.exec(v);\n return m ? m[2] : v;\n}\n\n/** Accept a YAML list (`string[]`) or a comma/space-separated scalar; trim + drop empties. */\nfunction toStringList(v: FrontmatterValue | undefined): string[] {\n if (Array.isArray(v)) return v.map((t) => t.trim()).filter((t) => t.length > 0);\n if (typeof v === \"string\") {\n return v\n .split(/[\\s,]+/)\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n }\n return [];\n}\n\n/** Does this file open with a frontmatter block at all? Its ABSENCE means \"not an agent\". */\nfunction hasFrontmatter(raw: string): boolean {\n return /^---\\s*\\n/.test(raw);\n}\n\nfunction splitFrontmatter(raw: string, filename: string): { frontmatter: string; body: string } {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Subagent ${filename} is missing frontmatter`, {\n code: \"subagent_missing_frontmatter\",\n });\n }\n return { frontmatter: match[1] ?? \"\", body: (match[2] ?? \"\").trim() };\n}\n\nfunction parseFrontmatterFields(frontmatter: string): Record<string, FrontmatterValue | undefined> {\n // Preserve the rich YAML value types (boolean/number/string[]): `sandbox: true` and\n // `mcp: [a, b]` are meaningful here, so narrowing everything to string (as the\n // pre-M33 loader did) would drop them. Per-field validation happens in parseSubagentMarkdown.\n return parseSimpleYaml(frontmatter);\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { defaultIndexPath, openMemoryDb, resolveMemoryRoot, lanceStoragePath, LanceIndex } from './chunk-
|
|
1
|
+
import { defaultIndexPath, openMemoryDb, resolveMemoryRoot, lanceStoragePath, LanceIndex } from './chunk-BZ3YMAMP.js';
|
|
2
2
|
import { replaceFileAtomic } from './chunk-3JHIFQ4I.js';
|
|
3
3
|
import { ConfigurationError } from './chunk-ALUN2B4W.js';
|
|
4
4
|
import { redactSecrets } from './chunk-CZJ6Q7CW.js';
|
|
@@ -200,5 +200,5 @@ async function migrateSqliteToLance(opts) {
|
|
|
200
200
|
}
|
|
201
201
|
|
|
202
202
|
export { appendDiaryEntry, diaryPath, entryHash, migrateSqliteToLance, readAllSqliteFacts, renderDiaryEntry };
|
|
203
|
-
//# sourceMappingURL=chunk-
|
|
204
|
-
//# sourceMappingURL=chunk-
|
|
203
|
+
//# sourceMappingURL=chunk-STGSMJMJ.js.map
|
|
204
|
+
//# sourceMappingURL=chunk-STGSMJMJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/memory/dreaming/diary.ts","../src/internal/memory/migrate-sqlite-to-lance.ts"],"names":["join"],"mappings":";;;;;;;;;AA6BO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAO,IAAA,CAAK,MAAM,gBAAgB,CAAA;AACpC;AAOO,SAAS,iBAAiB,KAAA,EAA2B;AAC1D,EAAA,MAAM,QAAQ,IAAI,IAAA,CAAK,KAAA,CAAM,WAAW,EAAE,WAAA,EAAY;AACtD,EAAA,MAAM,OAAO,SAAA,CAAU,KAAK,CAAA,CAAE,KAAA,CAAM,GAAG,CAAC,CAAA;AACxC,EAAA,OAAO;AAAA,IACL,MAAM,KAAK,CAAA,CAAA;AAAA,IACX,EAAA;AAAA,IACA,iBAAiB,IAAI,CAAA,CAAA;AAAA,IACrB,CAAA,gBAAA,EAAmB,MAAM,WAAW,CAAA,CAAA;AAAA,IACpC,CAAA,eAAA,EAAkB,MAAM,UAAU,CAAA,CAAA;AAAA,IAClC,CA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CAAA,CAAG,CAAA;AAC1C,EAAA,OAAO;AAAA,IACL,aAAa,WAAA,CAAY,MAAA;AAAA,IACzB,UAAA,EAAY,UAAA;AAAA,IACZ,SAAA,EAAW,IAAA;AAAA,IACX,iBAAA;AAAA,IACA,SAAA,EAAW,SAAA;AAAA,IACX,SAAA,EAAW;AAAA,GACb;AACF","file":"chunk-WS5ULCL4.js","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport type { MemoryRoot } from \"../storage/memory-root.js\";\n\n/**\n * Dream-diary append (ADR D7).\n *\n * Diary lives at `.theokit/memory/dream-diary.md` and grows with one entry\n * per sweep. Each entry is content-hashed so the same input produces the\n * same entry — idempotency contract.\n *\n * Writes go through `replaceFileAtomic` (EC-3 of edge-case review) so a\n * crash mid-write can never leave a half-written diary.\n *\n * Shared with `@theokit/sdk-memory`; see the memory-store barrel.\n */\n\nexport interface DiaryEntry {\n timestampMs: number;\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}\n\n/** `<memory root>/dream-diary.md`. Takes the RESOLVED ROOT — see `storage/memory-root.ts` (#463). */\nexport function diaryPath(root: MemoryRoot): string {\n return join(root, \"dream-diary.md\");\n}\n\n/**\n * One diary entry as the markdown that gets appended: a timestamp heading, the short entry hash,\n * and the counts the sweep produced. The hash is what makes a re-run recognisable as the same\n * sweep rather than a new one.\n */\nexport function renderDiaryEntry(entry: DiaryEntry): string {\n const stamp = new Date(entry.timestampMs).toISOString();\n const hash = entryHash(entry).slice(0, 8);\n return [\n `## ${stamp}`,\n \"\",\n `- entry-hash: ${hash}`,\n `- facts before: ${entry.factsBefore}`,\n `- facts after: ${entry.factsAfter}`,\n `- duplicates removed: ${entry.duplicatesRemoved}`,\n `- clusters created: ${entry.clustersCreated}`,\n `- notes written: ${entry.notesWritten}`,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Append one sweep's entry to `<memory root>/dream-diary.md`, creating the file with its header\n * when this is the first sweep. The diary is a human-readable record of what dreaming changed —\n * consolidations are otherwise invisible, because they alter the notes rather than announce\n * themselves.\n */\nexport async function appendDiaryEntry(root: MemoryRoot, entry: DiaryEntry): Promise<void> {\n const path = diaryPath(root);\n let raw = \"\";\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n raw = \"# Dream Diary\\n\\n\";\n }\n const next = `${raw.endsWith(\"\\n\") ? raw : `${raw}\\n`}${renderDiaryEntry(entry)}`;\n await replaceFileAtomic(path, next);\n}\n\n/**\n * A stable hash of one entry's counts, so two sweeps that did the same work read as the same work.\n * Rendered truncated in the entry; the full value is what callers compare.\n */\nexport function entryHash(entry: DiaryEntry): string {\n return createHash(\"sha256\")\n .update(\n [\n entry.factsBefore,\n entry.factsAfter,\n entry.duplicatesRemoved,\n entry.clustersCreated,\n entry.notesWritten,\n ].join(\"|\"),\n )\n .digest(\"hex\");\n}\n","import { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { defaultIndexPath, openMemoryDb } from \"./index-db.js\";\nimport { LanceIndex, lanceStoragePath } from \"./lance-index.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"./storage/memory-root.js\";\n\n/**\n * Migrate Memory.index from SQLite to LanceDB (ADR D44).\n *\n * EC-3 MUST FIX: validation uses NFC unicode normalization on both sides.\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel (#463).\n */\n\nexport interface MigrateOptions {\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to migrate, when the agent that wrote it\n * set `memory.directory`. Defaults to `<cwd>/.theokit/memory` (#463).\n */\n directory?: string;\n dryRun?: boolean;\n batchSize?: number;\n /** Inject for tests; defaults to console.log. */\n logger?: (msg: string) => void;\n}\n\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n /** Set when validation succeeded (or dryRun); false on validation failure. */\n validated: boolean;\n /** Per-fact compare results (size = sample count, up to 10). */\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n /** Lance storage location (final, after migration). */\n lancePath: string;\n /** Was the migration committed (false for dry-run). */\n committed: boolean;\n}\n\n/**\n * One row of the SQLite memory index, as the Lance migration reads it: the chunk plus the tenant\n * columns the target table needs. Shared with `@theokit/sdk-memory`, which migrates the same table.\n */\nexport interface SqliteFactRow {\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n namespace?: string | null;\n scope?: string | null;\n user_id?: string | null;\n}\n\n/**\n * Read all facts from the SQLite memory index. Returns empty array if the\n * SQLite db file does not exist (workspace never used Memory).\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel, so it carries no visibility\n * tag — naming that tag in this block would delete the function below it (#463).\n */\nexport async function readAllSqliteFacts(root: MemoryRoot): Promise<SqliteFactRow[]> {\n const dbPath = defaultIndexPath(root);\n if (!existsSync(dbPath)) return [];\n const db = await openMemoryDb({ filePath: dbPath });\n try {\n // SQLite schema: chunks table holds the facts. Schema may vary; we\n // probe column existence and fall back to safe defaults.\n const stmt = db.prepare(\"SELECT id, path, source, start_line, end_line, text FROM chunks\");\n const rows = stmt.all() as Array<{\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n }>;\n return rows.map((r) => ({\n ...r,\n namespace: \"default\",\n scope: \"agent\",\n user_id: \"default\",\n }));\n } finally {\n db.close();\n }\n}\n\n/**\n * Compare two strings via NFC normalization (EC-3 MUST FIX). Required\n * because SQLite/Lance native bindings can normalize unicode differently\n * (NFC vs NFD), producing false negatives on facts with accents/emojis.\n *\n * @internal\n */\nfunction nfcEqual(a: string, b: string): boolean {\n return a.normalize(\"NFC\") === b.normalize(\"NFC\");\n}\n\n/**\n * Refuse a `batchSize` the loop below cannot make progress with, before anything is migrated.\n *\n * The loop is `for (let i = 0; i < facts.length; i += batchSize)`, so the three ways this goes wrong\n * are all silent and all different:\n *\n * - 0 or negative: `i` never advances past the guard. The migration SPINS FOREVER, calling\n * `addFacts([])` and writing a \"Migrated x/y\" line every iteration — a hang with unbounded output,\n * which is the worst shape a failure can take because it looks like work.\n * - NaN (`Number(\"abc\")`): `i += NaN` makes the guard false on the first check, zero facts move, and\n * the caller is told \"Validation FAILED. SQLite preserved.\" A typo in an argument is reported as a\n * migration failure.\n * - a fraction: `slice` truncates and the loop still terminates, but the batch boundaries stop\n * matching the number the caller asked for.\n *\n * Validated HERE rather than only in the CLI that motivated the finding, because the CLI is a wrapper\n * over this function and a programmatic caller reaches it with no wrapper at all.\n *\n * @internal\n */\nfunction assertUsableBatchSize(batchSize: number | undefined): void {\n if (batchSize === undefined) return;\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new ConfigurationError(\n `migrateSqliteToLance: batchSize must be a whole number of at least 1; received ${String(batchSize)}.`,\n { code: \"invalid_batch_size\" },\n );\n }\n}\n\n/**\n * Run the migration. Writes Lance to `<cwd>/.theokit/memory/lance-new/`\n * first, validates round-trip, then renames to `lance/` on success.\n * SQLite db is preserved (CLI prompts user to delete).\n *\n * @internal\n */\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: migration is a single transaction (read → write → validate → commit-or-rollback); splitting harms atomicity reasoning.\nexport async function migrateSqliteToLance(opts: MigrateOptions): Promise<MigrateResult> {\n assertUsableBatchSize(opts.batchSize);\n const cwd = opts.cwd;\n // One resolution, reused by every path this migration touches (#463).\n const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });\n const finalPath = lanceStoragePath(memoryRoot);\n const newPath = join(memoryRoot, \"lance-new\");\n // T1.4 (ADR D68): wrap logger so any fact text containing secrets is\n // masked before reaching the destination (console or user-supplied sink).\n // Caller-supplied loggers cannot bypass — by design (D70).\n const rawLog = opts.logger ?? ((m: string) => console.log(m));\n const log = (m: string) => rawLog(redactSecrets(m));\n\n // EC: destination exists → typed error.\n if (existsSync(finalPath)) {\n throw new ConfigurationError(\n `Destination already exists: ${finalPath}. Remove it manually (\\`rm -rf ${finalPath}\\`) and re-run.`,\n { code: \"migration_destination_exists\" },\n );\n }\n if (existsSync(newPath)) {\n // Leftover from a previous failed/interrupted migration. Safe to delete.\n log(`Removing stale ${newPath} from a previous run...`);\n rmSync(newPath, { recursive: true, force: true });\n }\n\n log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);\n const sqliteFacts = await readAllSqliteFacts(memoryRoot);\n log(`SQLite has ${sqliteFacts.length} facts.`);\n if (sqliteFacts.length === 0) {\n return {\n countSqlite: 0,\n countLance: 0,\n validated: true,\n sampleComparisons: [],\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Reuse the embedding runtime configured in the workspace? For v1.2 we\n // require the caller to pass embedding explicitly via env. The migration\n // path is documented as: \"set OPENAI_API_KEY (or similar) before running.\"\n // Here we ship a placeholder embedder that uses a deterministic\n // content-hash — sufficient for migration validation; consumers should\n // re-embed on first real query after migration if needed.\n const placeholderEmbedding = {\n id: \"migration-placeholder\",\n model: \"deterministic-hash\",\n dimension: 8,\n embed: async (texts: ReadonlyArray<string>) => {\n // Simple deterministic hash → 8-dim vector (migration validation only).\n return texts.map((t) => {\n const arr = new Array(8).fill(0);\n for (let i = 0; i < t.length; i += 1) {\n arr[i % 8] += t.charCodeAt(i);\n }\n return arr.map((x) => x / 1000);\n });\n },\n stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 }),\n };\n\n mkdirSync(newPath, { recursive: true });\n log(`Writing Lance index to ${newPath} ...`);\n\n const lance = await LanceIndex.open({\n cwd,\n embedding: placeholderEmbedding,\n storagePath: newPath,\n });\n\n const batchSize = opts.batchSize ?? 100;\n for (let i = 0; i < sqliteFacts.length; i += batchSize) {\n const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({\n id: f.id,\n text: f.text,\n source: f.source,\n namespace: f.namespace ?? \"default\",\n scope: f.scope ?? \"agent\",\n user_id: f.user_id ?? \"default\",\n timestamp: 0,\n }));\n await lance.addFacts(batch);\n log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);\n }\n\n // Validation: count + sample compare (10 random) with NFC normalization.\n const lanceCount = await lance.countFacts(\"default\");\n log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);\n\n const sampleSize = Math.min(10, sqliteFacts.length);\n const sampleComparisons: { id: string; match: boolean }[] = [];\n for (let i = 0; i < sampleSize; i += 1) {\n const sqliteFact = sqliteFacts[Math.floor((i * sqliteFacts.length) / sampleSize)];\n if (sqliteFact === undefined) continue;\n // Search Lance for this fact's text — best-effort round-trip.\n const hits = await lance.search(sqliteFact.text, {\n namespace: sqliteFact.namespace ?? \"default\",\n limit: 1,\n });\n // EC-3: compare with NFC normalization.\n const hit = hits[0];\n const match = hit !== undefined && nfcEqual(hit.text, sqliteFact.text);\n sampleComparisons.push({ id: sqliteFact.id, match });\n }\n\n const allMatch = sampleComparisons.every((c) => c.match);\n const countMatch = lanceCount === sqliteFacts.length;\n const validated = allMatch && countMatch;\n\n await lance.close();\n\n if (opts.dryRun === true) {\n log(\"Dry-run mode — discarding Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n if (!validated) {\n log(\"Validation FAILED — leaving SQLite intact, removing Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: false,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Atomic commit via rename.\n renameSync(newPath, finalPath);\n log(`Migration committed to ${finalPath}.`);\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: true,\n sampleComparisons,\n lancePath: finalPath,\n committed: true,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/memory/dreaming/diary.ts","../src/internal/memory/migrate-sqlite-to-lance.ts"],"names":["join"],"mappings":";;;;;;;;;AA6BO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAO,IAAA,CAAK,MAAM,gBAAgB,CAAA;AACpC;AAOO,SAAS,iBAAiB,KAAA,EAA2B;AAC1D,EAAA,MAAM,QAAQ,IAAI,IAAA,CAAK,KAAA,CAAM,WAAW,EAAE,WAAA,EAAY;AACtD,EAAA,MAAM,OAAO,SAAA,CAAU,KAAK,CAAA,CAAE,KAAA,CAAM,GAAG,CAAC,CAAA;AACxC,EAAA,OAAO;AAAA,IACL,MAAM,KAAK,CAAA,CAAA;AAAA,IACX,EAAA;AAAA,IACA,iBAAiB,IAAI,CAAA,CAAA;AAAA,IACrB,CAAA,gBAAA,EAAmB,MAAM,WAAW,CAAA,CAAA;AAAA,IACpC,CAAA,eAAA,EAAkB,MAAM,UAAU,CAAA,CAAA;AAAA,IAClC,CAAA,sBAAA,EAAyB,MAAM,iBAAiB,CAAA,CAAA;AAAA,IAChD,CAAA,oBAAA,EAAuB,MAAM,eAAe,CAAA,CAAA;AAAA,IAC5C,CAAA,iBAAA,EAAoB,MAAM,YAAY,CAAA,CAAA;AAAA,IACtC;AAAA,GACF,CAAE,KAAK,IAAI,CAAA;AACb;AAQA,eAAsB,gBAAA,CAAiB,MAAkB,KAAA,EAAkC;AACzF,EAAA,MAAM,IAAA,GAAO,UAAU,IAAI,CAAA;AAC3B,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAM,QAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AAAA,EACnC,CAAA,CAAA,MAAQ;AACN,IAAA,GAAA,GAAM,mBAAA;AAAA,EACR;AACA,EAAA,MAAM,IAAA,GAAO,GAAG,GAAA,CAAI,QAAA,CAAS,IAAI,CAAA,GAAI,GAAA,G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IAAA,OAAO;AAAA,MACL,aAAa,WAAA,CAAY,MAAA;AAAA,MACzB,UAAA,EAAY,UAAA;AAAA,MACZ,SAAA;AAAA,MACA,iBAAA;AAAA,MACA,SAAA,EAAW,SAAA;AAAA,MACX,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AAEA,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,GAAA,CAAI,6EAAwE,CAAA;AAC5E,IAAA,MAAA,CAAO,SAAS,EAAE,SAAA,EAAW,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAChD,IAAA,OAAO;AAAA,MACL,aAAa,WAAA,CAAY,MAAA;AAAA,MACzB,UAAA,EAAY,UAAA;AAAA,MACZ,SAAA,EAAW,KAAA;AAAA,MACX,iBAAA;AAAA,MACA,SAAA,EAAW,SAAA;AAAA,MACX,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AAGA,EAAA,UAAA,CAAW,SAAS,SAAS,CAAA;AAC7B,EAAA,GAAA,CAAI,CAAA,uBAAA,EAA0B,SAAS,CAAA,CAAA,CAAG,CAAA;AAC1C,EAAA,OAAO;AAAA,IACL,aAAa,WAAA,CAAY,MAAA;AAAA,IACzB,UAAA,EAAY,UAAA;AAAA,IACZ,SAAA,EAAW,IAAA;AAAA,IACX,iBAAA;AAAA,IACA,SAAA,EAAW,SAAA;AAAA,IACX,SAAA,EAAW;AAAA,GACb;AACF","file":"chunk-STGSMJMJ.js","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport type { MemoryRoot } from \"../storage/memory-root.js\";\n\n/**\n * Dream-diary append (ADR D7).\n *\n * Diary lives at `.theokit/memory/dream-diary.md` and grows with one entry\n * per sweep. Each entry is content-hashed so the same input produces the\n * same entry — idempotency contract.\n *\n * Writes go through `replaceFileAtomic` (EC-3 of edge-case review) so a\n * crash mid-write can never leave a half-written diary.\n *\n * Shared with `@theokit/sdk-memory`; see the memory-store barrel.\n */\n\nexport interface DiaryEntry {\n timestampMs: number;\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}\n\n/** `<memory root>/dream-diary.md`. Takes the RESOLVED ROOT — see `storage/memory-root.ts` (#463). */\nexport function diaryPath(root: MemoryRoot): string {\n return join(root, \"dream-diary.md\");\n}\n\n/**\n * One diary entry as the markdown that gets appended: a timestamp heading, the short entry hash,\n * and the counts the sweep produced. The hash is what makes a re-run recognisable as the same\n * sweep rather than a new one.\n */\nexport function renderDiaryEntry(entry: DiaryEntry): string {\n const stamp = new Date(entry.timestampMs).toISOString();\n const hash = entryHash(entry).slice(0, 8);\n return [\n `## ${stamp}`,\n \"\",\n `- entry-hash: ${hash}`,\n `- facts before: ${entry.factsBefore}`,\n `- facts after: ${entry.factsAfter}`,\n `- duplicates removed: ${entry.duplicatesRemoved}`,\n `- clusters created: ${entry.clustersCreated}`,\n `- notes written: ${entry.notesWritten}`,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Append one sweep's entry to `<memory root>/dream-diary.md`, creating the file with its header\n * when this is the first sweep. The diary is a human-readable record of what dreaming changed —\n * consolidations are otherwise invisible, because they alter the notes rather than announce\n * themselves.\n */\nexport async function appendDiaryEntry(root: MemoryRoot, entry: DiaryEntry): Promise<void> {\n const path = diaryPath(root);\n let raw = \"\";\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n raw = \"# Dream Diary\\n\\n\";\n }\n const next = `${raw.endsWith(\"\\n\") ? raw : `${raw}\\n`}${renderDiaryEntry(entry)}`;\n await replaceFileAtomic(path, next);\n}\n\n/**\n * A stable hash of one entry's counts, so two sweeps that did the same work read as the same work.\n * Rendered truncated in the entry; the full value is what callers compare.\n */\nexport function entryHash(entry: DiaryEntry): string {\n return createHash(\"sha256\")\n .update(\n [\n entry.factsBefore,\n entry.factsAfter,\n entry.duplicatesRemoved,\n entry.clustersCreated,\n entry.notesWritten,\n ].join(\"|\"),\n )\n .digest(\"hex\");\n}\n","import { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { defaultIndexPath, openMemoryDb } from \"./index-db.js\";\nimport { LanceIndex, lanceStoragePath } from \"./lance-index.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"./storage/memory-root.js\";\n\n/**\n * Migrate Memory.index from SQLite to LanceDB (ADR D44).\n *\n * EC-3 MUST FIX: validation uses NFC unicode normalization on both sides.\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel (#463).\n */\n\nexport interface MigrateOptions {\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to migrate, when the agent that wrote it\n * set `memory.directory`. Defaults to `<cwd>/.theokit/memory` (#463).\n */\n directory?: string;\n dryRun?: boolean;\n batchSize?: number;\n /** Inject for tests; defaults to console.log. */\n logger?: (msg: string) => void;\n}\n\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n /** Set when validation succeeded (or dryRun); false on validation failure. */\n validated: boolean;\n /** Per-fact compare results (size = sample count, up to 10). */\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n /** Lance storage location (final, after migration). */\n lancePath: string;\n /** Was the migration committed (false for dry-run). */\n committed: boolean;\n}\n\n/**\n * One row of the SQLite memory index, as the Lance migration reads it: the chunk plus the tenant\n * columns the target table needs. Shared with `@theokit/sdk-memory`, which migrates the same table.\n */\nexport interface SqliteFactRow {\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n namespace?: string | null;\n scope?: string | null;\n user_id?: string | null;\n}\n\n/**\n * Read all facts from the SQLite memory index. Returns empty array if the\n * SQLite db file does not exist (workspace never used Memory).\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel, so it carries no visibility\n * tag — naming that tag in this block would delete the function below it (#463).\n */\nexport async function readAllSqliteFacts(root: MemoryRoot): Promise<SqliteFactRow[]> {\n const dbPath = defaultIndexPath(root);\n if (!existsSync(dbPath)) return [];\n const db = await openMemoryDb({ filePath: dbPath });\n try {\n // SQLite schema: chunks table holds the facts. Schema may vary; we\n // probe column existence and fall back to safe defaults.\n const stmt = db.prepare(\"SELECT id, path, source, start_line, end_line, text FROM chunks\");\n const rows = stmt.all() as Array<{\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n }>;\n return rows.map((r) => ({\n ...r,\n namespace: \"default\",\n scope: \"agent\",\n user_id: \"default\",\n }));\n } finally {\n db.close();\n }\n}\n\n/**\n * Compare two strings via NFC normalization (EC-3 MUST FIX). Required\n * because SQLite/Lance native bindings can normalize unicode differently\n * (NFC vs NFD), producing false negatives on facts with accents/emojis.\n *\n * @internal\n */\nfunction nfcEqual(a: string, b: string): boolean {\n return a.normalize(\"NFC\") === b.normalize(\"NFC\");\n}\n\n/**\n * Refuse a `batchSize` the loop below cannot make progress with, before anything is migrated.\n *\n * The loop is `for (let i = 0; i < facts.length; i += batchSize)`, so the three ways this goes wrong\n * are all silent and all different:\n *\n * - 0 or negative: `i` never advances past the guard. The migration SPINS FOREVER, calling\n * `addFacts([])` and writing a \"Migrated x/y\" line every iteration — a hang with unbounded output,\n * which is the worst shape a failure can take because it looks like work.\n * - NaN (`Number(\"abc\")`): `i += NaN` makes the guard false on the first check, zero facts move, and\n * the caller is told \"Validation FAILED. SQLite preserved.\" A typo in an argument is reported as a\n * migration failure.\n * - a fraction: `slice` truncates and the loop still terminates, but the batch boundaries stop\n * matching the number the caller asked for.\n *\n * Validated HERE rather than only in the CLI that motivated the finding, because the CLI is a wrapper\n * over this function and a programmatic caller reaches it with no wrapper at all.\n *\n * @internal\n */\nfunction assertUsableBatchSize(batchSize: number | undefined): void {\n if (batchSize === undefined) return;\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new ConfigurationError(\n `migrateSqliteToLance: batchSize must be a whole number of at least 1; received ${String(batchSize)}.`,\n { code: \"invalid_batch_size\" },\n );\n }\n}\n\n/**\n * Run the migration. Writes Lance to `<cwd>/.theokit/memory/lance-new/`\n * first, validates round-trip, then renames to `lance/` on success.\n * SQLite db is preserved (CLI prompts user to delete).\n *\n * @internal\n */\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: migration is a single transaction (read → write → validate → commit-or-rollback); splitting harms atomicity reasoning.\nexport async function migrateSqliteToLance(opts: MigrateOptions): Promise<MigrateResult> {\n assertUsableBatchSize(opts.batchSize);\n const cwd = opts.cwd;\n // One resolution, reused by every path this migration touches (#463).\n const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });\n const finalPath = lanceStoragePath(memoryRoot);\n const newPath = join(memoryRoot, \"lance-new\");\n // T1.4 (ADR D68): wrap logger so any fact text containing secrets is\n // masked before reaching the destination (console or user-supplied sink).\n // Caller-supplied loggers cannot bypass — by design (D70).\n const rawLog = opts.logger ?? ((m: string) => console.log(m));\n const log = (m: string) => rawLog(redactSecrets(m));\n\n // EC: destination exists → typed error.\n if (existsSync(finalPath)) {\n throw new ConfigurationError(\n `Destination already exists: ${finalPath}. Remove it manually (\\`rm -rf ${finalPath}\\`) and re-run.`,\n { code: \"migration_destination_exists\" },\n );\n }\n if (existsSync(newPath)) {\n // Leftover from a previous failed/interrupted migration. Safe to delete.\n log(`Removing stale ${newPath} from a previous run...`);\n rmSync(newPath, { recursive: true, force: true });\n }\n\n log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);\n const sqliteFacts = await readAllSqliteFacts(memoryRoot);\n log(`SQLite has ${sqliteFacts.length} facts.`);\n if (sqliteFacts.length === 0) {\n return {\n countSqlite: 0,\n countLance: 0,\n validated: true,\n sampleComparisons: [],\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Reuse the embedding runtime configured in the workspace? For v1.2 we\n // require the caller to pass embedding explicitly via env. The migration\n // path is documented as: \"set OPENAI_API_KEY (or similar) before running.\"\n // Here we ship a placeholder embedder that uses a deterministic\n // content-hash — sufficient for migration validation; consumers should\n // re-embed on first real query after migration if needed.\n const placeholderEmbedding = {\n id: \"migration-placeholder\",\n model: \"deterministic-hash\",\n dimension: 8,\n embed: async (texts: ReadonlyArray<string>) => {\n // Simple deterministic hash → 8-dim vector (migration validation only).\n return texts.map((t) => {\n const arr = new Array(8).fill(0);\n for (let i = 0; i < t.length; i += 1) {\n arr[i % 8] += t.charCodeAt(i);\n }\n return arr.map((x) => x / 1000);\n });\n },\n stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 }),\n };\n\n mkdirSync(newPath, { recursive: true });\n log(`Writing Lance index to ${newPath} ...`);\n\n const lance = await LanceIndex.open({\n cwd,\n embedding: placeholderEmbedding,\n storagePath: newPath,\n });\n\n const batchSize = opts.batchSize ?? 100;\n for (let i = 0; i < sqliteFacts.length; i += batchSize) {\n const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({\n id: f.id,\n text: f.text,\n source: f.source,\n namespace: f.namespace ?? \"default\",\n scope: f.scope ?? \"agent\",\n user_id: f.user_id ?? \"default\",\n timestamp: 0,\n }));\n await lance.addFacts(batch);\n log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);\n }\n\n // Validation: count + sample compare (10 random) with NFC normalization.\n const lanceCount = await lance.countFacts(\"default\");\n log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);\n\n const sampleSize = Math.min(10, sqliteFacts.length);\n const sampleComparisons: { id: string; match: boolean }[] = [];\n for (let i = 0; i < sampleSize; i += 1) {\n const sqliteFact = sqliteFacts[Math.floor((i * sqliteFacts.length) / sampleSize)];\n if (sqliteFact === undefined) continue;\n // Search Lance for this fact's text — best-effort round-trip.\n const hits = await lance.search(sqliteFact.text, {\n namespace: sqliteFact.namespace ?? \"default\",\n limit: 1,\n });\n // EC-3: compare with NFC normalization.\n const hit = hits[0];\n const match = hit !== undefined && nfcEqual(hit.text, sqliteFact.text);\n sampleComparisons.push({ id: sqliteFact.id, match });\n }\n\n const allMatch = sampleComparisons.every((c) => c.match);\n const countMatch = lanceCount === sqliteFacts.length;\n const validated = allMatch && countMatch;\n\n await lance.close();\n\n if (opts.dryRun === true) {\n log(\"Dry-run mode — discarding Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n if (!validated) {\n log(\"Validation FAILED — leaving SQLite intact, removing Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: false,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Atomic commit via rename.\n renameSync(newPath, finalPath);\n log(`Migration committed to ${finalPath}.`);\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: true,\n sampleComparisons,\n lancePath: finalPath,\n committed: true,\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { pluginBundleRoots, projectConfigRoots } from './chunk-
|
|
2
|
-
import { readWorkspaceDir, parseSimpleYaml } from './chunk-
|
|
1
|
+
import { pluginBundleRoots, projectConfigRoots } from './chunk-X7EUUHXU.js';
|
|
2
|
+
import { readWorkspaceDir, parseSimpleYaml } from './chunk-UOLBAPDM.js';
|
|
3
3
|
import { ConfigurationError } from './chunk-ALUN2B4W.js';
|
|
4
4
|
import { diag } from './chunk-CZJ6Q7CW.js';
|
|
5
5
|
import { readdir, readFile } from 'fs/promises';
|
|
@@ -94,12 +94,28 @@ function parseSubagentMarkdown(raw, filename) {
|
|
|
94
94
|
const name = asString(fields.name) ?? filename.replace(/\.md$/, "");
|
|
95
95
|
return { name, definition };
|
|
96
96
|
}
|
|
97
|
+
var KNOWN_CLAUDE_CODE_FIELDS = /* @__PURE__ */ new Set([
|
|
98
|
+
"disallowedTools",
|
|
99
|
+
"permissionMode",
|
|
100
|
+
"maxTurns",
|
|
101
|
+
"skills",
|
|
102
|
+
"memory",
|
|
103
|
+
"background",
|
|
104
|
+
"effort",
|
|
105
|
+
"isolation",
|
|
106
|
+
"initialPrompt",
|
|
107
|
+
"hooks",
|
|
108
|
+
"experimental",
|
|
109
|
+
"mcpServers"
|
|
110
|
+
]);
|
|
97
111
|
function rejectUnknownFields(fields, filename) {
|
|
98
112
|
for (const key of Object.keys(fields)) {
|
|
99
113
|
if (INERT_CLAUDE_CODE_FIELDS.has(key)) continue;
|
|
100
114
|
if (!ACCEPTED_FIELDS.has(key)) {
|
|
115
|
+
const siblings = [...KNOWN_CLAUDE_CODE_FIELDS].filter((f) => f !== key);
|
|
116
|
+
const origin = KNOWN_CLAUDE_CODE_FIELDS.has(key) ? ` \u2014 "${key}" is a Claude Code subagent field that this runtime does not support. The same applies to: ${siblings.join(", ")}. Removing them one at a time will meet each in turn; the tree is written for another runtime` : "";
|
|
101
117
|
throw new ConfigurationError(
|
|
102
|
-
`Subagent ${filename}: unknown frontmatter field "${key}" (accepted: ${[...ACCEPTED_FIELDS].join(", ")})`,
|
|
118
|
+
`Subagent ${filename}: unknown frontmatter field "${key}" (accepted: ${[...ACCEPTED_FIELDS].join(", ")})${origin}`,
|
|
103
119
|
{ code: "subagent_unknown_field" }
|
|
104
120
|
);
|
|
105
121
|
}
|
|
@@ -165,5 +181,5 @@ function parseFrontmatterFields(frontmatter) {
|
|
|
165
181
|
}
|
|
166
182
|
|
|
167
183
|
export { loadSubagents, pluginBundleDirs };
|
|
168
|
-
//# sourceMappingURL=chunk-
|
|
169
|
-
//# sourceMappingURL=chunk-
|
|
184
|
+
//# sourceMappingURL=chunk-T3ZDEYTJ.js.map
|
|
185
|
+
//# sourceMappingURL=chunk-T3ZDEYTJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/plugin-loader/plugin-bundles.ts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A,EAAA,CAAO,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA,EAAI,IAAA,EAAK,EAAE;AACtE;AAEA,SAAS,uBAAuB,WAAA,EAAmE;AAIjG,EAAA,OAAO,gBAAgB,WAAW,CAAA;AACpC","file":"chunk-T3ZDEYTJ.js","sourcesContent":["/**\n * Locating the plugin bundles a project carries.\n *\n * Shared by the skills and subagents loaders, which both need the same answer to \"which folders in\n * this project are plugins\" and would otherwise each grow their own copy of the directory walk.\n *\n * @internal\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pluginBundleRoots } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\n\n/**\n * Every plugin folder under the project's plugin roots.\n *\n * Returns the FOLDERS, not their contents — what a bundle contributes (`skills/`, `agents/`) is the\n * caller's business, and a loader that also knew the layout would have to change whenever the other\n * one did.\n *\n * A missing root is not an error: most projects carry no plugins, and treating their absence as a\n * failure would make \"none installed\" indistinguishable from \"the directory could not be read\".\n */\nexport async function pluginBundleDirs(\n cwd: string,\n /** Declared foreign dialects (#524). Empty reads `.theokit/plugins` only. */\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<string[]> {\n const dirs: string[] = [];\n for (const root of pluginBundleRoots(cwd, compatSources)) {\n let entries: Dirent[];\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (entry.isDirectory()) dirs.push(join(root, entry.name));\n }\n }\n return dirs;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport type { AgentDefinition } from \"../../../types/agent.js\";\nimport type { ModelSelection } from \"../../../types/agent-prims.js\";\nimport { diag } from \"../../diagnostics.js\";\nimport { projectConfigRoots } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\nimport { pluginBundleDirs } from \"../plugin-loader/plugin-bundles.js\";\n\n/**\n * Load file-based subagents from `.theokit/agents/*.md` and merge with\n * inline definitions. Inline overrides file-based on name conflict.\n *\n * Each markdown file has YAML frontmatter (description + optional model)\n * and a body that becomes the subagent prompt.\n *\n * @internal\n */\nexport async function loadSubagents(\n cwd: string,\n settingSourcesIncludeProject: boolean,\n inline: Record<string, AgentDefinition> | undefined,\n /** Declared foreign dialects (#524). Empty reads `.theokit/` only. */\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<Record<string, AgentDefinition>> {\n const result: Record<string, AgentDefinition> = {};\n if (settingSourcesIncludeProject) {\n const projectAgents = await readProjectSubagents(cwd, compatSources);\n for (const [name, definition] of Object.entries(projectAgents)) {\n result[name] = definition;\n }\n }\n if (inline !== undefined) {\n for (const [name, definition] of Object.entries(inline)) {\n result[name] = definition;\n }\n }\n return result;\n}\n\n/**\n * Read agent declarations from every project config root (`.theokit`, then `.claude`).\n *\n * FIRST occurrence of a name wins, which is what makes `projectConfigRoots`' order a contract rather\n * than a detail: a project declaring the same agent in both means the explicit namespace.\n */\nasync function readProjectSubagents(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[],\n): Promise<Record<string, AgentDefinition>> {\n const subagents: Record<string, AgentDefinition> = {};\n for (const configRoot of projectConfigRoots(cwd, compatSources, \"subagents\")) {\n await readSubagentsFrom(join(configRoot, \"agents\"), subagents);\n }\n // A Claude Code plugin is a BUNDLE, and its `agents/` is what it exists to contribute. Read after\n // the project's own, so a project can shadow an agent a plugin ships without editing the plugin.\n for (const bundle of await pluginBundleDirs(cwd, compatSources)) {\n await readSubagentsFrom(join(bundle, \"agents\"), subagents);\n }\n return subagents;\n}\n\nasync function readSubagentsFrom(\n root: string,\n subagents: Record<string, AgentDefinition>,\n): Promise<void> {\n const entries = await readWorkspaceDir(root, \"subagents_read_error\", \"subagents directory\");\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const path = join(root, entry.name);\n const raw = await readFile(path, \"utf8\");\n // A markdown file with NO frontmatter is not an agent declaration — a directory of agents\n // written for the Claude Code CLI conventionally carries documentation beside them, and\n // `.claude/agents/README.md` exists in this repository. Throwing on it made ONE such file stop\n // every agent in the directory from loading.\n //\n // Skipped with a warn rather than in silence, and ONLY for the no-frontmatter case: a file that\n // HAS frontmatter and gets it wrong is a broken agent and still fails loudly, which is what\n // keeps a typo'd `sandbox` from returning as a silent gate through this door.\n if (!hasFrontmatter(raw)) {\n diag(`[theokit-sdk] ${entry.name} has no frontmatter — not an agent declaration, skipping`);\n continue;\n }\n const definition = parseSubagentMarkdown(raw, entry.name);\n if (subagents[definition.name] === undefined) {\n // `path` is computed above to read the file and was then dropped. Keeping it is the whole\n // visibility fix (#524): without it a listing cannot say which root an agent came from.\n subagents[definition.name] = { ...definition.definition, source: path };\n }\n }\n}\n\n// The frontmatter keys a disk subagent may declare. Any other key is a typed load\n// error rather than a silent drop — a dropped `sandbox` an operator wrote believing\n// it confines the child is exactly the silent-gate failure class this guards against.\nconst ACCEPTED_FIELDS = new Set([\n \"name\",\n \"description\",\n \"model\",\n \"tools\",\n \"reasoning_effort\",\n \"mcp\",\n \"sandbox\",\n]);\n\n// Fields the Claude Code CLI writes that carry NO behaviour for this runtime. Accepted and ignored,\n// so an agent authored for the CLI loads here unchanged — measured 2026-08-26 across the 59 agent\n// files on one machine, where `color` appeared in 38 of them and made every one of those a\n// `subagent_unknown_field` load error.\n//\n// Named explicitly instead of loosening the check above, because that check's reason is sound: a\n// dropped `sandbox` an operator wrote believing it confines the child is a silent gate. A field that\n// COULD change behaviour must still fail loudly. This set is the difference between \"we know this\n// one and it does nothing\" and \"we have never heard of this\" — two facts a bare allow-everything\n// would collapse into one.\n//\n// Anything added here needs the same justification: inert for THIS runtime, not merely unfamiliar.\nconst INERT_CLAUDE_CODE_FIELDS = new Set([\n /** The CLI's label colour for the agent. Presentation only. */\n \"color\",\n]);\n\nfunction parseSubagentMarkdown(\n raw: string,\n filename: string,\n): { name: string; definition: AgentDefinition } {\n const { frontmatter, body } = splitFrontmatter(raw, filename);\n const fields = parseFrontmatterFields(frontmatter);\n rejectUnknownFields(fields, filename);\n rejectMcp(fields, filename);\n\n const definition: AgentDefinition = {\n description: asString(fields.description) ?? \"\",\n prompt: body,\n };\n const model = resolveModel(fields, filename);\n if (model !== undefined) definition.model = model;\n const tools = toStringList(fields.tools);\n if (tools.length > 0) definition.tools = tools;\n const sandbox = resolveSandbox(fields, filename);\n if (sandbox !== undefined) definition.sandbox = sandbox;\n\n const name = asString(fields.name) ?? filename.replace(/\\.md$/, \"\");\n return { name, definition };\n}\n\n/**\n * Frontmatter keys that Claude Code documents for a subagent and this runtime does not accept.\n *\n * Not an allow-list — every one of these still fails the load. It exists so the FAILURE can say\n * which kind of unknown it met. A user migrating a `.claude/agents/` tree used to learn one key per\n * round trip: fix `memory`, meet `permissionMode`, fix that, meet `maxTurns` — with nothing saying\n * the set was finite or that the tree was simply written for another runtime.\n *\n * The distinction this file already draws for `INERT_CLAUDE_CODE_FIELDS` is the same one: \"the\n * difference between 'we know this one and it does nothing' and 'we have never heard of this' — two\n * facts a bare allow-everything would collapse into one.\" This is the third fact beside them —\n * \"another runtime's field\" — and it changes only the message, never the verdict.\n */\nconst KNOWN_CLAUDE_CODE_FIELDS = new Set([\n \"disallowedTools\",\n \"permissionMode\",\n \"maxTurns\",\n \"skills\",\n \"memory\",\n \"background\",\n \"effort\",\n \"isolation\",\n \"initialPrompt\",\n \"hooks\",\n \"experimental\",\n \"mcpServers\",\n]);\n\nfunction rejectUnknownFields(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): void {\n for (const key of Object.keys(fields)) {\n if (INERT_CLAUDE_CODE_FIELDS.has(key)) continue;\n if (!ACCEPTED_FIELDS.has(key)) {\n const siblings = [...KNOWN_CLAUDE_CODE_FIELDS].filter((f) => f !== key);\n const origin = KNOWN_CLAUDE_CODE_FIELDS.has(key)\n ? ` — \"${key}\" is a Claude Code subagent field that this runtime does not support. ` +\n `The same applies to: ${siblings.join(\", \")}. Removing them one at a time will meet each ` +\n `in turn; the tree is written for another runtime`\n : \"\";\n throw new ConfigurationError(\n `Subagent ${filename}: unknown frontmatter field \"${key}\" (accepted: ${[...ACCEPTED_FIELDS].join(\", \")})${origin}`,\n { code: \"subagent_unknown_field\" },\n );\n }\n }\n}\n\n// mcp: a known field, but not yet honored on the LOCAL delegation path. The frontmatter YAML can only\n// express server NAMES (parseSimpleYaml has no nested-object support), while a child's `Agent.create`\n// needs `mcpServers` as a Record<name, config>; resolving names→config per-subagent in local delegation\n// is its own follow-up. Rather than silently drop it (the M26/M32 silent-gate class), it is a typed load\n// error that names the field and points at the alternative.\nfunction rejectMcp(fields: Record<string, FrontmatterValue | undefined>, filename: string): void {\n if (fields.mcp !== undefined) {\n throw new ConfigurationError(\n `Subagent ${filename}: per-subagent \"mcp\" is not yet supported on the local delegation path; declare MCP servers in .theokit/mcp.json (or the parent) instead`,\n { code: \"subagent_mcp_unsupported_local\" },\n );\n }\n}\n\n// model + reasoning_effort — effort rides inside `model.params[thinking]`, so it requires a concrete\n// model id to attach to (a child inheriting the parent's model cannot carry the parent's provider-\n// specific effort param safely).\nfunction resolveModel(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): ModelSelection | \"inherit\" | undefined {\n const modelId = asString(fields.model);\n const effort = asString(fields.reasoning_effort);\n // reasoning_effort rides in model.params[thinking], so it needs a CONCRETE model id to attach to.\n // Neither an absent model NOR `model: inherit` can carry it (the inherited id is unknown at load), so\n // both are typed errors rather than a silently-dropped effort — the silent-gate class this guards.\n if (effort !== undefined && (modelId === undefined || modelId === \"inherit\")) {\n throw new ConfigurationError(\n `Subagent ${filename}: reasoning_effort requires a concrete model (effort is a model parameter; an absent model or \"inherit\" cannot carry it)`,\n { code: \"subagent_reasoning_effort_without_model\" },\n );\n }\n if (modelId === undefined) return undefined;\n if (modelId === \"inherit\") return \"inherit\";\n return effort !== undefined\n ? { id: modelId, params: [{ id: \"thinking\", value: effort }] }\n : { id: modelId };\n}\n\n// sandbox: boolean only. A granular mode string (read-only/…) is unsupported by the SDK runtime and is\n// a typed error rather than a silent coercion to a boolean.\nfunction resolveSandbox(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): boolean | undefined {\n if (fields.sandbox === undefined) return undefined;\n if (typeof fields.sandbox !== \"boolean\") {\n throw new ConfigurationError(\n `Subagent ${filename}: sandbox must be a boolean (got \"${String(fields.sandbox)}\"); granular sandbox modes are not supported by the runtime`,\n { code: \"subagent_sandbox_not_boolean\" },\n );\n }\n return fields.sandbox;\n}\n\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n if (typeof v !== \"string\") return undefined;\n // parseSimpleYaml does not strip quotes (documented), and `model`/`reasoning_effort` are fields users\n // habitually quote (`model: \"openai/gpt-4o\"`). Strip a single matching surrounding quote pair so a\n // quoted id/effort does not slip past validation and fail only at the provider.\n const m = /^([\"'])(.*)\\1$/.exec(v);\n return m ? m[2] : v;\n}\n\n/** Accept a YAML list (`string[]`) or a comma/space-separated scalar; trim + drop empties. */\nfunction toStringList(v: FrontmatterValue | undefined): string[] {\n if (Array.isArray(v)) return v.map((t) => t.trim()).filter((t) => t.length > 0);\n if (typeof v === \"string\") {\n return v\n .split(/[\\s,]+/)\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n }\n return [];\n}\n\n/** Does this file open with a frontmatter block at all? Its ABSENCE means \"not an agent\". */\nfunction hasFrontmatter(raw: string): boolean {\n return /^---\\s*\\n/.test(raw);\n}\n\nfunction splitFrontmatter(raw: string, filename: string): { frontmatter: string; body: string } {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Subagent ${filename} is missing frontmatter`, {\n code: \"subagent_missing_frontmatter\",\n });\n }\n return { frontmatter: match[1] ?? \"\", body: (match[2] ?? \"\").trim() };\n}\n\nfunction parseFrontmatterFields(frontmatter: string): Record<string, FrontmatterValue | undefined> {\n // Preserve the rich YAML value types (boolean/number/string[]): `sandbox: true` and\n // `mcp: [a, b]` are meaningful here, so narrowing everything to string (as the\n // pre-M33 loader did) would drop them. Per-field validation happens in parseSubagentMarkdown.\n return parseSimpleYaml(frontmatter);\n}\n"]}
|
|
@@ -10,7 +10,7 @@ var CLAUDE_DIR_NAME = ".claude";
|
|
|
10
10
|
var NATIVE_SOURCE = {
|
|
11
11
|
kind: "theokit",
|
|
12
12
|
dirName: THEOKIT_DIR_LITERAL,
|
|
13
|
-
runtimeEnv: () => ({})
|
|
13
|
+
runtimeEnv: (cwd) => ({ THEOKIT_PROJECT_DIR: cwd })
|
|
14
14
|
};
|
|
15
15
|
var CLAUDE_CODE_SOURCE = {
|
|
16
16
|
kind: "claude-code",
|
|
@@ -31,6 +31,7 @@ function adaptersFor(kinds) {
|
|
|
31
31
|
return out;
|
|
32
32
|
}
|
|
33
33
|
var COMPAT_SURFACES = [
|
|
34
|
+
"context",
|
|
34
35
|
"hooks",
|
|
35
36
|
"plugins",
|
|
36
37
|
"skills",
|
|
@@ -83,7 +84,7 @@ function reportUndeclaredSources(cwd, declared) {
|
|
|
83
84
|
if (reported.has(dir)) continue;
|
|
84
85
|
reported.add(dir);
|
|
85
86
|
chunk6LHQPOMI_cjs.diagFailure(
|
|
86
|
-
`[theokit] ${adapter.dirName}/ is present but not declared, so its hooks, skills, subagents and
|
|
87
|
+
`[theokit] ${adapter.dirName}/ is present but not declared, so its hooks, skills, subagents, plugins and rules are ignored. To read it, add {"compat":{"adapters":["${adapter.kind}"]}} to .theokit/config.json \u2014 or, if you embed this SDK, pass local: { compatSources: ["${adapter.kind}"] } (usetheokit/theokit-sdk#524).
|
|
87
88
|
`
|
|
88
89
|
);
|
|
89
90
|
}
|
|
@@ -132,7 +133,10 @@ function displayTheokitHome(cwd) {
|
|
|
132
133
|
return resolved;
|
|
133
134
|
}
|
|
134
135
|
|
|
136
|
+
exports.CLAUDE_DIR_NAME = CLAUDE_DIR_NAME;
|
|
137
|
+
exports.THEOKIT_DIR_LITERAL = THEOKIT_DIR_LITERAL;
|
|
135
138
|
exports.adapterForConfigPath = adapterForConfigPath;
|
|
139
|
+
exports.adaptersForSurface = adaptersForSurface;
|
|
136
140
|
exports.displayTheokitHome = displayTheokitHome;
|
|
137
141
|
exports.getProfilesRoot = getProfilesRoot;
|
|
138
142
|
exports.getTheokitHome = getTheokitHome;
|
|
@@ -141,5 +145,5 @@ exports.projectConfigRoots = projectConfigRoots;
|
|
|
141
145
|
exports.reportUndeclaredSources = reportUndeclaredSources;
|
|
142
146
|
exports.theokitConfigRoot = theokitConfigRoot;
|
|
143
147
|
exports.undefinedVariablesIn = undefinedVariablesIn;
|
|
144
|
-
//# sourceMappingURL=chunk-
|
|
145
|
-
//# sourceMappingURL=chunk-
|
|
148
|
+
//# sourceMappingURL=chunk-TY56BKSK.cjs.map
|
|
149
|
+
//# sourceMappingURL=chunk-TY56BKSK.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/compat/foreign-config-sources.ts","../src/internal/persistence/paths.ts"],"names":["join","existsSync","diagFailure","homedir"],"mappings":";;;;;;;AAmDO,IAAM,mBAAA,GAAsB;AAG5B,IAAM,eAAA,GAAkB;AA+BxB,IAAM,aAAA,GAAqC;AAAA,EAChD,IAAA,EAAM,SAAA;AAAA,EACN,OAAA,EAAS,mBAAA;AAAA,EACT,UAAA,EAAY,CAAC,GAAA,MAAS,EAAE,qBAAqB,GAAA,EAAI;AACnD,CAAA;AAWO,IAAM,kBAAA,GAA0C;AAAA,EACrD,IAAA,EAAM,aAAA;AAAA,EACN,OAAA,EAAS,eAAA;AAAA,EACT,UAAA,EAAY,CAAC,GAAA,MAAS,EAAE,oBAAoB,GAAA,EAAI;AAClD,CAAA;AAEA,IAAM,eA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,IAAI,QAAA,CAAS,UAAA,CAAW,CAAA,EAAG,IAAI,GAAG,CAAA,EAAG;AACnC,IAAA,OAAO,CAAA,CAAA,EAAI,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,MAAM,CAAC,CAAA,CAAA;AAAA,EACxC;AACA,EAAA,OAAO,QAAA;AACT","file":"chunk-TY56BKSK.cjs","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { CompatSurface } from \"../../../types/agent.js\";\nimport { diagFailure } from \"../../diagnostics.js\";\n\n/*\n * The foreign configuration dialects this SDK can read, and what each one PRESUMES.\n *\n * ## Why a registry and not a list of directory names\n *\n * `projectConfigRoots` returned `[\".theokit\", \".claude\"]` — two paths — and that shape is what\n * usetheokit/theokit-sdk#522 fell through. A path says WHERE a file lives. It does not say how the\n * file is parsed, and it does not say what runtime the commands inside it were written against.\n *\n * Claude Code defines `$CLAUDE_PROJECT_DIR` for the hook commands in its `settings.json`, and its\n * documentation tells authors to reach project files through it — an absolute path would break for\n * every other person on the team, so the shape that failed here is the shape upstream recommends.\n * This SDK read the file and ran the command without the variable. `sh` expands an unset variable to\n * the empty string, so\n *\n * bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/guard.sh\" became bash \"/.claude/hooks/guard.sh\"\n *\n * which does not exist, which a hook runner correctly reads as a refusal. Every turn denied, in any\n * repository that also had Claude Code set up, with a message naming a file that was present and\n * executable all along.\n *\n * Importing a format means accepting the contract that format presumes. An adapter is where that\n * contract is written down, so the next dialect (`.codex/` is the obvious one) declares its own\n * instead of inheriting a hole.\n *\n * ## What an adapter deliberately does NOT do\n *\n * It does not make the foreign source trusted, and it does not make its hooks permissive: a script\n * that exits non-zero is still a refusal. It supplies the variables the format's authors were\n * entitled to assume, and nothing else — `env` here is merged over the scrubbed inherit policy by\n * `spawnAndCollect`, so it adds names rather than widening what a child can see.\n *\n * @internal\n */\n\n/**\n * The project config directory literal.\n *\n * Renamed from `THEOKIT_DIR_NAME` in #410. Sharing a name with the (now removed) sovereign env var\n * was the MECHANISM of that defect, not scenery: every grep for the variable landed on that const\n * and looked answered, so \"is it read?\" returned five hits and nobody checked what they were.\n *\n * Lives here rather than in `persistence/paths.ts` because a directory name is one third of what a\n * dialect is — the other two being how it parses and what it presumes — and splitting the three\n * across two modules is what let the third go unwritten.\n */\nexport const THEOKIT_DIR_LITERAL = \".theokit\";\n\n/** The Claude Code CLI's project configuration directory. */\nexport const CLAUDE_DIR_NAME = \".claude\";\n\n/** A configuration dialect this SDK understands. `theokit` is native; the rest are foreign. */\nexport interface ConfigSourceAdapter {\n /** Stable identifier, and what a consumer names to opt in. */\n readonly kind: string;\n /** The project-relative directory the dialect keeps its configuration in. */\n readonly dirName: string;\n /**\n * Variables the dialect's own runtime defines for commands it executes, under the dialect's own\n * documented spellings.\n *\n * Every dialect gets a project-directory variable, because none of them can locate a\n * project-relative script without one — the inherited environment says where the PROCESS is, and\n * a hook that has to depend on the process cwd is the dependency #522 removed for the foreign\n * side. Fixing one dialect and leaving the other different was the half-fix.\n *\n * The SPELLINGS differ on purpose: a ported script reaches for the name its own docs use, and a\n * native one for this runtime's.\n */\n runtimeEnv(cwd: string): Record<string, string>;\n}\n\n/**\n * The native source. Always read, never opted into, always first for precedence.\n *\n * `THEOKIT_PROJECT_DIR` is the native counterpart of `CLAUDE_PROJECT_DIR` below. This used to be\n * `{}`, on the reasoning that a `.theokit/` hook \"is written against THIS runtime and inherits it\n * already\" — true of the runtime's BEHAVIOUR and not of a project PATH. Nothing in the inherited\n * environment says where the project is, so a native hook had to depend on the process cwd.\n */\nexport const NATIVE_SOURCE: ConfigSourceAdapter = {\n kind: \"theokit\",\n dirName: THEOKIT_DIR_LITERAL,\n runtimeEnv: (cwd) => ({ THEOKIT_PROJECT_DIR: cwd }),\n};\n\n/**\n * Claude Code.\n *\n * `CLAUDE_PROJECT_DIR` is the documented way for a hook command in `settings.json` to reach a file\n * in the project. Only that one variable is supplied: `$CLAUDE_PLUGIN_ROOT` and the rest of that\n * runtime's surface are NOT defined here, because supplying a name whose value this SDK would have\n * to invent is worse than leaving it unset — an invented root sends a script somewhere real and\n * wrong, where an unset one fails loudly.\n */\nexport const CLAUDE_CODE_SOURCE: ConfigSourceAdapter = {\n kind: \"claude-code\",\n dirName: CLAUDE_DIR_NAME,\n runtimeEnv: (cwd) => ({ CLAUDE_PROJECT_DIR: cwd }),\n};\n\nconst FOREIGN_SOURCES: readonly ConfigSourceAdapter[] = [CLAUDE_CODE_SOURCE];\n\nconst BY_DIR_NAME: ReadonlyMap<string, ConfigSourceAdapter> = new Map(\n [NATIVE_SOURCE, ...FOREIGN_SOURCES].map((a) => [a.dirName, a]),\n);\n\n/**\n * The adapters a caller declared, in declaration order, skipping any name that names no adapter.\n *\n * An unknown name is DROPPED rather than turned into `<cwd>/<name>`: a typo must fail closed. Making\n * a directory out of an unrecognised string would import a dialect nothing knows how to parse — and\n * the whole reason this exists is that a directory name was never enough to describe a dialect.\n */\nexport function adaptersFor(kinds: readonly string[]): ConfigSourceAdapter[] {\n const byKind = new Map(FOREIGN_SOURCES.map((a) => [a.kind, a]));\n const out: ConfigSourceAdapter[] = [];\n for (const kind of kinds) {\n const adapter = byKind.get(kind);\n if (adapter !== undefined && !out.includes(adapter)) out.push(adapter);\n }\n return out;\n}\n\n/**\n * #586 — re-exported from `types/agent.ts` rather than declared here, which is what it used to be.\n *\n * Two independent declarations of one public contract: `AgentOptions.local.compatSources` was typed\n * by the public one, `persistence/paths.ts` by this one, and neither imported the other. Measured:\n * adding a member to one alone produced ZERO type errors, because structurally-identical unions\n * compare equal and the two halves would simply stop agreeing about which surfaces exist.\n *\n * Neither direction of that drift raises anything. Widen the public type and a caller declares a\n * surface the admission logic ignores; widen this one and the loader admits a surface no public\n * caller can name. Both produce a declaration that reads as honoured and is not — the failure #524\n * exists to prevent, one layer down.\n *\n * `types/` is a leaf by design (theokit#146), so the public declaration is the one that stays and\n * this module imports it. The docblock that lived here — a skill is text entering the system prompt,\n * a hook is command execution, a plugin is code loading — is on the declaration in `types/agent.ts`.\n */\nexport type { CompatSurface };\n\n/**\n * The runtime list. A type cannot be enumerated at runtime, so this is the one place the members are\n * written twice by necessity — and {@link assertCompatSurfacesExhaustive} below is what stops that\n * second copy from being a second source of truth.\n *\n * `as const satisfies` rather than an annotation, and the difference is the whole guard: annotating\n * it `readonly CompatSurface[]` widens each entry back to `CompatSurface`, so the check below\n * compares a type against itself and passes on any drift. Measured on the first attempt — a member\n * added to the public type alone produced zero errors. `satisfies` keeps the literals while still\n * rejecting an entry that is not a surface, which is both directions at once.\n */\nconst COMPAT_SURFACES = [\n \"context\",\n \"hooks\",\n \"plugins\",\n \"skills\",\n \"subagents\",\n] as const satisfies readonly CompatSurface[];\n\n/**\n * Compile-time guard: adding a member to {@link CompatSurface} without adding it to\n * {@link COMPAT_SURFACES} fails `tsc` here.\n *\n * Never called. It exists so the pairing is checked by the compiler rather than by whoever\n * remembers — which is the entire lesson of #586, applied to the copy that could not be removed.\n */\nfunction assertCompatSurfacesExhaustive(surface: CompatSurface): (typeof COMPAT_SURFACES)[number] {\n return surface;\n}\nvoid assertCompatSurfacesExhaustive;\n\n/**\n * A declared foreign source: a bare kind, or a kind with the surfaces it may be read for.\n */\nexport type CompatSourceDeclaration =\n | string\n | { readonly kind: string; readonly import?: readonly string[] };\n\n/**\n * The adapters admitted to ONE surface.\n *\n * Three rules, and each one fails closed:\n *\n * - A bare string admits every surface. It is what `5.0.0-next.1` published, so narrowing it\n * silently would turn a working opt-in into a no-op — the exact defect #524 is about, one level\n * up.\n * - An object with no `import` admits nothing. The issue's own rule, and safe to apply strictly\n * because the object form is new and nobody can be depending on it.\n * - An unrecognised surface name is dropped rather than matched loosely, for the same reason an\n * unrecognised KIND is dropped in {@link adaptersFor}: a typo must not silently widen access.\n */\nexport function adaptersForSurface(\n sources: readonly CompatSourceDeclaration[],\n surface: CompatSurface,\n): ConfigSourceAdapter[] {\n const admitted: string[] = [];\n for (const source of sources) {\n if (typeof source === \"string\") {\n admitted.push(source);\n continue;\n }\n const wanted = source.import ?? [];\n if (wanted.some((s) => s === surface && COMPAT_SURFACES.includes(s as CompatSurface))) {\n admitted.push(source.kind);\n }\n }\n return adaptersFor(admitted);\n}\n\n/**\n * The adapter whose directory an absolute config path sits under, or `undefined` for a path that\n * belongs to no registered dialect.\n *\n * Matched on the path SEGMENT rather than with `includes`, so a workspace that happens to live under\n * `/home/me/.claude-backups/repo` does not read as a Claude Code source.\n */\nexport function adapterForConfigPath(path: string): ConfigSourceAdapter | undefined {\n for (const segment of path.split(/[\\\\/]/)) {\n const adapter = BY_DIR_NAME.get(segment);\n if (adapter !== undefined) return adapter;\n }\n return undefined;\n}\n\n/**\n * Variable references in a shell command that nothing will define.\n *\n * The second half of #522, and the half that cost the debugging session. `sh` expands an unset\n * variable to the empty string and says nothing, so the failure surfaces ten characters later as a\n * path: `bash: /.claude/hooks/guard.sh: No such file or directory` — which reads as \"your script is\n * missing\" while the script is present and executable. Nothing in that message contains the name of\n * the variable that was actually missing, so the reader looks in the wrong place.\n *\n * Checked against BOTH the process environment and the variables the dialect supplies, because\n * either is a legitimate source: a hook may reasonably use `$HOME`.\n *\n * ## What it deliberately does not try to be\n *\n * This is not a shell parser. It finds `$NAME` and `${NAME}` outside single quotes, which is the\n * shape a config file's hook commands take. It does NOT understand `${NAME:-default}` (a default\n * makes the variable optional, so it is not reported), assignments earlier in the same command, or\n * variables a sourced script exports. A false NEGATIVE there costs the old behaviour — the confusing\n * path error — and a false positive would deny a hook that would have worked, so the parse errs\n * toward silence and the check only ever ADDS a name to a failure that already happened.\n */\nexport function undefinedVariablesIn(\n command: string,\n supplied: Readonly<Record<string, string>>,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string[] {\n // Single-quoted spans are literal in `sh`: `echo '$FOO'` prints the dollar sign.\n const unquoted = command.replace(/'[^']*'/g, \" \");\n const names = new Set<string>();\n for (const match of unquoted.matchAll(\n /\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}|\\$([A-Za-z_][A-Za-z0-9_]*)/g,\n )) {\n const name = match[1] ?? match[2];\n if (name === undefined) continue;\n if (name in supplied) continue;\n if (env[name] !== undefined) continue;\n names.add(name);\n }\n return [...names];\n}\n\n/**\n * Workspaces already reported, so repeated agent construction in one process says it once.\n *\n * Keyed by the resolved directory rather than by dialect kind, so a long-lived host that drives\n * several workspaces still reports each of them.\n */\nconst reported = new Set<string>();\n\n/**\n * Reports a foreign configuration directory that exists in the workspace and was not declared.\n *\n * ## Why the flip needs a voice\n *\n * Before #524 a `.claude/` was read with no opt-in; after it, the same directory is ignored. From\n * inside the repository the two states are indistinguishable — the hook file is there, it is\n * executable, and it does not run. The only remaining way to learn why is a CHANGELOG entry for a\n * version the reader may not know they crossed.\n *\n * ## Why `diagFailure` rather than `diag` (#563)\n *\n * This used `diag`, on the reasoning that ignoring an undeclared directory is not a failure and\n * that a repository which does NOT want the import should not pay a stderr line for behaving as\n * instructed. The reasoning was sound and rested on a premise nobody checked: that a host would\n * have installed a sink.\n *\n * Measured against the published `5.0.0`. `diag` returns without doing anything when no sink is\n * installed. The SDK installs none — `currentSink()` reads a `globalThis` slot only\n * `setDiagnosticsSink` fills. Neither observable host installs one either: `theocode` renamed the\n * key, and `theokit` exports `installDiagnosticSink` and never calls it. Two hosts out of two, and\n * the SDK itself. So the message the CHANGELOG promised — \"says so once, on the diagnostics\n * channel\" — reached nobody, while the consumer lost hooks, skills, subagents and plugins.\n *\n * A mitigation announced in release notes for a silent loss of capability is not a diagnostic. It\n * is the error path of the breaking change itself, and `diagFailure` exists for exactly the message\n * that must not be swallowed.\n *\n * The cost the old reasoning named is real and is now paid: a repository that wants the directory\n * ignored sees a line. What makes that acceptable — ONCE per directory per process, not per turn\n * (`reported` below); and before #524 that repository was having `.claude/` imported anyway, so the\n * line it now sees confirms the fix it wanted. The asymmetry is one line of text against silently\n * losing four subsystems.\n *\n * A host that installs a sink still owns its render surface: `diagFailure` prefers the sink and\n * only falls back to stderr when there is none.\n *\n * NOT solved here: there is no way to say \"I know, and I want none\". `compatSources: []` would be\n * the natural spelling, but `resolveCompatSources` collapses it into the same `[]` an absent option\n * produces, so this function cannot tell them apart. If the noise turns out to matter, threading\n * that distinction through is the shape of the fix.\n */\nexport function reportUndeclaredSources(\n cwd: string,\n declared: readonly CompatSourceDeclaration[],\n): void {\n // A kind named with a NARROW import list has still been declared: the consumer knows the\n // directory is there and chose which surfaces to admit. Warning them anyway would be the noise\n // that gets a warning ignored, and this one has exactly one job — telling somebody who does NOT\n // know the directory is being skipped.\n const declaredKinds = new Set(\n adaptersFor(declared.map((d) => (typeof d === \"string\" ? d : d.kind))).map((a) => a.kind),\n );\n for (const adapter of FOREIGN_SOURCES) {\n if (declaredKinds.has(adapter.kind)) continue;\n const dir = join(cwd, adapter.dirName);\n if (!existsSync(dir)) continue;\n if (reported.has(dir)) continue;\n reported.add(dir);\n // THE FILE IS NAMED FIRST because it is the entry point this message's reader can use.\n //\n // #524 gives the declaration two entry points for one shape: `.theokit/config.json`'s\n // `compat.adapters`, and `local.compatSources` in code. Until this change the warning named\n // only the second — and `local` is an argument the SDK's EMBEDDER passes, not something the\n // person reading the line can reach. Reported by the `theocode` session against 5.0.1: a user\n // of a host that embeds this SDK is told to pass an option that does not exist on their\n // surface, which is advice that is true about the mechanism and unusable as an action.\n //\n // The file is writable by anyone holding the workspace, which is exactly who sees this line.\n //\n // WHAT THIS LINE CANNOT KNOW, and it is a real limit rather than a caveat for form's sake. It\n // reports one fact: this SDK is ignoring the directory because nothing declared it. A HOST\n // embedding the SDK may be withholding the same directory for its own reasons — `theocode`\n // gates repository configuration on a trust posture — and the SDK cannot see that gate.\n //\n // So in a host that is also withholding, following this advice makes the warning stop and\n // changes nothing the user can do. That silence is honest about the SDK (it did stop ignoring\n // the directory) and uninformative about the outcome. Measured by the `theocode` session with\n // the control that settles it: a NATIVE `.theokit/` hook does not fire there either, so the\n // host's gate — not this declaration — is what holds the capability back.\n //\n // Nothing here can fix that. If a host ever gains a way to say \"I am withholding this too\",\n // this is the line where that belongs.\n diagFailure(\n `[theokit] ${adapter.dirName}/ is present but not declared, so its hooks, skills, subagents, ` +\n `plugins and rules are ignored. To read it, add ` +\n `{\"compat\":{\"adapters\":[\"${adapter.kind}\"]}} to .theokit/config.json — or, if you embed ` +\n `this SDK, pass local: { compatSources: [\"${adapter.kind}\"] } ` +\n `(usetheokit/theokit-sdk#524).\\n`,\n );\n }\n}\n","/**\n * Path resolution for SDK state files (ADR D60).\n *\n * Theokit anchors state at `<cwd>/.theokit/` by default (per-cwd). An\n * optional `THEOKIT_HOME` environment variable overrides this, enabling\n * test isolation, profile switching, and multi-tenant deployments.\n *\n * Rules:\n * - `getTheokitHome(cwd)` is the canonical resolver **for cwd-anchored state**. Never hardcode\n * `path.join(cwd, \".theokit\")` in callers — use this function so tests\n * and overrides stay consistent.\n *\n * M94 — this comment said \"the ONLY canonical resolver\", and stopped being true: the\n * transcript gained `transcriptRoot()`, which is **home-anchored** (`~/.theokit`) with the same\n * `THEOKIT_HOME` override. The two defaults differ on purpose — unifying would move the\n * transcript of everyone who does NOT set the variable, which is a data migration and not a\n * re-export.\n *\n * A consequence worth writing down: **without `THEOKIT_HOME` the state stays split in two**\n * — registry in `<cwd>/.theokit`, transcript in `~/.theokit`. M94 unifies only for those who set\n * the variable. Unifying both defaults is another milestone's work.\n * - `getProfilesRoot()` is intentionally home-anchored (not affected by\n * `THEOKIT_HOME`) so `theokit profile list` discovers all profiles\n * regardless of which is active.\n * - `displayTheokitHome(cwd)` returns a human-readable path for logs.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport {\n adaptersForSurface,\n type CompatSourceDeclaration,\n type CompatSurface,\n THEOKIT_DIR_LITERAL,\n} from \"../runtime/compat/foreign-config-sources.js\";\n\n// The directory names live with the dialect registry that owns them — a name is one third of what a\n// configuration dialect is, and keeping the three together is what stops the next one shipping\n// without its runtime contract (#522).\n\n/**\n * Resolve the directory cwd-anchored SDK state lives in.\n *\n * `THEOKIT_HOME` wins when it is set and not blank after trimming; the trimmed value is used, and\n * it is used VERBATIM — it is not resolved against `cwd`, so a relative value stays relative and\n * `.theokit` is not appended to it. Otherwise the answer is `<cwd>/.theokit`.\n *\n * The environment is read on every call, so a change to the variable takes effect immediately\n * rather than being frozen at import.\n *\n * This creates nothing and checks nothing: the returned path may not exist, and the caller owns\n * the `mkdir`. Call it instead of writing `join(cwd, \".theokit\")` by hand, or the override stops\n * working for that one call site and tests silently touch the real home.\n *\n * Not the whole story about where state lives — the transcript is home-anchored via\n * `transcriptRoot()`, honoring the same variable but defaulting to `~/.theokit`. With\n * `THEOKIT_HOME` unset, state is genuinely split between two roots.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function getTheokitHome(cwd: string): string {\n const override = process.env.THEOKIT_HOME?.trim();\n if (override !== undefined && override.length > 0) {\n return override;\n }\n return join(cwd, THEOKIT_DIR_LITERAL);\n}\n\n/**\n * The project's own configuration root: `<cwd>/.theokit`, always — never `THEOKIT_HOME`.\n *\n * `THEOKIT_HOME` relocates cwd-anchored SDK STATE (sessions, credentials). A project's\n * CONFIGURATION belongs to the repository: hooks, MCP servers, context sources, subagents, the\n * personality a project declares, all committed to git and shared by a team. Following the\n * override for any of them would move where a project's declared capabilities come from — a\n * behaviour change wearing the costume of a refactor, which is exactly what this function exists\n * to make impossible to do by accident: every config-class reader calls this instead of writing\n * `join(cwd, \".theokit\")` by hand.\n *\n * NOT for the `.claude/`-style foreign roots {@link adaptersForSurface} adds — those are additive,\n * opt-in, and each has its own directory name.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function theokitConfigRoot(cwd: string): string {\n return join(cwd, THEOKIT_DIR_LITERAL);\n}\n\n/**\n * Every directory a project's configuration may be read from, in precedence order.\n *\n * `.theokit` first — via {@link theokitConfigRoot}, so it is NEVER affected by `THEOKIT_HOME` for\n * the reason documented there — then `.claude`. The order is the whole contract: a project that\n * declares a skill, agent or rule in both means the explicit namespace to win, and a caller merging\n * these roots must therefore keep the FIRST occurrence of a name rather than the last.\n *\n * `.claude` is read because the formats already agree and only the location did not. Measured\n * 2026-08-26: the SKILL.md frontmatter this SDK requires (`name` + `description`) is exactly what\n * the CLI writes, its hook config is the same JSON shape, and 59 of the CLI's agent declarations\n * parse here unchanged. A repository set up for the CLI was failing on the directory name alone.\n *\n * NOT a rename of `.theokit`, and not a migration. Both are read, so nothing that works today stops\n * working — which is why this returns a LIST and not a single resolved answer.\n *\n * Creates nothing and checks nothing; either path may not exist, and the caller owns that.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function projectConfigRoots(\n cwd: string,\n sources: readonly CompatSourceDeclaration[],\n surface: CompatSurface,\n): string[] {\n const own = nativeAdmitsSurface(sources, surface) ? [theokitConfigRoot(cwd)] : [];\n return [\n ...own,\n ...adaptersForSurface(foreignOnly(sources), surface).map((a) => join(cwd, a.dirName)),\n ];\n}\n\n/** The kind a consumer names to declare THIS package's own root. */\nconst NATIVE_KIND = \"theokit\";\n\n/**\n * #631 — whether the native root contributes `surface`.\n *\n * Undeclared means every surface, which is what this function returned unconditionally before and\n * is what every existing caller gets. A consumer that names the kind is opting into the same\n * per-surface contract a foreign dialect already has, and the defaults match on purpose: a bare\n * string admits everything, an object admits exactly what its `import` lists. Two vocabularies that\n * look identical and disagree about the default would be worse than one.\n *\n * The asymmetry this closes had a measured cost. `hookConfigCandidates` reads `settings.json` from\n * every root, so a consumer keeping its own configuration in `.theokit/settings.json` had that\n * file's `hooks` key executed by this package, and `settingSources` gave it no way to decline: it\n * grants a foreign dialect per SOURCE, not per surface, so dropping `claude-code` to avoid its\n * hooks would also drop its skills, agents and rules.\n */\nfunction nativeAdmitsSurface(\n sources: readonly CompatSourceDeclaration[],\n surface: CompatSurface,\n): boolean {\n const declared = sources.filter((s) => (typeof s === \"string\" ? s : s.kind) === NATIVE_KIND);\n if (declared.length === 0) return true;\n return declared.some((s) => (typeof s === \"string\" ? true : (s.import ?? []).includes(surface)));\n}\n\n/**\n * The native declaration is consumed here and must not reach `adaptersForSurface`, which resolves\n * kinds to FOREIGN adapters. It would be dropped there as unrecognised — harmlessly, today — but\n * relying on that would make this behaviour depend on another function failing to find something,\n * which is the kind of coupling that breaks the moment an adapter of that name is added.\n */\nfunction foreignOnly(\n sources: readonly CompatSourceDeclaration[],\n): readonly CompatSourceDeclaration[] {\n return sources.filter((s) => (typeof s === \"string\" ? s : s.kind) !== NATIVE_KIND);\n}\n\n/**\n * Every directory that may hold a plugin BUNDLE contributed by the Claude Code CLI.\n *\n * A CLI plugin is not a JS entry point — it is a folder whose `skills/` and `agents/` are what it\n * exists to provide. Measured 2026-08-26 on an installed one: seven agents and three skills beside\n * a manifest in `.claude-plugin/plugin.json`. Parsing that manifest and stopping there produced a\n * plugin that loaded and did nothing.\n *\n * Project-scoped deliberately. The CLI also keeps plugins under `~/.claude/plugins/cache`, behind\n * its own installer and enable/disable state — reproducing that is an installation system, not\n * reading a project's configuration, and guessing at someone's enablement would run code they\n * turned off.\n */\nexport function pluginBundleRoots(\n cwd: string,\n sources: readonly CompatSourceDeclaration[],\n): string[] {\n // Always the `plugins` surface, including when the caller wants the SKILLS a bundle carries.\n // A bundle is code, and its skills arrive attached to it: admitting `skills` alone must not\n // reach inside a foreign plugin directory, or the narrower permission would silently grant the\n // wider one. `skills-manager` and `subagents-loader` both read bundle contents and both go\n // through here, so the rule holds in one place rather than three.\n return projectConfigRoots(cwd, sources, \"plugins\").map((root) => join(root, \"plugins\"));\n}\n\n/**\n * The directory holding every profile: always `~/.theokit/profiles`, from `os.homedir()`.\n *\n * Deliberately NOT affected by `THEOKIT_HOME`, which is the one thing to remember about it. If it\n * followed the override, a session pointed at one profile would only be able to see that profile,\n * and `theokit profile list` could never enumerate the rest. Profiles are the thing the override\n * switches between, so their index cannot live behind it.\n *\n * Takes no `cwd` for the same reason. Creates nothing; the path may not exist.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function getProfilesRoot(): string {\n return join(homedir(), THEOKIT_DIR_LITERAL, \"profiles\");\n}\n\n/**\n * The same path `getTheokitHome(cwd)` returns, shortened for display: the home directory prefix\n * collapses to `~`, so `/home/ada/.theokit` prints as `~/.theokit`.\n *\n * For humans only — log lines, CLI output, error messages. The result is NOT a usable path: `~`\n * is a shell convention that `fs` does not expand, so passing this to a filesystem call resolves\n * a literal directory named `~` relative to the process cwd. Use `getTheokitHome` for anything\n * that touches disk.\n *\n * Collapsing is a prefix match on the home directory followed by a literal `/`, so a sibling like\n * `/home/adalovelace` is left alone even though `/home/ada` is a string prefix of it. A path\n * outside the home directory comes back unchanged — and so does a Windows path, where the\n * separator is a backslash and the prefix test therefore never matches.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function displayTheokitHome(cwd: string): string {\n const resolved = getTheokitHome(cwd);\n const home = homedir();\n if (resolved === home) return \"~\";\n if (resolved.startsWith(`${home}/`)) {\n return `~${resolved.slice(home.length)}`;\n }\n return resolved;\n}\n"]}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { ConfigurationError } from './chunk-ALUN2B4W.js';
|
|
2
|
+
import { readdir } from 'fs/promises';
|
|
3
|
+
|
|
4
|
+
async function readWorkspaceDir(root, errorCode, describe) {
|
|
5
|
+
try {
|
|
6
|
+
return await readdir(root, { withFileTypes: true });
|
|
7
|
+
} catch (cause) {
|
|
8
|
+
const err = cause;
|
|
9
|
+
if (err.code === "ENOENT") return [];
|
|
10
|
+
throw new ConfigurationError(`Failed to read ${describe}: ${root}`, {
|
|
11
|
+
code: errorCode,
|
|
12
|
+
cause
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// src/internal/runtime/context/yaml-frontmatter.ts
|
|
18
|
+
function parseSimpleYaml(text) {
|
|
19
|
+
const fields = {};
|
|
20
|
+
const lines = text.split(/\r?\n/);
|
|
21
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
22
|
+
const entry = splitEntry(lines[i] ?? "");
|
|
23
|
+
if (entry === void 0) continue;
|
|
24
|
+
const { key, raw } = entry;
|
|
25
|
+
const block = raw.length === 0 ? collectBlockList(lines, i + 1) : void 0;
|
|
26
|
+
if (block !== void 0 && block.items.length > 0) {
|
|
27
|
+
fields[key] = block.items;
|
|
28
|
+
i = block.end - 1;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
fields[key] = coerce(raw);
|
|
32
|
+
}
|
|
33
|
+
return fields;
|
|
34
|
+
}
|
|
35
|
+
function splitEntry(line) {
|
|
36
|
+
const colonIndex = line.indexOf(":");
|
|
37
|
+
if (colonIndex === -1) return void 0;
|
|
38
|
+
const key = line.slice(0, colonIndex).trim();
|
|
39
|
+
if (key.length === 0) return void 0;
|
|
40
|
+
return { key, raw: line.slice(colonIndex + 1).trim() };
|
|
41
|
+
}
|
|
42
|
+
function collectBlockList(lines, start) {
|
|
43
|
+
const items = [];
|
|
44
|
+
let j = start;
|
|
45
|
+
for (; j < lines.length; j += 1) {
|
|
46
|
+
const next = (lines[j] ?? "").trim();
|
|
47
|
+
if (next === "" || next.startsWith("#")) continue;
|
|
48
|
+
if (!next.startsWith("- ")) break;
|
|
49
|
+
items.push(next.slice(2).trim());
|
|
50
|
+
}
|
|
51
|
+
return { items, end: j };
|
|
52
|
+
}
|
|
53
|
+
function coerce(raw) {
|
|
54
|
+
if (raw.length === 0) return void 0;
|
|
55
|
+
if (raw.startsWith("[") && raw.endsWith("]")) {
|
|
56
|
+
return raw.slice(1, -1).split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
57
|
+
}
|
|
58
|
+
if (raw === "true" || raw === "false") return raw === "true";
|
|
59
|
+
const n = Number(raw);
|
|
60
|
+
if (Number.isFinite(n) && raw === String(n)) return n;
|
|
61
|
+
return raw;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export { parseSimpleYaml, readWorkspaceDir };
|
|
65
|
+
//# sourceMappingURL=chunk-UOLBAPDM.js.map
|
|
66
|
+
//# sourceMappingURL=chunk-UOLBAPDM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/config/workspace-dir.ts","../src/internal/runtime/context/yaml-frontmatter.ts"],"names":[],"mappings":";;;AAyBA,eAAsB,gBAAA,CACpB,IAAA,EACA,SAAA,EACA,QAAA,EAC8B;AAC9B,EAAA,IAAI;AACF,IAAA,OAAQ,MAAM,OAAA,CAAQ,IAAA,EAAM,EAAE,aAAA,EAAe,MAAM,CAAA;AAAA,EACrD,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,GAAA,GAAM,KAAA;AACZ,IAAA,IAAI,GAAA,CAAI,IAAA,KAAS,QAAA,EAAU,OAAO,EAAC;AACnC,IAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,eAAA,EAAkB,QAAQ,CAAA,EAAA,EAAK,IAAI,CAAA,CAAA,EAAI;AAAA,MAClE,IAAA,EAAM,SAAA;AAAA,MACN;AAAA,KACD,CAAA;AAAA,EACH;AACF;;;ACfO,SAAS,gBAAgB,IAAA,EAA4D;AAC1F,EAAA,MAAM,SAAuD,EAAC;AAC9D,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,OAAO,CAAA;AAChC,EAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,MAAA,EAAQ,KAAK,CAAA,EAAG;AACxC,IAAA,MAAM,KAAA,GAAQ,UAAA,CAAW,KAAA,CAAM,CAAC,KAAK,EAAE,CAAA;AACvC,IAAA,IAAI,UAAU,MAAA,EAAW;AACzB,IAAA,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AAK,UAAA,CAAW,GAAG,CAAA,EAAG;AACzC,IAAA,IAAI,CAAC,IAAA,CAAK,UAAA,CAAW,IAAI,CAAA,EAAG;AAC5B,IAAA,KAAA,CAAM,KAAK,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,CAAE,MAAM,CAAA;AAAA,EACjC;AACA,EAAA,OAAO,EAAE,KAAA,EAAO,GAAA,EAAK,CAAA,EAAE;AACzB;AAEA,SAAS,OAAO,GAAA,EAA2C;AAEzD,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,CAAA,EAAG,OAAO,MAAA;AAC7B,EAAA,IAAI,IAAI,UAAA,CAAW,GAAG,KAAK,GAAA,CAAI,QAAA,CAAS,GAAG,CAAA,EAAG;AAC5C,IAAA,OAAO,GAAA,CACJ,MAAM,CAAA,EAAG,EAAE,EACX,KAAA,CAAM,GAAG,EACT,GAAA,CAAI,CAAC,MAAM,CAAA,CAAE,IAAA,EAAM,CAAA,CACnB,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,CAAC,CAAA;AAAA,EAC/B;AACA,EAAA,IAAI,GAAA,KAAQ,MAAA,IAAU,GAAA,KAAQ,OAAA,SAAgB,GAAA,KAAQ,MAAA;AACtD,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,IAAI,MAAA,CAAO,SAAS,CAAC,CAAA,IAAK,QAAQ,MAAA,CAAO,CAAC,GAAG,OAAO,CAAA;AACpD,EAAA,OAAO,GAAA;AACT","file":"chunk-UOLBAPDM.js","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 * - a → [\"a\",\"b\"] (block list, when `- ` items follow a bare key)\n * - b\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 * - Inline list values cannot contain a literal comma inside an element; the\n * `tags: [a,b, c]` splitter is greedy on `,`. Use the block form above or\n * reword if you need this — and note that the block form was, for a while,\n * what this line recommended and the parser could not read.\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 const lines = text.split(/\\r?\\n/);\n for (let i = 0; i < lines.length; i += 1) {\n const entry = splitEntry(lines[i] ?? \"\");\n if (entry === undefined) continue;\n const { key, raw } = entry;\n\n // `key:` with nothing after it may open a block list. Collect first, then decide: items found →\n // a list; none → `undefined`, which is the long-standing meaning of a bare key and what a\n // caller's Zod default relies on.\n const block = raw.length === 0 ? collectBlockList(lines, i + 1) : undefined;\n if (block !== undefined && block.items.length > 0) {\n fields[key] = block.items;\n // `end` is the first line that is NOT part of this list, and the loop's own `i += 1` steps\n // past it — so stop one short, or the key after a block list is swallowed.\n i = block.end - 1;\n continue;\n }\n\n fields[key] = coerce(raw);\n }\n return fields;\n}\n\n/**\n * Split one line into its key and its raw value, or report that it carries neither.\n *\n * A line with no `:` is not an entry (a `- item` continuation is the case that matters here), and\n * neither is one whose key is blank. Both were `continue`s inside the loop; they are the same\n * question — \"is this line an entry?\" — and asking it in one place is what keeps the loop under the\n * repository's cognitive-complexity limit.\n */\nfunction splitEntry(line: string): { key: string; raw: string } | undefined {\n const colonIndex = line.indexOf(\":\");\n if (colonIndex === -1) return undefined;\n const key = line.slice(0, colonIndex).trim();\n if (key.length === 0) return undefined;\n return { key, raw: line.slice(colonIndex + 1).trim() };\n}\n\n/**\n * Read the `- item` lines that follow a bare `key:`, and report where they stop.\n *\n * Line-oriented parsing skipped these outright — a `- item` has no colon — so the key coerced to\n * `undefined` and the values went nowhere. A reader saw the key on disk and found no behaviour,\n * with nothing to grep for. The docblock above made it sharper by advising \"use multi-line lists\"\n * for a limitation of the inline form; multi-line was the one shape this parser could not read.\n *\n * Extracted rather than inlined because inlining it put `parseSimpleYaml` at a cognitive complexity\n * of 24 against a limit of 10 — measured, not assumed: the pre-change function raised no such\n * diagnostic on the same file path.\n *\n * Blank and `#` lines do not end a list; anything else does. `end` is the index of that first\n * non-item line, so the caller resumes there rather than re-reading what it consumed.\n */\nfunction collectBlockList(lines: string[], start: number): { items: string[]; end: number } {\n const items: string[] = [];\n let j = start;\n for (; j < lines.length; j += 1) {\n const next = (lines[j] ?? \"\").trim();\n if (next === \"\" || next.startsWith(\"#\")) continue;\n if (!next.startsWith(\"- \")) break;\n items.push(next.slice(2).trim());\n }\n return { items, end: j };\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"]}
|