theokit 0.19.1 → 0.19.3
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/dist/{actions-virtual-module-J3XSNY6L.js → actions-virtual-module-JB5ZTS5U.js} +2 -2
- package/dist/{actions-virtual-module-HD3D75C2.js → actions-virtual-module-Z2IXNF72.js} +3 -3
- package/dist/{agent-5UMCZYY4.js → agent-LFS3MXL7.js} +3 -3
- package/dist/{agents-typed-client-LQ36PCHL.js → agents-typed-client-2K3UAOUF.js} +2 -2
- package/dist/agents-typed-client-2K3UAOUF.js.map +1 -0
- package/dist/{agents-typed-client-D3LXWGCF.js → agents-typed-client-DPFVM2OY.js} +2 -2
- package/dist/agents-typed-client-DPFVM2OY.js.map +1 -0
- package/dist/{app-typed-client-OTXG3VZB.js → app-typed-client-VMSRQGKL.js} +2 -2
- package/dist/{app-typed-client-X6WKTFX2.js → app-typed-client-YCQC3MZ7.js} +3 -3
- package/dist/{build-QGHSA7FT.js → build-B675HLFR.js} +7 -7
- package/dist/build-B675HLFR.js.map +1 -0
- package/dist/{chunk-5VNZ5EG3.js → chunk-5YBUPJC2.js} +12 -7
- package/dist/{chunk-5VNZ5EG3.js.map → chunk-5YBUPJC2.js.map} +1 -1
- package/dist/{chunk-567NA7Y6.js → chunk-AFVTEAES.js} +2 -2
- package/dist/{chunk-YJAUJXZS.js → chunk-GSO77FSM.js} +7 -1
- package/dist/chunk-GSO77FSM.js.map +1 -0
- package/dist/{chunk-X53XXQCX.js → chunk-QSLNS5EZ.js} +33 -20
- package/dist/chunk-QSLNS5EZ.js.map +1 -0
- package/dist/{chunk-AKTGTUU5.js → chunk-RKDH4DWL.js} +5 -5
- package/dist/chunk-RKDH4DWL.js.map +1 -0
- package/dist/{chunk-34YQOXGM.js → chunk-TERFLG67.js} +3 -3
- package/dist/chunk-TERFLG67.js.map +1 -0
- package/dist/{chunk-N3WK6MKO.js → chunk-UGK6KR4D.js} +28 -21
- package/dist/chunk-UGK6KR4D.js.map +1 -0
- package/dist/{chunk-TIZBKEDV.js → chunk-YJWEADAW.js} +4 -4
- package/dist/chunk-YJWEADAW.js.map +1 -0
- package/dist/cli/index.js +8 -8
- package/dist/{dev-HBXSZSDL.js → dev-ORWXOTNX.js} +10 -6
- package/dist/dev-ORWXOTNX.js.map +1 -0
- package/dist/{dev-emit-YSQ7SMXA.js → dev-emit-5FVWJIKR.js} +2 -2
- package/dist/{dev-emit-M4KBDBB6.js → dev-emit-EFQRBVYS.js} +3 -3
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -2
- package/dist/{info-7PE2PZJI.js → info-2OOXFTJX.js} +3 -3
- package/dist/{internal-api-IBZ4QZAC.js → internal-api-KPULK7ZK.js} +2 -2
- package/dist/{internal-api-U3ARINWN.js → internal-api-Y5REPVUS.js} +3 -3
- package/dist/{load-config-JKYO5RFK.js → load-config-3EAQTXPH.js} +3 -3
- package/dist/{mcp-VWUOA7T7.js → mcp-MQTG6IS4.js} +6 -5
- package/dist/mcp-MQTG6IS4.js.map +1 -0
- package/dist/{openapi-PAXSR4UA.js → openapi-ERYWAT3A.js} +5 -5
- package/dist/{routes-WKG3UKDX.js → routes-TJQIXCOS.js} +3 -3
- package/dist/{schema-7CAY6IZR.js → schema-LYOLNHZ7.js} +2 -2
- package/dist/server/index.js +1 -1
- package/dist/server/scan/index.d.ts +1 -1
- package/dist/server/scan/index.js +1 -1
- package/dist/{start-A5BPZ3KH.js → start-ILT6E25Q.js} +11 -11
- package/dist/start-ILT6E25Q.js.map +1 -0
- package/dist/vite-plugin/index.d.ts +13 -0
- package/dist/vite-plugin/index.js +2 -2
- package/dist/{vite-plugin-QOCVYPFI.js → vite-plugin-WIJ5RMQQ.js} +6 -6
- package/package.json +1 -1
- package/dist/agents-typed-client-D3LXWGCF.js.map +0 -1
- package/dist/agents-typed-client-LQ36PCHL.js.map +0 -1
- package/dist/build-QGHSA7FT.js.map +0 -1
- package/dist/chunk-34YQOXGM.js.map +0 -1
- package/dist/chunk-AKTGTUU5.js.map +0 -1
- package/dist/chunk-N3WK6MKO.js.map +0 -1
- package/dist/chunk-TIZBKEDV.js.map +0 -1
- package/dist/chunk-X53XXQCX.js.map +0 -1
- package/dist/chunk-YJAUJXZS.js.map +0 -1
- package/dist/dev-HBXSZSDL.js.map +0 -1
- package/dist/mcp-VWUOA7T7.js.map +0 -1
- package/dist/start-A5BPZ3KH.js.map +0 -1
- /package/dist/{actions-virtual-module-J3XSNY6L.js.map → actions-virtual-module-JB5ZTS5U.js.map} +0 -0
- /package/dist/{actions-virtual-module-HD3D75C2.js.map → actions-virtual-module-Z2IXNF72.js.map} +0 -0
- /package/dist/{agent-5UMCZYY4.js.map → agent-LFS3MXL7.js.map} +0 -0
- /package/dist/{app-typed-client-OTXG3VZB.js.map → app-typed-client-VMSRQGKL.js.map} +0 -0
- /package/dist/{app-typed-client-X6WKTFX2.js.map → app-typed-client-YCQC3MZ7.js.map} +0 -0
- /package/dist/{chunk-567NA7Y6.js.map → chunk-AFVTEAES.js.map} +0 -0
- /package/dist/{dev-emit-YSQ7SMXA.js.map → dev-emit-5FVWJIKR.js.map} +0 -0
- /package/dist/{dev-emit-M4KBDBB6.js.map → dev-emit-EFQRBVYS.js.map} +0 -0
- /package/dist/{info-7PE2PZJI.js.map → info-2OOXFTJX.js.map} +0 -0
- /package/dist/{internal-api-IBZ4QZAC.js.map → internal-api-KPULK7ZK.js.map} +0 -0
- /package/dist/{internal-api-U3ARINWN.js.map → internal-api-Y5REPVUS.js.map} +0 -0
- /package/dist/{load-config-JKYO5RFK.js.map → load-config-3EAQTXPH.js.map} +0 -0
- /package/dist/{openapi-PAXSR4UA.js.map → openapi-ERYWAT3A.js.map} +0 -0
- /package/dist/{routes-WKG3UKDX.js.map → routes-TJQIXCOS.js.map} +0 -0
- /package/dist/{schema-7CAY6IZR.js.map → schema-LYOLNHZ7.js.map} +0 -0
- /package/dist/{vite-plugin-QOCVYPFI.js.map → vite-plugin-WIJ5RMQQ.js.map} +0 -0
|
@@ -5,7 +5,7 @@ import "./chunk-VMEWD57H.js";
|
|
|
5
5
|
import "./chunk-JQSKBMXP.js";
|
|
6
6
|
import {
|
|
7
7
|
scanServerActionsEnriched
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-RKDH4DWL.js";
|
|
9
9
|
import "./chunk-WSJKACWB.js";
|
|
10
10
|
import "./chunk-JBCHWRKF.js";
|
|
11
11
|
import "./chunk-C3ZZ56YZ.js";
|
|
@@ -221,4 +221,4 @@ export const actions = manifest
|
|
|
221
221
|
export {
|
|
222
222
|
actionsVirtualModule
|
|
223
223
|
};
|
|
224
|
-
//# sourceMappingURL=actions-virtual-module-
|
|
224
|
+
//# sourceMappingURL=actions-virtual-module-JB5ZTS5U.js.map
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import "./chunk-KXA37ONC.js";
|
|
4
4
|
import "./chunk-WR4F4EEZ.js";
|
|
5
|
-
import "./chunk-
|
|
6
|
-
import "./chunk-
|
|
5
|
+
import "./chunk-YJWEADAW.js";
|
|
6
|
+
import "./chunk-TERFLG67.js";
|
|
7
7
|
import {
|
|
8
8
|
scanServerActionsEnriched
|
|
9
9
|
} from "./chunk-FRUEDJFX.js";
|
|
@@ -211,4 +211,4 @@ export const actions = manifest
|
|
|
211
211
|
export {
|
|
212
212
|
actionsVirtualModule
|
|
213
213
|
};
|
|
214
|
-
//# sourceMappingURL=actions-virtual-module-
|
|
214
|
+
//# sourceMappingURL=actions-virtual-module-Z2IXNF72.js.map
|
|
@@ -3,13 +3,13 @@ import "tsx/esm";
|
|
|
3
3
|
import {
|
|
4
4
|
agentCommand,
|
|
5
5
|
createAgentSsrLoader
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-5YBUPJC2.js";
|
|
7
7
|
import "./chunk-M6NMS5LR.js";
|
|
8
8
|
import "./chunk-GDN3PXFH.js";
|
|
9
|
-
import "./chunk-
|
|
9
|
+
import "./chunk-TERFLG67.js";
|
|
10
10
|
import "./chunk-P37RZRFV.js";
|
|
11
11
|
export {
|
|
12
12
|
agentCommand,
|
|
13
13
|
createAgentSsrLoader
|
|
14
14
|
};
|
|
15
|
-
//# sourceMappingURL=agent-
|
|
15
|
+
//# sourceMappingURL=agent-LFS3MXL7.js.map
|
|
@@ -118,7 +118,7 @@ function agentsTypedClientPlugin(opts) {
|
|
|
118
118
|
},
|
|
119
119
|
configureServer(server) {
|
|
120
120
|
viteServer = server;
|
|
121
|
-
const agentsGlob = posix.join(opts.projectRoot.replace(/\\/g, "/"), "agents");
|
|
121
|
+
const agentsGlob = posix.join(opts.projectRoot.replace(/\\/g, "/"), opts.agentsDir ?? "agents");
|
|
122
122
|
const onFile = (file) => {
|
|
123
123
|
if (file.replace(/\\/g, "/").startsWith(agentsGlob)) scheduleEmit();
|
|
124
124
|
};
|
|
@@ -142,4 +142,4 @@ export {
|
|
|
142
142
|
agentsTypedClientPlugin,
|
|
143
143
|
generateAgentsDts
|
|
144
144
|
};
|
|
145
|
-
//# sourceMappingURL=agents-typed-client-
|
|
145
|
+
//# sourceMappingURL=agents-typed-client-2K3UAOUF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vite-plugin/agents-typed-client.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Codegen-time fs ops: all paths derive from `opts.projectRoot` / `opts.distDir`\n * (vite plugin opts — trusted, set by the framework's CLI). Never serves HTTP input.\n */\n/**\n * M2 (theokit-ai-first) — end-to-end typed binding for the `agents/*.ts` convention.\n *\n * Sibling of `app-typed-client.ts` (kept separate so the `@theo/client` output stays\n * byte-unchanged). Two parts:\n *\n * 1. `generateAgentsDts({ manifest, dtsOutPath, projectRoot })` — pure function emitting\n * `.theokit/agents.d.ts` (the virtual `@theo/agents` module) with `AppAgents` mapping\n * each scanned agent to `InferAgentInput` of its `defineAgent({ input })` schema, plus a\n * typed `useAgent` signature — so the client binds to `/api/agents/<name>` with the right\n * request type and ZERO manual wiring (DoD line 2).\n * 2. `agentsTypedClientPlugin(opts)` — Vite plugin that emits (1), rewrites on `agents/*`\n * changes, and serves the virtual `@theo/agents` runtime (`useAgent` from `theokit/client`).\n */\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, posix } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport type { TheoManifest } from '../server/internal-api.js'\n\nconst FILE_HEADER = `// AUTO-GENERATED by theokit — do not edit.\n// Source: theokit/packages/theo/src/vite-plugin/agents-typed-client.ts (M2).\n// To refresh: \\`pnpm dev\\` or \\`pnpm build\\` regenerates this on every agents/ change.\n\n/* eslint-disable */\n`\n\n/** A safe TS identifier alias for an agent (name may contain path separators). */\nfunction aliasFor(name: string): string {\n return `_agent_${name.replace(/[^\\w$]/g, '_')}`\n}\n\n/** Relative `import type` path from the .d.ts dir to the agent source (extension stripped). */\nfunction importPath(dtsOutPath: string, projectRoot: string, filePath: string): string {\n const fromDir = dirname(dtsOutPath).replace(/\\\\/g, '/')\n const abs = posix.join(projectRoot.replace(/\\\\/g, '/'), filePath.replace(/\\\\/g, '/'))\n const noExt = abs.replace(/\\.[jt]sx?$/, '')\n let rel = posix.relative(fromDir, noExt)\n if (!rel.startsWith('.')) rel = `./${rel}`\n return rel\n}\n\nexport interface GenerateAgentsDtsOptions {\n manifest: TheoManifest\n /** Absolute path to the .d.ts that will be emitted (drives the import paths). */\n dtsOutPath: string\n /** Absolute project root — agents live at `<projectRoot>/agents`. */\n projectRoot: string\n}\n\nexport function generateAgentsDts({\n manifest,\n dtsOutPath,\n projectRoot,\n}: GenerateAgentsDtsOptions): string {\n const agents = manifest.agents ?? []\n const imports: string[] = []\n const entries: string[] = []\n for (const agent of agents) {\n const alias = aliasFor(agent.name)\n imports.push(\n ` import type ${alias} from '${importPath(dtsOutPath, projectRoot, agent.filePath)}'`,\n )\n entries.push(\n ` '${agent.name}': { input: InferAgentInput<${alias}>; tools: InferAgentToolNames<${alias}> }`,\n )\n }\n\n const body =\n entries.length > 0\n ? `{\\n${entries.join('\\n')}\\n }`\n : `{\\n // No agents detected — add \\`agents/*.ts\\` to populate this binding.\\n }`\n\n const importBlock = imports.length > 0 ? `${imports.join('\\n')}\\n` : ''\n\n return `${FILE_HEADER}\ndeclare module '@theo/agents' {\n import type { InferAgentInput, InferAgentToolNames } from '@theokit/agents'\n import type { UseAgentReturn } from 'theokit/client'\n${importBlock}\n export interface AppAgents ${body}\n\n export function useAgent<K extends keyof AppAgents>(\n name: K,\n ): UseAgentReturn<AppAgents[K]['input'], AppAgents[K]['tools']>\n}\n`\n}\n\n// ─── Vite plugin ─────────────────────────────────────────────────────────────\n\nconst VIRTUAL_AGENTS_ID = '@theo/agents'\nconst RESOLVED_AGENTS_ID = '\\0@theo/agents'\n\nexport interface AgentsTypedClientPluginOptions {\n /** Absolute project root (agents live at `<projectRoot>/<agentsDir>`). */\n projectRoot: string\n /** Agents dir name (config `agentsDir`, default \"agents\"), relative to projectRoot — the watch glob. */\n agentsDir?: string\n /** Absolute `.theokit/` output dir (where `agents.d.ts` lands). */\n distDir: string\n /** Injects the scanned agents; returns the current manifest-shaped agent list. */\n scanManifest: (projectRoot: string) => TheoManifest\n}\n\n/** Atomic write via tmp + rename; skips when content is unchanged. */\nfunction writeIfChanged(filePath: string, content: string): void {\n if (existsSync(filePath)) {\n try {\n if (readFileSync(filePath, 'utf-8') === content) return\n } catch {\n /* fall through to write */\n }\n }\n mkdirSync(dirname(filePath), { recursive: true })\n const tmp = `${filePath}.${process.pid}.tmp`\n writeFileSync(tmp, content)\n renameSync(tmp, filePath)\n}\n\nfunction emitAgentsDts(opts: AgentsTypedClientPluginOptions): string {\n const dtsOutPath = posix.join(opts.distDir.replace(/\\\\/g, '/'), 'agents.d.ts')\n const content = generateAgentsDts({\n manifest: opts.scanManifest(opts.projectRoot),\n dtsOutPath,\n projectRoot: opts.projectRoot,\n })\n writeIfChanged(dtsOutPath, content)\n return dtsOutPath\n}\n\nexport function agentsTypedClientPlugin(opts: AgentsTypedClientPluginOptions): Plugin {\n let debounce: NodeJS.Timeout | undefined\n let viteServer: ViteDevServer | undefined\n\n const scheduleEmit = (): void => {\n if (debounce) clearTimeout(debounce)\n debounce = setTimeout(() => {\n try {\n emitAgentsDts(opts)\n if (viteServer) {\n const mod = viteServer.moduleGraph.getModuleById(RESOLVED_AGENTS_ID)\n if (mod) viteServer.moduleGraph.invalidateModule(mod)\n }\n } catch (err) {\n console.error('[theokit:agents-typed-client] codegen error:', err)\n }\n }, 100)\n }\n\n return {\n name: 'theokit:agents-typed-client',\n enforce: 'post',\n configResolved() {\n try {\n emitAgentsDts(opts)\n } catch (err) {\n console.error('[theokit:agents-typed-client] initial codegen error:', err)\n }\n },\n buildEnd() {\n try {\n emitAgentsDts(opts)\n } catch (err) {\n console.error('[theokit:agents-typed-client] buildEnd codegen error:', err)\n }\n },\n configureServer(server) {\n viteServer = server\n const agentsGlob = posix.join(opts.projectRoot.replace(/\\\\/g, '/'), opts.agentsDir ?? 'agents')\n const onFile = (file: string): void => {\n if (file.replace(/\\\\/g, '/').startsWith(agentsGlob)) scheduleEmit()\n }\n server.watcher.on('add', onFile)\n server.watcher.on('change', onFile)\n server.watcher.on('unlink', onFile)\n },\n resolveId(id) {\n return id === VIRTUAL_AGENTS_ID ? RESOLVED_AGENTS_ID : null\n },\n load(id) {\n if (id === RESOLVED_AGENTS_ID) {\n return `export { useAgent } from 'theokit/client'\\n`\n }\n return null\n },\n }\n}\n"],"mappings":";;;;AAkBA,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,SAAS,aAAa;AAM/B,IAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAQpB,SAAS,SAAS,MAAsB;AACtC,SAAO,UAAU,KAAK,QAAQ,WAAW,GAAG,CAAC;AAC/C;AAGA,SAAS,WAAW,YAAoB,aAAqB,UAA0B;AACrF,QAAM,UAAU,QAA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,SAAS,CAAC,SAAuB;AACrC,YAAI,KAAK,QAAQ,OAAO,GAAG,EAAE,WAAW,UAAU,EAAG,cAAa;AAAA,MACpE;AACA,aAAO,QAAQ,GAAG,OAAO,MAAM;AAC/B,aAAO,QAAQ,GAAG,UAAU,MAAM;AAClC,aAAO,QAAQ,GAAG,UAAU,MAAM;AAAA,IACpC;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,oBAAoB,qBAAqB;AAAA,IACzD;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,oBAAoB;AAC7B,eAAO;AAAA;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
|
@@ -117,7 +117,7 @@ function agentsTypedClientPlugin(opts) {
|
|
|
117
117
|
},
|
|
118
118
|
configureServer(server) {
|
|
119
119
|
viteServer = server;
|
|
120
|
-
const agentsGlob = posix.join(opts.projectRoot.replace(/\\/g, "/"), "agents");
|
|
120
|
+
const agentsGlob = posix.join(opts.projectRoot.replace(/\\/g, "/"), opts.agentsDir ?? "agents");
|
|
121
121
|
const onFile = (file) => {
|
|
122
122
|
if (file.replace(/\\/g, "/").startsWith(agentsGlob)) scheduleEmit();
|
|
123
123
|
};
|
|
@@ -141,4 +141,4 @@ export {
|
|
|
141
141
|
agentsTypedClientPlugin,
|
|
142
142
|
generateAgentsDts
|
|
143
143
|
};
|
|
144
|
-
//# sourceMappingURL=agents-typed-client-
|
|
144
|
+
//# sourceMappingURL=agents-typed-client-DPFVM2OY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vite-plugin/agents-typed-client.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Codegen-time fs ops: all paths derive from `opts.projectRoot` / `opts.distDir`\n * (vite plugin opts — trusted, set by the framework's CLI). Never serves HTTP input.\n */\n/**\n * M2 (theokit-ai-first) — end-to-end typed binding for the `agents/*.ts` convention.\n *\n * Sibling of `app-typed-client.ts` (kept separate so the `@theo/client` output stays\n * byte-unchanged). Two parts:\n *\n * 1. `generateAgentsDts({ manifest, dtsOutPath, projectRoot })` — pure function emitting\n * `.theokit/agents.d.ts` (the virtual `@theo/agents` module) with `AppAgents` mapping\n * each scanned agent to `InferAgentInput` of its `defineAgent({ input })` schema, plus a\n * typed `useAgent` signature — so the client binds to `/api/agents/<name>` with the right\n * request type and ZERO manual wiring (DoD line 2).\n * 2. `agentsTypedClientPlugin(opts)` — Vite plugin that emits (1), rewrites on `agents/*`\n * changes, and serves the virtual `@theo/agents` runtime (`useAgent` from `theokit/client`).\n */\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, posix } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport type { TheoManifest } from '../server/internal-api.js'\n\nconst FILE_HEADER = `// AUTO-GENERATED by theokit — do not edit.\n// Source: theokit/packages/theo/src/vite-plugin/agents-typed-client.ts (M2).\n// To refresh: \\`pnpm dev\\` or \\`pnpm build\\` regenerates this on every agents/ change.\n\n/* eslint-disable */\n`\n\n/** A safe TS identifier alias for an agent (name may contain path separators). */\nfunction aliasFor(name: string): string {\n return `_agent_${name.replace(/[^\\w$]/g, '_')}`\n}\n\n/** Relative `import type` path from the .d.ts dir to the agent source (extension stripped). */\nfunction importPath(dtsOutPath: string, projectRoot: string, filePath: string): string {\n const fromDir = dirname(dtsOutPath).replace(/\\\\/g, '/')\n const abs = posix.join(projectRoot.replace(/\\\\/g, '/'), filePath.replace(/\\\\/g, '/'))\n const noExt = abs.replace(/\\.[jt]sx?$/, '')\n let rel = posix.relative(fromDir, noExt)\n if (!rel.startsWith('.')) rel = `./${rel}`\n return rel\n}\n\nexport interface GenerateAgentsDtsOptions {\n manifest: TheoManifest\n /** Absolute path to the .d.ts that will be emitted (drives the import paths). */\n dtsOutPath: string\n /** Absolute project root — agents live at `<projectRoot>/agents`. */\n projectRoot: string\n}\n\nexport function generateAgentsDts({\n manifest,\n dtsOutPath,\n projectRoot,\n}: GenerateAgentsDtsOptions): string {\n const agents = manifest.agents ?? []\n const imports: string[] = []\n const entries: string[] = []\n for (const agent of agents) {\n const alias = aliasFor(agent.name)\n imports.push(\n ` import type ${alias} from '${importPath(dtsOutPath, projectRoot, agent.filePath)}'`,\n )\n entries.push(\n ` '${agent.name}': { input: InferAgentInput<${alias}>; tools: InferAgentToolNames<${alias}> }`,\n )\n }\n\n const body =\n entries.length > 0\n ? `{\\n${entries.join('\\n')}\\n }`\n : `{\\n // No agents detected — add \\`agents/*.ts\\` to populate this binding.\\n }`\n\n const importBlock = imports.length > 0 ? `${imports.join('\\n')}\\n` : ''\n\n return `${FILE_HEADER}\ndeclare module '@theo/agents' {\n import type { InferAgentInput, InferAgentToolNames } from '@theokit/agents'\n import type { UseAgentReturn } from 'theokit/client'\n${importBlock}\n export interface AppAgents ${body}\n\n export function useAgent<K extends keyof AppAgents>(\n name: K,\n ): UseAgentReturn<AppAgents[K]['input'], AppAgents[K]['tools']>\n}\n`\n}\n\n// ─── Vite plugin ─────────────────────────────────────────────────────────────\n\nconst VIRTUAL_AGENTS_ID = '@theo/agents'\nconst RESOLVED_AGENTS_ID = '\\0@theo/agents'\n\nexport interface AgentsTypedClientPluginOptions {\n /** Absolute project root (agents live at `<projectRoot>/<agentsDir>`). */\n projectRoot: string\n /** Agents dir name (config `agentsDir`, default \"agents\"), relative to projectRoot — the watch glob. */\n agentsDir?: string\n /** Absolute `.theokit/` output dir (where `agents.d.ts` lands). */\n distDir: string\n /** Injects the scanned agents; returns the current manifest-shaped agent list. */\n scanManifest: (projectRoot: string) => TheoManifest\n}\n\n/** Atomic write via tmp + rename; skips when content is unchanged. */\nfunction writeIfChanged(filePath: string, content: string): void {\n if (existsSync(filePath)) {\n try {\n if (readFileSync(filePath, 'utf-8') === content) return\n } catch {\n /* fall through to write */\n }\n }\n mkdirSync(dirname(filePath), { recursive: true })\n const tmp = `${filePath}.${process.pid}.tmp`\n writeFileSync(tmp, content)\n renameSync(tmp, filePath)\n}\n\nfunction emitAgentsDts(opts: AgentsTypedClientPluginOptions): string {\n const dtsOutPath = posix.join(opts.distDir.replace(/\\\\/g, '/'), 'agents.d.ts')\n const content = generateAgentsDts({\n manifest: opts.scanManifest(opts.projectRoot),\n dtsOutPath,\n projectRoot: opts.projectRoot,\n })\n writeIfChanged(dtsOutPath, content)\n return dtsOutPath\n}\n\nexport function agentsTypedClientPlugin(opts: AgentsTypedClientPluginOptions): Plugin {\n let debounce: NodeJS.Timeout | undefined\n let viteServer: ViteDevServer | undefined\n\n const scheduleEmit = (): void => {\n if (debounce) clearTimeout(debounce)\n debounce = setTimeout(() => {\n try {\n emitAgentsDts(opts)\n if (viteServer) {\n const mod = viteServer.moduleGraph.getModuleById(RESOLVED_AGENTS_ID)\n if (mod) viteServer.moduleGraph.invalidateModule(mod)\n }\n } catch (err) {\n console.error('[theokit:agents-typed-client] codegen error:', err)\n }\n }, 100)\n }\n\n return {\n name: 'theokit:agents-typed-client',\n enforce: 'post',\n configResolved() {\n try {\n emitAgentsDts(opts)\n } catch (err) {\n console.error('[theokit:agents-typed-client] initial codegen error:', err)\n }\n },\n buildEnd() {\n try {\n emitAgentsDts(opts)\n } catch (err) {\n console.error('[theokit:agents-typed-client] buildEnd codegen error:', err)\n }\n },\n configureServer(server) {\n viteServer = server\n const agentsGlob = posix.join(opts.projectRoot.replace(/\\\\/g, '/'), opts.agentsDir ?? 'agents')\n const onFile = (file: string): void => {\n if (file.replace(/\\\\/g, '/').startsWith(agentsGlob)) scheduleEmit()\n }\n server.watcher.on('add', onFile)\n server.watcher.on('change', onFile)\n server.watcher.on('unlink', onFile)\n },\n resolveId(id) {\n return id === VIRTUAL_AGENTS_ID ? RESOLVED_AGENTS_ID : null\n },\n load(id) {\n if (id === RESOLVED_AGENTS_ID) {\n return `export { useAgent } from 'theokit/client'\\n`\n }\n return null\n },\n }\n}\n"],"mappings":";;;AAkBA,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC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,MACpB,SAAS,KAAK;AACZ,gBAAQ,MAAM,yDAAyD,GAAG;AAAA,MAC5E;AAAA,IACF;AAAA,IACA,gBAAgB,QAAQ;AACtB,mBAAa;AACb,YAAM,aAAa,MAAM,KAAK,KAAK,YAAY,QAAQ,OAAO,GAAG,GAAG,KAAK,aAAa,QAAQ;AAC9F,YAAM,SAAS,CAAC,SAAuB;AACrC,YAAI,KAAK,QAAQ,OAAO,GAAG,EAAE,WAAW,UAAU,EAAG,cAAa;AAAA,MACpE;AACA,aAAO,QAAQ,GAAG,OAAO,MAAM;AAC/B,aAAO,QAAQ,GAAG,UAAU,MAAM;AAClC,aAAO,QAAQ,GAAG,UAAU,MAAM;AAAA,IACpC;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,oBAAoB,qBAAqB;AAAA,IACzD;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,oBAAoB;AAC7B,eAAO;AAAA;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import "./chunk-VMEWD57H.js";
|
|
|
5
5
|
import "./chunk-JQSKBMXP.js";
|
|
6
6
|
import {
|
|
7
7
|
generateManifest
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-RKDH4DWL.js";
|
|
9
9
|
import {
|
|
10
10
|
HTTP_METHODS
|
|
11
11
|
} from "./chunk-WSJKACWB.js";
|
|
@@ -296,4 +296,4 @@ export {
|
|
|
296
296
|
emitClientDts,
|
|
297
297
|
generateClientDts
|
|
298
298
|
};
|
|
299
|
-
//# sourceMappingURL=app-typed-client-
|
|
299
|
+
//# sourceMappingURL=app-typed-client-VMSRQGKL.js.map
|
|
@@ -4,8 +4,8 @@ import "./chunk-KXA37ONC.js";
|
|
|
4
4
|
import "./chunk-WR4F4EEZ.js";
|
|
5
5
|
import {
|
|
6
6
|
generateManifest
|
|
7
|
-
} from "./chunk-
|
|
8
|
-
import "./chunk-
|
|
7
|
+
} from "./chunk-YJWEADAW.js";
|
|
8
|
+
import "./chunk-TERFLG67.js";
|
|
9
9
|
import {
|
|
10
10
|
HTTP_METHODS
|
|
11
11
|
} from "./chunk-FRUEDJFX.js";
|
|
@@ -286,4 +286,4 @@ export {
|
|
|
286
286
|
emitClientDts,
|
|
287
287
|
generateClientDts
|
|
288
288
|
};
|
|
289
|
-
//# sourceMappingURL=app-typed-client-
|
|
289
|
+
//# sourceMappingURL=app-typed-client-YCQC3MZ7.js.map
|
|
@@ -13,11 +13,11 @@ import {
|
|
|
13
13
|
import {
|
|
14
14
|
importUserModule,
|
|
15
15
|
loadConfig
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-AFVTEAES.js";
|
|
17
17
|
import {
|
|
18
18
|
loadEnv
|
|
19
19
|
} from "./chunk-GDN3PXFH.js";
|
|
20
|
-
import "./chunk-
|
|
20
|
+
import "./chunk-GSO77FSM.js";
|
|
21
21
|
import {
|
|
22
22
|
buildManifest,
|
|
23
23
|
writeManifest
|
|
@@ -25,8 +25,8 @@ import {
|
|
|
25
25
|
import {
|
|
26
26
|
generateManifest,
|
|
27
27
|
writeManifest as writeManifest2
|
|
28
|
-
} from "./chunk-
|
|
29
|
-
import "./chunk-
|
|
28
|
+
} from "./chunk-YJWEADAW.js";
|
|
29
|
+
import "./chunk-TERFLG67.js";
|
|
30
30
|
import "./chunk-FRUEDJFX.js";
|
|
31
31
|
import {
|
|
32
32
|
walkSourceFiles
|
|
@@ -485,7 +485,7 @@ async function buildCommand(options) {
|
|
|
485
485
|
`);
|
|
486
486
|
const serverDir = resolve(cwd, config.serverDir);
|
|
487
487
|
const distDir = distDirAbs;
|
|
488
|
-
const manifest = generateManifest(serverDir);
|
|
488
|
+
const manifest = generateManifest(serverDir, cwd, config.agentsDir);
|
|
489
489
|
writeManifest2(manifest, distDir);
|
|
490
490
|
const totalEndpoints = manifest.routes.length + manifest.actions.length + manifest.websockets.length;
|
|
491
491
|
console.log(
|
|
@@ -531,7 +531,7 @@ async function buildCommand(options) {
|
|
|
531
531
|
`);
|
|
532
532
|
}
|
|
533
533
|
async function runAdapterBuild(target, config, cwd) {
|
|
534
|
-
const { theoPluginAsync } = await import("./vite-plugin-
|
|
534
|
+
const { theoPluginAsync } = await import("./vite-plugin-WIJ5RMQQ.js");
|
|
535
535
|
const { default: react } = await import("@vitejs/plugin-react");
|
|
536
536
|
const ctx = {
|
|
537
537
|
// `react()` may return Plugin or Plugin[] depending on version; spread the
|
|
@@ -606,4 +606,4 @@ function relativize3(absPath, root) {
|
|
|
606
606
|
export {
|
|
607
607
|
buildCommand
|
|
608
608
|
};
|
|
609
|
-
//# sourceMappingURL=build-
|
|
609
|
+
//# sourceMappingURL=build-B675HLFR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands/build.ts","../src/adapters/types.ts","../src/server/cron/adapter-translators.ts","../src/server/_internal/atomic-write.ts","../src/server/cron/cron-manifest.ts","../src/server/cron/cron-scan.ts","../src/server/jobs/job-manifest.ts","../src/server/jobs/job-scan.ts","../src/cli/cleanup/cleanup.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\n// T1.1 (architecture-medium-deferrals) — nodeAdapter no longer static-imported.\n// All adapters dispatch via `adapterRegistry` (lazy-imported within runAdapterBuild).\nimport { VALID_TARGETS, type BuildTarget, type AdapterBuildContext } from '../../adapters/types.js'\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport { validateProjectStructure } from '../../config/validate-structure.js'\nimport {\n ExistingConfigUnparseableError,\n translateCronToAws,\n translateCronToCloudflare,\n translateCronToDeno,\n translateCronToVercel,\n} from '../../server/cron/adapter-translators.js'\nimport { writeCronManifest } from '../../server/cron/cron-manifest.js'\nimport { scanCrons } from '../../server/cron/cron-scan.js'\nimport { writeJobManifest } from '../../server/jobs/job-manifest.js'\nimport { scanJobs } from '../../server/jobs/job-scan.js'\nimport { generateManifest, writeManifest } from '../../server/scan/manifest.js'\nimport {\n buildManifest as buildServicesManifest,\n writeManifest as writeServicesManifest,\n} from '../../services/index.js'\n// G2 T2.2 — OpenAPI emit. Opt-in via `config.openapi`. Dual output:\n// 1. <distDir>/openapi.json (pre-Vite, dev surface + manifests sibling)\n// 2. dist/openapi.json (post-Vite, build artifact)\n// The dist emit awaits runAdapterBuild — if Vite fails, the second emit\n// never runs (EC-2 absorbed: no stale dist artifact).\nimport { emitOpenApi } from '../../vite-plugin/openapi-emit/emit.js'\nimport { loadRoutesForOpenApi } from '../../vite-plugin/openapi-emit/load-routes.js'\nimport { cleanOutDir } from '../cleanup/cleanup.js'\nimport { preflightNodeAndBindings } from '../preflight-node-version.js'\n\n// Adapters that do NOT support cron triggers natively. Build still\n// succeeds with crons declared, but emits a warning + skip note.\nconst CRON_NA_TARGETS = new Set<BuildTarget>(['bun', 'netlify', 'static'])\n\nexport async function buildCommand(options?: { target?: string }): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n // Phase 1 (T1.2) — Load .env BEFORE config load.\n loadEnv({ cwd, mode: 'production' })\n\n const config = await loadConfig(cwd)\n validateProjectStructure(cwd)\n\n // T2.2 — Clean .theokit/ at build start (Astro pattern). Skip .git*.\n const distDirAbs = resolve(cwd, config.distDir)\n await cleanOutDir({ dir: distDirAbs })\n\n const target = (options?.target ?? 'node') as BuildTarget\n\n if (!VALID_TARGETS.includes(target)) {\n throw new Error(\n `Invalid build target \"${target}\". Available targets: ${VALID_TARGETS.join(', ')}`,\n )\n }\n\n // EC-201 — cross-reference note when config.adapters[] diverges from\n // the --target flag. --target is authoritative per ADR D2.\n const configAdapters = (config as { adapters?: readonly string[] }).adapters\n if (configAdapters && configAdapters.length > 0) {\n const otherAdapters = configAdapters.filter((a) => a !== target)\n if (otherAdapters.length > 0) {\n console.log(\n `\\n Note: theo.config.ts.adapters lists [${otherAdapters.join(', ')}]; ` +\n `this build translates for ${target} only. ` +\n `Run \\`theokit build --target=<adapter>\\` separately for each (cross-reference).`,\n )\n }\n }\n\n console.log(`\\n Building for ${target}...\\n`)\n\n // Manifests emit BEFORE adapter bundling (Vite). Why: manifests are\n // fast + deterministic + don't depend on Vite. If Vite fails (missing\n // dep, malformed entry), the user still gets manifests for diagnostics.\n const serverDir = resolve(cwd, config.serverDir)\n const distDir = distDirAbs\n // #95 follow-up — pass projectRoot (cwd) + config.agentsDir so agents scan honors a custom dir.\n const manifest = generateManifest(serverDir, cwd, config.agentsDir)\n writeManifest(manifest, distDir)\n\n const totalEndpoints =\n manifest.routes.length + manifest.actions.length + manifest.websockets.length\n console.log(\n ` ✓ Manifest: ${manifest.routes.length} routes, ${manifest.actions.length} actions, ${manifest.websockets.length} ws (${totalEndpoints} total)`,\n )\n\n // T1.1 — cron scan + manifest + per-target adapter translation\n await emitCronArtifacts({ cwd, serverDir, distDir, target })\n\n // T1.2 — job scan + manifest (no per-target translation needed)\n await emitJobArtifacts({ cwd, serverDir, distDir })\n\n // Wave 2 (T1.2) — services manifest at <cwd>/.theokit/services.json. Always\n // emit (empty array when services: {} is empty) so adapters can rely on\n // the file existing. Topological order preserved by buildServicesManifest.\n //\n // Plan v1.2 T2.1 — when theo.config.ts declares `name`, emit services.json\n // v2 with that project identifier. Falling back to v1 (no project field)\n // keeps TheoCloud's deprecation warning path intact (services-bundle).\n const projectName = config.name\n const servicesManifest = buildServicesManifest(config.services, projectName)\n writeServicesManifest(cwd, servicesManifest)\n if (servicesManifest.services.length > 0) {\n const versionLabel = `v${String(servicesManifest.version)}`\n const projectLabel =\n servicesManifest.version === 2 ? ` project=\"${servicesManifest.project}\"` : ''\n console.log(\n ` ✓ Services manifest (${versionLabel}${projectLabel}): ${String(servicesManifest.services.length)} service(s) ` +\n `(${servicesManifest.services.map((s) => s.name).join(', ')})`,\n )\n } else if (servicesManifest.version === 1) {\n console.log(\n ' ⚠ services.json emitted as v1 (no `name` in theo.config.ts). ' +\n 'TheoCloud will accept this with a deprecation warning; sunset in theokit 0.6.0. ' +\n 'Run `theokit migrate services-json-v1-to-v2` to upgrade.',\n )\n }\n\n // G2 T2.2 — OpenAPI dev-surface emit (pre-Vite, sibling of manifests).\n // Opt-in: only when config.openapi is defined. Best-effort: a route load\n // failure produces a warning, not a build abort.\n if (config.openapi !== undefined) {\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const devResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distDir },\n })\n console.log(` ✓ OpenAPI: ${String(hydrated.length)} ops → ${devResult.path}`)\n }\n\n // Now run the adapter-specific bundling (Vite + adapter-specific work).\n await runAdapterBuild(target, config, cwd)\n\n // G2 T2.2 — OpenAPI build-artifact emit (post-Vite, EC-2 gated on success).\n // If runAdapterBuild threw, execution never reaches this point — no stale\n // dist/openapi.json is written.\n if (config.openapi !== undefined) {\n const distOut = resolve(cwd, 'dist')\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const distResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distOut },\n })\n console.log(` ✓ OpenAPI (dist): ${distResult.path}`)\n }\n\n const ssrNote = config.ssr ? ' (SSR)' : ''\n console.log(`\\n ✓ Build complete → ${target}${ssrNote}\\n`)\n}\n\nasync function runAdapterBuild(\n target: BuildTarget,\n config: Awaited<ReturnType<typeof loadConfig>>,\n cwd: string,\n): Promise<void> {\n // T1.1 (architecture-cleanup) — CLI composes the Vite Plugin[] and INJECTS it into\n // the adapter via ctx.makeVitePlugins. This inverts the previous `adapters → vite-plugin`\n // edge — adapters no longer import from vite-plugin/ directly.\n //\n // theoPlugin AND `@vitejs/plugin-react` are dynamically imported so the deps are\n // materialized only when needed (adapter is `node`). This keeps the CLI's startup\n // path independent of optional build-time deps (so e.g. `theokit build --target=static`\n // does not need react installed). dep-cruiser's per-module rule allows `cli → vite-plugin`.\n //\n // 0.2.2 regression fix: switched sync `theoPlugin()` → `theoPluginAsync()` so the\n // returned Plugin[] includes the @theo/actions virtual module + typed-client +\n // services + @theokit/ui auto-chain. Without async, build-time Rollup couldn't\n // resolve `@theo/actions` even though dev-time Vite (which already used async)\n // could. See https://github.com/usetheo/theokit/commits — 0.2.2 changelog.\n const { theoPluginAsync } = await import('../../vite-plugin/index.js')\n const { default: react } = await import('@vitejs/plugin-react')\n const ctx: AdapterBuildContext = {\n // `react()` may return Plugin or Plugin[] depending on version; spread the\n // async chain so the contract returns a flat Plugin[] (AdapterBuildContext\n // type updated to `Plugin[] | Promise<Plugin[]>`).\n makeVitePlugins: async (opts) => [react(), ...(await theoPluginAsync(opts))].flat(),\n }\n\n // T1.1 (architecture-medium-deferrals, ADR D1) — Adapter Registry replaces\n // the previous 9-case switch. New adapters add 1 line in `adapters/registry.ts`;\n // CLI is closed for modification (OCP).\n const { resolveAdapter } = await import('../../adapters/registry.js')\n const adapter = await resolveAdapter(target)\n await adapter.build(config, cwd, ctx)\n}\n\nasync function emitCronArtifacts(opts: {\n cwd: string\n serverDir: string\n distDir: string\n target: BuildTarget\n}): Promise<void> {\n const cronsDir = resolve(opts.serverDir, 'crons')\n\n const cronNodes = existsSync(cronsDir) ? await scanCrons(cronsDir) : []\n const manifestPath = resolve(opts.distDir, 'crons.json')\n writeCronManifest(manifestPath, cronNodes, opts.cwd)\n\n console.log(` ✓ Crons: ${cronNodes.length} declared`)\n\n if (cronNodes.length === 0) return\n\n // EC-201: target-specific translation. N/A targets emit a warning + skip.\n if (CRON_NA_TARGETS.has(opts.target)) {\n console.log(\n ` ⚠ Cron not supported by target \"${opts.target}\" — declared crons skipped. ` +\n `See docs/concepts/crons.md for supported targets.`,\n )\n return\n }\n\n const manifestEntries = cronNodes.map((n) => ({\n name: n.name,\n filePath: relativize(n.filePath, opts.cwd),\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n\n try {\n switch (opts.target) {\n case 'vercel':\n translateCronToVercel(resolve(opts.cwd, 'vercel.json'), manifestEntries)\n console.log(` ✓ Cron → vercel.json crons[] (${cronNodes.length} entries)`)\n break\n case 'cloudflare':\n translateCronToCloudflare(resolve(opts.cwd, 'wrangler.toml'), manifestEntries)\n console.log(` ✓ Cron → wrangler.toml [triggers] (${cronNodes.length})`)\n break\n case 'aws-lambda':\n translateCronToAws(resolve(opts.cwd, 'serverless.yml'), manifestEntries)\n console.log(` ✓ Cron → serverless.yml functions (${cronNodes.length})`)\n break\n case 'deno-deploy':\n translateCronToDeno(resolve(opts.distDir, 'crons-entry.ts'), manifestEntries)\n console.log(` ✓ Cron → ${opts.distDir}/crons-entry.ts (Deno.cron)`)\n break\n case 'node':\n console.log(` ✓ Cron → in-process scheduler (theokit start)`)\n break\n }\n } catch (err) {\n if (err instanceof ExistingConfigUnparseableError) throw err\n throw err\n }\n}\n\nasync function emitJobArtifacts(opts: {\n cwd: string\n serverDir: string\n distDir: string\n}): Promise<void> {\n const jobsDir = resolve(opts.serverDir, 'jobs')\n\n const jobNodes = existsSync(jobsDir) ? await scanJobs(jobsDir) : []\n const manifestPath = resolve(opts.distDir, 'jobs.json')\n writeJobManifest(manifestPath, jobNodes, opts.cwd)\n console.log(` ✓ Jobs: ${jobNodes.length} declared`)\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","import type { Plugin } from 'vite'\n\nimport type { TheoConfig } from '../config/schema.js'\n\n/**\n * Build context injected by the CLI into adapter.build.\n *\n * - `makeVitePlugins` — optional factory provided by CLI for adapters\n * that drive `viteBuild()` directly (currently: `nodeAdapter`).\n * When omitted, adapters that need Vite must fail with an actionable\n * error. This inverts the previous direct edge `adapters → vite-plugin`\n * per ADR-0001 v3 (T1.1 of the architecture-cleanup plan).\n *\n * The factory MAY return a Promise — `theokit build` uses\n * `theoPluginAsync` to wire the full Plugin[] chain (actions virtual\n * module + typed client + services + @theokit/ui auto-chain) so adapters\n * MUST `await` the result. See `cli/commands/build.ts` for the canonical\n * invocation.\n */\nexport interface AdapterBuildContext {\n makeVitePlugins?: (opts: { root: string; ssr?: boolean }) => Plugin[] | Promise<Plugin[]>\n}\n\nexport interface DeployAdapter {\n name: string\n build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void>\n}\n\nexport type BuildTarget =\n | 'node'\n | 'vercel'\n | 'cloudflare'\n | 'static'\n | 'bun'\n | 'deno-deploy'\n | 'netlify'\n | 'aws-lambda'\n | 'theo-cloud'\n\nexport const VALID_TARGETS: BuildTarget[] = [\n 'node',\n 'vercel',\n 'cloudflare',\n 'static',\n 'bun',\n 'deno-deploy',\n 'netlify',\n 'aws-lambda',\n 'theo-cloud',\n]\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time adapter translators: caller-controlled paths only.\n */\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronManifestEntry } from './cron-manifest.js'\n\n/**\n * Thrown when an existing platform-config file (vercel.json, wrangler.toml,\n * serverless.yml) cannot be parsed. Caller must fix the file before\n * re-running `theokit build`. We NEVER silently overwrite a user's config.\n */\nexport class ExistingConfigUnparseableError extends Error {\n readonly code = 'EXISTING_CONFIG_UNPARSEABLE'\n constructor(\n public readonly filePath: string,\n public readonly parseError: string,\n ) {\n super(\n `Existing config \"${filePath}\" could not be parsed: ${parseError}. ` +\n 'Fix or remove the file before re-running build — TheoKit never silently overwrites user configuration.',\n )\n this.name = 'ExistingConfigUnparseableError'\n }\n}\n\n// ──────────────────────────────────────────────────────────\n// Vercel — vercel.json crons[]\n// ──────────────────────────────────────────────────────────\n\ninterface VercelJson {\n crons?: { path: string; schedule: string }[]\n [key: string]: unknown\n}\n\n/**\n * Translate a TheoKit cron manifest into `vercel.json crons[]`.\n *\n * EC-105: existing fields (functions, headers, redirects, rewrites, env,\n * etc.) are preserved verbatim — ONLY the `crons[]` slice is replaced.\n */\nexport function translateCronToVercel(\n vercelJsonPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n let existing: VercelJson = {}\n if (existsSync(vercelJsonPath)) {\n const raw = readFileSync(vercelJsonPath, 'utf8')\n try {\n existing = JSON.parse(raw) as VercelJson\n } catch (err) {\n throw new ExistingConfigUnparseableError(\n vercelJsonPath,\n err instanceof Error ? err.message : String(err),\n )\n }\n }\n const merged: VercelJson = {\n ...existing,\n crons: crons.map((c) => ({\n path: `/api/__crons/${c.name}`,\n schedule: c.schedule,\n })),\n }\n writeAtomic(vercelJsonPath, JSON.stringify(merged, null, 2))\n}\n\n// ──────────────────────────────────────────────────────────\n// Cloudflare — wrangler.toml [triggers] crons\n// ──────────────────────────────────────────────────────────\n\n/**\n * Translate a TheoKit cron manifest into `wrangler.toml [triggers] crons`.\n *\n * EC-105: regex-based mutation that preserves comments + other sections\n * verbatim. Replaces only the `[triggers]` block (or appends if absent).\n */\nexport function translateCronToCloudflare(\n wranglerTomlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const schedules = crons.map((c) => `\"${c.schedule}\"`).join(', ')\n const triggersBlock = `[triggers]\\ncrons = [${schedules}]\\n`\n\n if (!existsSync(wranglerTomlPath)) {\n writeAtomic(wranglerTomlPath, triggersBlock)\n return\n }\n\n const existing = readFileSync(wranglerTomlPath, 'utf8')\n\n // Replace existing [triggers] section if present. Strategy: split into\n // line array, find the [triggers] header line, drop subsequent lines\n // until the next section header (line starting with `[`) or EOF.\n const lines = existing.split('\\n')\n const triggersIdx = lines.findIndex((l) => l.trim() === '[triggers]')\n\n let next: string\n if (triggersIdx !== -1) {\n let endIdx = lines.length\n for (let i = triggersIdx + 1; i < lines.length; i++) {\n if (lines[i].trim().startsWith('[')) {\n endIdx = i\n break\n }\n }\n const before = lines.slice(0, triggersIdx).join('\\n')\n const after = lines.slice(endIdx).join('\\n')\n next = `${before}\\n${triggersBlock.trimEnd()}\\n${after}`.replace(/\\n{3,}/g, '\\n\\n')\n } else {\n next = existing.endsWith('\\n')\n ? `${existing}\\n${triggersBlock}`\n : `${existing}\\n\\n${triggersBlock}`\n }\n writeAtomic(wranglerTomlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// AWS Lambda — serverless.yml functions.<fn>.events: schedule\n// ──────────────────────────────────────────────────────────\n\n/**\n * Convert TheoKit's 5-field UTC cron to AWS EventBridge's 6-field format.\n * EventBridge requires `?` in EITHER day-of-month OR day-of-week (not both `*`).\n *\n * Algorithm:\n * - If DOM is \"*\" and DOW is \"*\" → insert ? in DOW (default)\n * - If DOM is \"*\" and DOW is specific → insert ? in DOM\n * - If DOM is specific and DOW is \"*\" → insert ? in DOW\n * - Append \"*\" year field at end.\n */\nexport function convertToAwsCron(schedule: string): string {\n const parts = schedule.trim().split(/\\s+/)\n if (parts.length !== 5) {\n throw new Error(`Invalid 5-field schedule for AWS conversion: \"${schedule}\"`)\n }\n const [minute, hour, dom, month, dow] = parts\n let awsDom = dom\n let awsDow = dow\n if (dom === '*' && dow === '*') {\n awsDow = '?'\n } else if (dom === '*') {\n awsDom = '?'\n } else if (dow === '*') {\n awsDow = '?'\n }\n return `cron(${minute} ${hour} ${awsDom} ${month} ${awsDow} *)`\n}\n\n/**\n * Translate a TheoKit cron manifest into a `serverless.yml` functions\n * map with `events: - schedule: cron(...)` entries.\n *\n * EC-105: appends to `functions:` block, preserving all existing\n * functions/sections. Cron functions are named `cron_<name>` to avoid\n * collision with user-declared functions.\n */\nexport function translateCronToAws(\n serverlessYmlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const cronFunctionsYaml = crons\n .map(\n (c) => ` cron_${c.name}:\n handler: .theokit/server/crons/${c.name}.handler\n events:\n - schedule: ${convertToAwsCron(c.schedule)}`,\n )\n .join('\\n')\n\n const block = `\\nfunctions:\\n${cronFunctionsYaml}\\n`\n\n if (!existsSync(serverlessYmlPath)) {\n // Minimal serverless.yml scaffold\n writeAtomic(\n serverlessYmlPath,\n `service: theokit-app\\nprovider:\\n name: aws\\n runtime: nodejs22.x\\n${block}`,\n )\n return\n }\n\n const existing = readFileSync(serverlessYmlPath, 'utf8')\n\n // Look for an existing top-level `functions:` block; if present, append our\n // cron entries under it (don't replace user-declared functions).\n const functionsRe = /^functions:\\s*\\n/m\n let next: string\n if (functionsRe.test(existing)) {\n next = existing.replace(functionsRe, (match) => `${match}${cronFunctionsYaml}\\n`)\n } else {\n next = existing.endsWith('\\n') ? `${existing}${block}` : `${existing}\\n${block}`\n }\n writeAtomic(serverlessYmlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// Deno Deploy — Deno.cron registrations\n// ──────────────────────────────────────────────────────────\n\n/**\n * Emit a Deno entry file that registers each cron via `Deno.cron`.\n *\n * Unlike Vercel/CF/AWS, Deno.cron is an in-process runtime API — the\n * entry file is a managed artifact (overwritten each build), not a user\n * config (so EC-105 doesn't apply here).\n */\nexport function translateCronToDeno(entryPath: string, crons: readonly CronManifestEntry[]): void {\n const lines = crons.map(\n (c) =>\n `Deno.cron(\"${c.name}\", \"${c.schedule}\", async () => {\n const mod = await import(\"../${c.filePath}\");\n const def = mod.default;\n await def.handler({\n traceId: crypto.randomUUID().replace(/-/g, \"\"),\n scheduledAt: new Date(),\n signal: AbortSignal.timeout(60_000),\n });\n});`,\n )\n const content = `// AUTOGENERATED by TheoKit cron build — DO NOT EDIT.\n// Source: server/crons/*.ts → .theokit/crons.json → this file.\n${lines.join('\\n\\n')}\n`\n writeAtomic(entryPath, content)\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time atomic write: caller-controlled paths only. No HTTP input\n * reaches these fs calls.\n */\n// T5a.1b — Web Crypto migration. Build-time only; node:fs + node:path stay\n// because this is a manifest-write leaf (e.g. .theokit/jobs.json) and per\n// ADR-0028 the runtime-portable boundary is the request handler, not the\n// scanner. Only node:crypto is swapped out — Web Crypto's\n// getRandomValues works in every supported runtime.\nimport { mkdirSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\n/**\n * Write `content` to `path` atomically via the tmp + rename pattern.\n *\n * Two concurrent calls to `writeAtomic(path, ...)` are guaranteed to\n * leave `path` containing valid content from ONE of the calls (never\n * truncated, never interleaved). POSIX rename is atomic on the same\n * filesystem.\n *\n * EC-106 (jobs-crons-webhooks-cost-tracking-plan) — shared helper for\n * `.theokit/crons.json` and `.theokit/jobs.json` manifest writes so a\n * concurrent dev-server scan + build manifest emit never produces\n * partial JSON.\n *\n * @param path destination path\n * @param content bytes (UTF-8 string) to write\n */\nexport function writeAtomic(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n // Include a random suffix so two concurrent writes don't trample each\n // other's tmp file. Web Crypto getRandomValues is non-blocking +\n // collision-safe for the tiny entropy we need (8 hex chars = 32 bits).\n // Hex-encoded manually to avoid Buffer (runtime-agnostic per ADR-0028).\n const randBuf = new Uint8Array(4)\n globalThis.crypto.getRandomValues(randBuf)\n let suffix = ''\n for (const b of randBuf) suffix += b.toString(16).padStart(2, '0')\n const tmp = `${path}.tmp-${process.pid}-${suffix}`\n writeFileSync(tmp, content, 'utf8')\n renameSync(tmp, path)\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronNode } from './cron-scan.js'\n\nexport const CRON_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface CronManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: 'forbid' | 'allow'\n}\n\nexport interface CronManifest {\n readonly schemaVersion: typeof CRON_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly crons: readonly CronManifestEntry[]\n}\n\n/**\n * Build a `CronManifest` from scanned `CronNode[]`. Filepaths are kept\n * relative to the caller's project root for portability.\n */\nexport function buildCronManifest(nodes: readonly CronNode[], projectRoot?: string): CronManifest {\n const crons: CronManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n return {\n schemaVersion: CRON_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n crons,\n }\n}\n\n/**\n * Write the cron manifest to `path` atomically (EC-106).\n *\n * Accepts either a pre-built `CronManifest` OR an array of `CronNode[]`\n * (which gets converted via `buildCronManifest`). The atomic-write\n * helper guarantees `path` always contains valid JSON, even under\n * concurrent writes (e.g., dev-server rescan + build).\n */\nexport function writeCronManifest(\n path: string,\n input: readonly CronNode[] | CronManifest,\n projectRoot?: string,\n): void {\n const manifest: CronManifest = isManifest(input) ? input : buildCronManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is CronManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'crons' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only. No HTTP\n * input ever reaches these fs calls.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { CronConcurrencyPolicy, CronDefinition } from './cron-types.js'\n\n/**\n * One discovered cron from build-time scan. The handler is intentionally\n * NOT included — manifest is platform-neutral and consumed by adapters\n * that emit static config. Runtime dispatch loads the handler at fire time.\n */\nexport interface CronNode {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: CronConcurrencyPolicy\n}\n\nexport class DuplicateCronNameError extends Error {\n readonly code = 'DUPLICATE_CRON_NAME'\n constructor(\n public readonly cronName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate cron name \"${cronName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Cron names must be unique across server/crons/.',\n )\n this.name = 'DuplicateCronNameError'\n }\n}\n\nconst CRON_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface CronModule {\n default?: unknown\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.schedule === 'string' &&\n typeof def.handler === 'function' &&\n (def.concurrency === 'forbid' || def.concurrency === 'allow')\n )\n}\n\n/**\n * Scan a directory for cron definition files and return the discovered\n * `CronNode[]` sorted by name. Throws `DuplicateCronNameError` on name\n * collision and `Error` on missing default export.\n *\n * Sequential by design — module imports are awaited one-by-one to keep\n * error messages anchored to the file that failed.\n */\nexport async function scanCrons(cronsDir: string): Promise<CronNode[]> {\n if (!existsSync(cronsDir)) return []\n\n const filePaths: string[] = []\n walkSourceFiles(cronsDir, { extensions: CRON_EXTENSIONS }, (p) => {\n const base = basename(p)\n // Skip private helpers (`_helper.ts`) and OS junk (`.DS_Store`).\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n\n const nodes: CronNode[] = []\n for (const filePath of filePaths) {\n let mod: CronModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import cron file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `Cron file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n schedule: exported.schedule,\n concurrency: exported.concurrency,\n })\n }\n\n // Dup-name detection\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateCronNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => a.name.localeCompare(b.name))\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { JobNode } from './job-scan.js'\n\nexport const JOB_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface JobManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport interface JobManifest {\n readonly schemaVersion: typeof JOB_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly jobs: readonly JobManifestEntry[]\n}\n\nexport function buildJobManifest(nodes: readonly JobNode[], projectRoot?: string): JobManifest {\n const jobs: JobManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n maxAttempts: n.maxAttempts,\n hasInputSchema: n.hasInputSchema,\n }))\n return {\n schemaVersion: JOB_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n jobs,\n }\n}\n\nexport function writeJobManifest(\n path: string,\n input: readonly JobNode[] | JobManifest,\n projectRoot?: string,\n): void {\n const manifest: JobManifest = isManifest(input) ? input : buildJobManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is JobManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'jobs' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { JobDefinition } from './job-types.js'\n\nexport interface JobNode {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport class DuplicateJobNameError extends Error {\n readonly code = 'DUPLICATE_JOB_NAME'\n constructor(\n public readonly jobName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate job name \"${jobName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Job names must be unique across server/jobs/.',\n )\n this.name = 'DuplicateJobNameError'\n }\n}\n\nconst JOB_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface JobModule {\n default?: unknown\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.handler === 'function' &&\n typeof def.maxAttempts === 'number' &&\n typeof def.hasInputSchema === 'boolean'\n )\n}\n\nexport async function scanJobs(jobsDir: string): Promise<JobNode[]> {\n if (!existsSync(jobsDir)) return []\n\n const filePaths: string[] = []\n walkSourceFiles(jobsDir, { extensions: JOB_EXTENSIONS }, (p) => {\n const base = basename(p)\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n\n const nodes: JobNode[] = []\n for (const filePath of filePaths) {\n let mod: JobModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import job file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isJobDefinition(exported)) {\n throw new Error(\n `Job file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineJob(name, { handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n maxAttempts: exported.maxAttempts,\n hasInputSchema: exported.hasInputSchema,\n })\n }\n\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateJobNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => a.name.localeCompare(b.name))\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Cleanup helpers. Paths are caller-controlled (CLI/config); EC-3 path-safety\n * guard rejects absolute paths outside cwd to prevent catastrophic data loss.\n */\n/**\n * State cleanup utilities (Phase 2 of\n * docs/plans/framework-zero-config-polish-plan.md).\n *\n * - `cleanOutDir` — Astro pattern: empty a directory except a skip list,\n * used at `theokit build` start.\n * - `gcAgentRegistry` — Nuxt LRU pattern: delete oldest agent dirs when\n * count exceeds cap, used at `theokit dev` startup.\n *\n * EC-3 (MUST FIX, CRITICAL): cleanOutDir refuses to wipe anything outside\n * the current cwd. Prevents catastrophic `distDir: '/'` data loss.\n * EC-9 (SHOULD TEST): gcAgentRegistry handles dirs with mtime=0 (Docker overlay).\n * EC-11 (SHOULD TEST): cleanOutDir normalizes trailing-slash in skip basenames.\n * EC-12 (SHOULD TEST): cleanOutDir catches EROFS and continues.\n */\n\nimport { promises as fs } from 'node:fs'\nimport { basename, resolve as resolvePath, sep } from 'node:path'\n\nimport type {\n CleanOutDirOptions,\n CleanOutDirResult,\n GcAgentRegistryOptions,\n GcAgentRegistryResult,\n} from './cleanup-types.js'\n\nconst DEFAULT_SKIP = ['.git', '.gitkeep', '.gitignore']\n// DEFAULT_MAX_AGENTS removed in Phase 7 — gcAgentRegistry is a tombstone.\n\nfunction normalizeSkipName(name: string): string {\n // EC-11 — strip trailing slash + leading `./`\n return basename(name.replace(/\\/$/, ''))\n}\n\n/**\n * Empty a directory, preserving entries in the skip list.\n *\n * Throws if `opts.dir` is not inside `process.cwd()` (EC-3 path safety).\n * Returns `{deleted:0, kept:0}` when the directory does not exist.\n */\nexport async function cleanOutDir(opts: CleanOutDirOptions): Promise<CleanOutDirResult> {\n const resolvedDir = resolvePath(opts.dir)\n const resolvedCwd = resolvePath(process.cwd())\n\n // EC-3 — path safety guard. CRITICAL.\n if (resolvedDir === resolvedCwd) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be a child of cwd, not cwd itself`,\n )\n }\n if (!resolvedDir.startsWith(resolvedCwd + sep)) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be inside cwd (${resolvedCwd})`,\n )\n }\n\n const skip = new Set((opts.skip ?? DEFAULT_SKIP).map(normalizeSkipName))\n\n let entries: { name: string }[]\n try {\n entries = await fs.readdir(resolvedDir, { withFileTypes: true })\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return { deleted: 0, kept: 0 }\n throw err\n }\n\n let deleted = 0\n let kept = 0\n for (const entry of entries) {\n const name = entry.name\n if (skip.has(name)) {\n kept++\n continue\n }\n const fullPath = resolvePath(resolvedDir, name)\n try {\n await fs.rm(fullPath, { recursive: true, force: true, maxRetries: 3 })\n deleted++\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n deleted++ // already gone\n continue\n }\n // EC-12 — EROFS or other rm failure: warn + continue, don't crash.\n console.warn(\n `[theokit] cleanOutDir could not remove ${fullPath} (${code ?? 'unknown'}); skipping`,\n )\n kept++\n }\n }\n\n return { deleted, kept }\n}\n\n/**\n * Phase 7 — TOMBSTONE for backward-compat. The SDK v1.1.0's `Agent.registry`\n * handles GC natively; this function is a no-op + emits a deprecation warning\n * ONCE per process (EC-10).\n *\n * Will be deleted entirely in TheoKit 0.4.0. Marked deprecated via runtime\n * warning rather than `@deprecated` JSDoc tag to avoid the eslint\n * sonarjs/deprecation flagging our own internal symbols.\n */\nlet warnedOnce = false\nexport async function gcAgentRegistry(\n _opts: GcAgentRegistryOptions,\n): Promise<GcAgentRegistryResult> {\n if (!warnedOnce) {\n warnedOnce = true\n console.warn(\n '[theokit] gcAgentRegistry is deprecated; SDK Agent.registry handles GC natively (configure via theo.config.ts > agents.registry)',\n )\n }\n return Promise.resolve({ deleted: 0, kept: 0 })\n}\n\n/**\n * @internal — testing helper. Resets the module-scoped warnedOnce flag.\n */\nexport function __resetGcDeprecationWarnedForTests(): void {\n warnedOnce = false\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,eAAe;;;ACsCjB,I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M,eAAe,QAAQ,KAAK,SAAS,WAAW;AACtD,mBAAiB,cAAc,UAAU,KAAK,GAAG;AACjD,UAAQ,IAAI,kBAAa,SAAS,MAAM,WAAW;AACrD;AAEA,SAASC,YAAW,SAAiB,MAAsB;AACzD,MAAI,QAAQ,WAAW,IAAI,GAAG;AAC5B,UAAM,UAAU,QAAQ,MAAM,KAAK,MAAM;AACzC,WAAO,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAAA,EACtD;AACA,SAAO;AACT;","names":["existsSync","existsSync","existsSync","relativize","isManifest","existsSync","basename","existsSync","basename","basename","writeManifest","existsSync","relativize"]}
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
} from "./chunk-GDN3PXFH.js";
|
|
10
10
|
import {
|
|
11
11
|
scanAgents
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-TERFLG67.js";
|
|
13
13
|
|
|
14
14
|
// src/server/agent/run-terminal-agent.ts
|
|
15
15
|
import {
|
|
@@ -149,10 +149,11 @@ async function agentCommand(name, message, deps = {}) {
|
|
|
149
149
|
throw new Error('theokit agent: a message is required. Usage: theokit agent <name> "<message>"');
|
|
150
150
|
}
|
|
151
151
|
const projectRoot = deps.projectRoot ?? process.cwd();
|
|
152
|
-
const
|
|
152
|
+
const agentsDir = deps.agentsDir ?? (await (await import("./load-config-3EAQTXPH.js")).loadConfig(projectRoot)).agentsDir;
|
|
153
|
+
const agents = scanAgents(projectRoot, agentsDir);
|
|
153
154
|
const agent = agents.find((a) => a.name === name);
|
|
154
155
|
if (!agent) {
|
|
155
|
-
const names = agents.map((a) => a.name).join(", ") ||
|
|
156
|
+
const names = agents.map((a) => a.name).join(", ") || `(none found in ${agentsDir}/)`;
|
|
156
157
|
throw new Error(`theokit agent: '${name}' not found. Available agents: ${names}`);
|
|
157
158
|
}
|
|
158
159
|
const runAgent = deps.runAgent ?? runAgentInTerminal;
|
|
@@ -177,14 +178,18 @@ async function agentCommand(name, message, deps = {}) {
|
|
|
177
178
|
async function createAgentSsrLoader(projectRoot) {
|
|
178
179
|
const { createServer } = await import("vite");
|
|
179
180
|
const react = (await import("@vitejs/plugin-react")).default;
|
|
180
|
-
const { theoPluginAsync } = await import("./vite-plugin-
|
|
181
|
-
const { loadConfig } = await import("./load-config-
|
|
181
|
+
const { theoPluginAsync } = await import("./vite-plugin-WIJ5RMQQ.js");
|
|
182
|
+
const { loadConfig } = await import("./load-config-3EAQTXPH.js");
|
|
182
183
|
const config = await loadConfig(projectRoot);
|
|
183
184
|
const theoPlugins = await theoPluginAsync({
|
|
184
185
|
root: projectRoot,
|
|
185
186
|
ssr: config.ssr,
|
|
186
187
|
services: config.services,
|
|
187
|
-
viteOptimizeDeps: config.viteOptimizeDeps
|
|
188
|
+
viteOptimizeDeps: config.viteOptimizeDeps,
|
|
189
|
+
// #95 — honor config `serverDir` so the terminal SSR loader transpiles under the same root as dev.
|
|
190
|
+
serverDir: config.serverDir,
|
|
191
|
+
// #95 follow-up — honor config `agentsDir`.
|
|
192
|
+
agentsDir: config.agentsDir
|
|
188
193
|
});
|
|
189
194
|
const server = await createServer({
|
|
190
195
|
root: projectRoot,
|
|
@@ -207,4 +212,4 @@ export {
|
|
|
207
212
|
agentCommand,
|
|
208
213
|
createAgentSsrLoader
|
|
209
214
|
};
|
|
210
|
-
//# sourceMappingURL=chunk-
|
|
215
|
+
//# sourceMappingURL=chunk-5YBUPJC2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/agent/run-terminal-agent.ts","../src/server/agent/render-terminal.ts","../src/cli/commands/agent.ts"],"sourcesContent":["/**\n * M5 (theokit-ai-first) — run a compiled agent in the terminal, reusing the M4 harness.\n *\n * The web `mountAgent` renders `streamAgentUIMessages` to an HTTP `Response` and resolves HITL\n * approvals via the approve route. This is its terminal sibling: SAME `compileAgentModule` + SAME\n * `streamAgentUIMessages` + SAME in-process approval registry — only the render surface (stdout) and\n * the approval input (a readline prompt) differ (ADR 0039 D2). In a single-process CLI the stream's\n * `awaitApproval` (→ `registry.register`) and the terminal prompt (→ `registry.resolve`) share the one\n * in-process registry — the M4 singleton's exact fit. No new runtime, no LLM call, no tool dispatch.\n */\nimport {\n compileAgentModule,\n streamAgentUIMessages,\n type HumanInTheLoopOptions,\n} from '@theokit/agents'\n\nimport { getApprovalRegistry, type ApprovalRegistry } from './approval-registry.js'\nimport {\n promptTerminalApproval,\n renderAgentStreamToTerminal,\n type TerminalOut,\n} from './render-terminal.js'\n\nexport interface RunTerminalAgentInput {\n message: string\n /** Resume key; a fresh id per run when omitted. */\n sessionId?: string\n /** Injectable sink (defaults to `process.stdout` at the CLI entry). */\n stdout?: TerminalOut\n /** Injectable shared registry (defaults to the process singleton). */\n registry?: ApprovalRegistry\n /** Injectable approval prompt (defaults to the readline prompt over the process streams). */\n promptApproval?: (req: { toolName: string; timeoutMs?: number }) => Promise<boolean>\n /** Labels a fail-fast `AgentDefinitionError` (the file path). */\n source?: string\n}\n\n/**\n * Compile the module (M4, gathers `@Mixin` toolboxes), stream it, and render to the terminal. When the\n * agent has `@HumanInTheLoop`-gated tools, the terminal prompts and resolves the shared registry —\n * approve runs the tool, deny/timeout/non-TTY denies and the run continues.\n */\nexport async function runAgentInTerminal(\n mod: unknown,\n apiKey: string,\n input: RunTerminalAgentInput,\n): Promise<{ sawError: boolean }> {\n const compiled = compileAgentModule(mod, input.source)\n const stdout = input.stdout ?? process.stdout\n const registry = input.registry ?? getApprovalRegistry()\n const sessionId = input.sessionId ?? crypto.randomUUID()\n const promptApproval =\n input.promptApproval ??\n ((req: { toolName: string; timeoutMs?: number }) =>\n promptTerminalApproval(req, { input: process.stdin, output: process.stdout }, req.timeoutMs))\n\n // Mirror mount-agent's HITL wiring; absent ⇒ the non-HITL stream path (M2), unchanged.\n const gated = compiled.hitl\n const hitl =\n gated && gated.size > 0\n ? {\n gated,\n awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions) =>\n registry.register(approvalId, {\n timeoutMs: opts.timeout ?? 300_000,\n onTimeout: opts.onTimeout ?? 'abort',\n }),\n }\n : undefined\n\n const chunks = streamAgentUIMessages(compiled, apiKey, {\n message: input.message,\n sessionId,\n hitl,\n })\n return renderAgentStreamToTerminal(chunks, {\n stdout,\n onApproval: async ({ approvalId, toolName }) => {\n // The renderer paused here (the SDK run is paused in its awaited pre_tool_call hook); prompt,\n // then resolve the SAME registry the stream registered into — the run resumes with the decision.\n // The prompt shares the gated tool's timeout so it can never outlive the registry-settled run.\n const timeoutMs = gated?.get(toolName)?.timeout ?? 300_000\n const approved = await promptApproval({ toolName, timeoutMs })\n registry.resolve(approvalId, approved)\n },\n })\n}\n","/**\n * M5 (theokit-ai-first) — the terminal render surface for the M4 agent harness.\n *\n * Consumes the M4 `UIMessageChunk` stream (`streamAgentUIMessages`) and writes it to the terminal:\n * streaming text, a dim reasoning line, `▸ tool(input)` / result cards, a checkpoint notice, errors.\n * On a HITL `tool-approval-request` it delegates to the injected `onApproval` (the entry wires that to\n * a readline prompt + the approval registry). This is the ONLY new code M5 adds — no runtime, no LLM\n * call, no tool dispatch (ADR 0039 D2). I/O is INJECTED (`stdout`, prompt streams) so the whole\n * surface is deterministically testable without a TTY (ADR 0039 D4 / ADR-M5a).\n */\nimport { createInterface } from 'node:readline'\nimport type { Readable, Writable } from 'node:stream'\n\nimport type { UIMessageChunk } from 'ai'\n\n/** ANSI helpers — applied only on a TTY so a captured (non-TTY) sink stays plain-text for tests. */\nconst ANSI = {\n dim: '\\x1b[2m',\n red: '\\x1b[31m',\n cyan: '\\x1b[36m',\n green: '\\x1b[32m',\n reset: '\\x1b[0m',\n}\nfunction paint(text: string, color: keyof typeof ANSI, tty: boolean | undefined): string {\n return tty ? `${ANSI[color]}${text}${ANSI.reset}` : text\n}\n\n/** A stdout-like sink; `isTTY` gates color (Node's `process.stdout` carries it, a test sink does not). */\nexport type TerminalOut = Writable & { isTTY?: boolean }\n\nexport interface TerminalRenderOptions {\n stdout: TerminalOut\n /** Resolve a HITL approval (the entry prompts + resolves the registry). */\n onApproval: (req: { approvalId: string; toolName: string }) => Promise<void>\n}\n\n/** Render an `unknown` tool output/input for display (string as-is; other JSON-ish values stringified). */\nfunction display(value: unknown): string {\n return typeof value === 'string' ? value : JSON.stringify(value ?? {})\n}\n\n/**\n * Map a single (non-approval) `UIMessageChunk` to its terminal line(s), or `''` for chunks that render\n * nothing (`start`/`text-start`/`reasoning-start`/…). Pure — the async loop owns approval + I/O.\n * Narrows the `ai` discriminated union directly on `chunk.type` (no cast; G3).\n */\nfunction renderChunkLine(chunk: UIMessageChunk, tty: boolean | undefined): string {\n switch (chunk.type) {\n case 'text-delta':\n return chunk.delta\n case 'text-end':\n case 'finish':\n return '\\n'\n case 'reasoning-delta':\n return paint(chunk.delta, 'dim', tty)\n case 'reasoning-end':\n return '\\n'\n case 'tool-input-available':\n return paint(`\\n▸ ${chunk.toolName}(${display(chunk.input)})\\n`, 'cyan', tty)\n case 'tool-output-available':\n return paint(` ✓ ${display(chunk.output)}\\n`, 'green', tty)\n case 'tool-output-error':\n return paint(` ✗ ${chunk.errorText}\\n`, 'red', tty)\n case 'error':\n return paint(`\\n✗ ${chunk.errorText}\\n`, 'red', tty)\n default:\n // ai-sdk `data-*` transient parts (e.g. the M4 `data-checkpoint` resume handle).\n return chunk.type === 'data-checkpoint'\n ? paint('\\n⎇ checkpoint saved — resume with the same session id\\n', 'dim', tty)\n : ''\n }\n}\n\n/**\n * Render the `UIMessageChunk` stream to `stdout`. Sequential: one chunk → its line(s). The SDK run is\n * already paused inside the awaited `pre_tool_call` hook when a `tool-approval-request` arrives, so a\n * blocking `await onApproval(...)` here is correct — no frame buffer, no concurrency. Returns whether\n * an `error` chunk was seen so the caller can signal a non-zero exit (fail-loud, not silent exit 0).\n */\nexport async function renderAgentStreamToTerminal(\n chunks: AsyncIterable<UIMessageChunk>,\n opts: TerminalRenderOptions,\n): Promise<{ sawError: boolean }> {\n const tty = opts.stdout.isTTY\n const write = (s: string): void => {\n if (s) opts.stdout.write(s)\n }\n // toolCallId → toolName, so the approval prompt (whose chunk carries only ids) can name the tool.\n const toolNames = new Map<string, string>()\n let sawError = false\n\n for await (const chunk of chunks) {\n if (chunk.type === 'tool-approval-request') {\n const toolName = toolNames.get(chunk.toolCallId)\n await opts.onApproval({ approvalId: chunk.approvalId, toolName: toolName ?? 'tool' })\n continue\n }\n if (chunk.type === 'tool-input-available' && chunk.toolCallId) {\n toolNames.set(chunk.toolCallId, chunk.toolName)\n }\n if (chunk.type === 'error') sawError = true\n write(renderChunkLine(chunk, tty))\n }\n return { sawError }\n}\n\n/** Injectable I/O for the approval prompt (defaults to the process streams at the CLI entry). */\nexport interface PromptIO {\n input: Readable & { isTTY?: boolean }\n output: Writable & { isTTY?: boolean }\n}\n\n/**\n * Prompt `Approve <tool>? (y/N)` and resolve to the decision. A non-interactive environment (piped /\n * CI — either stream is not a TTY) AUTO-DENIES without prompting (ADR-M5b fail-safe: a decision that\n * cannot be obtained is a deny, never an auto-approve; mirrors HITL `onTimeout: 'abort'`).\n *\n * `timeoutMs` (the gated tool's `@HumanInTheLoop` timeout) auto-denies + closes the prompt when the\n * human walks away — WITHOUT it the readline question would outlive the SDK run (the registry settles\n * the run at its own timeout but readline has no timer), hanging the CLI on a now-irrelevant prompt.\n */\nexport function promptTerminalApproval(\n req: { toolName: string },\n io: PromptIO,\n timeoutMs?: number,\n): Promise<boolean> {\n if (!io.input.isTTY || !io.output.isTTY) {\n io.output.write(`\\n⚠ Non-interactive terminal — auto-denying approval for '${req.toolName}'.\\n`)\n return Promise.resolve(false)\n }\n return new Promise<boolean>((resolve) => {\n const rl = createInterface({ input: io.input, output: io.output })\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (approved: boolean): void => {\n if (timer) clearTimeout(timer)\n rl.close()\n resolve(approved)\n }\n if (timeoutMs !== undefined && timeoutMs > 0) {\n timer = setTimeout(() => {\n io.output.write(`\\n⚠ Approval timed out — denying '${req.toolName}'.\\n`)\n settle(false)\n }, timeoutMs)\n }\n rl.question(`\\n❔ Approve ${req.toolName}? (y/N) `, (answer) => {\n const a = answer.trim().toLowerCase()\n settle(a === 'y' || a === 'yes')\n })\n })\n}\n","/**\n * M5 (theokit-ai-first) — `theokit agent <name> [message]`: run a scanned agent in the terminal.\n *\n * Scans the top-level `agents/` directory (M2), loads the matched `agents/<name>.ts` through the\n * framework's OWN Vite pipeline (the SAME transpile `theokit dev` uses — legacy `@Agent`/`@Tool`\n * decorators need it; Node's native loader can't transpile TS), resolves the provider apiKey, and\n * runs it in the terminal via the M4 harness (`runAgentInTerminal`). A dev-time surface (ADR 0039 D1),\n * not a CLI product. `deps` is injectable so the fail-fast branches are tested without Vite/an LLM.\n */\nimport { loadEnv } from '../../config/load-env.js'\nimport { resolveProvider } from '../../server/agent/provider-resolver.js'\nimport { runAgentInTerminal } from '../../server/agent/run-terminal-agent.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\n\nexport interface AgentCommandDeps {\n projectRoot?: string\n /** Load a TS agent module; defaults to a fresh minimal Vite SSR server (framework transpile). */\n loadModule?: (filePath: string) => Promise<Record<string, unknown>>\n runAgent?: typeof runAgentInTerminal\n resolveApiKey?: () => string\n}\n\nexport async function agentCommand(\n name: string,\n message: string | undefined,\n deps: AgentCommandDeps = {},\n): Promise<{ sawError: boolean }> {\n if (!message || message.trim().length === 0) {\n throw new Error('theokit agent: a message is required. Usage: theokit agent <name> \"<message>\"')\n }\n const projectRoot = deps.projectRoot ?? process.cwd()\n const agents = scanAgents(projectRoot)\n const agent = agents.find((a) => a.name === name)\n if (!agent) {\n const names = agents.map((a) => a.name).join(', ') || '(none found in agents/)'\n throw new Error(`theokit agent: '${name}' not found. Available agents: ${names}`)\n }\n\n const runAgent = deps.runAgent ?? runAgentInTerminal\n // Load .env into process.env BEFORE resolving the provider key — parity with `theokit dev`\n // (dev.ts loadEnv), so an app with OPENROUTER_API_KEY in .env works here too (review H1). Skipped\n // when the key is injected (tests) — a temp project has no .env anyway.\n const apiKey =\n deps.resolveApiKey?.() ??\n (() => {\n loadEnv({ cwd: projectRoot, mode: 'development' })\n return resolveProvider().apiKey\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 try {\n const mod = await loadModule(agent.filePath)\n return await runAgent(mod, apiKey, { message, source: agent.filePath })\n } finally {\n if (dispose) await dispose()\n }\n}\n\n/**\n * A minimal middleware-mode Vite server built from the SAME `theoPluginAsync` plugin set `theokit dev`\n * uses (`cli/commands/dev.ts`) — so a class-decorated `agents/<name>.ts` transpiles identically. No\n * HTTP listen, no service orchestration, silent — just `ssrLoadModule`. Caller MUST `dispose()`.\n */\nexport async function createAgentSsrLoader(projectRoot: string): Promise<{\n load: (p: string) => Promise<Record<string, unknown>>\n dispose: () => Promise<void>\n}> {\n const { createServer } = await import('vite')\n const react = (await import('@vitejs/plugin-react')).default\n const { theoPluginAsync } = await import('../../vite-plugin/index.js')\n const { loadConfig } = await import('../../config/load-config.js')\n // Pass the project's ssr/services/optimizeDeps config through, exactly as dev.ts does — so an app\n // that customizes ssr.noExternal transpiles here identically to `theokit dev` (review L1).\n const config = await loadConfig(projectRoot)\n const theoPlugins = await theoPluginAsync({\n root: projectRoot,\n ssr: config.ssr,\n services: config.services,\n viteOptimizeDeps: config.viteOptimizeDeps,\n })\n const server = await createServer({\n root: projectRoot,\n plugins: [react(), ...theoPlugins],\n server: { middlewareMode: true },\n appType: 'custom',\n logLevel: 'silent',\n })\n return {\n load: (p) => server.ssrLoadModule(p) as Promise<Record<string, unknown>>,\n dispose: async () => {\n // Surface a cleanup failure instead of swallowing it (error-handling.md) — non-fatal, the run\n // already finished, so warn rather than throw past the CLI boundary.\n await server.close().catch((err: unknown) => {\n console.warn('[theokit agent] Vite server cleanup error:', err)\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,EAC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A,EACZ,CAAC;AACD,SAAO;AAAA,IACL,MAAM,CAAC,MAAM,OAAO,cAAc,CAAC;AAAA,IACnC,SAAS,YAAY;AAGnB,YAAM,OAAO,MAAM,EAAE,MAAM,CAAC,QAAiB;AAC3C,gBAAQ,KAAK,8CAA8C,GAAG;AAAA,MAChE,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server/agent/run-terminal-agent.ts","../src/server/agent/render-terminal.ts","../src/cli/commands/agent.ts"],"sourcesContent":["/**\n * M5 (theokit-ai-first) — run a compiled agent in the terminal, reusing the M4 harness.\n *\n * The web `mountAgent` renders `streamAgentUIMessages` to an HTTP `Response` and resolves HITL\n * approvals via the approve route. This is its terminal sibling: SAME `compileAgentModule` + SAME\n * `streamAgentUIMessages` + SAME in-process approval registry — only the render surface (stdout) and\n * the approval input (a readline prompt) differ (ADR 0039 D2). In a single-process CLI the stream's\n * `awaitApproval` (→ `registry.register`) and the terminal prompt (→ `registry.resolve`) share the one\n * in-process registry — the M4 singleton's exact fit. No new runtime, no LLM call, no tool dispatch.\n */\nimport {\n compileAgentModule,\n streamAgentUIMessages,\n type HumanInTheLoopOptions,\n} from '@theokit/agents'\n\nimport { getApprovalRegistry, type ApprovalRegistry } from './approval-registry.js'\nimport {\n promptTerminalApproval,\n renderAgentStreamToTerminal,\n type TerminalOut,\n} from './render-terminal.js'\n\nexport interface RunTerminalAgentInput {\n message: string\n /** Resume key; a fresh id per run when omitted. */\n sessionId?: string\n /** Injectable sink (defaults to `process.stdout` at the CLI entry). */\n stdout?: TerminalOut\n /** Injectable shared registry (defaults to the process singleton). */\n registry?: ApprovalRegistry\n /** Injectable approval prompt (defaults to the readline prompt over the process streams). */\n promptApproval?: (req: { toolName: string; timeoutMs?: number }) => Promise<boolean>\n /** Labels a fail-fast `AgentDefinitionError` (the file path). */\n source?: string\n}\n\n/**\n * Compile the module (M4, gathers `@Mixin` toolboxes), stream it, and render to the terminal. When the\n * agent has `@HumanInTheLoop`-gated tools, the terminal prompts and resolves the shared registry —\n * approve runs the tool, deny/timeout/non-TTY denies and the run continues.\n */\nexport async function runAgentInTerminal(\n mod: unknown,\n apiKey: string,\n input: RunTerminalAgentInput,\n): Promise<{ sawError: boolean }> {\n const compiled = compileAgentModule(mod, input.source)\n const stdout = input.stdout ?? process.stdout\n const registry = input.registry ?? getApprovalRegistry()\n const sessionId = input.sessionId ?? crypto.randomUUID()\n const promptApproval =\n input.promptApproval ??\n ((req: { toolName: string; timeoutMs?: number }) =>\n promptTerminalApproval(req, { input: process.stdin, output: process.stdout }, req.timeoutMs))\n\n // Mirror mount-agent's HITL wiring; absent ⇒ the non-HITL stream path (M2), unchanged.\n const gated = compiled.hitl\n const hitl =\n gated && gated.size > 0\n ? {\n gated,\n awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions) =>\n registry.register(approvalId, {\n timeoutMs: opts.timeout ?? 300_000,\n onTimeout: opts.onTimeout ?? 'abort',\n }),\n }\n : undefined\n\n const chunks = streamAgentUIMessages(compiled, apiKey, {\n message: input.message,\n sessionId,\n hitl,\n })\n return renderAgentStreamToTerminal(chunks, {\n stdout,\n onApproval: async ({ approvalId, toolName }) => {\n // The renderer paused here (the SDK run is paused in its awaited pre_tool_call hook); prompt,\n // then resolve the SAME registry the stream registered into — the run resumes with the decision.\n // The prompt shares the gated tool's timeout so it can never outlive the registry-settled run.\n const timeoutMs = gated?.get(toolName)?.timeout ?? 300_000\n const approved = await promptApproval({ toolName, timeoutMs })\n registry.resolve(approvalId, approved)\n },\n })\n}\n","/**\n * M5 (theokit-ai-first) — the terminal render surface for the M4 agent harness.\n *\n * Consumes the M4 `UIMessageChunk` stream (`streamAgentUIMessages`) and writes it to the terminal:\n * streaming text, a dim reasoning line, `▸ tool(input)` / result cards, a checkpoint notice, errors.\n * On a HITL `tool-approval-request` it delegates to the injected `onApproval` (the entry wires that to\n * a readline prompt + the approval registry). This is the ONLY new code M5 adds — no runtime, no LLM\n * call, no tool dispatch (ADR 0039 D2). I/O is INJECTED (`stdout`, prompt streams) so the whole\n * surface is deterministically testable without a TTY (ADR 0039 D4 / ADR-M5a).\n */\nimport { createInterface } from 'node:readline'\nimport type { Readable, Writable } from 'node:stream'\n\nimport type { UIMessageChunk } from 'ai'\n\n/** ANSI helpers — applied only on a TTY so a captured (non-TTY) sink stays plain-text for tests. */\nconst ANSI = {\n dim: '\\x1b[2m',\n red: '\\x1b[31m',\n cyan: '\\x1b[36m',\n green: '\\x1b[32m',\n reset: '\\x1b[0m',\n}\nfunction paint(text: string, color: keyof typeof ANSI, tty: boolean | undefined): string {\n return tty ? `${ANSI[color]}${text}${ANSI.reset}` : text\n}\n\n/** A stdout-like sink; `isTTY` gates color (Node's `process.stdout` carries it, a test sink does not). */\nexport type TerminalOut = Writable & { isTTY?: boolean }\n\nexport interface TerminalRenderOptions {\n stdout: TerminalOut\n /** Resolve a HITL approval (the entry prompts + resolves the registry). */\n onApproval: (req: { approvalId: string; toolName: string }) => Promise<void>\n}\n\n/** Render an `unknown` tool output/input for display (string as-is; other JSON-ish values stringified). */\nfunction display(value: unknown): string {\n return typeof value === 'string' ? value : JSON.stringify(value ?? {})\n}\n\n/**\n * Map a single (non-approval) `UIMessageChunk` to its terminal line(s), or `''` for chunks that render\n * nothing (`start`/`text-start`/`reasoning-start`/…). Pure — the async loop owns approval + I/O.\n * Narrows the `ai` discriminated union directly on `chunk.type` (no cast; G3).\n */\nfunction renderChunkLine(chunk: UIMessageChunk, tty: boolean | undefined): string {\n switch (chunk.type) {\n case 'text-delta':\n return chunk.delta\n case 'text-end':\n case 'finish':\n return '\\n'\n case 'reasoning-delta':\n return paint(chunk.delta, 'dim', tty)\n case 'reasoning-end':\n return '\\n'\n case 'tool-input-available':\n return paint(`\\n▸ ${chunk.toolName}(${display(chunk.input)})\\n`, 'cyan', tty)\n case 'tool-output-available':\n return paint(` ✓ ${display(chunk.output)}\\n`, 'green', tty)\n case 'tool-output-error':\n return paint(` ✗ ${chunk.errorText}\\n`, 'red', tty)\n case 'error':\n return paint(`\\n✗ ${chunk.errorText}\\n`, 'red', tty)\n default:\n // ai-sdk `data-*` transient parts (e.g. the M4 `data-checkpoint` resume handle).\n return chunk.type === 'data-checkpoint'\n ? paint('\\n⎇ checkpoint saved — resume with the same session id\\n', 'dim', tty)\n : ''\n }\n}\n\n/**\n * Render the `UIMessageChunk` stream to `stdout`. Sequential: one chunk → its line(s). The SDK run is\n * already paused inside the awaited `pre_tool_call` hook when a `tool-approval-request` arrives, so a\n * blocking `await onApproval(...)` here is correct — no frame buffer, no concurrency. Returns whether\n * an `error` chunk was seen so the caller can signal a non-zero exit (fail-loud, not silent exit 0).\n */\nexport async function renderAgentStreamToTerminal(\n chunks: AsyncIterable<UIMessageChunk>,\n opts: TerminalRenderOptions,\n): Promise<{ sawError: boolean }> {\n const tty = opts.stdout.isTTY\n const write = (s: string): void => {\n if (s) opts.stdout.write(s)\n }\n // toolCallId → toolName, so the approval prompt (whose chunk carries only ids) can name the tool.\n const toolNames = new Map<string, string>()\n let sawError = false\n\n for await (const chunk of chunks) {\n if (chunk.type === 'tool-approval-request') {\n const toolName = toolNames.get(chunk.toolCallId)\n await opts.onApproval({ approvalId: chunk.approvalId, toolName: toolName ?? 'tool' })\n continue\n }\n if (chunk.type === 'tool-input-available' && chunk.toolCallId) {\n toolNames.set(chunk.toolCallId, chunk.toolName)\n }\n if (chunk.type === 'error') sawError = true\n write(renderChunkLine(chunk, tty))\n }\n return { sawError }\n}\n\n/** Injectable I/O for the approval prompt (defaults to the process streams at the CLI entry). */\nexport interface PromptIO {\n input: Readable & { isTTY?: boolean }\n output: Writable & { isTTY?: boolean }\n}\n\n/**\n * Prompt `Approve <tool>? (y/N)` and resolve to the decision. A non-interactive environment (piped /\n * CI — either stream is not a TTY) AUTO-DENIES without prompting (ADR-M5b fail-safe: a decision that\n * cannot be obtained is a deny, never an auto-approve; mirrors HITL `onTimeout: 'abort'`).\n *\n * `timeoutMs` (the gated tool's `@HumanInTheLoop` timeout) auto-denies + closes the prompt when the\n * human walks away — WITHOUT it the readline question would outlive the SDK run (the registry settles\n * the run at its own timeout but readline has no timer), hanging the CLI on a now-irrelevant prompt.\n */\nexport function promptTerminalApproval(\n req: { toolName: string },\n io: PromptIO,\n timeoutMs?: number,\n): Promise<boolean> {\n if (!io.input.isTTY || !io.output.isTTY) {\n io.output.write(`\\n⚠ Non-interactive terminal — auto-denying approval for '${req.toolName}'.\\n`)\n return Promise.resolve(false)\n }\n return new Promise<boolean>((resolve) => {\n const rl = createInterface({ input: io.input, output: io.output })\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (approved: boolean): void => {\n if (timer) clearTimeout(timer)\n rl.close()\n resolve(approved)\n }\n if (timeoutMs !== undefined && timeoutMs > 0) {\n timer = setTimeout(() => {\n io.output.write(`\\n⚠ Approval timed out — denying '${req.toolName}'.\\n`)\n settle(false)\n }, timeoutMs)\n }\n rl.question(`\\n❔ Approve ${req.toolName}? (y/N) `, (answer) => {\n const a = answer.trim().toLowerCase()\n settle(a === 'y' || a === 'yes')\n })\n })\n}\n","/**\n * M5 (theokit-ai-first) — `theokit agent <name> [message]`: run a scanned agent in the terminal.\n *\n * Scans the top-level `agents/` directory (M2), loads the matched `agents/<name>.ts` through the\n * framework's OWN Vite pipeline (the SAME transpile `theokit dev` uses — legacy `@Agent`/`@Tool`\n * decorators need it; Node's native loader can't transpile TS), resolves the provider apiKey, and\n * runs it in the terminal via the M4 harness (`runAgentInTerminal`). A dev-time surface (ADR 0039 D1),\n * not a CLI product. `deps` is injectable so the fail-fast branches are tested without Vite/an LLM.\n */\nimport { loadEnv } from '../../config/load-env.js'\nimport { resolveProvider } from '../../server/agent/provider-resolver.js'\nimport { runAgentInTerminal } from '../../server/agent/run-terminal-agent.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\n\nexport interface AgentCommandDeps {\n projectRoot?: string\n /** Load a TS agent module; defaults to a fresh minimal Vite SSR server (framework transpile). */\n loadModule?: (filePath: string) => Promise<Record<string, unknown>>\n runAgent?: typeof runAgentInTerminal\n resolveApiKey?: () => string\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 agentCommand(\n name: string,\n message: string | undefined,\n deps: AgentCommandDeps = {},\n): Promise<{ sawError: boolean }> {\n if (!message || message.trim().length === 0) {\n throw new Error('theokit agent: a message is required. Usage: theokit agent <name> \"<message>\"')\n }\n const projectRoot = deps.projectRoot ?? process.cwd()\n // #95 follow-up — resolve the agents dir from config (default \"agents\") so `agentsDir: \"core/agents\"`\n // is honored in the terminal, same as dev. Tests inject `agentsDir` to skip the config load.\n const agentsDir =\n deps.agentsDir ??\n (await (await import('../../config/load-config.js')).loadConfig(projectRoot)).agentsDir\n const agents = scanAgents(projectRoot, agentsDir)\n const agent = agents.find((a) => a.name === name)\n if (!agent) {\n const names = agents.map((a) => a.name).join(', ') || `(none found in ${agentsDir}/)`\n throw new Error(`theokit agent: '${name}' not found. Available agents: ${names}`)\n }\n\n const runAgent = deps.runAgent ?? runAgentInTerminal\n // Load .env into process.env BEFORE resolving the provider key — parity with `theokit dev`\n // (dev.ts loadEnv), so an app with OPENROUTER_API_KEY in .env works here too (review H1). Skipped\n // when the key is injected (tests) — a temp project has no .env anyway.\n const apiKey =\n deps.resolveApiKey?.() ??\n (() => {\n loadEnv({ cwd: projectRoot, mode: 'development' })\n return resolveProvider().apiKey\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 try {\n const mod = await loadModule(agent.filePath)\n return await runAgent(mod, apiKey, { message, source: agent.filePath })\n } finally {\n if (dispose) await dispose()\n }\n}\n\n/**\n * A minimal middleware-mode Vite server built from the SAME `theoPluginAsync` plugin set `theokit dev`\n * uses (`cli/commands/dev.ts`) — so a class-decorated `agents/<name>.ts` transpiles identically. No\n * HTTP listen, no service orchestration, silent — just `ssrLoadModule`. Caller MUST `dispose()`.\n */\nexport async function createAgentSsrLoader(projectRoot: string): Promise<{\n load: (p: string) => Promise<Record<string, unknown>>\n dispose: () => Promise<void>\n}> {\n const { createServer } = await import('vite')\n const react = (await import('@vitejs/plugin-react')).default\n const { theoPluginAsync } = await import('../../vite-plugin/index.js')\n const { loadConfig } = await import('../../config/load-config.js')\n // Pass the project's ssr/services/optimizeDeps config through, exactly as dev.ts does — so an app\n // that customizes ssr.noExternal transpiles here identically to `theokit dev` (review L1).\n const config = await loadConfig(projectRoot)\n const theoPlugins = await theoPluginAsync({\n root: projectRoot,\n ssr: config.ssr,\n services: config.services,\n viteOptimizeDeps: config.viteOptimizeDeps,\n // #95 — honor config `serverDir` so the terminal SSR loader transpiles under the same root as dev.\n serverDir: config.serverDir,\n // #95 follow-up — honor config `agentsDir`.\n agentsDir: config.agentsDir,\n })\n const server = await createServer({\n root: projectRoot,\n plugins: [react(), ...theoPlugins],\n server: { middlewareMode: true },\n appType: 'custom',\n logLevel: 'silent',\n })\n return {\n load: (p) => server.ssrLoadModule(p) as Promise<Record<string, unknown>>,\n dispose: async () => {\n // Surface a cleanup failure instead of swallowing it (error-handling.md) — non-fatal, the run\n // already finished, so warn rather than throw past the CLI boundary.\n await server.close().catch((err: unknown) => {\n console.warn('[theokit agent] Vite server cleanup error:', err)\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;;;ACJP,SAAS,uBAAuB;AAMhC,IAAM,OAAO;AAAA,EACX,KAAK;AAAA,EACL,KAAK;AAAA,EACL,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AACA,SAAS,MAAM,MAAc,OAA0B,KAAkC;AACvF,SAAO,MAAM,GAAG,KAAK,KAAK,CAAC,GAAG,IAAI,GAAG,KAAK,KAAK,KAAK;AACtD;AAYA,SAAS,QAAQ,OAAwB;AACvC,SAAO,OAAO,UAAU,WA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AQ,KAAK,8CAA8C,GAAG;AAAA,MAChE,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from "./chunk-GDN3PXFH.js";
|
|
6
6
|
import {
|
|
7
7
|
theoConfigSchema
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-GSO77FSM.js";
|
|
9
9
|
|
|
10
10
|
// src/config/load-config.ts
|
|
11
11
|
import { existsSync } from "fs";
|
|
@@ -140,4 +140,4 @@ export {
|
|
|
140
140
|
deepMerge,
|
|
141
141
|
loadConfig
|
|
142
142
|
};
|
|
143
|
-
//# sourceMappingURL=chunk-
|
|
143
|
+
//# sourceMappingURL=chunk-AFVTEAES.js.map
|
|
@@ -177,6 +177,12 @@ var theoConfigSchema = z8.object({
|
|
|
177
177
|
).optional(),
|
|
178
178
|
appDir: z8.string().default("app"),
|
|
179
179
|
serverDir: z8.string().default("server"),
|
|
180
|
+
/**
|
|
181
|
+
* Directory (relative to the project root) holding `agents/<name>.ts` definitions, scanned by
|
|
182
|
+
* dev/build/terminal/mcp. Defaults to `"agents"` — apps that keep the canonical layout are
|
|
183
|
+
* unaffected. Set to e.g. `"core/agents"` to organize agents under a domain root (#95 follow-up).
|
|
184
|
+
*/
|
|
185
|
+
agentsDir: z8.string().default("agents"),
|
|
180
186
|
/**
|
|
181
187
|
* T2.2 / EC-4 — Build output directory. Must be a relative path inside
|
|
182
188
|
* the project root. Refused absolute or parent-relative paths to prevent
|
|
@@ -397,4 +403,4 @@ export {
|
|
|
397
403
|
storageSchema,
|
|
398
404
|
theoConfigSchema
|
|
399
405
|
};
|
|
400
|
-
//# sourceMappingURL=chunk-
|
|
406
|
+
//# sourceMappingURL=chunk-GSO77FSM.js.map
|