theokit 0.78.1 → 0.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +5 -2
  2. package/dist/adapters/agent-mount.js +2 -2
  3. package/dist/{agent-IBDE65UJ.js → agent-OM47ZAIN.js} +2 -2
  4. package/dist/{build-WBQZWGED.js → build-TQAYRHJH.js} +4 -4
  5. package/dist/{chunk-3GM4GACM.js → chunk-2Z3GHQ64.js} +22 -9
  6. package/dist/{chunk-3GM4GACM.js.map → chunk-2Z3GHQ64.js.map} +1 -1
  7. package/dist/{chunk-7MCEJVGV.js → chunk-APUYC5BE.js} +2 -2
  8. package/dist/{chunk-ZWIKURA5.js → chunk-C5H2JHDW.js} +24 -11
  9. package/dist/chunk-C5H2JHDW.js.map +1 -0
  10. package/dist/{chunk-YM6ONZYE.js → chunk-CFJN5JHJ.js} +3 -3
  11. package/dist/{chunk-5UJRZC4J.js → chunk-H7Y4C2DO.js} +2 -2
  12. package/dist/{chunk-RAUYMVUO.js → chunk-JUJI3FZM.js} +81 -111
  13. package/dist/chunk-JUJI3FZM.js.map +1 -0
  14. package/dist/{chunk-PQWVT6JC.js → chunk-OS55GAM5.js} +9 -2
  15. package/dist/{chunk-PQWVT6JC.js.map → chunk-OS55GAM5.js.map} +1 -1
  16. package/dist/{chunk-IBZITTK7.js → chunk-QEVTZ3IH.js} +10 -3
  17. package/dist/chunk-QEVTZ3IH.js.map +1 -0
  18. package/dist/{chunk-FCBRWSBH.js → chunk-QKWBT7IY.js} +4 -4
  19. package/dist/{chunk-TQEE36VD.js → chunk-RN5NDLUS.js} +57 -45
  20. package/dist/{chunk-TQEE36VD.js.map → chunk-RN5NDLUS.js.map} +1 -1
  21. package/dist/{chunk-BDH5GKFZ.js → chunk-TF44PW3F.js} +43 -44
  22. package/dist/chunk-TF44PW3F.js.map +1 -0
  23. package/dist/{chunk-VSK5Y4ET.js → chunk-W55B6BRC.js} +2 -2
  24. package/dist/cli/index.js +12 -12
  25. package/dist/db-OHFGYI5J.js +120 -0
  26. package/dist/db-OHFGYI5J.js.map +1 -0
  27. package/dist/{dev-SCS6SPET.js → dev-CDCYJTDM.js} +7 -7
  28. package/dist/{docker-3ARABEZ2.js → docker-ED6W4ILB.js} +14 -9
  29. package/dist/docker-ED6W4ILB.js.map +1 -0
  30. package/dist/{generate-DAVXE5RV.js → generate-PFIEBKJC.js} +3 -3
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +3 -3
  33. package/dist/{info-AYTNH6YT.js → info-WP55WIB5.js} +3 -3
  34. package/dist/{load-config-YU5E76DL.js → load-config-2ND2LIRV.js} +3 -3
  35. package/dist/{mcp-UBGNYDMW.js → mcp-4OM4QSYT.js} +9 -6
  36. package/dist/mcp-4OM4QSYT.js.map +1 -0
  37. package/dist/{openapi-ICJB2RBE.js → openapi-POPJFXGI.js} +3 -3
  38. package/dist/{preview-USC6FF55.js → preview-C52WW62N.js} +3 -3
  39. package/dist/{routes-XYXXR72Z.js → routes-U6QTLLFA.js} +3 -3
  40. package/dist/{schema-2EAIJFWA.js → schema-YGNNE4H6.js} +2 -2
  41. package/dist/server/agent/index.d.ts +33 -69
  42. package/dist/server/agent/index.js +6 -2
  43. package/dist/server/cron/index.js +1 -1
  44. package/dist/server/index.d.ts +2 -1
  45. package/dist/server/index.js +7 -3
  46. package/dist/server/index.js.map +1 -1
  47. package/dist/{start-QCGCORTH.js → start-4NBJTPCR.js} +12 -10
  48. package/dist/start-4NBJTPCR.js.map +1 -0
  49. package/dist/vite-plugin/index.js +3 -3
  50. package/dist/{vite-plugin-JMWUVMP3.js → vite-plugin-CK5E4PA5.js} +6 -6
  51. package/package.json +6 -6
  52. package/dist/chunk-BDH5GKFZ.js.map +0 -1
  53. package/dist/chunk-IBZITTK7.js.map +0 -1
  54. package/dist/chunk-RAUYMVUO.js.map +0 -1
  55. package/dist/chunk-ZWIKURA5.js.map +0 -1
  56. package/dist/db-72T47G5S.js +0 -86
  57. package/dist/db-72T47G5S.js.map +0 -1
  58. package/dist/docker-3ARABEZ2.js.map +0 -1
  59. package/dist/mcp-UBGNYDMW.js.map +0 -1
  60. package/dist/start-QCGCORTH.js.map +0 -1
  61. /package/dist/{agent-IBDE65UJ.js.map → agent-OM47ZAIN.js.map} +0 -0
  62. /package/dist/{build-WBQZWGED.js.map → build-TQAYRHJH.js.map} +0 -0
  63. /package/dist/{chunk-7MCEJVGV.js.map → chunk-APUYC5BE.js.map} +0 -0
  64. /package/dist/{chunk-YM6ONZYE.js.map → chunk-CFJN5JHJ.js.map} +0 -0
  65. /package/dist/{chunk-5UJRZC4J.js.map → chunk-H7Y4C2DO.js.map} +0 -0
  66. /package/dist/{chunk-FCBRWSBH.js.map → chunk-QKWBT7IY.js.map} +0 -0
  67. /package/dist/{chunk-VSK5Y4ET.js.map → chunk-W55B6BRC.js.map} +0 -0
  68. /package/dist/{dev-SCS6SPET.js.map → dev-CDCYJTDM.js.map} +0 -0
  69. /package/dist/{generate-DAVXE5RV.js.map → generate-PFIEBKJC.js.map} +0 -0
  70. /package/dist/{info-AYTNH6YT.js.map → info-WP55WIB5.js.map} +0 -0
  71. /package/dist/{load-config-YU5E76DL.js.map → load-config-2ND2LIRV.js.map} +0 -0
  72. /package/dist/{openapi-ICJB2RBE.js.map → openapi-POPJFXGI.js.map} +0 -0
  73. /package/dist/{preview-USC6FF55.js.map → preview-C52WW62N.js.map} +0 -0
  74. /package/dist/{routes-XYXXR72Z.js.map → routes-U6QTLLFA.js.map} +0 -0
  75. /package/dist/{schema-2EAIJFWA.js.map → schema-YGNNE4H6.js.map} +0 -0
  76. /package/dist/{vite-plugin-JMWUVMP3.js.map → vite-plugin-CK5E4PA5.js.map} +0 -0
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+ import "tsx/esm";
3
+ import {
4
+ loadConfig
5
+ } from "./chunk-H7Y4C2DO.js";
6
+ import "./chunk-3QPVEJ7D.js";
7
+ import "./chunk-O5JZ6ROY.js";
8
+ import "./chunk-OS55GAM5.js";
9
+ import "./chunk-L4V5V2TI.js";
10
+ import {
11
+ storageSchema
12
+ } from "./chunk-MAJZ2L3A.js";
13
+
14
+ // src/cli/commands/db.ts
15
+ import { execFileSync } from "child_process";
16
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
17
+ import { createRequire } from "module";
18
+ import { dirname, join, resolve } from "path";
19
+ var VALID_ACTIONS = /* @__PURE__ */ new Set(["migrate", "push", "generate", "seed"]);
20
+ function resolveToolBin(cwd, tool) {
21
+ const req = createRequire(join(cwd, "package.json"));
22
+ let pkgPath;
23
+ try {
24
+ pkgPath = req.resolve(`${tool}/package.json`);
25
+ } catch {
26
+ throw new Error(`${tool} not found. Run: npm install -D ${tool}`);
27
+ }
28
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
29
+ const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.[tool];
30
+ if (rel === void 0) throw new Error(`${tool} has no "${tool}" bin in its package.json`);
31
+ return resolve(dirname(pkgPath), rel);
32
+ }
33
+ var runInherited = (tool, args, cwd) => {
34
+ execFileSync(process.execPath, [resolveToolBin(cwd, tool), ...args], { cwd, stdio: "inherit" });
35
+ };
36
+ function assertFileExists(cwd, relPath, hint) {
37
+ if (!existsSync(resolve(cwd, relPath))) {
38
+ throw new Error(`${relPath} not found. ${hint}`);
39
+ }
40
+ }
41
+ function assertBinExists(cwd, bin) {
42
+ const binPath = resolve(cwd, "node_modules", ".bin", bin);
43
+ if (!existsSync(binPath)) {
44
+ throw new Error(`${bin} not found. Run: npm install -D ${bin}`);
45
+ }
46
+ }
47
+ var DRIZZLE_KIT_VERBS = {
48
+ migrate: { args: ["drizzle-kit", "migrate"], message: "Migrations applied" },
49
+ push: { args: ["drizzle-kit", "push"], message: "Schema pushed to the database" },
50
+ generate: { args: ["drizzle-kit", "generate"], message: "Migration files generated" }
51
+ };
52
+ async function runSeed(cwd, run) {
53
+ const { serverDir, storage } = await loadConfig(cwd);
54
+ const seedPath = join(serverDir, "db", "seed.ts");
55
+ assertFileExists(cwd, seedPath, `Create ${seedPath} with your seed data.`);
56
+ console.log("\n \u25B8 Running seed...\n");
57
+ const preloadDir = resolve(cwd, "node_modules", ".cache", "theokit");
58
+ const preload = join(preloadDir, "seed-preload.mjs");
59
+ const hasStorage = storage !== void 0;
60
+ if (hasStorage) {
61
+ mkdirSync(preloadDir, { recursive: true });
62
+ const parsed = JSON.stringify(storageSchema.parse(storage));
63
+ writeFileSync(
64
+ preload,
65
+ `import { getStorageManager } from 'theokit/server/storage'
66
+ getStorageManager().configure(${parsed})
67
+ `
68
+ );
69
+ }
70
+ try {
71
+ run("tsx", hasStorage ? ["--import", preload, seedPath] : [seedPath], cwd);
72
+ } finally {
73
+ if (hasStorage) rmSync(preload, { force: true });
74
+ }
75
+ return "Database seeded successfully";
76
+ }
77
+ async function dbCommand(action, cwd, run = runInherited) {
78
+ if (!VALID_ACTIONS.has(action)) {
79
+ return {
80
+ status: "invalid_action",
81
+ message: `Unknown db action "${action}". Available: ${[...VALID_ACTIONS].join(", ")}`
82
+ };
83
+ }
84
+ const dbAction = action;
85
+ try {
86
+ if (dbAction === "seed") {
87
+ return { status: "success", message: await runSeed(cwd, run), action: dbAction };
88
+ }
89
+ const verb = DRIZZLE_KIT_VERBS[dbAction];
90
+ assertFileExists(cwd, "drizzle.config.ts", "Create a drizzle.config.ts for your project.");
91
+ assertBinExists(cwd, "drizzle-kit");
92
+ console.log(`
93
+ \u25B8 Running ${verb.args.join(" ")}...
94
+ `);
95
+ run("drizzle-kit", verb.args.slice(1), cwd);
96
+ return { status: "success", message: verb.message, action: dbAction };
97
+ } catch (err) {
98
+ const msg = err instanceof Error ? err.message : String(err);
99
+ return { status: "error", message: msg, action: dbAction };
100
+ }
101
+ }
102
+ async function dbCommandCli(action) {
103
+ const result = await dbCommand(action, process.cwd());
104
+ if (result.status === "success") {
105
+ console.log(`
106
+ \u2713 ${result.message}
107
+ `);
108
+ } else {
109
+ console.error(`
110
+ \u2717 ${result.message}
111
+ `);
112
+ process.exit(1);
113
+ }
114
+ }
115
+ export {
116
+ dbCommand,
117
+ dbCommandCli,
118
+ resolveToolBin
119
+ };
120
+ //# sourceMappingURL=db-OHFGYI5J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/db.ts"],"sourcesContent":["import { execFileSync } from 'node:child_process'\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join, resolve } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { storageSchema } from '../../config/schema.js'\n\ntype DbAction = 'migrate' | 'push' | 'generate' | 'seed'\n\nconst VALID_ACTIONS = new Set<DbAction>(['migrate', 'push', 'generate', 'seed'])\n\ninterface DbCommandResult {\n status: 'success' | 'error' | 'invalid_action'\n message: string\n action?: DbAction\n}\n\ntype DbTool = 'drizzle-kit' | 'tsx'\n\n/**\n * Runs one of the project's own tools, without a shell: the tool name and its argv, so a path with a\n * space or a quote is never parsed. Injected so a test can see the command without running it.\n */\ntype RunCommand = (tool: DbTool, args: readonly string[], cwd: string) => void\n\n/**\n * The JS entry of a tool installed in the project, read from its package.json `bin`. Running it with\n * `process.execPath` needs neither a shell nor `npx`/`.cmd` shims, which Node refuses to spawn\n * without a shell on Windows (CVE-2024-27980).\n */\nexport function resolveToolBin(cwd: string, tool: DbTool): string {\n const req = createRequire(join(cwd, 'package.json'))\n let pkgPath: string\n try {\n pkgPath = req.resolve(`${tool}/package.json`)\n } catch {\n throw new Error(`${tool} not found. Run: npm install -D ${tool}`)\n }\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[tool]\n if (rel === undefined) throw new Error(`${tool} has no \"${tool}\" bin in its package.json`)\n return resolve(dirname(pkgPath), rel)\n}\n\nconst runInherited: RunCommand = (tool, args, cwd) => {\n execFileSync(process.execPath, [resolveToolBin(cwd, tool), ...args], { cwd, stdio: 'inherit' })\n}\n\nfunction assertFileExists(cwd: string, relPath: string, hint: string): void {\n if (!existsSync(resolve(cwd, relPath))) {\n throw new Error(`${relPath} not found. ${hint}`)\n }\n}\n\nfunction assertBinExists(cwd: string, bin: string): void {\n const binPath = resolve(cwd, 'node_modules', '.bin', bin)\n if (!existsSync(binPath)) {\n throw new Error(`${bin} not found. Run: npm install -D ${bin}`)\n }\n}\n\n/**\n * Each verb runs the drizzle-kit command of the same name.\n *\n * `migrate` used to run `drizzle-kit push` (usetheokit/theokit#1021). Push diffs the schema straight\n * into the database: it never reads the files `generate` writes and keeps no\n * `drizzle.__drizzle_migrations` journal, so a deploy script calling `theokit db migrate` applied\n * an unreviewed diff with no record of it. `migrate` now applies the generated files, and the old\n * behaviour stays available, under its real name, as `push`.\n */\nconst DRIZZLE_KIT_VERBS = {\n migrate: { args: ['drizzle-kit', 'migrate'], message: 'Migrations applied' },\n push: { args: ['drizzle-kit', 'push'], message: 'Schema pushed to the database' },\n generate: { args: ['drizzle-kit', 'generate'], message: 'Migration files generated' },\n} as const\n\nasync function runSeed(cwd: string, run: RunCommand): Promise<string> {\n // The seed file lives under the configured `serverDir`; a hardcoded `server/` missed the\n // scaffold's `src/server` layout.\n const { serverDir, storage } = await loadConfig(cwd)\n const seedPath = join(serverDir, 'db', 'seed.ts')\n assertFileExists(cwd, seedPath, `Create ${seedPath} with your seed data.`)\n console.log('\\n ▸ Running seed...\\n')\n // #1439 — the seed is a bare child process, so `config.storage` never reached its storage manager\n // and any seed importing a `usePostgres('main', ...)` module threw \"Database not configured\".\n // A preload applies the parsed storage config through the project's own `theokit` instance.\n const preloadDir = resolve(cwd, 'node_modules', '.cache', 'theokit')\n const preload = join(preloadDir, 'seed-preload.mjs')\n const hasStorage = storage !== undefined\n if (hasStorage) {\n mkdirSync(preloadDir, { recursive: true })\n const parsed = JSON.stringify(storageSchema.parse(storage))\n writeFileSync(\n preload,\n `import { getStorageManager } from 'theokit/server/storage'\\ngetStorageManager().configure(${parsed})\\n`,\n )\n }\n try {\n run('tsx', hasStorage ? ['--import', preload, seedPath] : [seedPath], cwd)\n } finally {\n if (hasStorage) rmSync(preload, { force: true })\n }\n return 'Database seeded successfully'\n}\n\nexport async function dbCommand(\n action: string,\n cwd: string,\n run: RunCommand = runInherited,\n): Promise<DbCommandResult> {\n if (!VALID_ACTIONS.has(action as DbAction)) {\n return {\n status: 'invalid_action',\n message: `Unknown db action \"${action}\". Available: ${[...VALID_ACTIONS].join(', ')}`,\n }\n }\n\n const dbAction = action as DbAction\n\n try {\n if (dbAction === 'seed') {\n return { status: 'success', message: await runSeed(cwd, run), action: dbAction }\n }\n const verb = DRIZZLE_KIT_VERBS[dbAction]\n assertFileExists(cwd, 'drizzle.config.ts', 'Create a drizzle.config.ts for your project.')\n assertBinExists(cwd, 'drizzle-kit')\n console.log(`\\n ▸ Running ${verb.args.join(' ')}...\\n`)\n run('drizzle-kit', verb.args.slice(1), cwd)\n return { status: 'success', message: verb.message, action: dbAction }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { status: 'error', message: msg, action: dbAction }\n }\n}\n\nexport async function dbCommandCli(action: string): Promise<void> {\n const result = await dbCommand(action, process.cwd())\n if (result.status === 'success') {\n console.log(`\\n ✓ ${result.message}\\n`)\n } else {\n console.error(`\\n ✗ ${result.message}\\n`)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,YAAY,WAAW,cAAc,QAAQ,qBAAqB;AAC3E,SAAS,qBAAqB;AAC9B,SAAS,SAAS,MAAM,eAAe;AAOvC,IAAM,gBAAgB,oBAAI,IAAc,CAAC,WAAW,QAAQ,YAAY,MAAM,CAAC;AAqBxE,SAAS,eAAe,KAAa,MAAsB;AAChE,QAAM,MAAM,cAAc,KAAK,KAAK,cAAc,CAAC;AACnD,MAAI;AACJ,MAAI;AACF,cAA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AS,KAAK,SAAS,QAAQ,SAAS;AAAA,EACtE,SAAS,KAAK;AACZ,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,WAAO,EAAE,QAAQ,SAAS,SAAS,KAAK,QAAQ,SAAS;AAAA,EAC3D;AACF;AAEA,eAAsB,aAAa,QAA+B;AAChE,QAAM,SAAS,MAAM,UAAU,QAAQ,QAAQ,IAAI,CAAC;AACpD,MAAI,OAAO,WAAW,WAAW;AAC/B,YAAQ,IAAI;AAAA,WAAS,OAAO,OAAO;AAAA,CAAI;AAAA,EACzC,OAAO;AACL,YAAQ,MAAM;AAAA,WAAS,OAAO,OAAO;AAAA,CAAI;AACzC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":[]}
@@ -19,15 +19,15 @@ import {
19
19
  prepareJobBackend,
20
20
  resolveListenPort,
21
21
  startJobWorker
22
- } from "./chunk-ZWIKURA5.js";
22
+ } from "./chunk-C5H2JHDW.js";
23
23
  import {
24
24
  preflightNodeAndBindings
25
25
  } from "./chunk-KTMQUYED.js";
26
26
  import {
27
27
  theoPluginAsync
28
- } from "./chunk-YM6ONZYE.js";
29
- import "./chunk-VSK5Y4ET.js";
30
- import "./chunk-BDH5GKFZ.js";
28
+ } from "./chunk-CFJN5JHJ.js";
29
+ import "./chunk-W55B6BRC.js";
30
+ import "./chunk-TF44PW3F.js";
31
31
  import "./chunk-3PWQQWT6.js";
32
32
  import "./chunk-FDOOBTXJ.js";
33
33
  import "./chunk-MSSUMKFR.js";
@@ -44,12 +44,12 @@ import "./chunk-4WP7A7RX.js";
44
44
  import "./chunk-Z7CJHDLS.js";
45
45
  import {
46
46
  loadConfig
47
- } from "./chunk-5UJRZC4J.js";
47
+ } from "./chunk-H7Y4C2DO.js";
48
48
  import {
49
49
  loadEnv
50
50
  } from "./chunk-3QPVEJ7D.js";
51
51
  import "./chunk-O5JZ6ROY.js";
52
- import "./chunk-PQWVT6JC.js";
52
+ import "./chunk-OS55GAM5.js";
53
53
  import {
54
54
  orchestrateDev
55
55
  } from "./chunk-L4V5V2TI.js";
@@ -180,4 +180,4 @@ export {
180
180
  devCommand,
181
181
  startDevServer
182
182
  };
183
- //# sourceMappingURL=dev-SCS6SPET.js.map
183
+ //# sourceMappingURL=dev-CDCYJTDM.js.map
@@ -5,10 +5,10 @@ import {
5
5
  } from "./chunk-V3LMUQSB.js";
6
6
  import {
7
7
  loadConfig
8
- } from "./chunk-5UJRZC4J.js";
8
+ } from "./chunk-H7Y4C2DO.js";
9
9
  import "./chunk-3QPVEJ7D.js";
10
10
  import "./chunk-O5JZ6ROY.js";
11
- import "./chunk-PQWVT6JC.js";
11
+ import "./chunk-OS55GAM5.js";
12
12
  import "./chunk-L4V5V2TI.js";
13
13
  import "./chunk-MAJZ2L3A.js";
14
14
 
@@ -63,12 +63,16 @@ function generateDockerfile(input) {
63
63
  // Inside a container `localhost` answers nobody, the image's own health check included (#402).
64
64
  "ENV HOST=0.0.0.0",
65
65
  "ENV PORT=3000",
66
- `COPY --from=builder /app/${distDir} ./${distDir}`,
67
- ...copySources,
68
- ...input.hasConfigFile ? ["COPY --from=builder /app/theo.config.ts ./theo.config.ts"] : [],
69
- ...manifests.map((file) => `COPY --from=builder /app/${file} ./${file}`),
70
- "COPY --from=builder /app/node_modules ./node_modules",
66
+ `COPY --from=builder --chown=node:node /app/${distDir} ./${distDir}`,
67
+ ...copySources.map(
68
+ (line) => line.replace("--from=builder", "--from=builder --chown=node:node")
69
+ ),
70
+ ...input.hasConfigFile ? ["COPY --from=builder --chown=node:node /app/theo.config.ts ./theo.config.ts"] : [],
71
+ ...manifests.map((file) => `COPY --from=builder --chown=node:node /app/${file} ./${file}`),
72
+ "COPY --from=builder --chown=node:node /app/node_modules ./node_modules",
71
73
  "",
74
+ // The node image ships an unprivileged `node` user; without USER the server runs as root.
75
+ "USER node",
72
76
  "EXPOSE 3000",
73
77
  `CMD ["${THEOKIT_BIN}", "start"]`,
74
78
  ""
@@ -125,6 +129,7 @@ async function dockerCommand(options) {
125
129
  `);
126
130
  }
127
131
  export {
128
- dockerCommand
132
+ dockerCommand,
133
+ generateDockerfile
129
134
  };
130
- //# sourceMappingURL=docker-3ARABEZ2.js.map
135
+ //# sourceMappingURL=docker-ED6W4ILB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/docker.ts"],"sourcesContent":["import { existsSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { AUTHORED_AGENT_CONTEXT } from '../cleanup/cleanup.js'\n\nfunction detectPkgManager(cwd: string): PkgManager {\n if (existsSync(resolve(cwd, 'pnpm-lock.yaml'))) return 'pnpm'\n if (existsSync(resolve(cwd, 'yarn.lock'))) return 'yarn'\n return 'npm'\n}\n\ntype PkgManager = 'pnpm' | 'npm' | 'yarn'\n\ninterface DockerfileInput {\n readonly pkgManager: PkgManager\n /** Top-level directories holding the server and agent sources, e.g. `['src']` for the scaffold. */\n readonly sourceRoots: readonly string[]\n /** The configured build output directory, `.theokit` by default. */\n readonly distDir: string\n readonly hasConfigFile: boolean\n readonly hasPnpmWorkspace: boolean\n}\n\n/**\n * The installed CLI, by path. `npx theo build` asked the registry for a package named `theo`, an\n * unrelated design-tokens tool, then installed and ran it inside the image build (#1069). A path\n * into `node_modules/.bin` cannot fall back to the registry under any package manager.\n */\nconst THEOKIT_BIN = './node_modules/.bin/theokit'\n\n/**\n * The top-level directory a configured path lives in. The runner copies whole roots: the scaffold's\n * `src/server` imports `src/shared`, so copying only `serverDir` would leave an import dangling.\n */\nfunction topLevelDir(path: string): string {\n return path.replace(/^\\.\\//, '').split('/')[0]\n}\n\nexport function generateDockerfile(input: DockerfileInput): string {\n const { pkgManager, distDir } = input\n const installCmd = {\n pnpm: 'RUN corepack enable && pnpm install --frozen-lockfile',\n npm: 'RUN npm ci',\n yarn: 'RUN yarn install --frozen-lockfile',\n }[pkgManager]\n\n const lockfile = {\n pnpm: 'pnpm-lock.yaml',\n npm: 'package-lock.json',\n yarn: 'yarn.lock',\n }[pkgManager]\n\n // pnpm 10 reads `allowBuilds` from pnpm-workspace.yaml; installing without it leaves esbuild unbuilt.\n const manifests = [\n 'package.json',\n lockfile,\n ...(pkgManager === 'pnpm' && input.hasPnpmWorkspace ? ['pnpm-workspace.yaml'] : []),\n ]\n\n const copySources = [...new Set(input.sourceRoots)].map(\n (root) => `COPY --from=builder /app/${root} ./${root}`,\n )\n\n return [\n '# Generated by TheoKit',\n '# Multi-stage build for production',\n '',\n '# Stage 1: Build',\n 'FROM node:22-alpine AS builder',\n 'WORKDIR /app',\n `COPY ${manifests.join(' ')} ./`,\n installCmd,\n 'COPY . .',\n `RUN ${THEOKIT_BIN} build`,\n '',\n '# Stage 2: Production',\n 'FROM node:22-alpine AS runner',\n 'WORKDIR /app',\n 'ENV NODE_ENV=production',\n // Inside a container `localhost` answers nobody, the image's own health check included (#402).\n 'ENV HOST=0.0.0.0',\n 'ENV PORT=3000',\n `COPY --from=builder --chown=node:node /app/${distDir} ./${distDir}`,\n ...copySources.map((line) =>\n line.replace('--from=builder', '--from=builder --chown=node:node'),\n ),\n ...(input.hasConfigFile\n ? ['COPY --from=builder --chown=node:node /app/theo.config.ts ./theo.config.ts']\n : []),\n ...manifests.map((file) => `COPY --from=builder --chown=node:node /app/${file} ./${file}`),\n 'COPY --from=builder --chown=node:node /app/node_modules ./node_modules',\n '',\n // The node image ships an unprivileged `node` user; without USER the server runs as root.\n 'USER node',\n 'EXPOSE 3000',\n `CMD [\"${THEOKIT_BIN}\", \"start\"]`,\n '',\n ].join('\\n')\n}\n\n/**\n * `.theokit` is both the build output and the agent context (#1079). The context a person writes\n * (THEO.md, rules, personalities ...) goes into the image; local agent state such as memory and MCP\n * tokens stays out, and so does a stale local build, which the image rebuilds anyway.\n */\nfunction generateDockerignore(distDir = '.theokit'): string {\n return [\n 'node_modules',\n '.git',\n `${distDir}/*`,\n // A re-included directory brings its contents: Docker matches a pattern against every parent.\n ...AUTHORED_AGENT_CONTEXT.map((entry) => `!${distDir}/${entry}`),\n 'dist',\n '.env',\n '.env.*',\n '!.env.example',\n '*.log',\n '.DS_Store',\n '.vscode',\n '.idea',\n 'Dockerfile',\n '.dockerignore',\n '',\n ].join('\\n')\n}\n\nexport async function dockerCommand(options?: { force?: boolean }): Promise<void> {\n const cwd = process.cwd()\n const dockerfilePath = resolve(cwd, 'Dockerfile')\n const dockerignorePath = resolve(cwd, '.dockerignore')\n\n const pkgManager = detectPkgManager(cwd)\n const { serverDir, agentsDir, distDir } = await loadConfig(cwd)\n const dockerfile = generateDockerfile({\n pkgManager,\n sourceRoots: [topLevelDir(serverDir), topLevelDir(agentsDir)],\n distDir,\n hasConfigFile: existsSync(resolve(cwd, 'theo.config.ts')),\n hasPnpmWorkspace: existsSync(resolve(cwd, 'pnpm-workspace.yaml')),\n })\n\n // `wx` refuses an existing file in the same call that creates it. A separate exists check\n // followed by a write leaves a window, wider now that the config load sits between them.\n try {\n writeFileSync(dockerfilePath, dockerfile, { flag: options?.force ? 'w' : 'wx' })\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err\n console.log('\\n ⚠ Dockerfile already exists. Use --force to overwrite.\\n')\n return\n }\n writeFileSync(dockerignorePath, generateDockerignore(distDir))\n\n console.log(`\\n ✓ Generated Dockerfile (${pkgManager})`)\n console.log(` ✓ Generated .dockerignore`)\n console.log(`\\n Next steps:`)\n console.log(` docker build -t my-app .`)\n console.log(` docker run -p 3000:3000 my-app\\n`)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,YAAY,qBAAqB;AAC1C,SAAS,eAAe;AAKxB,SAAS,iBAAiB,KAAyB;AACjD,MAAI,WAAW,QAAQ,KAAK,gBAAgB,CAAC,EAAG,QAAO;AACvD,MAAI,WAAW,QAAQ,KAAK,WAAW,CAAC,EAAG,QAAO;AAClD,SAAO;AACT;AAmBA,IAAM,cAAc;AAMpB,SAAS,YAAY,MAAsB;AACzC,SAA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
16
16
  loadConfig
17
- } from "./chunk-5UJRZC4J.js";
17
+ } from "./chunk-H7Y4C2DO.js";
18
18
  import "./chunk-3QPVEJ7D.js";
19
19
  import "./chunk-O5JZ6ROY.js";
20
- import "./chunk-PQWVT6JC.js";
20
+ import "./chunk-OS55GAM5.js";
21
21
  import "./chunk-L4V5V2TI.js";
22
22
  import "./chunk-MAJZ2L3A.js";
23
23
 
@@ -1068,4 +1068,4 @@ export {
1068
1068
  generate,
1069
1069
  generateCommand
1070
1070
  };
1071
- //# sourceMappingURL=generate-DAVXE5RV.js.map
1071
+ //# sourceMappingURL=generate-PFIEBKJC.js.map
package/dist/index.d.ts CHANGED
@@ -221,6 +221,7 @@ declare const theoConfigSchema: z.ZodObject<{
221
221
  pollIntervalMs: z.ZodDefault<z.ZodNumber>;
222
222
  batchSize: z.ZodDefault<z.ZodNumber>;
223
223
  lockSeconds: z.ZodDefault<z.ZodNumber>;
224
+ shutdownTimeoutMs: z.ZodDefault<z.ZodNumber>;
224
225
  }, z.core.$strip>>;
225
226
  }, z.core.$strip>>;
226
227
  storage: z.ZodOptional<z.ZodObject<{
package/dist/index.js CHANGED
@@ -8,11 +8,11 @@ import {
8
8
  scanRoutes,
9
9
  theoConfigSchema,
10
10
  theoPlugin
11
- } from "./chunk-IBZITTK7.js";
11
+ } from "./chunk-QEVTZ3IH.js";
12
12
  import "./chunk-7NRFZBAL.js";
13
13
  import "./chunk-SSYDEKWF.js";
14
14
  import "./chunk-SHBPXX5E.js";
15
- import "./chunk-7MCEJVGV.js";
15
+ import "./chunk-APUYC5BE.js";
16
16
  import "./chunk-4XZOUS5G.js";
17
17
  import "./chunk-OIGJOYX6.js";
18
18
  import "./chunk-U3SPBLJF.js";
@@ -39,7 +39,7 @@ import "./chunk-V6Y2SMRG.js";
39
39
  import "./chunk-ACKBVBUI.js";
40
40
  import "./chunk-IZ3TIL6K.js";
41
41
  import "./chunk-TRCJHFAX.js";
42
- import "./chunk-TQEE36VD.js";
42
+ import "./chunk-RN5NDLUS.js";
43
43
  import "./chunk-54BIQFP4.js";
44
44
  import "./chunk-ZICY2CD7.js";
45
45
  import "./chunk-YSJOZEI6.js";
@@ -5,10 +5,10 @@ import {
5
5
  } from "./chunk-47MM2JUK.js";
6
6
  import {
7
7
  loadConfig
8
- } from "./chunk-5UJRZC4J.js";
8
+ } from "./chunk-H7Y4C2DO.js";
9
9
  import "./chunk-3QPVEJ7D.js";
10
10
  import "./chunk-O5JZ6ROY.js";
11
- import "./chunk-PQWVT6JC.js";
11
+ import "./chunk-OS55GAM5.js";
12
12
  import "./chunk-L4V5V2TI.js";
13
13
  import "./chunk-MAJZ2L3A.js";
14
14
 
@@ -103,4 +103,4 @@ export {
103
103
  buildInfo,
104
104
  infoCommand
105
105
  };
106
- //# sourceMappingURL=info-AYTNH6YT.js.map
106
+ //# sourceMappingURL=info-WP55WIB5.js.map
@@ -3,14 +3,14 @@ import "tsx/esm";
3
3
  import {
4
4
  deepMerge,
5
5
  loadConfig
6
- } from "./chunk-5UJRZC4J.js";
6
+ } from "./chunk-H7Y4C2DO.js";
7
7
  import "./chunk-3QPVEJ7D.js";
8
8
  import "./chunk-O5JZ6ROY.js";
9
- import "./chunk-PQWVT6JC.js";
9
+ import "./chunk-OS55GAM5.js";
10
10
  import "./chunk-L4V5V2TI.js";
11
11
  import "./chunk-MAJZ2L3A.js";
12
12
  export {
13
13
  deepMerge,
14
14
  loadConfig
15
15
  };
16
- //# sourceMappingURL=load-config-YU5E76DL.js.map
16
+ //# sourceMappingURL=load-config-2ND2LIRV.js.map
@@ -2,11 +2,11 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  createAgentSsrLoader
5
- } from "./chunk-FCBRWSBH.js";
5
+ } from "./chunk-QKWBT7IY.js";
6
6
  import {
7
7
  extractAppResources,
8
8
  handleMcpJsonRpc
9
- } from "./chunk-BDH5GKFZ.js";
9
+ } from "./chunk-TF44PW3F.js";
10
10
  import "./chunk-4JRXZTVQ.js";
11
11
  import {
12
12
  scanAgents
@@ -19,7 +19,7 @@ import "./chunk-NF7LXSXZ.js";
19
19
  import { createInterface } from "readline";
20
20
 
21
21
  // src/server/agent/mcp-stdio.ts
22
- async function handleMcpStdioLine(line, mod, name, appResources = []) {
22
+ async function answerLine(line, respond) {
23
23
  const trimmed = line.trim();
24
24
  if (trimmed.length === 0) return null;
25
25
  let body;
@@ -32,10 +32,13 @@ async function handleMcpStdioLine(line, mod, name, appResources = []) {
32
32
  error: { code: -32700, message: "Parse error" }
33
33
  });
34
34
  }
35
- const response = await handleMcpJsonRpc(mod, name, body, appResources);
35
+ const response = await respond(body);
36
36
  const payload = await response.json();
37
37
  return JSON.stringify(payload);
38
38
  }
39
+ function handleMcpStdioLine(line, mod, name, appResources = []) {
40
+ return answerLine(line, (body) => handleMcpJsonRpc(mod, name, body, appResources));
41
+ }
39
42
  async function serveMcpStdio(mod, name, appResources, streams) {
40
43
  for await (const line of streams.lines) {
41
44
  const out = await handleMcpStdioLine(line, mod, name, appResources);
@@ -47,7 +50,7 @@ async function serveMcpStdio(mod, name, appResources, streams) {
47
50
  // src/cli/commands/mcp.ts
48
51
  async function mcpCommand(name, deps = {}) {
49
52
  const projectRoot = deps.projectRoot ?? process.cwd();
50
- const agentsDir = deps.agentsDir ?? (await (await import("./load-config-YU5E76DL.js")).loadConfig(projectRoot)).agentsDir;
53
+ const agentsDir = deps.agentsDir ?? (await (await import("./load-config-2ND2LIRV.js")).loadConfig(projectRoot)).agentsDir;
51
54
  const agent = scanAgents(projectRoot, agentsDir).find((a) => a.name === name);
52
55
  if (!agent) {
53
56
  const names = scanAgents(projectRoot, agentsDir).map((a) => a.name).join(", ");
@@ -76,4 +79,4 @@ async function mcpCommand(name, deps = {}) {
76
79
  export {
77
80
  mcpCommand
78
81
  };
79
- //# sourceMappingURL=mcp-UBGNYDMW.js.map
82
+ //# sourceMappingURL=mcp-4OM4QSYT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/mcp.ts","../src/server/agent/mcp-stdio.ts"],"sourcesContent":["/**\n * `theokit mcp <agent>` — expose a scanned agent as an MCP server over stdio.\n *\n * The stdio sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`): a desktop MCP client\n * (e.g. Claude Desktop) spawns this command and speaks newline-delimited JSON-RPC over the pipe.\n * It reuses the framework's OWN `serveMcpStdio` / `handleMcpJsonRpc` (no LLM call, no runtime — a\n * TRANSPORT, like the HTTP route). `deps` is injectable so the routing is tested without Vite/stdin.\n */\nimport { createInterface } from 'node:readline'\n\nimport { extractAppResources } from '../../server/agent/mcp-app-resources.js'\nimport { type StdioStreams, serveMcpStdio } from '../../server/agent/mcp-stdio.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\n\nimport { createAgentSsrLoader } from './agent.js'\n\ninterface McpCommandDeps {\n projectRoot?: string\n /** Load a TS agent module; defaults to the framework's Vite SSR loader (same transpile as dev). */\n loadModule?: (filePath: string) => Promise<Record<string, unknown>>\n /** stdio streams; defaults to `readline(process.stdin)` + `process.stdout`. Injected in tests. */\n streams?: StdioStreams\n /** Agents dir name (config `agentsDir`); defaults to the loaded config's value (\"agents\"). Tests inject it. */\n agentsDir?: string\n}\n\nexport async function mcpCommand(name: string, deps: McpCommandDeps = {}): Promise<void> {\n const projectRoot = deps.projectRoot ?? process.cwd()\n // #95 follow-up — resolve agents dir from config (default \"agents\") so `agentsDir` is honored here too.\n const agentsDir =\n deps.agentsDir ??\n (await (await import('../../config/load-config.js')).loadConfig(projectRoot)).agentsDir\n const agent = scanAgents(projectRoot, agentsDir).find((a) => a.name === name)\n if (!agent) {\n const names = scanAgents(projectRoot, agentsDir)\n .map((a) => a.name)\n .join(', ')\n throw new Error(\n `theokit mcp: agent '${name}' not found. Available: ${names || '(none in agents/)'}`,\n )\n }\n\n let loadModule = deps.loadModule\n let dispose: (() => Promise<void>) | undefined\n if (!loadModule) {\n const loader = await createAgentSsrLoader(projectRoot)\n loadModule = loader.load\n dispose = loader.dispose\n }\n\n const streams =\n deps.streams ??\n ({\n lines: createInterface({ input: process.stdin }),\n write: (line: string) => process.stdout.write(line),\n } satisfies StdioStreams)\n\n try {\n const mod = await loadModule(agent.filePath)\n await serveMcpStdio(mod, agent.name, extractAppResources(mod), streams)\n } finally {\n if (dispose) await dispose()\n }\n}\n","/**\n * MCP stdio transport (M16 follow-up) — expose a TheoKit agent as an MCP server over stdin/stdout,\n * the sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`). A desktop MCP client (e.g.\n * Claude Desktop) spawns `theokit mcp <agent>` and speaks newline-delimited JSON-RPC over the pipe.\n *\n * This is a TRANSPORT over the framework's OWN {@link handleMcpJsonRpc} — it reuses the exact handler\n * the HTTP route uses; it calls no LLM, spawns no MCP client, and reimplements no runtime (G2 /\n * sdk-runtime.md). Distinct from the SDK's MCP CLIENT stdio (which spawns external MCP servers via\n * `mcpServers` command/args) — that stays SDK-side. Here TheoKit is the SERVER. The framework-side\n * placement of this server-exposure transport is recorded in ADR-0042 (refining ADR-0040's M16 note).\n */\nimport type { CustomTool } from '@theokit/sdk'\n\nimport type { AppResource } from './mcp-app-resources.js'\nimport { handleMcpJsonRpc, handleMcpToolsJsonRpc } from './mcp-handler.js'\n\n/** Parse one line and answer it via `respond`; `null` for a blank line, `-32700` for bad JSON. */\nasync function answerLine(\n line: string,\n respond: (body: unknown) => Promise<Response>,\n): Promise<string | null> {\n const trimmed = line.trim()\n if (trimmed.length === 0) return null\n let body: unknown\n try {\n body = JSON.parse(trimmed)\n } catch {\n return JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error' },\n })\n }\n const response = await respond(body)\n const payload: unknown = await response.json()\n return JSON.stringify(payload)\n}\n\n/**\n * Handle one newline-delimited JSON-RPC line. Returns the response line to write to stdout, or\n * `null` for a blank line (nothing to emit). A malformed JSON line yields a `-32700` (Parse error)\n * envelope — never throws, so the stdio loop never dies on bad input.\n */\nexport function handleMcpStdioLine(\n line: string,\n mod: unknown,\n name: string,\n appResources: readonly AppResource[] = [],\n): Promise<string | null> {\n return answerLine(line, (body) => handleMcpJsonRpc(mod, name, body, appResources))\n}\n\n/** A minimal readable line source (an async iterable of lines) + a writable sink. */\nexport interface StdioStreams {\n /** Async iterable of newline-delimited input lines (e.g. `readline.createInterface({ input })`). */\n lines: AsyncIterable<string>\n /** Write a response line (the caller appends no newline). */\n write: (line: string) => void\n}\n\n/**\n * Drive the MCP stdio server loop: for each input line, dispatch via {@link handleMcpStdioLine} and\n * write the response line (with a trailing `\\n`). Returns when the input stream ends (EOF).\n */\nexport async function serveMcpStdio(\n mod: unknown,\n name: string,\n appResources: readonly AppResource[],\n streams: StdioStreams,\n): Promise<void> {\n for await (const line of streams.lines) {\n const out = await handleMcpStdioLine(line, mod, name, appResources)\n if (out !== null) streams.write(`${out}\\n`)\n }\n}\n\n/**\n * Stdio loop for a plain list of tools (no agent module), the sibling of {@link serveMcpStdio}.\n * No approval gate: whoever passes a tool in decides it may run unattended. Duplicate tool names\n * are refused (rejects) before any line is read.\n */\nexport async function serveMcpToolsStdio(\n tools: readonly CustomTool[],\n name: string,\n streams: StdioStreams,\n): Promise<void> {\n const respond = (body: unknown): Promise<Response> => handleMcpToolsJsonRpc(tools, name, body)\n // Validate eagerly so a duplicate fails the call, not the first request.\n await respond(null)\n for await (const line of streams.lines) {\n const out = await answerLine(line, respond)\n if (out !== null) streams.write(`${out}\\n`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,SAAS,uBAAuB;;;ACShC,eAAe,WACb,MACA,SACwB;AACxB,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAO,KAAK,UAAU;AAAA,MACpB,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,OAAO,EAAE,MAAM,QAAQ,SAAS,cAAc;AAAA,IAChD,CAAC;AAAA,EACH;AACA,Q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,MAAM,MAAM,WAAW,MAAM,QAAQ;AAC3C,UAAM,cAAc,KAAK,MAAM,MAAM,oBAAoB,GAAG,GAAG,OAAO;AAAA,EACxE,UAAE;AACA,QAAI,QAAS,OAAM,QAAQ;AAAA,EAC7B;AACF;","names":[]}
@@ -12,10 +12,10 @@ import "./chunk-4WP7A7RX.js";
12
12
  import "./chunk-Z7CJHDLS.js";
13
13
  import {
14
14
  loadConfig
15
- } from "./chunk-5UJRZC4J.js";
15
+ } from "./chunk-H7Y4C2DO.js";
16
16
  import "./chunk-3QPVEJ7D.js";
17
17
  import "./chunk-O5JZ6ROY.js";
18
- import "./chunk-PQWVT6JC.js";
18
+ import "./chunk-OS55GAM5.js";
19
19
  import "./chunk-L4V5V2TI.js";
20
20
  import "./chunk-MAJZ2L3A.js";
21
21
 
@@ -84,4 +84,4 @@ function emitOpenApiInMemory(manifest, config) {
84
84
  export {
85
85
  openapiCommand
86
86
  };
87
- //# sourceMappingURL=openapi-ICJB2RBE.js.map
87
+ //# sourceMappingURL=openapi-POPJFXGI.js.map
@@ -4,8 +4,8 @@ import "tsx/esm";
4
4
  // src/cli/commands/preview.ts
5
5
  async function defaultSteps() {
6
6
  const [{ buildCommand }, { startCommand }] = await Promise.all([
7
- import("./build-WBQZWGED.js"),
8
- import("./start-QCGCORTH.js")
7
+ import("./build-TQAYRHJH.js"),
8
+ import("./start-4NBJTPCR.js")
9
9
  ]);
10
10
  return {
11
11
  build: (opts) => buildCommand(opts),
@@ -20,4 +20,4 @@ async function previewCommand(options = {}, steps) {
20
20
  export {
21
21
  previewCommand
22
22
  };
23
- //# sourceMappingURL=preview-USC6FF55.js.map
23
+ //# sourceMappingURL=preview-C52WW62N.js.map
@@ -11,10 +11,10 @@ import {
11
11
  import "./chunk-Z7CJHDLS.js";
12
12
  import {
13
13
  loadConfig
14
- } from "./chunk-5UJRZC4J.js";
14
+ } from "./chunk-H7Y4C2DO.js";
15
15
  import "./chunk-3QPVEJ7D.js";
16
16
  import "./chunk-O5JZ6ROY.js";
17
- import "./chunk-PQWVT6JC.js";
17
+ import "./chunk-OS55GAM5.js";
18
18
  import "./chunk-L4V5V2TI.js";
19
19
  import "./chunk-MAJZ2L3A.js";
20
20
 
@@ -64,4 +64,4 @@ async function routesCommand() {
64
64
  export {
65
65
  routesCommand
66
66
  };
67
- //# sourceMappingURL=routes-XYXXR72Z.js.map
67
+ //# sourceMappingURL=routes-U6QTLLFA.js.map
@@ -2,7 +2,7 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  theoConfigSchema
5
- } from "./chunk-PQWVT6JC.js";
5
+ } from "./chunk-OS55GAM5.js";
6
6
  import "./chunk-L4V5V2TI.js";
7
7
  import {
8
8
  cacheSchema,
@@ -17,4 +17,4 @@ export {
17
17
  storageSchema,
18
18
  theoConfigSchema
19
19
  };
20
- //# sourceMappingURL=schema-2EAIJFWA.js.map
20
+ //# sourceMappingURL=schema-YGNNE4H6.js.map
@@ -3,6 +3,7 @@ import { C as CustomTool } from '../../define-agent-tool-aYYLpMeo.js';
3
3
  import { CustomTool as CustomTool$1 } from '@theokit/sdk';
4
4
  import { AcpTransport } from '@theokit/agents';
5
5
  export { AgentModule, InProcessApprovalRequest, InProcessApprovalRequiredError, InProcessAwaitApproval, StreamAgentTurnDeps, StreamAgentTurnInProcessInput, streamAgentTurnInProcess } from '@theokit/agents';
6
+ export { CodeModeApi, CodeModeConfig, CodeModePermission, CodeModePermissionDeniedError, Sandbox, createCodeMode } from '@theokit/agents/code-mode';
6
7
  import { V as VerifyFn, S as SubscribeFn } from '../../whatsapp-4W2eK2ij.js';
7
8
  export { P as ProviderDescriptor, R as ResolvedProvider, l as listProviders, a as registerProvider, b as resetProviderRegistry, r as resolveProvider, t as tryResolveProvider } from '../../provider-resolver-Cc9C3-Rb.js';
8
9
 
@@ -76,7 +77,11 @@ declare class NodeAcpTransport implements AcpToolTransport {
76
77
  private readonly listeners;
77
78
  /** Settles when the process has exited (or never started). */
78
79
  private readonly exited;
79
- constructor(command: string, args?: string[], cwd?: string);
80
+ constructor(command: string, args?: string[], cwd?: string,
81
+ /** The agent's whole environment. Omitted: the parent's. Given: only these variables. */
82
+ env?: Record<string, string | undefined>,
83
+ /** Receives what the agent writes to stderr. Omitted: it goes to the parent's stderr. */
84
+ onStderr?: (chunk: string) => void);
80
85
  send(line: string): void;
81
86
  subscribe(onData: (chunk: string) => void): void;
82
87
  onClose(listener: (error: AcpTransportClosedError) => void): void;
@@ -143,6 +148,15 @@ interface AcpToolConfig {
143
148
  args?: string[];
144
149
  /** Working directory for the spawned agent. */
145
150
  cwd?: string;
151
+ /**
152
+ * The spawned agent's whole environment: when given, the agent sees exactly these variables and
153
+ * none of the parent's (so channel tokens stay out of it). Omitted, it inherits `process.env`.
154
+ */
155
+ env?: Record<string, string | undefined>;
156
+ /**
157
+ * Receives what the agent writes to its stderr. Omitted, the agent's stderr is the parent's.
158
+ */
159
+ onStderr?: (chunk: string) => void;
146
160
  /** Tool name the model calls. */
147
161
  name: string;
148
162
  /** Tool description surfaced to the model. */
@@ -216,73 +230,6 @@ interface VendorAgentToolConfig {
216
230
  */
217
231
  declare function createVendorAgentTool(config: VendorAgentToolConfig): CustomTool;
218
232
 
219
- /**
220
- * M29 (ADR-0041) — `createCodeMode`: expose a set of tools to agent-authored code run inside an
221
- * ISOLATION boundary, so the agent composes tools programmatically instead of one call at a time.
222
- *
223
- * Security posture (the whole point of this feature):
224
- * - The isolation boundary (`sandbox`) is **injected**, never hand-rolled here (Top-risk 1). The app
225
- * supplies a vetted sandbox — isolated-vm, QuickJS-WASM, or a locked-down worker. TheoKit core
226
- * ships no VM and adds no sandbox dependency (same posture as the injected deploy adapter / the
227
- * M17 transport). `node:vm` is NOT a security boundary and MUST NOT be used as the sandbox.
228
- * - TheoKit owns the **restricted API** (only the declared tools are reachable from the code — no
229
- * `fs`, `process`, `require`, or network unless a declared, permission-gated tool provides it) and
230
- * the **mandatory permission gate**: every tool call from the code passes `onPermissionRequest`
231
- * first, and there is NO default-allow (mirrors M17 `onPermissionRequest`).
232
- *
233
- * Threat model (summary): a malicious model could author code that (a) calls a dangerous tool, or
234
- * (b) tries to reach a host capability. (a) is stopped by the permission gate (deny → the API call
235
- * throws). (b) is stopped by the injected sandbox (the restricted API is the ONLY surface the code
236
- * sees). If the app injects a weak sandbox, (b) is on the app — hence the vetted-sandbox requirement.
237
- */
238
-
239
- /** The restricted API handed to sandboxed code: declared tool names → permission-gated callables. */
240
- type CodeModeApi = Record<string, (args: unknown) => Promise<unknown>>;
241
- /** The injected isolation boundary. The app supplies a vetted implementation. */
242
- interface Sandbox {
243
- /** Run `code` with access to ONLY `api` (the restricted tool surface). Resolve the code's result. */
244
- run(code: string, api: CodeModeApi): Promise<unknown>;
245
- }
246
- /** A permission decision for one tool call from sandboxed code. */
247
- interface CodeModePermission {
248
- granted: boolean;
249
- /** Optional reason surfaced to the model on denial. */
250
- reason?: string;
251
- }
252
- interface CodeModeConfig {
253
- /** The tools reachable from the code (the restricted API). */
254
- tools: CustomTool[];
255
- /** The injected isolation boundary (vetted sandbox — NEVER node:vm). */
256
- sandbox: Sandbox;
257
- /**
258
- * REQUIRED — decide each tool call the code attempts. Security by default: NO default-allow.
259
- * Return `{ granted }` (may be async). Mirrors M17 `onPermissionRequest`.
260
- */
261
- onPermissionRequest: (req: {
262
- tool: string;
263
- args: unknown;
264
- }) => CodeModePermission | Promise<CodeModePermission>;
265
- /** Tool name the model calls (default `run_code`). */
266
- name?: string;
267
- /** Tool description surfaced to the model. */
268
- description?: string;
269
- }
270
- /** Thrown when the permission gate denies a tool call from sandboxed code. */
271
- declare class CodeModePermissionDeniedError extends Error {
272
- constructor(tool: string, reason?: string);
273
- }
274
- /**
275
- * Build a code-mode tool + its generated model instructions (M40 / ADR-0049). Fails fast if
276
- * `onPermissionRequest` or `sandbox` is missing (security by default). `tool` takes `{ code }`,
277
- * assembles the permission-gated restricted API from `tools`, runs the code in the injected sandbox,
278
- * and returns the code's result. `instructions` (add it to the agent's system prompt) teaches the
279
- * model the sandboxed-code contract + the available `api.<name>(input)` calls.
280
- */
281
- declare function createCodeMode(config: CodeModeConfig): {
282
- tool: CustomTool;
283
- instructions: string;
284
- };
285
-
286
233
  /**
287
234
  * M27 (ADR-0041) — channel webhook routes: `POST /api/agents/<name>/channels/<platform>/webhook`.
288
235
  *
@@ -428,5 +375,22 @@ interface StdioStreams {
428
375
  * write the response line (with a trailing `\n`). Returns when the input stream ends (EOF).
429
376
  */
430
377
  declare function serveMcpStdio(mod: unknown, name: string, appResources: readonly AppResource[], streams: StdioStreams): Promise<void>;
378
+ /**
379
+ * Stdio loop for a plain list of tools (no agent module), the sibling of {@link serveMcpStdio}.
380
+ * No approval gate: whoever passes a tool in decides it may run unattended. Duplicate tool names
381
+ * are refused (rejects) before any line is read.
382
+ */
383
+ declare function serveMcpToolsStdio(tools: readonly CustomTool$1[], name: string, streams: StdioStreams): Promise<void>;
384
+
385
+ /**
386
+ * Handle one MCP JSON-RPC request for a plain list of tools (no agent module). Same JSON-RPC
387
+ * handling as {@link handleMcpJsonRpc}; advertises `capabilities.tools` only (no resources).
388
+ *
389
+ * There is NO approval gate: a list of tools carries no human-approval policy, so none is refused as
390
+ * "requires human approval". Whoever passes a tool in decides it may run unattended.
391
+ *
392
+ * @throws when two tools share a name (checked when called, before any request is answered).
393
+ */
394
+ declare function handleMcpToolsJsonRpc(tools: readonly CustomTool$1[], name: string, body: unknown): Promise<Response>;
431
395
 
432
- export { AcpRequestTimeoutError, type AcpToolConfig, type AcpToolTransport, AcpTransportClosedError, AcpTurnStoppedError, type AppResource, type AppResourceInput, type ChannelMessage, type ChannelWebhookConfig, type CodeModeApi, type CodeModeConfig, type CodeModePermission, CodeModePermissionDeniedError, DEFAULT_ACP_TIMEOUT_MS, type McpResourceContents, type McpResourceDescriptor, NodeAcpTransport, type Sandbox, type StdioStreams, type VendorAgentClient, type VendorAgentToolConfig, type WorkflowLike, type WorkflowToolConfig, buildResourceDescriptors, createACPTool, createCodeMode, createVendorAgentTool, createWorkflowTool, defineAppResource, extractAppResources, handleChannelWebhook, handleMcpStdioLine, isChannelPath, parseChannelPath, readAppResource, serveMcpStdio };
396
+ export { AcpRequestTimeoutError, type AcpToolConfig, type AcpToolTransport, AcpTransportClosedError, AcpTurnStoppedError, type AppResource, type AppResourceInput, type ChannelMessage, type ChannelWebhookConfig, DEFAULT_ACP_TIMEOUT_MS, type McpResourceContents, type McpResourceDescriptor, NodeAcpTransport, type StdioStreams, type VendorAgentClient, type VendorAgentToolConfig, type WorkflowLike, type WorkflowToolConfig, buildResourceDescriptors, createACPTool, createVendorAgentTool, createWorkflowTool, defineAppResource, extractAppResources, handleChannelWebhook, handleMcpStdioLine, handleMcpToolsJsonRpc, isChannelPath, parseChannelPath, readAppResource, serveMcpStdio, serveMcpToolsStdio };