@theokit/sdk 4.57.0 → 4.59.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 +120 -0
- package/dist/{agent-ZIYCVEZL.js → agent-ST27RIJE.js} +10 -9
- package/dist/{agent-ZIYCVEZL.js.map → agent-ST27RIJE.js.map} +1 -1
- package/dist/{agent-2T2EJIP6.cjs → agent-VHRX7XGW.cjs} +11 -10
- package/dist/{agent-2T2EJIP6.cjs.map → agent-VHRX7XGW.cjs.map} +1 -1
- package/dist/{chunk-E7JHD6QJ.cjs → chunk-554J7UQH.cjs} +44 -27
- package/dist/chunk-554J7UQH.cjs.map +1 -0
- package/dist/{chunk-E3WZ6Y4H.cjs → chunk-7BG5UH3T.cjs} +8 -8
- package/dist/{chunk-E3WZ6Y4H.cjs.map → chunk-7BG5UH3T.cjs.map} +1 -1
- package/dist/{chunk-X7O4255I.cjs → chunk-7GUIET73.cjs} +4 -4
- package/dist/{chunk-X7O4255I.cjs.map → chunk-7GUIET73.cjs.map} +1 -1
- package/dist/{chunk-7TCRNXNK.js → chunk-7LOIUIQZ.js} +69 -29
- package/dist/chunk-7LOIUIQZ.js.map +1 -0
- package/dist/chunk-AQO3NSRG.cjs +41 -0
- package/dist/chunk-AQO3NSRG.cjs.map +1 -0
- package/dist/{chunk-LEM2GOMI.js → chunk-D5NWEOCO.js} +3 -3
- package/dist/{chunk-LEM2GOMI.js.map → chunk-D5NWEOCO.js.map} +1 -1
- package/dist/{chunk-U2AC6JUP.cjs → chunk-J2UROOIG.cjs} +2 -27
- package/dist/chunk-J2UROOIG.cjs.map +1 -0
- package/dist/{chunk-ZNW6V4Y6.cjs → chunk-LKFET5A3.cjs} +23 -2
- package/dist/chunk-LKFET5A3.cjs.map +1 -0
- package/dist/{chunk-YMA4S2WO.js → chunk-MZ2FGBLZ.js} +33 -11
- package/dist/chunk-MZ2FGBLZ.js.map +1 -0
- package/dist/{chunk-53CBTBWO.cjs → chunk-P6H23T43.cjs} +33 -11
- package/dist/chunk-P6H23T43.cjs.map +1 -0
- package/dist/{chunk-7FHZ4VQX.js → chunk-SAVIWMZB.js} +3 -3
- package/dist/{chunk-7FHZ4VQX.js.map → chunk-SAVIWMZB.js.map} +1 -1
- package/dist/{chunk-M2JWHKO6.cjs → chunk-SMUAG2DY.cjs} +103 -63
- package/dist/chunk-SMUAG2DY.cjs.map +1 -0
- package/dist/{chunk-UPRJR6IP.js → chunk-UCBJBJ27.js} +3 -25
- package/dist/chunk-UCBJBJ27.js.map +1 -0
- package/dist/chunk-UFLD2HEV.js +35 -0
- package/dist/chunk-UFLD2HEV.js.map +1 -0
- package/dist/{chunk-GTKFV7O5.js → chunk-WFC26L6Y.js} +23 -2
- package/dist/chunk-WFC26L6Y.js.map +1 -0
- package/dist/{chunk-HJBMA5MB.cjs → chunk-WNTAPVU5.cjs} +47 -6
- package/dist/chunk-WNTAPVU5.cjs.map +1 -0
- package/dist/{chunk-G6EEYRDD.js → chunk-ZA255A62.js} +43 -26
- package/dist/chunk-ZA255A62.js.map +1 -0
- package/dist/{chunk-2QKTVKH3.js → chunk-ZHPWGIUX.js} +48 -8
- package/dist/chunk-ZHPWGIUX.js.map +1 -0
- package/dist/context/index.cjs +7 -7
- package/dist/context/index.js +3 -3
- package/dist/{context-VMIE4BMD.cjs → context-LCKNH2XI.cjs} +7 -6
- package/dist/{context-VMIE4BMD.cjs.map → context-LCKNH2XI.cjs.map} +1 -1
- package/dist/context-MZSKGKYR.js +7 -0
- package/dist/{context-FDOON2DB.js.map → context-MZSKGKYR.js.map} +1 -1
- package/dist/cron.cjs +10 -9
- package/dist/cron.js +9 -8
- package/dist/eval.cjs +9 -8
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +8 -7
- package/dist/eval.js.map +1 -1
- package/dist/{index-manager-AO4LJQZ4.cjs → index-manager-A3XPHAWF.cjs} +5 -4
- package/dist/{index-manager-AO4LJQZ4.cjs.map → index-manager-A3XPHAWF.cjs.map} +1 -1
- package/dist/{index-manager-QDPIYIGV.js → index-manager-A64I7KYV.js} +4 -3
- package/dist/{index-manager-QDPIYIGV.js.map → index-manager-A64I7KYV.js.map} +1 -1
- package/dist/index.cjs +32 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +12 -13
- package/dist/index.js.map +1 -1
- package/dist/internal/memory/storage/markdown-store.d.ts +34 -4
- package/dist/internal/persistence/index.cjs +17 -16
- package/dist/internal/persistence/index.cjs.map +1 -1
- package/dist/internal/persistence/index.js +2 -1
- package/dist/internal/persistence/index.js.map +1 -1
- package/dist/internal/persistence/paths.d.cts +42 -0
- package/dist/internal/persistence/paths.d.ts +42 -0
- package/dist/internal/persistence/session-dir.d.cts +15 -0
- package/dist/internal/persistence/session-dir.d.ts +15 -0
- package/dist/internal/runtime/memory/memory-store.d.ts +2 -2
- package/dist/internal/runtime/plugins/plugin-bundles.d.ts +19 -0
- package/dist/project.cjs +3 -3
- package/dist/project.js +1 -1
- package/dist/subagents-loader-6ATCDEKN.js +8 -0
- package/dist/{subagents-loader-J54ESLDV.js.map → subagents-loader-6ATCDEKN.js.map} +1 -1
- package/dist/subagents-loader-X5QKODCL.cjs +17 -0
- package/dist/{subagents-loader-AZIXJ7D3.cjs.map → subagents-loader-X5QKODCL.cjs.map} +1 -1
- package/dist/subagents-loader.cjs +3 -2
- package/dist/subagents-loader.cjs.map +1 -1
- package/dist/subagents-loader.js +2 -1
- package/dist/subagents-loader.js.map +1 -1
- package/docs/error-codes.md +15 -15
- package/package.json +1 -1
- package/dist/chunk-2QKTVKH3.js.map +0 -1
- package/dist/chunk-53CBTBWO.cjs.map +0 -1
- package/dist/chunk-7TCRNXNK.js.map +0 -1
- package/dist/chunk-E7JHD6QJ.cjs.map +0 -1
- package/dist/chunk-G6EEYRDD.js.map +0 -1
- package/dist/chunk-GTKFV7O5.js.map +0 -1
- package/dist/chunk-HJBMA5MB.cjs.map +0 -1
- package/dist/chunk-M2JWHKO6.cjs.map +0 -1
- package/dist/chunk-U2AC6JUP.cjs.map +0 -1
- package/dist/chunk-UPRJR6IP.js.map +0 -1
- package/dist/chunk-YMA4S2WO.js.map +0 -1
- package/dist/chunk-ZNW6V4Y6.cjs.map +0 -1
- package/dist/context-FDOON2DB.js +0 -6
- package/dist/subagents-loader-AZIXJ7D3.cjs +0 -16
- package/dist/subagents-loader-J54ESLDV.js +0 -7
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { atomicWriteJson } from './chunk-VF7EWVDG.js';
|
|
2
2
|
import { diag } from './chunk-T7O6K6PX.js';
|
|
3
3
|
import { readFile, rename } from 'fs/promises';
|
|
4
|
-
import { homedir } from 'os';
|
|
5
|
-
import { join } from 'path';
|
|
6
4
|
|
|
7
5
|
function migrateSchema(opts) {
|
|
8
6
|
const { db, currentVersion, migrations, label = "db" } = opts;
|
|
@@ -77,27 +75,7 @@ async function writeVersionedJson(path, data, currentVersion) {
|
|
|
77
75
|
};
|
|
78
76
|
await atomicWriteJson(path, file);
|
|
79
77
|
}
|
|
80
|
-
var THEOKIT_DIR_NAME = ".theokit";
|
|
81
|
-
function getTheokitHome(cwd) {
|
|
82
|
-
const override = process.env.THEOKIT_HOME?.trim();
|
|
83
|
-
if (override !== void 0 && override.length > 0) {
|
|
84
|
-
return override;
|
|
85
|
-
}
|
|
86
|
-
return join(cwd, THEOKIT_DIR_NAME);
|
|
87
|
-
}
|
|
88
|
-
function getProfilesRoot() {
|
|
89
|
-
return join(homedir(), THEOKIT_DIR_NAME, "profiles");
|
|
90
|
-
}
|
|
91
|
-
function displayTheokitHome(cwd) {
|
|
92
|
-
const resolved = getTheokitHome(cwd);
|
|
93
|
-
const home = homedir();
|
|
94
|
-
if (resolved === home) return "~";
|
|
95
|
-
if (resolved.startsWith(`${home}/`)) {
|
|
96
|
-
return `~${resolved.slice(home.length)}`;
|
|
97
|
-
}
|
|
98
|
-
return resolved;
|
|
99
|
-
}
|
|
100
78
|
|
|
101
|
-
export {
|
|
102
|
-
//# sourceMappingURL=chunk-
|
|
103
|
-
//# sourceMappingURL=chunk-
|
|
79
|
+
export { migrateSchema, readVersionedJson, writeVersionedJson };
|
|
80
|
+
//# sourceMappingURL=chunk-UCBJBJ27.js.map
|
|
81
|
+
//# sourceMappingURL=chunk-UCBJBJ27.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/schema-version.ts"],"names":[],"mappings":";;;;AA4HO,SAAS,cAAc,IAAA,EAAiD;AAC7E,EAAA,MAAM,EAAE,EAAA,EAAI,cAAA,EAAgB,UAAA,EAAY,KAAA,GAAQ,MAAK,GAAI,IAAA;AACzD,EAAA,MAAM,YAAY,EAAA,CAAG,MAAA,CAAO,gBAAgB,EAAE,MAAA,EAAQ,MAAM,CAAA;AAC5D,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,KAAc,QAAA,GAAW,SAAA,GAAY,CAAA;AAE3D,EAAA,IAAI,SAAS,cAAA,EAAgB;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,CAAA,EAAI,KAAK,CAAA,iBAAA,EAAoB,MAAM,cAAc,cAAc,CAAA,0DAAA;AAAA,KAEjE;AAAA,EACF;AAEA,EAAA,IAAI,WAAW,cAAA,EAAgB;AAC7B,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,EAAA,EAAI,MAAA,EAAQ,KAAK,CAAA,EAAE;AAAA,EAC5C;AAEA,EAAA,MAAM,OAAA,GAAU,CAAC,GAAG,UAAU,EAC3B,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,SAAA,GAAY,EAAE,SAAS,CAAA,CACxC,OAAO,CAAC,CAAA,KAAM,EAAE,SAAA,GAAY,MAAA,IAAU,CAAA,CAAE,SAAA,IAAa,cAAc,CAAA;AAEtE,EAAA,IAAI,GAAA,GAAM,CAAA;AACV,EAAA,IAAI,WAAA,GAAc,M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A,EACtB;AAEA,EAAA,IAAI,OAAO,MAAA,KAAW,QAAA,IAAY,MAAA,KAAW,IAAA,EAAM;AACjD,IAAA,OAAO,YAAA,EAAa;AAAA,EACtB;AAEA,EAAA,MAAM,IAAA,GAAO,MAAA;AACb,EAAA,MAAM,YAAY,IAAA,CAAK,cAAA;AACvB,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,KAAc,QAAA,GAAW,SAAA,GAAY,CAAA;AAE3D,EAAA,IAAI,WAAW,cAAA,EAAgB;AAC7B,IAAA,OAAO,IAAA,CAAK,IAAA;AAAA,EACd;AAEA,EAAA,IAAI,SAAS,cAAA,EAAgB;AAC3B,IAAA,IAAA;AAAA,MACE,CAAA,cAAA,EAAiB,IAAI,CAAA,gBAAA,EAAmB,MAAM,cAAc,cAAc,CAAA;AAAA;AAAA,KAE5E;AACA,IAAA,OAAO,YAAA,EAAa;AAAA,EACtB;AAKA,EAAA,OAAO,OAAA,CAAQ,QAAQ,MAAM,CAAA;AAC/B;AAyBA,eAAsB,kBAAA,CACpB,IAAA,EACA,IAAA,EACA,cAAA,EACe;AACf,EAAA,MAAM,IAAA,GAA6B;AAAA,IACjC,cAAA,EAAgB,cAAA;AAAA,IAChB;AAAA,GACF;AACA,EAAA,MAAM,eAAA,CAAgB,MAAM,IAAI,CAAA;AAClC","file":"chunk-UCBJBJ27.js","sourcesContent":["/**\n * Schema versioning helpers (ADR D62).\n *\n * Two parallel APIs:\n * - `migrateSchema` — SQLite via `PRAGMA user_version` + ordered forward-only migrations.\n * - `readVersionedJson` / `writeVersionedJson` — JSON files with `_schemaVersion` field.\n *\n * Forward-only: never deletes data, never downgrades. Migration callbacks\n * own the transformation; this module owns the bookkeeping.\n *\n * @internal\n */\n\nimport { readFile, rename } from \"node:fs/promises\";\nimport { diag } from \"../diagnostics.js\";\nimport { atomicWriteJson } from \"./atomic-write.js\";\n\n// ────────────────────── SQLite migrations ──────────────────────\n\n/**\n * The three `better-sqlite3` methods this module actually uses, declared structurally so nothing\n * here imports the driver.\n *\n * A real `better-sqlite3` `Database` satisfies it. `pragma` is called both to read\n * (`pragma(\"user_version\", { simple: true })`, which must return the number itself rather than a\n * row array) and to write (`pragma(\"user_version = N\")`). `transaction` must return a function\n * that, when called, runs the wrapped body inside a real SQLite transaction and rolls it back if\n * the body throws — a stub that merely calls through gives `migrateSchema` no atomicity, and a\n * half-applied migration is exactly what it exists to prevent.\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 interface SqliteLike {\n pragma: (statement: string, options?: { simple?: boolean }) => unknown;\n exec: (sql: string) => void;\n transaction: <Args extends unknown[], R>(fn: (...args: Args) => R) => (...args: Args) => R;\n}\n\n/**\n * One forward migration step.\n *\n * `up` runs inside the shared transaction and must be self-contained: it may not commit, and any\n * error it throws aborts the whole run and rolls back every step in it, including the ones that\n * already succeeded. `user_version` is set to `toVersion` immediately after `up` returns, inside\n * the same transaction, so version and schema move together or not at all.\n *\n * `toVersion` is the version the database reaches, not the one it starts from. Steps are ordered\n * by it, gaps are allowed, and two steps sharing a `toVersion` both run — nothing deduplicates\n * them.\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 interface Migration {\n toVersion: number;\n up: (db: SqliteLike) => void;\n}\n\n/**\n * Arguments to `migrateSchema`.\n *\n * `currentVersion` is the version the code expects, and it is the ceiling: a migration whose\n * `toVersion` exceeds it is left unapplied for a later release. `migrations` may be given in any\n * order and may contain steps already applied — both are filtered and sorted here. `label` only\n * ever appears in the downgrade error message.\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 interface MigrateSchemaOptions {\n db: SqliteLike;\n currentVersion: number;\n migrations: ReadonlyArray<Migration>;\n /** For log/error context (e.g., \"memory-index\", \"registry\"). */\n label?: string;\n}\n\n/**\n * What `migrateSchema` did.\n *\n * `from` is the `user_version` found on the database, `to` is the version it holds afterwards,\n * and `ran` is how many steps executed. When nothing was pending, `to === from` and `ran === 0`.\n *\n * `to` is the `toVersion` of the last step applied, NOT `currentVersion`. A database at version 3\n * against `currentVersion: 5` with no migration in that range comes back as\n * `{ from: 3, to: 3, ran: 0 }` — the gap is reported, not closed. Comparing `to` with\n * `currentVersion` is how a caller notices that the migration list is missing a step.\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 interface MigrateSchemaResult {\n from: number;\n to: number;\n ran: number;\n}\n\n/**\n * Bring a SQLite database's `user_version` up to `currentVersion` by running the steps that sit\n * between the two.\n *\n * Steps are sorted ascending by `toVersion` and filtered to `> stored && <= currentVersion`, then\n * run in that order inside ONE transaction: each `up` is followed immediately by the matching\n * `user_version` write. Either every step in the run commits or none does — a step that throws\n * aborts the transaction, propagates the error, and leaves the database at the version it started\n * from. There is no partially-migrated state and no resume point.\n *\n * Forward-only. When the stored version is greater than `currentVersion` — an older build opening\n * a database a newer one already migrated — this throws immediately, before touching anything,\n * with a message naming both versions and `label`. Nothing downgrades, and no data is deleted on\n * any path here; what a step does is the step's own business.\n *\n * A stored version equal to `currentVersion` returns without opening a transaction. A `user_version`\n * that is absent or not a number is read as 0, so a fresh database runs every step.\n *\n * Concurrency: the SQLite transaction is the only serialization. This takes no file lock, so two\n * processes migrating the same file at once are arbitrated by SQLite's own write lock — the loser\n * gets a busy or locked error from the driver, not a queued turn. Wrap the call in `withFileLock`\n * if that matters.\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 migrateSchema(opts: MigrateSchemaOptions): MigrateSchemaResult {\n const { db, currentVersion, migrations, label = \"db\" } = opts;\n const storedRaw = db.pragma(\"user_version\", { simple: true });\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored > currentVersion) {\n throw new Error(\n `[${label}] schema version ${stored} > current ${currentVersion}; ` +\n \"did you downgrade the SDK? Forward-only migrations only.\",\n );\n }\n\n if (stored === currentVersion) {\n return { from: stored, to: stored, ran: 0 };\n }\n\n const pending = [...migrations]\n .sort((a, b) => a.toVersion - b.toVersion)\n .filter((m) => m.toVersion > stored && m.toVersion <= currentVersion);\n\n let ran = 0;\n let lastApplied = stored;\n\n db.transaction(() => {\n for (const m of pending) {\n m.up(db);\n db.pragma(`user_version = ${m.toVersion}`);\n lastApplied = m.toVersion;\n ran += 1;\n }\n })();\n\n return { from: stored, to: lastApplied, ran };\n}\n\n// ────────────────────── JSON versioned files ──────────────────────\n\n/**\n * The on-disk envelope: the payload under `data`, its schema version alongside it.\n *\n * `writeVersionedJson` always produces this shape. `readVersionedJson` reads it, but tolerates a\n * file that is not in it — a legacy object with no `_schemaVersion` is treated as version 0 and\n * handed to the migrate callback whole, so this type describes what is written, not everything\n * that can be read.\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 interface VersionedJsonFile<T> {\n _schemaVersion: number;\n data: T;\n}\n\n/**\n * Upgrade callback for `readVersionedJson`, invoked only when the stored version is BELOW the\n * current one.\n *\n * `parsed` is the whole parsed JSON value, not `parsed.data`. That is deliberate: a legacy file\n * predating the envelope has its fields at the top level, and a callback handed only `.data`\n * would receive `undefined` for exactly the files that need migrating. It is typed `unknown`\n * because nothing has validated it — narrow before reading.\n *\n * `fromVersion` is the `_schemaVersion` found on disk, or 0 when the field is missing or not a\n * number.\n *\n * The return value is used as-is and is NOT written back; the file on disk still holds the old\n * shape until someone calls `writeVersionedJson`. Throwing here propagates out of\n * `readVersionedJson`, which otherwise never throws — return the default value instead if an\n * unmigratable file should be survivable.\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 type VersionedJsonMigrate<T> = (parsed: unknown, fromVersion: number) => T;\n\n/**\n * Arguments to `readVersionedJson`.\n *\n * `defaultValue` is a factory rather than a value because it is called on several paths and each\n * caller must get its own object — returning a shared mutable default would let one caller's\n * edits appear in another's. It is called for a missing file, an unreadable one, a corrupt one,\n * a non-object payload, and a file written by a newer version.\n *\n * `migrate` is called only for a stored version strictly below `currentVersion`.\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 interface ReadVersionedJsonOptions<T> {\n path: string;\n currentVersion: number;\n migrate: VersionedJsonMigrate<T>;\n defaultValue: () => T;\n}\n\n/**\n * Read a versioned JSON file, migrating or falling back rather than failing.\n *\n * What comes back, by case:\n *\n * - version matches `currentVersion` — the file's `data` field, returned as `T` WITHOUT\n * validation. A file whose envelope is right but whose payload is not gets through.\n * - version below `currentVersion` — whatever `migrate(parsed, stored)` returns. The migrated\n * value is not persisted; the file is untouched.\n * - version above `currentVersion` — `defaultValue()`, plus a warning. Forward-only: a file\n * written by a newer build is left alone rather than downgraded.\n * - file missing, or unreadable for any other reason (permissions, a directory in its place) —\n * `defaultValue()`, silently. Absence and denial are not distinguished.\n * - file present but not valid JSON — `defaultValue()`, and the file is RENAMED to\n * `<path>.corrupt.<epoch-ms>` so the next run starts clean and the bad bytes stay available.\n * A rename that itself fails is warned about and the read still returns the default, which\n * means the same corrupt file will be met again next time.\n * - JSON that parses to a non-object (a number, a string, `null`) — `defaultValue()`, silently\n * and without moving the file aside.\n *\n * The only ways this throws are through the callbacks you supply: `migrate` or `defaultValue`\n * raising. Nothing else here rejects.\n *\n * There is no locking. A concurrent `writeVersionedJson` on the same path is atomic at the rename,\n * so a reader sees either the old file or the new one, never a half-written one — but a\n * read-modify-write built from this pair is NOT atomic across the two calls, and needs\n * `withFileLock` around both.\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 async function readVersionedJson<T>(opts: ReadVersionedJsonOptions<T>): Promise<T> {\n const { path, currentVersion, migrate, defaultValue } = opts;\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf-8\");\n } catch {\n return defaultValue();\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // T5.10 — move corrupt file aside so (a) user can investigate and\n // (b) next run starts fresh instead of hitting the same warning loop.\n const asidePath = `${path}.corrupt.${Date.now()}`;\n try {\n await rename(path, asidePath);\n diag(`[theokit-sdk] ${path} is corrupt; moved to ${asidePath}. Using default value.\\n`);\n } catch {\n diag(`[theokit-sdk] ${path} is corrupt; using default value.\\n`);\n }\n return defaultValue();\n }\n\n if (typeof parsed !== \"object\" || parsed === null) {\n return defaultValue();\n }\n\n const file = parsed as { _schemaVersion?: unknown; data?: unknown };\n const storedRaw = file._schemaVersion;\n const stored = typeof storedRaw === \"number\" ? storedRaw : 0;\n\n if (stored === currentVersion) {\n return file.data as T;\n }\n\n if (stored > currentVersion) {\n diag(\n `[theokit-sdk] ${path} schema version ${stored} > current ${currentVersion}; ` +\n \"using default value (forward-only).\\n\",\n );\n return defaultValue();\n }\n\n // EC-2 fix: pass the FULL parsed object to migrate, not just `file.data`.\n // Legacy shapes (e.g., `{ schemaVersion: \"1.0\", agents: {...} }` without\n // a `data` field) need to inspect the whole thing.\n return migrate(parsed, stored);\n}\n\n/**\n * Write `data` wrapped in the version envelope, replacing the file atomically.\n *\n * The bytes go to a temp file in the same directory and are moved into place with `rename`, so a\n * crash or a concurrent reader never observes a partial file: the path holds either the previous\n * content or the complete new content. Parent directories are created as needed, and the file is\n * created with mode 0600 (subject to the process umask), formatted with two-space indentation and\n * a trailing newline.\n *\n * `currentVersion` is stamped verbatim as `_schemaVersion`; nothing checks it against what was\n * already on disk, so this will happily overwrite a newer file with an older version. Read first\n * if that matters.\n *\n * Rejects when `data` cannot be serialized — a circular reference, or a `toJSON` that throws.\n * Serialization happens before any filesystem call, so on that path no directory is created, no\n * temp file exists, and the file already on disk is untouched.\n *\n * Atomicity is the rename's, so it is as strong as the filesystem's: on NFS, SMB or FUSE the\n * underlying writer emits a one-shot warning that the guarantee is weaker there.\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 async function writeVersionedJson<T>(\n path: string,\n data: T,\n currentVersion: number,\n): Promise<void> {\n const file: VersionedJsonFile<T> = {\n _schemaVersion: currentVersion,\n data,\n };\n await atomicWriteJson(path, file);\n}\n"]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { homedir } from 'os';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
|
|
4
|
+
// src/internal/persistence/paths.ts
|
|
5
|
+
var THEOKIT_DIR_LITERAL = ".theokit";
|
|
6
|
+
var CLAUDE_DIR_NAME = ".claude";
|
|
7
|
+
function getTheokitHome(cwd) {
|
|
8
|
+
const override = process.env.THEOKIT_HOME?.trim();
|
|
9
|
+
if (override !== void 0 && override.length > 0) {
|
|
10
|
+
return override;
|
|
11
|
+
}
|
|
12
|
+
return join(cwd, THEOKIT_DIR_LITERAL);
|
|
13
|
+
}
|
|
14
|
+
function projectConfigRoots(cwd) {
|
|
15
|
+
return [join(cwd, THEOKIT_DIR_LITERAL), join(cwd, CLAUDE_DIR_NAME)];
|
|
16
|
+
}
|
|
17
|
+
function pluginBundleRoots(cwd) {
|
|
18
|
+
return projectConfigRoots(cwd).map((root) => join(root, "plugins"));
|
|
19
|
+
}
|
|
20
|
+
function getProfilesRoot() {
|
|
21
|
+
return join(homedir(), THEOKIT_DIR_LITERAL, "profiles");
|
|
22
|
+
}
|
|
23
|
+
function displayTheokitHome(cwd) {
|
|
24
|
+
const resolved = getTheokitHome(cwd);
|
|
25
|
+
const home = homedir();
|
|
26
|
+
if (resolved === home) return "~";
|
|
27
|
+
if (resolved.startsWith(`${home}/`)) {
|
|
28
|
+
return `~${resolved.slice(home.length)}`;
|
|
29
|
+
}
|
|
30
|
+
return resolved;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export { displayTheokitHome, getProfilesRoot, getTheokitHome, pluginBundleRoots, projectConfigRoots };
|
|
34
|
+
//# sourceMappingURL=chunk-UFLD2HEV.js.map
|
|
35
|
+
//# sourceMappingURL=chunk-UFLD2HEV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/paths.ts"],"names":[],"mappings":";;;;AAuCA,IAAM,mBAAA,GAAsB,UAAA;AAG5B,IAAM,eAAA,GAAkB,SAAA;AAuBjB,SAAS,eAAe,GAAA,EAAqB;AAClD,EAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,YAAA,EAAc,IAAA,EAAK;AAChD,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,QAAA,CAAS,MAAA,GAAS,CAAA,EAAG;AACjD,IAAA,OAAO,QAAA;AAAA,EACT;AACA,EAAA,OAAO,IAAA,CAAK,KAAK,mBAAmB,CAAA;AACtC;AA6BO,SAAS,mBAAmB,GAAA,EAAuB;AACxD,EAAA,OAAO,CAAC,KAAK,GAAA,EAAK,mBAAmB,GAAG,IAAA,CAAK,GAAA,EAAK,eAAe,CAAC,CAAA;AACpE;AAeO,SAAS,kBAAkB,GAAA,EAAuB;AACvD,EAAA,OAAO,kBAAA,CAAmB,GAAG,CAAA,CAAE,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,IAAA,EAAM,SAAS,CAAC,CAAA;AACpE;AAeO,SAAS,eAAA,GAA0B;AACxC,EAAA,OAAO,IAAA,CAAK,OAAA,EAAQ,EAAG,mBAAA,EAAqB,UAAU,CAAA;AACxD;AAmBO,SAAS,mBAAmB,GAAA,EAAqB;AACtD,EAAA,MAAM,QAAA,GAAW,eAAe,GAAG,CAAA;AACnC,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,IAAI,QAAA,KAAa,MAAM,OAAO,GAAA;AAC9B,EAAA,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-UFLD2HEV.js","sourcesContent":["/**\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\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 this const\n * and looked answered, so \"is it read?\" returned five hits and nobody checked what they were.\n */\nconst THEOKIT_DIR_LITERAL = \".theokit\";\n\n/** The Claude Code CLI's project configuration directory. */\nconst CLAUDE_DIR_NAME = \".claude\";\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 * Every directory a project's configuration may be read from, in precedence order.\n *\n * `.theokit` first, then `.claude`. The order is the whole contract: a project that declares a\n * skill, agent or rule in both means the explicit namespace to win, and a caller merging these\n * 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 * Deliberately NOT affected by `THEOKIT_HOME`, and this is the one thing to remember about it.\n * That variable relocates cwd-anchored SDK *state* — sessions, the credential store. A project's\n * *configuration* is a property of the repository, not of where this SDK keeps its state, and the\n * loaders that read these directories have always anchored on `cwd` directly. Honouring the\n * override here would silently move where a project's agents and skills come from, which is a\n * behaviour change wearing the costume of a refactor.\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(cwd: string): string[] {\n return [join(cwd, THEOKIT_DIR_LITERAL), join(cwd, CLAUDE_DIR_NAME)];\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(cwd: string): string[] {\n return projectConfigRoots(cwd).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"]}
|
|
@@ -44,6 +44,27 @@ var DEFAULT_DISCOVERY_SPECS = [
|
|
|
44
44
|
followImports: false,
|
|
45
45
|
priority: 45
|
|
46
46
|
},
|
|
47
|
+
{
|
|
48
|
+
// Rules written for the Claude Code CLI. Measured 2026-08-26 over this repository's 32 rule
|
|
49
|
+
// files: none carries frontmatter, and `rules-frontmatter` already reads a file without it as
|
|
50
|
+
// `alwaysApply: true` — the format needed nothing, only a spec pointing at the directory.
|
|
51
|
+
//
|
|
52
|
+
// 47, not 46. Specs sort ascending and a context budget drops the tail first, so it must land
|
|
53
|
+
// AFTER `.theokit/rules` (45) — the explicit namespace should survive a squeeze the borrowed one
|
|
54
|
+
// does not. It must also leave a slot on BOTH sides: B-127 makes these numbers a public contract
|
|
55
|
+
// precisely so a consumer can place its own source between two defaults, and 46 would have left
|
|
56
|
+
// no room between 45 and itself. 47 keeps 46 free below and 48–49 free above.
|
|
57
|
+
//
|
|
58
|
+
// The reckoning B-127's docblock asks for: no published priority MOVES, so a consumer that chose
|
|
59
|
+
// 46, 48 or 49 is unaffected. A consumer that had chosen 47 now collides — that is the cost of
|
|
60
|
+
// an eighth default, paid once and recorded here rather than discovered later.
|
|
61
|
+
id: "claude-rules",
|
|
62
|
+
pattern: ".claude/rules/*.md",
|
|
63
|
+
scope: "globbed",
|
|
64
|
+
parser: "rules-frontmatter",
|
|
65
|
+
followImports: false,
|
|
66
|
+
priority: 47
|
|
67
|
+
},
|
|
47
68
|
{
|
|
48
69
|
id: "theokit-context",
|
|
49
70
|
pattern: ".theokit/context/*.md",
|
|
@@ -124,5 +145,5 @@ async function walkUpForGlob(cwd, pattern) {
|
|
|
124
145
|
}
|
|
125
146
|
|
|
126
147
|
export { DEFAULT_DISCOVERY_SPECS, findGitRoot, isSafePattern, walkUpForFile, walkUpForGlob };
|
|
127
|
-
//# sourceMappingURL=chunk-
|
|
128
|
-
//# sourceMappingURL=chunk-
|
|
148
|
+
//# sourceMappingURL=chunk-WFC26L6Y.js.map
|
|
149
|
+
//# sourceMappingURL=chunk-WFC26L6Y.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/context/context-discovery.ts"],"names":[],"mappings":";;;;;AAsFO,IAAM,uBAAA,GAAwD;AAAA,EACnE;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAAA,IACR,aAAA,EAAe,KAAA;AAAA,IACf,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAAA,IACR,aAAA,EAAe,IAAA;AAAA,IACf,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAAA,IACR,aAAA,EAAe,IAAA;AAAA,IACf,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;AAAA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s D150 / D151).\n *\n * Discovers context files via three scopes:\n * - `cwd-only` — single dir, single path lookup\n * - `git-root-walk` — walk cwd → git-root, collect every directory's match\n * (nearest-first ordering)\n * - `globbed` — glob pattern relative to cwd (e.g. `.cursor/rules/*.mdc`)\n *\n * Pure `existsSync` checks — **no `.gitignore` parsing** (EC-A, KISS) and\n * **no invented `.theokitignore`** (EC-B). Paths normalized via\n * `realpath` to dedup symlink chains pointing to the same physical file\n * (EC-F). Git worktrees work transparently because `.git` exists as a\n * file in that case (EC-N).\n *\n * @internal\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { glob } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\n/** Single filename (\"AGENTS.md\") or relative glob (\".cursor/rules/*.mdc\"). */\nexport type DiscoveryScope = \"cwd-only\" | \"git-root-walk\" | \"globbed\";\n\n/** Parser to apply once file is read. */\nexport type DiscoveryParser = \"plain-markdown\" | \"mdc\" | \"frontmatter-zod\" | \"rules-frontmatter\";\n\n/**\n * One kind of context file the runner knows how to find and read. The shipped registry is\n * `DEFAULT_DISCOVERY_SPECS`; a caller supplies its own array to change the set.\n *\n * `scope` decides how `pattern` is used and how many files a single spec can yield:\n * `cwd-only` looks for one path and stops, `git-root-walk` collects a match in every directory\n * from `cwd` up to the git root (nearest first), and `globbed` expands `pattern` as a glob\n * relative to `cwd`. So `pattern` is a filename for the first two and a glob for the third —\n * putting a glob on a walk scope silently finds nothing.\n *\n * `priority` orders the merged prompt, ascending, and is a plain number rather than an index, so\n * a new spec can be slotted between two existing ones. Lower means earlier and therefore more\n * general; later content wins on conflict.\n *\n * `parser` must match the file format — `plain-markdown` reads the whole file, `mdc` and\n * `rules-frontmatter` parse frontmatter and can DECLINE the file when its activation conditions\n * do not hold, and `frontmatter-zod` is the legacy path the runner currently skips entirely.\n *\n * `followImports` is honored only by `plain-markdown`, and turns `@path` directives in the body\n * into inlined content bounded by the import root. Setting it on a frontmatter parser does\n * nothing.\n *\n * `id` names the source in `<source name=\"\">` and in telemetry. When one spec matches files in\n * several directories, the runner suffixes it with the path relative to the git root to keep them\n * apart.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport interface DiscoverySpec {\n /** Stable identifier — used as `<source name=\"\">` and telemetry key. */\n readonly id: string;\n /** Priority for merge (lower = earlier in prompt). */\n readonly priority: number;\n /** Filename (cwd-only/git-root-walk) or glob (globbed). */\n readonly pattern: string;\n readonly scope: DiscoveryScope;\n readonly parser: DiscoveryParser;\n /** Whether to follow `@path` import directives (CLAUDE.md / GEMINI.md). */\n readonly followImports: boolean;\n}\n\n/**\n * The context files theokit looks for out of the box, in the order they are concatenated.\n *\n * Two things follow from the ordering. `AGENTS.md` comes first at priority 10 and `THEO.md` last,\n * so theokit-specific instruction wins over the vendor-neutral file on conflict. And the array is\n * consumed in the order written — the runner does not re-sort it — so a caller passing its own\n * array is responsible for keeping `priority` and array position consistent.\n *\n * `CLAUDE.md` and `GEMINI.md` are the only two entries with `followImports: true`, which means\n * they are the only files whose `@path` directives pull other files into the prompt. Those\n * imports cannot escape the import root.\n *\n * Frozen only by type: `ReadonlyArray` is a compile-time constraint, and the array and its\n * elements are not deep-frozen at runtime. Build a new array rather than mutating this one.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport const DEFAULT_DISCOVERY_SPECS: ReadonlyArray<DiscoverySpec> = [\n {\n id: \"AGENTS.md\",\n pattern: \"AGENTS.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 10,\n },\n {\n id: \"GEMINI.md\",\n pattern: \"GEMINI.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 20,\n },\n {\n id: \"CLAUDE.md\",\n pattern: \"CLAUDE.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 30,\n },\n {\n id: \"cursor-rules\",\n pattern: \".cursor/rules/*.mdc\",\n scope: \"globbed\",\n parser: \"mdc\",\n followImports: false,\n priority: 40,\n },\n {\n id: \"theokit-rules\",\n pattern: \".theokit/rules/*.md\",\n scope: \"globbed\",\n parser: \"rules-frontmatter\",\n followImports: false,\n priority: 45,\n },\n {\n // Rules written for the Claude Code CLI. Measured 2026-08-26 over this repository's 32 rule\n // files: none carries frontmatter, and `rules-frontmatter` already reads a file without it as\n // `alwaysApply: true` — the format needed nothing, only a spec pointing at the directory.\n //\n // 47, not 46. Specs sort ascending and a context budget drops the tail first, so it must land\n // AFTER `.theokit/rules` (45) — the explicit namespace should survive a squeeze the borrowed one\n // does not. It must also leave a slot on BOTH sides: B-127 makes these numbers a public contract\n // precisely so a consumer can place its own source between two defaults, and 46 would have left\n // no room between 45 and itself. 47 keeps 46 free below and 48–49 free above.\n //\n // The reckoning B-127's docblock asks for: no published priority MOVES, so a consumer that chose\n // 46, 48 or 49 is unaffected. A consumer that had chosen 47 now collides — that is the cost of\n // an eighth default, paid once and recorded here rather than discovered later.\n id: \"claude-rules\",\n pattern: \".claude/rules/*.md\",\n scope: \"globbed\",\n parser: \"rules-frontmatter\",\n followImports: false,\n priority: 47,\n },\n {\n id: \"theokit-context\",\n pattern: \".theokit/context/*.md\",\n scope: \"globbed\",\n parser: \"frontmatter-zod\",\n followImports: false,\n priority: 50,\n },\n {\n id: \"THEO.md\",\n pattern: \".theokit/THEO.md\",\n scope: \"cwd-only\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 60,\n },\n];\n\nconst SAFE_FILENAME = /^[a-zA-Z0-9_.\\-/*]+$/;\nconst TRAVERSAL_RE = /(^|\\/)\\.\\.(\\/|$)/;\n\n/**\n * Reject patterns that contain path traversal (`..`) or non-allowed\n * characters (D81 parity, EC-4).\n *\n * @internal\n */\nexport function isSafePattern(pattern: string): boolean {\n if (typeof pattern !== \"string\" || pattern.length === 0) return false;\n if (TRAVERSAL_RE.test(pattern)) return false;\n if (isAbsolute(pattern)) return false;\n return SAFE_FILENAME.test(pattern);\n}\n\n/**\n * Walk upward from `cwd` looking for the closest directory containing\n * a `.git` entry (file OR directory — worktrees use a `.git` FILE,\n * EC-N). Returns the absolute path of that directory, or `undefined`\n * when no git root exists at or above `cwd`.\n *\n * @internal\n */\nexport function findGitRoot(cwd: string): string | undefined {\n if (typeof cwd !== \"string\" || cwd.length === 0) return undefined;\n let current = resolve(cwd);\n // Guard against infinite loops on weird filesystems.\n for (let i = 0; i < 64; i += 1) {\n if (existsSync(join(current, \".git\"))) return current;\n const parent = dirname(current);\n if (parent === current) return undefined;\n current = parent;\n }\n return undefined;\n}\n\n/**\n * Walk `cwd` upward to `stopDir` (inclusive) collecting every existing\n * occurrence of `filename`. Returns absolute, realpath-deduped paths in\n * nearest-first order (innermost dir first).\n *\n * No `.gitignore` parsing (EC-A). Realpath collapses symlink chains\n * pointing to the same physical file (EC-F). Filesystem races (file\n * deleted mid-walk) are skipped silently (EC-5).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: walk-up loop combines validation + realpath dedup + FS-race handling + stopDir guard in a single bounded loop; splitting fragments the dedup invariant.\nexport function walkUpForFile(\n cwd: string,\n filename: string,\n stopDir: string | undefined,\n): string[] {\n if (!isSafePattern(filename)) {\n return [];\n }\n const start = resolve(cwd);\n const stop = stopDir !== undefined ? resolve(stopDir) : undefined;\n const found: string[] = [];\n const seenReal = new Set<string>();\n let current = start;\n // 64-level depth cap.\n for (let i = 0; i < 64; i += 1) {\n const candidate = join(current, filename);\n if (existsSync(candidate)) {\n let real: string;\n try {\n real = realpathSync(candidate);\n } catch {\n // FS race (deleted mid-walk) — skip.\n real = candidate;\n }\n if (!seenReal.has(real)) {\n seenReal.add(real);\n found.push(real);\n }\n }\n if (stop !== undefined && current === stop) break;\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return found;\n}\n\n/**\n * Glob-style discovery under `cwd` (e.g. `.cursor/rules/*.mdc`, `.theokit/rules/**\\/*.md`).\n * Returns absolute, lex-sorted paths.\n *\n * `*` matches within one path segment and `**` spans any depth, including zero — so\n * `.theokit/rules/**\\/*.md` finds `rules/top.md` as well as `rules/deep/nested/inner.md`, while\n * `.theokit/rules/*.md` keeps its flat meaning and finds only the first. That distinction is the\n * compatibility contract: every existing spec uses a single `*`, and widening it would silently\n * start absorbing nested files nobody chose to expose.\n *\n * ## Why this used to be flat, and what changed (B-119)\n *\n * The previous implementation split the pattern at its LAST `/`, treated the prefix as a literal\n * directory and did one `readdir` — documented as \"nested directories deferred to v2\" (EC-R). The\n * deferral was deliberate; what made it a defect was measured from a consumer. TheoCode's own rule\n * loader descends recursively, so migrating it onto the `theokit-rules` spec would have silently\n * dropped every nested rule — on the path that decides whether a repository's hooks execute. And a\n * pattern written to say so, `.theokit/rules/**\\/*.md`, resolved its directory part to a literal\n * `**` and matched NOTHING, not even the top-level file it matched before the globstar was added.\n *\n * ## Why the stdlib rather than a walker\n *\n * `fs.promises.glob` (Node ≥ 22, and this package requires ≥ 22.12) implements exactly these\n * semantics, verified against a fixture before adoption: `**\\/*.md` returns all three depths,\n * `*.md` returns one, and it emits no experimental warning. Writing a recursive walker here would\n * have been a third implementation of matching inside one package — the same duplication that let\n * the enumerator and the compiler in `context-glob.ts` disagree in the first place. `globToRegex`\n * stays where it belongs: deciding whether a rule APPLIES to a set of paths, which is a different\n * question from which files exist.\n *\n * `isSafePattern` still runs first and is unchanged, so `..` is refused before any I/O.\n *\n * @internal\n */\nexport async function walkUpForGlob(cwd: string, pattern: string): Promise<string[]> {\n if (!isSafePattern(pattern)) return [];\n const found: string[] = [];\n try {\n for await (const entry of glob(pattern, { cwd })) {\n found.push(resolve(cwd, entry));\n }\n } catch {\n // A pattern whose directory does not exist is the ordinary case — most projects have no\n // `.cursor/rules/`. Same outcome as matching nothing.\n return [];\n }\n // Sorted, because discovery order becomes prompt order and must not vary with the filesystem.\n //\n // The comparator is explicit and deliberately NOT `localeCompare`, which is the usual suggestion\n // for a bare `.sort()`. `localeCompare` orders by the machine's locale, so the same tree would\n // assemble a different prompt on a differently-configured machine — trading one source of\n // non-determinism for a subtler one. Code-unit ordering is what a bare `.sort()` already does for\n // strings; writing it out states the intent and keeps the result machine-independent.\n return found.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n"]}
|
|
@@ -1,10 +1,29 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var chunkAQO3NSRG_cjs = require('./chunk-AQO3NSRG.cjs');
|
|
3
4
|
var chunkIWBGCBR6_cjs = require('./chunk-IWBGCBR6.cjs');
|
|
4
5
|
var chunkK3FW2XZD_cjs = require('./chunk-K3FW2XZD.cjs');
|
|
6
|
+
var chunkNUKRL3I6_cjs = require('./chunk-NUKRL3I6.cjs');
|
|
5
7
|
var promises = require('fs/promises');
|
|
6
8
|
var path = require('path');
|
|
7
9
|
|
|
10
|
+
async function pluginBundleDirs(cwd) {
|
|
11
|
+
const dirs = [];
|
|
12
|
+
for (const root of chunkAQO3NSRG_cjs.pluginBundleRoots(cwd)) {
|
|
13
|
+
let entries;
|
|
14
|
+
try {
|
|
15
|
+
entries = await promises.readdir(root, { withFileTypes: true });
|
|
16
|
+
} catch {
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
for (const entry of entries) {
|
|
20
|
+
if (entry.isDirectory()) dirs.push(path.join(root, entry.name));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return dirs;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/internal/runtime/skills/subagents-loader.ts
|
|
8
27
|
async function loadSubagents(cwd, settingSourcesIncludeProject, inline) {
|
|
9
28
|
const result = {};
|
|
10
29
|
if (settingSourcesIncludeProject) {
|
|
@@ -21,17 +40,30 @@ async function loadSubagents(cwd, settingSourcesIncludeProject, inline) {
|
|
|
21
40
|
return result;
|
|
22
41
|
}
|
|
23
42
|
async function readProjectSubagents(cwd) {
|
|
24
|
-
const root = path.join(cwd, ".theokit", "agents");
|
|
25
|
-
const entries = await chunkIWBGCBR6_cjs.readWorkspaceDir(root, "subagents_read_error", "subagents directory");
|
|
26
43
|
const subagents = {};
|
|
44
|
+
for (const configRoot of chunkAQO3NSRG_cjs.projectConfigRoots(cwd)) {
|
|
45
|
+
await readSubagentsFrom(path.join(configRoot, "agents"), subagents);
|
|
46
|
+
}
|
|
47
|
+
for (const bundle of await pluginBundleDirs(cwd)) {
|
|
48
|
+
await readSubagentsFrom(path.join(bundle, "agents"), subagents);
|
|
49
|
+
}
|
|
50
|
+
return subagents;
|
|
51
|
+
}
|
|
52
|
+
async function readSubagentsFrom(root, subagents) {
|
|
53
|
+
const entries = await chunkIWBGCBR6_cjs.readWorkspaceDir(root, "subagents_read_error", "subagents directory");
|
|
27
54
|
for (const entry of entries) {
|
|
28
55
|
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
|
|
29
56
|
const path$1 = path.join(root, entry.name);
|
|
30
57
|
const raw = await promises.readFile(path$1, "utf8");
|
|
58
|
+
if (!hasFrontmatter(raw)) {
|
|
59
|
+
chunkNUKRL3I6_cjs.diag(`[theokit-sdk] ${entry.name} has no frontmatter \u2014 not an agent declaration, skipping`);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
31
62
|
const definition = parseSubagentMarkdown(raw, entry.name);
|
|
32
|
-
subagents[definition.name]
|
|
63
|
+
if (subagents[definition.name] === void 0) {
|
|
64
|
+
subagents[definition.name] = definition.definition;
|
|
65
|
+
}
|
|
33
66
|
}
|
|
34
|
-
return subagents;
|
|
35
67
|
}
|
|
36
68
|
var ACCEPTED_FIELDS = /* @__PURE__ */ new Set([
|
|
37
69
|
"name",
|
|
@@ -42,6 +74,10 @@ var ACCEPTED_FIELDS = /* @__PURE__ */ new Set([
|
|
|
42
74
|
"mcp",
|
|
43
75
|
"sandbox"
|
|
44
76
|
]);
|
|
77
|
+
var INERT_CLAUDE_CODE_FIELDS = /* @__PURE__ */ new Set([
|
|
78
|
+
/** The CLI's label colour for the agent. Presentation only. */
|
|
79
|
+
"color"
|
|
80
|
+
]);
|
|
45
81
|
function parseSubagentMarkdown(raw, filename) {
|
|
46
82
|
const { frontmatter, body } = splitFrontmatter(raw, filename);
|
|
47
83
|
const fields = parseFrontmatterFields(frontmatter);
|
|
@@ -62,6 +98,7 @@ function parseSubagentMarkdown(raw, filename) {
|
|
|
62
98
|
}
|
|
63
99
|
function rejectUnknownFields(fields, filename) {
|
|
64
100
|
for (const key of Object.keys(fields)) {
|
|
101
|
+
if (INERT_CLAUDE_CODE_FIELDS.has(key)) continue;
|
|
65
102
|
if (!ACCEPTED_FIELDS.has(key)) {
|
|
66
103
|
throw new chunkK3FW2XZD_cjs.ConfigurationError(
|
|
67
104
|
`Subagent ${filename}: unknown frontmatter field "${key}" (accepted: ${[...ACCEPTED_FIELDS].join(", ")})`,
|
|
@@ -113,6 +150,9 @@ function toStringList(v) {
|
|
|
113
150
|
}
|
|
114
151
|
return [];
|
|
115
152
|
}
|
|
153
|
+
function hasFrontmatter(raw) {
|
|
154
|
+
return /^---\s*\n/.test(raw);
|
|
155
|
+
}
|
|
116
156
|
function splitFrontmatter(raw, filename) {
|
|
117
157
|
const match = /^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/.exec(raw);
|
|
118
158
|
if (match === null) {
|
|
@@ -127,5 +167,6 @@ function parseFrontmatterFields(frontmatter) {
|
|
|
127
167
|
}
|
|
128
168
|
|
|
129
169
|
exports.loadSubagents = loadSubagents;
|
|
130
|
-
|
|
131
|
-
//# sourceMappingURL=chunk-
|
|
170
|
+
exports.pluginBundleDirs = pluginBundleDirs;
|
|
171
|
+
//# sourceMappingURL=chunk-WNTAPVU5.cjs.map
|
|
172
|
+
//# sourceMappingURL=chunk-WNTAPVU5.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/plugins/plugin-bundles.ts","../src/internal/runtime/skills/subagents-loader.ts"],"names":["pluginBundleRoots","readdir","join","projectConfigRoots","readWorkspaceDir","path","readFile","diag","ConfigurationError","parseS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AA;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-WNTAPVU5.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\";\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(cwd: string): Promise<string[]> {\n const dirs: string[] = [];\n for (const root of pluginBundleRoots(cwd)) {\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 { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\nimport { pluginBundleDirs } from \"../plugins/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): Promise<Record<string, AgentDefinition>> {\n const result: Record<string, AgentDefinition> = {};\n if (settingSourcesIncludeProject) {\n const projectAgents = await readProjectSubagents(cwd);\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(cwd: string): Promise<Record<string, AgentDefinition>> {\n const subagents: Record<string, AgentDefinition> = {};\n for (const configRoot of projectConfigRoots(cwd)) {\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)) {\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 subagents[definition.name] = definition.definition;\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\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 throw new ConfigurationError(\n `Subagent ${filename}: unknown frontmatter field \"${key}\" (accepted: ${[...ACCEPTED_FIELDS].join(\", \")})`,\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,6 +1,7 @@
|
|
|
1
1
|
import { LruEmbeddingCache } from './chunk-H73MEMQB.js';
|
|
2
2
|
import { splitFrontmatter, parseSimpleYaml } from './chunk-KVNWIAO4.js';
|
|
3
3
|
import { sanitizeIdentifier, safePathJoin, safeFilenameForId } from './chunk-QARJGQSA.js';
|
|
4
|
+
import { encodeProjectDir } from './chunk-FKMUFNQE.js';
|
|
4
5
|
import { openSqliteResilient, sanitizeFts5Query } from './chunk-CQ2TQ32Y.js';
|
|
5
6
|
import { withCwdMutex } from './chunk-Q5EWJPRY.js';
|
|
6
7
|
import { replaceFileAtomic } from './chunk-VF7EWVDG.js';
|
|
@@ -11,6 +12,7 @@ import { readdir, readFile, mkdir, stat } from 'fs/promises';
|
|
|
11
12
|
import { join, resolve, relative } from 'path';
|
|
12
13
|
import { mkdirSync } from 'fs';
|
|
13
14
|
import { createRequire } from 'module';
|
|
15
|
+
import { homedir } from 'os';
|
|
14
16
|
|
|
15
17
|
// src/internal/memory/escape-like-pattern.ts
|
|
16
18
|
function escapeLikePattern(query) {
|
|
@@ -363,23 +365,37 @@ var FACTS_HEADING = "## Facts";
|
|
|
363
365
|
function memoryDir(cwd) {
|
|
364
366
|
return join(cwd, ".theokit", "memory");
|
|
365
367
|
}
|
|
368
|
+
function memoryWriteDir(cwd, sessionDir) {
|
|
369
|
+
if (sessionDir === void 0 || sessionDir.trim().length === 0) return memoryDir(cwd);
|
|
370
|
+
return join(sessionDir, "projects", encodeProjectDir(cwd), "memory");
|
|
371
|
+
}
|
|
372
|
+
function claudeProjectMemoryDir(cwd) {
|
|
373
|
+
const home = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
374
|
+
const root = home !== void 0 && home.length > 0 ? home : join(homedir(), ".claude");
|
|
375
|
+
return join(root, "projects", encodeProjectDir(cwd), "memory");
|
|
376
|
+
}
|
|
366
377
|
function memoryMdPath(cwd) {
|
|
367
378
|
return join(memoryDir(cwd), "MEMORY.md");
|
|
368
379
|
}
|
|
369
380
|
function notesDir(cwd) {
|
|
370
381
|
return join(memoryDir(cwd), "notes");
|
|
371
382
|
}
|
|
372
|
-
async function readFactsFromMarkdown(cwd) {
|
|
373
|
-
let entries;
|
|
374
|
-
try {
|
|
375
|
-
entries = await readdir(memoryDir(cwd));
|
|
376
|
-
} catch {
|
|
377
|
-
return [];
|
|
378
|
-
}
|
|
383
|
+
async function readFactsFromMarkdown(cwd, sessionDir) {
|
|
379
384
|
const facts = [];
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
385
|
+
const roots = [
|
|
386
|
+
.../* @__PURE__ */ new Set([memoryDir(cwd), memoryWriteDir(cwd, sessionDir), claudeProjectMemoryDir(cwd)])
|
|
387
|
+
];
|
|
388
|
+
for (const dir of roots) {
|
|
389
|
+
let entries;
|
|
390
|
+
try {
|
|
391
|
+
entries = await readdir(dir);
|
|
392
|
+
} catch {
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
for (const entry of entries.sort()) {
|
|
396
|
+
const fact = await readMemoryFileIn(dir, entry);
|
|
397
|
+
if (fact !== void 0) facts.push(fact);
|
|
398
|
+
}
|
|
383
399
|
}
|
|
384
400
|
try {
|
|
385
401
|
facts.push(...parseFactsSection(await readFile(memoryMdPath(cwd), "utf8")));
|
|
@@ -387,24 +403,25 @@ async function readFactsFromMarkdown(cwd) {
|
|
|
387
403
|
}
|
|
388
404
|
return facts;
|
|
389
405
|
}
|
|
390
|
-
async function
|
|
406
|
+
async function readMemoryFileIn(dir, entry) {
|
|
391
407
|
if (!entry.endsWith(".md") || entry === "MEMORY.md") return void 0;
|
|
392
408
|
let raw;
|
|
393
409
|
try {
|
|
394
|
-
raw = await readFile(join(
|
|
410
|
+
raw = await readFile(join(dir, entry), "utf8");
|
|
395
411
|
} catch {
|
|
396
412
|
return void 0;
|
|
397
413
|
}
|
|
398
414
|
const parsed = parseMemoryFile(raw);
|
|
399
415
|
if (parsed === void 0) return void 0;
|
|
416
|
+
const body = parsed.body.trim();
|
|
400
417
|
return {
|
|
401
|
-
text: parsed.description,
|
|
418
|
+
text: body.length > 0 ? body : parsed.description,
|
|
402
419
|
...parsed.kind !== void 0 ? { kind: parsed.kind } : {},
|
|
403
420
|
...parsed.modified !== void 0 ? { modified: parsed.modified } : {}
|
|
404
421
|
};
|
|
405
422
|
}
|
|
406
|
-
function appendFactToMarkdown(cwd, fact) {
|
|
407
|
-
return withCwdMutex(
|
|
423
|
+
function appendFactToMarkdown(cwd, fact, targetDir = memoryDir(cwd)) {
|
|
424
|
+
return withCwdMutex(targetDir, async () => {
|
|
408
425
|
if (fact.kind !== void 0 && !MEMORY_KINDS.includes(fact.kind)) {
|
|
409
426
|
throw new ConfigurationError(
|
|
410
427
|
`Unknown memory fact kind "${fact.kind}". Expected one of: ${MEMORY_KINDS.join(", ")}.`,
|
|
@@ -413,9 +430,9 @@ function appendFactToMarkdown(cwd, fact) {
|
|
|
413
430
|
}
|
|
414
431
|
const text = redactSecrets(fact.text);
|
|
415
432
|
const name = slugForFact(text);
|
|
416
|
-
await mkdir(
|
|
433
|
+
await mkdir(targetDir, { recursive: true });
|
|
417
434
|
await replaceFileAtomic(
|
|
418
|
-
join(
|
|
435
|
+
join(targetDir, `${name}.md`),
|
|
419
436
|
renderMemoryFile({
|
|
420
437
|
name,
|
|
421
438
|
description: text,
|
|
@@ -424,13 +441,13 @@ function appendFactToMarkdown(cwd, fact) {
|
|
|
424
441
|
body: text
|
|
425
442
|
})
|
|
426
443
|
);
|
|
427
|
-
await replaceFileAtomic(
|
|
444
|
+
await replaceFileAtomic(join(targetDir, "MEMORY.md"), await nextIndex(targetDir, text, name));
|
|
428
445
|
});
|
|
429
446
|
}
|
|
430
|
-
async function nextIndex(
|
|
447
|
+
async function nextIndex(dir, text, name) {
|
|
431
448
|
let existing = "";
|
|
432
449
|
try {
|
|
433
|
-
existing = await readFile(
|
|
450
|
+
existing = await readFile(join(dir, "MEMORY.md"), "utf8");
|
|
434
451
|
} catch {
|
|
435
452
|
existing = "";
|
|
436
453
|
}
|
|
@@ -451,13 +468,13 @@ function parseFactsSection(raw) {
|
|
|
451
468
|
const block = nextHeading === -1 ? tail : tail.slice(0, nextHeading);
|
|
452
469
|
return block.split("\n").map((line) => line.trim()).filter((line) => line.startsWith("- ")).map((line) => line.slice(2).trim()).filter((body) => !INDEX_ENTRY.test(body)).map((body) => ({ text: body }));
|
|
453
470
|
}
|
|
454
|
-
async function readFacts(cwd, config) {
|
|
471
|
+
async function readFacts(cwd, config, memoryHome) {
|
|
455
472
|
if (!config.enabled) return [];
|
|
456
|
-
return readFactsFromMarkdown(cwd);
|
|
473
|
+
return readFactsFromMarkdown(cwd, memoryHome);
|
|
457
474
|
}
|
|
458
|
-
async function appendFact(cwd, config, fact) {
|
|
475
|
+
async function appendFact(cwd, config, fact, memoryHome) {
|
|
459
476
|
if (!config.enabled) return;
|
|
460
|
-
await appendFactToMarkdown(cwd, fact);
|
|
477
|
+
await appendFactToMarkdown(cwd, fact, memoryWriteDir(cwd, memoryHome));
|
|
461
478
|
}
|
|
462
479
|
var MAX_TURN_CHARS = 2e3;
|
|
463
480
|
function sessionsDir(cwd) {
|
|
@@ -1045,5 +1062,5 @@ var IndexManager = class _IndexManager {
|
|
|
1045
1062
|
};
|
|
1046
1063
|
|
|
1047
1064
|
export { IndexManager, LanceIndex, MEMORY_KINDS, appendFact, appendFactToMarkdown, defaultIndexPath, lanceStoragePath, legacyMemoryJsonPath, memoryDir, memoryMdPath, openMemoryDb, readFacts, readFactsFromMarkdown, writeSessionSummary };
|
|
1048
|
-
//# sourceMappingURL=chunk-
|
|
1049
|
-
//# sourceMappingURL=chunk-
|
|
1065
|
+
//# sourceMappingURL=chunk-ZA255A62.js.map
|
|
1066
|
+
//# sourceMappingURL=chunk-ZA255A62.js.map
|