theokit 0.75.1 → 0.76.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/README.md +88 -1
  2. package/dist/{actions-virtual-module-MIQPBAZW.js → actions-virtual-module-52O6HJZT.js} +11 -9
  3. package/dist/actions-virtual-module-52O6HJZT.js.map +1 -0
  4. package/dist/{actions-virtual-module-QEI6QPK4.js → actions-virtual-module-HS4W7HQU.js} +6 -5
  5. package/dist/{actions-virtual-module-QEI6QPK4.js.map → actions-virtual-module-HS4W7HQU.js.map} +1 -1
  6. package/dist/adapters/agent-mount.js +9 -7
  7. package/dist/{agent-N4OV5MDY.js → agent-HCK5RHH7.js} +4 -3
  8. package/dist/{app-typed-client-CHSITA46.js → app-typed-client-BWITJLJA.js} +6 -5
  9. package/dist/{app-typed-client-CHSITA46.js.map → app-typed-client-BWITJLJA.js.map} +1 -1
  10. package/dist/{app-typed-client-XQJXF646.js → app-typed-client-CJCOALMM.js} +11 -9
  11. package/dist/app-typed-client-CJCOALMM.js.map +1 -0
  12. package/dist/{aws-lambda-K5Y6XS5V.js → aws-lambda-XT7ZDJ6B.js} +3 -3
  13. package/dist/{build-GNKTCEES.js → build-Y3CWTWP6.js} +24 -92
  14. package/dist/build-Y3CWTWP6.js.map +1 -0
  15. package/dist/{bun-VPXMWFBA.js → bun-PJLDELDT.js} +5 -5
  16. package/dist/{chunk-J2KYVTPD.js → chunk-2SGNODVJ.js} +30 -16
  17. package/dist/chunk-2SGNODVJ.js.map +1 -0
  18. package/dist/chunk-2SQ7YAU3.js +85 -0
  19. package/dist/chunk-2SQ7YAU3.js.map +1 -0
  20. package/dist/{chunk-SYIQV4UH.js → chunk-36ZACTF3.js} +5 -5
  21. package/dist/{chunk-RY6D4EXL.js → chunk-3GM4GACM.js} +25 -4
  22. package/dist/{chunk-RY6D4EXL.js.map → chunk-3GM4GACM.js.map} +1 -1
  23. package/dist/{chunk-EW5IG7GA.js → chunk-42TYMRBG.js} +1 -1
  24. package/dist/{chunk-EW5IG7GA.js.map → chunk-42TYMRBG.js.map} +1 -1
  25. package/dist/{chunk-BINRCILF.js → chunk-4JRXZTVQ.js} +4 -13
  26. package/dist/chunk-4JRXZTVQ.js.map +1 -0
  27. package/dist/{chunk-R4AMIBZL.js → chunk-4XZOUS5G.js} +8 -8
  28. package/dist/chunk-4XZOUS5G.js.map +1 -0
  29. package/dist/{chunk-ICXXHV4V.js → chunk-54BIQFP4.js} +4 -13
  30. package/dist/chunk-54BIQFP4.js.map +1 -0
  31. package/dist/{chunk-VPK7ABMB.js → chunk-7MCEJVGV.js} +3 -3
  32. package/dist/{chunk-D7STTNQN.js → chunk-BXQCJJPT.js} +3 -3
  33. package/dist/{chunk-NX3P5MLH.js → chunk-C2BRSL4W.js} +50 -6
  34. package/dist/chunk-C2BRSL4W.js.map +1 -0
  35. package/dist/{chunk-E5QTCOKC.js → chunk-FEK25JUL.js} +88 -24
  36. package/dist/chunk-FEK25JUL.js.map +1 -0
  37. package/dist/{chunk-NLHAYGQQ.js → chunk-G3DDIEYE.js} +4 -2
  38. package/dist/chunk-G3DDIEYE.js.map +1 -0
  39. package/dist/chunk-IXXZBZF7.js +70 -0
  40. package/dist/chunk-IXXZBZF7.js.map +1 -0
  41. package/dist/{chunk-PVNMLZ5G.js → chunk-JO462JZM.js} +2 -2
  42. package/dist/chunk-LXV5IEBB.js +76 -0
  43. package/dist/chunk-LXV5IEBB.js.map +1 -0
  44. package/dist/{chunk-D2R5SJEL.js → chunk-MAJZ2L3A.js} +2 -2
  45. package/dist/{chunk-D2R5SJEL.js.map → chunk-MAJZ2L3A.js.map} +1 -1
  46. package/dist/chunk-NF7LXSXZ.js +19 -0
  47. package/dist/chunk-NF7LXSXZ.js.map +1 -0
  48. package/dist/chunk-OED37LE5.js +469 -0
  49. package/dist/chunk-OED37LE5.js.map +1 -0
  50. package/dist/{chunk-CLSYYO5F.js → chunk-OIYSUQM7.js} +2 -2
  51. package/dist/{chunk-2Z7TANA4.js → chunk-PVCXREGE.js} +6 -6
  52. package/dist/{chunk-EVKNHQWG.js → chunk-QBK6YYZA.js} +48 -5
  53. package/dist/chunk-QBK6YYZA.js.map +1 -0
  54. package/dist/{chunk-4X43VTST.js → chunk-TODO6J42.js} +1 -1
  55. package/dist/chunk-TODO6J42.js.map +1 -0
  56. package/dist/{chunk-ZDCCILMP.js → chunk-TQTEKNOL.js} +2 -69
  57. package/dist/chunk-TQTEKNOL.js.map +1 -0
  58. package/dist/{chunk-3MKRDJQ2.js → chunk-UQQQ3V43.js} +278 -75
  59. package/dist/chunk-UQQQ3V43.js.map +1 -0
  60. package/dist/{chunk-MX63AWEK.js → chunk-VXDTQO3S.js} +22 -6
  61. package/dist/{chunk-MX63AWEK.js.map → chunk-VXDTQO3S.js.map} +1 -1
  62. package/dist/{chunk-OZB2TKGJ.js → chunk-W2I6L4IJ.js} +2 -2
  63. package/dist/{chunk-UWV3B3RY.js → chunk-XDLFOATW.js} +5 -5
  64. package/dist/{chunk-RQKMY3JW.js → chunk-XI4FALFZ.js} +3 -3
  65. package/dist/chunk-XI4FALFZ.js.map +1 -0
  66. package/dist/{chunk-2FHNJ7LI.js → chunk-Z76QQR7I.js} +2 -2
  67. package/dist/chunk-ZICY2CD7.js +16 -0
  68. package/dist/chunk-ZICY2CD7.js.map +1 -0
  69. package/dist/chunk-ZN5H7CUR.js +24 -0
  70. package/dist/chunk-ZN5H7CUR.js.map +1 -0
  71. package/dist/{chunk-I5PDEWZZ.js → chunk-ZQJORKBM.js} +9 -3
  72. package/dist/chunk-ZQJORKBM.js.map +1 -0
  73. package/dist/cli/index.js +21 -15
  74. package/dist/cli/index.js.map +1 -1
  75. package/dist/{cloudflare-7EZQE4UV.js → cloudflare-F7KLBOU4.js} +6 -6
  76. package/dist/{config-support-HUZ4DXR7.js → config-support-2TER2BYD.js} +28 -21
  77. package/dist/config-support-2TER2BYD.js.map +1 -0
  78. package/dist/cron-lock-CfAvLApv.d.ts +36 -0
  79. package/dist/db-ZWDKD57T.js +86 -0
  80. package/dist/db-ZWDKD57T.js.map +1 -0
  81. package/dist/{deno-deploy-M5V3PYWU.js → deno-deploy-LJ5JQQVR.js} +5 -5
  82. package/dist/{dev-7PMNIIOF.js → dev-R2ZYHZV4.js} +60 -11
  83. package/dist/dev-R2ZYHZV4.js.map +1 -0
  84. package/dist/{engine-singleton-X4R7AZBJ.js → engine-singleton-BQ5QOMTC.js} +15 -9
  85. package/dist/{engine-singleton-X4R7AZBJ.js.map → engine-singleton-BQ5QOMTC.js.map} +1 -1
  86. package/dist/{generate-RW3NO3NR.js → generate-VXBSMUMW.js} +291 -85
  87. package/dist/generate-VXBSMUMW.js.map +1 -0
  88. package/dist/{index-CmkWlIDO.d.ts → index-DfsJ3Qhk.d.ts} +1 -1
  89. package/dist/index.d.ts +10 -1
  90. package/dist/index.js +12 -10
  91. package/dist/index.js.map +1 -1
  92. package/dist/{info-6NAUW5XY.js → info-IPMW56PI.js} +4 -4
  93. package/dist/{internal-api-R7TTYMCY.js → internal-api-6RAOYIET.js} +6 -5
  94. package/dist/{internal-api-A5HA7TYF.js → internal-api-YGFPLQ4E.js} +14 -11
  95. package/dist/job-backend-WvUs5rO1.d.ts +119 -0
  96. package/dist/{load-config-CLFWJOXN.js → load-config-USRR4GXP.js} +4 -4
  97. package/dist/{mcp-3NRZAQKY.js → mcp-FBXEX45H.js} +5 -4
  98. package/dist/{mcp-3NRZAQKY.js.map → mcp-FBXEX45H.js.map} +1 -1
  99. package/dist/{netlify-NI4HYDKN.js → netlify-ZPQNREFH.js} +2 -2
  100. package/dist/{node-LORYECWI.js → node-3EV3CVWB.js} +2 -2
  101. package/dist/{observability-bootstrap-DOWRMADT.js → observability-bootstrap-DMJ7R6WA.js} +3 -3
  102. package/dist/{openapi-ZHKJB3XL.js → openapi-CA3E3LZH.js} +4 -4
  103. package/dist/{preview-SNS7VJWH.js → preview-DLIVPM7A.js} +3 -3
  104. package/dist/registry-3D2KR7UE.js +34 -0
  105. package/dist/{routes-SMNSI2ZX.js → routes-BJ7GGRCV.js} +4 -4
  106. package/dist/{schema-DJH3IOVR.js → schema-FBM2UH72.js} +3 -3
  107. package/dist/{schemas-2R2J64ZH.js → schemas-BUR6PWSA.js} +2 -2
  108. package/dist/server/agent/index.d.ts +1 -1
  109. package/dist/server/agent/index.js +2 -1
  110. package/dist/server/cost/index.d.ts +2 -2
  111. package/dist/server/cost/index.js +1 -1
  112. package/dist/server/cost/sqlite/index.d.ts +2 -2
  113. package/dist/server/cost/sqlite/index.js +1 -1
  114. package/dist/server/cron/index.d.ts +20 -7
  115. package/dist/server/cron/index.js +8 -2
  116. package/dist/server/http/index.d.ts +2 -2
  117. package/dist/server/http/index.js +9 -7
  118. package/dist/server/index.d.ts +19 -10
  119. package/dist/server/index.js +103 -41
  120. package/dist/server/index.js.map +1 -1
  121. package/dist/server/jobs/index.d.ts +85 -44
  122. package/dist/server/jobs/index.js +9 -2
  123. package/dist/server/observability/index.js +9 -8
  124. package/dist/server/storage/index.d.ts +6 -2
  125. package/dist/server/storage/index.js +5 -1
  126. package/dist/server/webhook/index.d.ts +4 -5
  127. package/dist/server/webhook/index.js +1 -1
  128. package/dist/{server-boundary-ZT6HN7ON.js → server-boundary-EKIGYL7B.js} +6 -5
  129. package/dist/{server-boundary-ZT6HN7ON.js.map → server-boundary-EKIGYL7B.js.map} +1 -1
  130. package/dist/{server-boundary-HYLYGFZY.js → server-boundary-IDWIB24L.js} +11 -9
  131. package/dist/server-boundary-IDWIB24L.js.map +1 -0
  132. package/dist/{start-L5TGWGLU.js → start-LNT5UVSY.js} +118 -185
  133. package/dist/start-LNT5UVSY.js.map +1 -0
  134. package/dist/{static-O2RZ5NLR.js → static-VNN4HYRN.js} +2 -2
  135. package/dist/{storage-manager-3O5PDO6O.js → storage-manager-3IUIEG2P.js} +49 -5
  136. package/dist/storage-manager-3IUIEG2P.js.map +1 -0
  137. package/dist/{storage-manager-BtG38jYl.d.ts → storage-manager-Clu2RBpH.d.ts} +15 -3
  138. package/dist/{storage-types-CFGPFIdB.d.ts → storage-types-ndO0ZZqH.d.ts} +2 -2
  139. package/dist/{theo-cloud-B4R7GCWK.js → theo-cloud-243SPOIA.js} +2 -2
  140. package/dist/{vercel-INHLOCSZ.js → vercel-EXKSZ2OQ.js} +5 -5
  141. package/dist/vite-plugin/index.js +12 -10
  142. package/dist/{vite-plugin-UXEXT7GX.js → vite-plugin-LE42ZIGV.js} +10 -9
  143. package/dist/{whatsapp-D_Fnl1LX.d.ts → whatsapp-4W2eK2ij.d.ts} +1 -1
  144. package/package.json +1 -1
  145. package/dist/actions-virtual-module-MIQPBAZW.js.map +0 -1
  146. package/dist/app-typed-client-XQJXF646.js.map +0 -1
  147. package/dist/build-GNKTCEES.js.map +0 -1
  148. package/dist/chunk-3MKRDJQ2.js.map +0 -1
  149. package/dist/chunk-4X43VTST.js.map +0 -1
  150. package/dist/chunk-BINRCILF.js.map +0 -1
  151. package/dist/chunk-E5QTCOKC.js.map +0 -1
  152. package/dist/chunk-EVKNHQWG.js.map +0 -1
  153. package/dist/chunk-I5PDEWZZ.js.map +0 -1
  154. package/dist/chunk-ICXXHV4V.js.map +0 -1
  155. package/dist/chunk-IDEZ7FU2.js +0 -18
  156. package/dist/chunk-IDEZ7FU2.js.map +0 -1
  157. package/dist/chunk-J2KYVTPD.js.map +0 -1
  158. package/dist/chunk-NLHAYGQQ.js.map +0 -1
  159. package/dist/chunk-NX3P5MLH.js.map +0 -1
  160. package/dist/chunk-R4AMIBZL.js.map +0 -1
  161. package/dist/chunk-RQKMY3JW.js.map +0 -1
  162. package/dist/chunk-YCF3N4JS.js +0 -26
  163. package/dist/chunk-YCF3N4JS.js.map +0 -1
  164. package/dist/chunk-ZDCCILMP.js.map +0 -1
  165. package/dist/config-support-HUZ4DXR7.js.map +0 -1
  166. package/dist/db-IVVCQE5Z.js +0 -76
  167. package/dist/db-IVVCQE5Z.js.map +0 -1
  168. package/dist/dev-7PMNIIOF.js.map +0 -1
  169. package/dist/generate-RW3NO3NR.js.map +0 -1
  170. package/dist/job-backend-CgC8Xf33.d.ts +0 -68
  171. package/dist/registry-3SVWZVIJ.js +0 -34
  172. package/dist/server-boundary-HYLYGFZY.js.map +0 -1
  173. package/dist/start-L5TGWGLU.js.map +0 -1
  174. package/dist/storage-manager-3O5PDO6O.js.map +0 -1
  175. /package/dist/{agent-N4OV5MDY.js.map → agent-HCK5RHH7.js.map} +0 -0
  176. /package/dist/{aws-lambda-K5Y6XS5V.js.map → aws-lambda-XT7ZDJ6B.js.map} +0 -0
  177. /package/dist/{bun-VPXMWFBA.js.map → bun-PJLDELDT.js.map} +0 -0
  178. /package/dist/{chunk-SYIQV4UH.js.map → chunk-36ZACTF3.js.map} +0 -0
  179. /package/dist/{chunk-VPK7ABMB.js.map → chunk-7MCEJVGV.js.map} +0 -0
  180. /package/dist/{chunk-D7STTNQN.js.map → chunk-BXQCJJPT.js.map} +0 -0
  181. /package/dist/{chunk-PVNMLZ5G.js.map → chunk-JO462JZM.js.map} +0 -0
  182. /package/dist/{chunk-CLSYYO5F.js.map → chunk-OIYSUQM7.js.map} +0 -0
  183. /package/dist/{chunk-2Z7TANA4.js.map → chunk-PVCXREGE.js.map} +0 -0
  184. /package/dist/{chunk-OZB2TKGJ.js.map → chunk-W2I6L4IJ.js.map} +0 -0
  185. /package/dist/{chunk-UWV3B3RY.js.map → chunk-XDLFOATW.js.map} +0 -0
  186. /package/dist/{chunk-2FHNJ7LI.js.map → chunk-Z76QQR7I.js.map} +0 -0
  187. /package/dist/{cloudflare-7EZQE4UV.js.map → cloudflare-F7KLBOU4.js.map} +0 -0
  188. /package/dist/{deno-deploy-M5V3PYWU.js.map → deno-deploy-LJ5JQQVR.js.map} +0 -0
  189. /package/dist/{info-6NAUW5XY.js.map → info-IPMW56PI.js.map} +0 -0
  190. /package/dist/{internal-api-R7TTYMCY.js.map → internal-api-6RAOYIET.js.map} +0 -0
  191. /package/dist/{internal-api-A5HA7TYF.js.map → internal-api-YGFPLQ4E.js.map} +0 -0
  192. /package/dist/{load-config-CLFWJOXN.js.map → load-config-USRR4GXP.js.map} +0 -0
  193. /package/dist/{netlify-NI4HYDKN.js.map → netlify-ZPQNREFH.js.map} +0 -0
  194. /package/dist/{node-LORYECWI.js.map → node-3EV3CVWB.js.map} +0 -0
  195. /package/dist/{observability-bootstrap-DOWRMADT.js.map → observability-bootstrap-DMJ7R6WA.js.map} +0 -0
  196. /package/dist/{openapi-ZHKJB3XL.js.map → openapi-CA3E3LZH.js.map} +0 -0
  197. /package/dist/{preview-SNS7VJWH.js.map → preview-DLIVPM7A.js.map} +0 -0
  198. /package/dist/{registry-3SVWZVIJ.js.map → registry-3D2KR7UE.js.map} +0 -0
  199. /package/dist/{routes-SMNSI2ZX.js.map → routes-BJ7GGRCV.js.map} +0 -0
  200. /package/dist/{schema-DJH3IOVR.js.map → schema-FBM2UH72.js.map} +0 -0
  201. /package/dist/{schemas-2R2J64ZH.js.map → schemas-BUR6PWSA.js.map} +0 -0
  202. /package/dist/{static-O2RZ5NLR.js.map → static-VNN4HYRN.js.map} +0 -0
  203. /package/dist/{theo-cloud-B4R7GCWK.js.map → theo-cloud-243SPOIA.js.map} +0 -0
  204. /package/dist/{vercel-INHLOCSZ.js.map → vercel-EXKSZ2OQ.js.map} +0 -0
  205. /package/dist/{vite-plugin-UXEXT7GX.js.map → vite-plugin-LE42ZIGV.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/generate.ts","../src/cli/commands/generate-containment.ts","../src/cli/commands/generate-policy-placeholder.ts","../src/cli/commands/generate-resource.ts","../src/cli/commands/generate-schedule.ts","../src/server/cron/define-cron.ts","../src/cli/commands/generate-types.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { posix, resolve, dirname } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\n\nimport { pathTraversalRefusal } from './generate-containment.js'\nimport {\n UNDECIDED_POLICY_IDENT,\n undecidedPolicyDeclaration,\n} from './generate-policy-placeholder.js'\nimport { generateResource } from './generate-resource.js'\nimport { resolveScheduleTarget } from './generate-schedule.js'\nimport {\n VALID_TYPES,\n type GeneratorType,\n type GenerateOptions,\n type GenerateResult,\n type GenerateStatus,\n} from './generate-types.js'\n\nexport {}\n\nfunction toKebabCase(name: string): boolean {\n return /^[a-z][a-z0-9/-]*$/.test(name)\n}\n\n/**\n * Reserved JS identifier names that conflict with object prototype machinery\n * or would shadow built-in module shapes if used as action/route names.\n * Mirrors action-scan's RESERVED_NAMES (T1.4).\n */\nconst RESERVED_BASENAMES = new Set([\n 'index',\n 'constructor',\n '__proto__',\n 'prototype',\n 'hasOwnProperty',\n])\n\n/**\n * Validate that a name segment doesn't hit the reserved-identifier list.\n * Checks the BASENAME (last `/` segment) — nested `admin/constructor` still\n * rejected because the file `constructor.ts` would be the conflict.\n */\nfunction hasReservedSegment(name: string): boolean {\n const basename = name.includes('/') ? (name.split('/').pop() ?? name) : name\n return RESERVED_BASENAMES.has(basename)\n}\n\nfunction toPascalCase(name: string): string {\n return name\n .split(/[-/]/)\n .map((s) => s.charAt(0).toUpperCase() + s.slice(1))\n .join('')\n}\n\nfunction toCamelCase(name: string): string {\n const pascal = toPascalCase(name)\n return pascal.charAt(0).toLowerCase() + pascal.slice(1)\n}\n\nfunction generateRouteTemplate(name: string, displayPath: string): string {\n return [\n `import { route, type AccessDecision } from 'theokit/server'`,\n `import { z } from 'zod'`,\n ``,\n ...undecidedPolicyDeclaration(displayPath, 'a stub today is a real handler tomorrow'),\n ``,\n `export const GET = route()`,\n ` .policy(${UNDECIDED_POLICY_IDENT})`,\n ` .handler(({ ctx }) => {`,\n ` return { message: 'TODO: implement ${name} GET' }`,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateControllerTemplate(name: string): string {\n const className = toPascalCase(name) + 'Controller'\n const baseName = name.split('/').pop() ?? name\n return [\n `// AUTO-GENERATED by \\`theokit generate controller ${name}\\``,\n `import { Controller, Get } from '@theokit/http'`,\n ``,\n `@Controller('${baseName}')`,\n `export class ${className} {`,\n ` @Get()`,\n ` findAll(): string {`,\n ` return 'This action returns all ${baseName}'`,\n ` }`,\n `}`,\n ``,\n ].join('\\n')\n}\n\nfunction generateActionTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { action } from 'theokit/server'`,\n `import { z } from 'zod'`,\n ``,\n `export const ${camel} = action()`,\n ` .input(z.object({}))`,\n ` .handler(({ input, ctx }) => {`,\n ` return { message: 'TODO: implement ${name}' }`,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\n/**\n * Co-located test template for `theokit generate action <name>` (T5.2 +\n * plan Q4 scenario 1: roundtrip serialize). Skeleton uses vitest BDD shape\n * per testing.md.\n */\nfunction generateAgentTemplate(name: string, displayPath: string): string {\n return [\n `import { AgentBuilder } from '@theokit/agents'`,\n `import type { AccessDecision } from 'theokit/server'`,\n `import { z } from 'zod'`,\n ``,\n `// Zero-config: this file is auto-served at POST /api/agents/${name}.`,\n `// Add tools with tool('name')...build() and chain them via .tool(...).`,\n ``,\n ...undecidedPolicyDeclaration(displayPath, 'an agent endpoint runs a model on your key'),\n `export const policy = ${UNDECIDED_POLICY_IDENT}`,\n ``,\n `export default AgentBuilder.create()`,\n ` .input(z.object({ message: z.string() }))`,\n ` .model('openai/gpt-4o-mini')`,\n ` .system('You are a helpful ${name} assistant.')`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateToolboxTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { tool } from 'theokit/server'`,\n `import { z } from 'zod'`,\n ``,\n `export const ${camel}Hello = tool('${name}_hello')`,\n ` .describe('Say hello')`,\n ` .input(z.object({ name: z.string() }))`,\n ` .execute(({ name }) => \\`Hello, \\${name}!\\`)`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateWorkflowTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { Workflow, fn } from '@theokit/sdk/workflow'`,\n ``,\n `/**`,\n ` * A minimal workflow — a typed, multi-step pipeline (@theokit/sdk). Each \\`fn(...)\\` step is a pure`,\n ` * function; a step can also run an agent via \\`agentStep(name, agent, mapInput)\\`. Import + run it from`,\n ` * a route, action, cron job, or tool:`,\n ` *`,\n ` * const run = await ${camel}Workflow.run({ name: 'Ada' })`,\n ` * console.log(run.status, run.output) // 'completed' 'Hello, Ada!'`,\n ` */`,\n `export const ${camel}Workflow = Workflow.create({ name: '${name}' })`,\n ` .then(fn('normalize', (input: { name: string }) => ({ name: input.name.trim() })))`,\n ` .then(fn('greet', (step: { name: string }) => \\`Hello, \\${step.name}!\\`))`,\n ` .commit()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateEvalTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { Eval, Scorers } from '@theokit/sdk/eval'`,\n ``,\n `/**`,\n ` * An eval for your agent (@theokit/sdk) — runs the model over a dataset and scores each output.`,\n ` * To score the REAL agent, mirror its config: point \\`agent.model\\` (and, ideally, a \\`systemPrompt\\`)`,\n ` * at the same values your \\`agents/chat.ts\\` uses. Run it (needs a provider key in the environment):`,\n ` *`,\n ` * const run = await ${camel}Eval.run()`,\n ` * console.log(run.aggregate.meanScore)`,\n ` */`,\n `export const ${camel}Eval = Eval.create({`,\n ` name: '${name}',`,\n ` dataset: [{ input: 'Say ok', expected: 'ok' }],`,\n ` scorers: [Scorers.containsExpected({ caseSensitive: false })],`,\n ` // Mirror your agent: same model (+ systemPrompt) so this evaluates the agent your users talk to.`,\n ` agent: { apiKey: process.env.OPENROUTER_API_KEY ?? '', model: { id: 'openai/gpt-4o-mini' } },`,\n `})`,\n ``,\n ].join('\\n')\n}\n\nfunction generateSandboxTemplate(name: string): string {\n const camel = toCamelCase(name)\n const base = name.split('/').pop() ?? name\n const snake = base.replace(/-/g, '_')\n return [\n `import { tool } from 'theokit/server'`,\n `import { LocalSandbox } from '@theokit/sdk/sandbox'`,\n `import { z } from 'zod'`,\n ``,\n `/**`,\n ` * A sandbox-backed agent tool. \\`LocalSandbox\\` (@theokit/sdk) runs a shell command with a timeout +`,\n ` * output cap, isolated from your app process — so the agent can run commands SAFELY. This IS an agent`,\n ` * capability: connect it to your agent with \\`.tool(...)\\`:`,\n ` *`,\n ` * // agents/chat.ts`,\n ` * import { ${camel}Tool } from './sandbox/${base}.js'`,\n ` * AgentBuilder.create().model(...).tool(${camel}Tool).build()`,\n ` */`,\n `export const ${camel}Tool = tool('${snake}')`,\n ` .describe('Run a shell command in an isolated sandbox and return its output.')`,\n ` .input(z.object({ command: z.string().describe('The shell command to run, e.g. \"ls -la\"') }))`,\n ` .execute(async ({ command }) => {`,\n ` const sandbox = new LocalSandbox({ timeoutMs: 5_000 })`,\n ` const { stdout, stderr, exitCode } = await sandbox.execute(command)`,\n ` return exitCode === 0 ? stdout : \\`exit \\${exitCode}: \\${stderr}\\``,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateMemoryTemplate(_name: string): string {\n return [\n `/**`,\n ` * Conversation memory — nothing to wire.`,\n ` *`,\n ` * Since @theokit/sdk 4.0, every agent session persists AUTOMATICALLY to a native Claude-shaped`,\n ` * transcript. TheoKit roots it at your app under \\`.data/agent-sessions/projects/<cwd>/<agentId>.jsonl\\`,`,\n ` * keyed by the conversation's session id — a same-session follow-up request resumes prior turns with`,\n ` * zero setup. There is no storage adapter to construct or pass to the agent anymore.`,\n ` *`,\n ` * Keep these transcripts out of git — add \\`.data/\\` to your \\`.gitignore\\`.`,\n ` *`,\n ` * Advanced: to change WHERE sessions are written (e.g. \\`~/.claude\\` so the Claude Code CLI can`,\n ` * \\`--continue\\` them), set the SDK's \\`local.baseDir\\` where you create the agent. Most apps never need to.`,\n ` */`,\n `export {}`,\n ``,\n ].join('\\n')\n}\n\n/** The project directories from `theo.config.ts`, each relative to the project root. */\ninterface ProjectLayout {\n appDir: string\n serverDir: string\n agentsDir: string\n}\n\n/** Where a single-file kind is written, relative to the project root, and what it says. */\ninterface SingleFileKind {\n path: (name: string, layout: ProjectLayout) => string\n /** `displayPath` is the project-relative path, for a template that names its own file. */\n template: (name: string, displayPath: string) => string\n}\n\n/**\n * The single-file kinds. `resource` writes several files and `schedule` checks more than its\n * directory, so neither is here. Every path starts from a directory `theo.config.ts` declares: the\n * scaffold puts them under `src/`, and a hardcoded `server/` wrote files no scanner reads (#1031).\n */\nconst SINGLE_FILE_KINDS: Partial<Record<GeneratorType, SingleFileKind>> = {\n // Agent-capability generators. These live UNDER `agentsDir` — they are facets of the agent\n // domain, not standalone top-level concerns — and the folder-semantic scanner treats each as\n // composition (never a phantom route).\n workflow: {\n path: (name, { agentsDir }) => posix.join(agentsDir, 'workflows', `${name}.ts`),\n template: generateWorkflowTemplate,\n },\n eval: {\n path: (name, { agentsDir }) => posix.join(agentsDir, 'evals', `${name}.ts`),\n template: generateEvalTemplate,\n },\n sandbox: {\n path: (name, { agentsDir }) => posix.join(agentsDir, 'sandbox', `${name}.ts`),\n template: generateSandboxTemplate,\n },\n memory: {\n path: (name, { agentsDir }) => posix.join(agentsDir, 'memory', `${name}.ts`),\n template: generateMemoryTemplate,\n },\n route: {\n path: (name, { serverDir }) => posix.join(serverDir, 'routes', `${name}.ts`),\n template: generateRouteTemplate,\n },\n action: {\n path: (name, { serverDir }) => posix.join(serverDir, 'actions', `${name}.ts`),\n template: generateActionTemplate,\n },\n page: {\n path: (name, { appDir }) => posix.join(appDir, name, 'page.tsx'),\n template: generatePageTemplate,\n },\n ws: {\n path: (name, { serverDir }) => posix.join(serverDir, 'ws', `${name}.ts`),\n template: generateWsTemplate,\n },\n controller: {\n path: (name, { serverDir }) => posix.join(serverDir, 'controllers', `${name}.controller.ts`),\n template: generateControllerTemplate,\n },\n // `<agentsDir>/<name>.ts` is what the agent scanner serves at `/api/agents/<name>`, the URL the\n // template promises. The old `server/agents/<name>.agent.ts` was outside `agentsDir` in both the\n // flat and the scaffold layout, so the agent was never served.\n agent: {\n path: (name, { agentsDir }) => posix.join(agentsDir, `${name}.ts`),\n template: generateAgentTemplate,\n },\n toolbox: {\n path: (name, { serverDir }) => posix.join(serverDir, 'toolboxes', `${name}.tools.ts`),\n template: generateToolboxTemplate,\n },\n}\n\n/** The project layout from `theo.config.ts`, or the refusal naming why it could not be read. */\nasync function readLayout(cwd: string): Promise<ProjectLayout | GenerateResult> {\n try {\n const { appDir, serverDir, agentsDir } = await loadConfig(cwd)\n return { appDir, serverDir, agentsDir }\n } catch (err) {\n return {\n status: 'invalid_config',\n message: `Cannot read ${resolve(cwd, 'theo.config.ts')}: ${(err as Error).message}`,\n }\n }\n}\n\nasync function resolveTemplate(\n cwd: string,\n kind: GeneratorType,\n name: string,\n): Promise<Target | GenerateResult | null> {\n const spec = SINGLE_FILE_KINDS[kind]\n if (spec === undefined) return null\n const layout = await readLayout(cwd)\n if ('status' in layout) return layout\n const displayPath = spec.path(name, layout)\n return { filePath: resolve(cwd, displayPath), content: spec.template(name, displayPath) }\n}\n\nfunction generateActionTestTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { describe, it, expect } from 'vitest'`,\n ``,\n `import { ${camel} } from './${name.split('/').pop()}.js'`,\n ``,\n `describe('${name} action', () => {`,\n ` it('should accept a valid input shape', () => {`,\n ` expect(${camel}.input).toBeDefined()`,\n ` expect(typeof ${camel}.handler).toBe('function')`,\n ` })`,\n ``,\n ` it('should reject invalid input via zod schema', () => {`,\n ` const parsed = ${camel}.input.safeParse({ __invalid: true })`,\n ` // Empty object schema accepts {}; tighten this assertion when adding fields.`,\n ` expect(parsed.success).toBe(true)`,\n ` })`,\n `})`,\n ``,\n ].join('\\n')\n}\n\nfunction generatePageTemplate(name: string): string {\n const pascal = toPascalCase(name)\n return [`export default function ${pascal}Page() {`, ` return <h1>${pascal}</h1>`, `}`, ``].join(\n '\\n',\n )\n}\n\nfunction generateWsTemplate(_name: string): string {\n return [\n `import { defineWebSocket } from 'theokit/server'`,\n ``,\n `export default defineWebSocket({`,\n ` onMessage(ws, data) {`,\n ` ws.send(\\`echo: \\${data}\\`)`,\n ` },`,\n `})`,\n ``,\n ].join('\\n')\n}\n\n/** A file to write: where it goes and what it says. */\ninterface Target {\n filePath: string\n content: string\n}\n\n/** Whether `value` names a generator kind. */\nfunction isGeneratorType(value: string): value is GeneratorType {\n return (VALID_TYPES as readonly string[]).includes(value)\n}\n\n/**\n * The refusal for options `generate` cannot act on: not a project, an unknown kind, a name that is\n * not kebab-case, or a reserved basename. `undefined` when the options are acceptable.\n */\nfunction refuseOptions({ cwd, type, name }: GenerateOptions): GenerateResult | undefined {\n if (!existsSync(resolve(cwd, 'theo.config.ts')) && !existsSync(resolve(cwd, 'theo.config.js'))) {\n return {\n status: 'not_a_project',\n message: 'Not a Theo project. cwd has no theo.config.ts or theo.config.js',\n }\n }\n\n if (!isGeneratorType(type)) {\n return {\n status: 'invalid_kind',\n message: `Invalid generator type \"${type}\". Available: ${VALID_TYPES.join(', ')}`,\n }\n }\n\n if (!name || !toKebabCase(name)) {\n return {\n status: 'invalid_name',\n message: `Invalid name \"${name}\". Use kebab-case: lowercase letters, numbers, hyphens. Example: my-route`,\n }\n }\n\n // EC-2-related: reject reserved JS identifier basenames (would shadow\n // built-in prototype machinery in virtual module emit or scan).\n if (hasReservedSegment(name)) {\n return {\n status: 'invalid_name',\n message: `Reserved name \"${name}\" — basename collides with built-in identifier (index/constructor/__proto__/prototype/hasOwnProperty).`,\n }\n }\n return undefined\n}\n\n/** Where a single-file kind goes and what it says, or the refusal that explains why it cannot. */\nasync function resolveTarget(\n cwd: string,\n type: GeneratorType,\n name: string,\n): Promise<Target | GenerateResult> {\n // A schedule's directory comes from the project config, so resolving it is async and may refuse.\n if (type === 'schedule') return resolveScheduleTarget(cwd, name)\n const target = await resolveTemplate(cwd, type, name)\n if (target === null) return { status: 'invalid_kind', message: `Unknown type: ${type}` }\n return target\n}\n\n/** Write `target` unless it escapes the project or already exists. */\nfunction writeTarget(\n cwd: string,\n type: GeneratorType,\n name: string,\n { filePath, content }: Target,\n): GenerateResult {\n // EC-4: confirm the resolved filePath stays inside cwd. `toKebabCase` rejects most traversal\n // vectors in the name, but a directory read from config (`agentsDir`) can still point outside.\n const escaped = pathTraversalRefusal(cwd, filePath)\n if (escaped !== undefined) return escaped\n\n if (existsSync(filePath)) {\n return { status: 'already_exists', filePath, kind: type, name }\n }\n\n mkdirSync(dirname(filePath), { recursive: true })\n writeFileSync(filePath, content)\n\n // T5.2 + plan Q4: emit co-located test file alongside actions (only\n // for action type; routes/pages/ws keep prior single-file behavior).\n // Skip if existing test file present (preserve user-customized tests).\n if (type === 'action') {\n const testPath = filePath.replace(/\\.ts$/, '.test.ts')\n if (!existsSync(testPath)) {\n writeFileSync(testPath, generateActionTestTemplate(name))\n }\n }\n\n return { status: 'created', filePath, kind: type, name }\n}\n\n/**\n * Programmatic generate. Returns a structured result instead of throwing —\n * Studio (`theokit_generate` tool) consumes this directly. The CLI wrapper\n * below maps the structured result to console output + exit code semantics.\n */\nexport async function generate(opts: GenerateOptions): Promise<GenerateResult> {\n const refused = refuseOptions(opts)\n if (refused !== undefined) return refused\n const { cwd, name } = opts\n // refuseOptions refused every value that is not a generator kind.\n const kind = opts.type as GeneratorType\n\n // Resource generates multiple files — handle separately\n if (kind === 'resource') {\n const layout = await readLayout(cwd)\n if ('status' in layout) return layout\n return generateResource(cwd, name, opts.fields ?? [], layout.serverDir)\n }\n\n const resolved = await resolveTarget(cwd, kind, name)\n if ('status' in resolved) return resolved\n return writeTarget(cwd, kind, name, resolved)\n}\n\n/** The statuses the CLI reports by throwing, and the message each throws. */\nconst CLI_REFUSALS: Record<\n Exclude<GenerateStatus, 'created' | 'already_exists'>,\n (result: GenerateResult, name: string) => string\n> = {\n // The generator's own reason when it gave one: `generate resource` refuses a project that HAS a\n // theo.config.ts when the schema file is missing, and the generic text blamed the config (#1022).\n not_a_project: (result) =>\n result.message ?? 'Not a Theo project. Run this from a project root with theo.config.ts',\n invalid_kind: (result) => result.message ?? 'Invalid kind',\n // `generate` returns invalid_name for a malformed name, a reserved name and a path that\n // resolves outside the project; each message says which, so the CLI must not replace it.\n invalid_name: (result, name) => result.message ?? `Invalid name \"${name}\"`,\n invalid_config: (result) => result.message ?? 'Invalid theo.config.ts',\n agent_not_found: (result) => result.message ?? 'No chat agent found',\n}\n\n/**\n * CLI entry point — preserves the original surface (throws + console.log).\n * Wraps the programmatic `generate` function.\n */\nexport async function generateCommand(\n type: string,\n name: string,\n fields?: string[],\n): Promise<void> {\n const result = await generate({ cwd: process.cwd(), type, name, fields })\n if (result.status === 'already_exists') {\n console.log(`\\n ⚠ ${result.filePath} already exists. Skipping.\\n`)\n } else if (result.status === 'created') {\n console.log(`\\n ✓ Created ${type}: ${result.filePath}\\n`)\n } else {\n throw new Error(CLI_REFUSALS[result.status](result, name))\n }\n}\n","/**\n * The one rule every generator applies before writing: the file stays inside the project. Shared\n * by `generate` and the schedule generator, which checks it before looking for the chat agent so an\n * `agentsDir` outside the project is refused as traversal, never reported as a missing agent there.\n */\nimport { isAbsolute, relative, resolve, sep } from 'node:path'\n\nimport type { GenerateResult } from './generate-types.js'\n\n/**\n * Whether `filePath` lies strictly inside `cwd`. Decided by `path.relative`, never by a string\n * prefix: `/tmp/x/app-outside/...` starts with `/tmp/x/app` and is still outside it. A null byte,\n * an absolute path and a `..` escape are all outside.\n */\nfunction isPathInside(cwd: string, filePath: string): boolean {\n if (filePath.includes('\\x00')) return false\n const fromRoot = relative(resolve(cwd), filePath)\n return fromRoot !== '' && !isAbsolute(fromRoot) && fromRoot.split(sep)[0] !== '..'\n}\n\n/** The refusal for a `filePath` outside the project at `cwd`, or `undefined` when it is inside. */\nexport function pathTraversalRefusal(cwd: string, filePath: string): GenerateResult | undefined {\n if (isPathInside(cwd, filePath)) return undefined\n return {\n status: 'invalid_name',\n message: `Path traversal denied: \"${filePath}\" is outside the project root ${resolve(cwd)}.`,\n }\n}\n","/**\n * The access policy a generated route carries until its author decides one.\n *\n * ADR 0001 made an undeclared `policy` a build error because \"a route that nobody had thought\n * about was indistinguishable from a route deliberately left open\". The generators then wrote\n * `'public'` — including on five methods that read and write a database table — so a generated\n * file was the not-thought-about case wearing the deliberate value, which is the precise state\n * the gate exists to make impossible (usetheokit/theokit#416). `theo build` accepted it, because\n * `assertEveryMethodDeclaresPolicy` asks whether a policy was declared, not which one.\n *\n * A generated route now REFUSES. The author still has to write the answer down — the gate's whole\n * purpose — but the value standing in until they do is the safe one rather than the open one.\n *\n * ## Why an AccessDecision and not `() => false`\n *\n * `evaluateRoutePolicy` maps a bare `false` to \"access denied by route policy\", which tells the\n * reader nothing about where to go. The contract already says a denial \"carries its reason so the\n * caller can say it\", so the refusal names its own file: the first `curl` against a forgotten\n * route prints the path to edit.\n *\n * ## Why a named const rather than a lambda per method\n *\n * Five methods would mean five copies, and deleting four of them is the kind of chore that leaves\n * the fifth behind. One const is one thing to replace, and `grep -rn undecidedPolicy` counts the\n * routes still awaiting a decision — which is the number ADR 0001 wanted to make greppable, and\n * which `grep -c \"policy('public')\"` could not give once generated placeholders were mixed in with\n * real decisions.\n */\n\n/** The identifier the generated methods reference. Exported so callers cannot misspell it. */\nexport const UNDECIDED_POLICY_IDENT = 'undecidedPolicy'\n\n/**\n * Lines declaring the placeholder, to splice into a generated module.\n *\n * @param routePath - the generated file's own path, repo-relative, so the refusal can name it\n * @param what - what the route does, in one clause, for the TODO comment\n */\nexport function undecidedPolicyDeclaration(routePath: string, what: string): string[] {\n return [\n `// TODO(policy): every route declares who may call it (ADR 0001). Generated as a REFUSAL`,\n `// rather than 'public', because the generator cannot know your access model —`,\n `// ${what}.`,\n `// Replace this with 'public' if the route is genuinely open, or with a check such as`,\n `// \\`({ subject, params }) => requireOwner(subject, ownerOf(params.id))\\`, then delete the const.`,\n `const ${UNDECIDED_POLICY_IDENT} = (): AccessDecision => ({`,\n ` allowed: false,`,\n ` reason:`,\n ` '${routePath} still carries the policy the generator wrote, which refuses everyone. ' +`,\n ` 'Declare who may call this route (ADR 0001).',`,\n `})`,\n ]\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\n\nimport {\n UNDECIDED_POLICY_IDENT,\n undecidedPolicyDeclaration,\n} from './generate-policy-placeholder.js'\nimport type { GenerateResult } from './generate-types.js'\n\n// --- Field parsing ---\n\nconst ALLOWED_FIELD_TYPES = new Set(['string', 'text', 'number', 'boolean'])\nconst RESERVED_FIELDS = new Set(['id', 'createdAt', 'created_at'])\n\ninterface ResourceField {\n name: string\n type: 'string' | 'text' | 'number' | 'boolean'\n zodType: string\n}\n\nfunction parseResourceFields(args: string[]): ResourceField[] {\n if (args.length === 0) {\n throw new Error(\n 'Resource requires at least one field. Example: theokit generate resource posts title:string',\n )\n }\n return args.map((arg) => {\n const parts = arg.split(':')\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(`Invalid field \"${arg}\". Use name:type format (e.g. title:string)`)\n }\n const [name, type] = parts\n if (!ALLOWED_FIELD_TYPES.has(type)) {\n throw new Error(\n `Unknown field type \"${type}\" in \"${arg}\". Valid types: ${[...ALLOWED_FIELD_TYPES].join(', ')}`,\n )\n }\n if (RESERVED_FIELDS.has(name)) {\n throw new Error(`Field \"${name}\" is reserved (auto-generated by the framework)`)\n }\n const fieldType = type as ResourceField['type']\n return {\n name,\n type: fieldType,\n zodType: mapZodType(fieldType),\n }\n })\n}\n\n// --- Dialects ---\n\n/**\n * The SQL dialects the generator writes code for. Drizzle's synchronous SQLite drivers expose\n * `.all()`/`.get()`/`.run()` on a query; the Postgres drivers do not, so the two need different\n * table builders AND different handler bodies (usetheokit/theokit#1022).\n */\ntype ResourceDialect = 'sqlite' | 'postgresql'\n\ninterface DialectSpec {\n /** The Drizzle module the table builders come from. */\n readonly module: string\n /** A minimal `<serverDir>/db/index.ts` exporting `db`, shown when the project has none. */\n readonly dbIndexExample: readonly string[]\n /** Matches an existing named import from `module`; group 1 is the list of names. */\n readonly importPattern: RegExp\n /** The table builder function. */\n readonly table: string\n /** Every column builder the generated table may use, imported up front. */\n readonly columns: readonly string[]\n readonly idColumn: string\n readonly createdAtColumn: readonly string[]\n readonly column: (name: string, type: ResourceField['type']) => string\n}\n\nconst DIALECTS: Record<ResourceDialect, DialectSpec> = {\n sqlite: {\n module: 'drizzle-orm/sqlite-core',\n dbIndexExample: [\n `import Database from 'better-sqlite3'`,\n `import { drizzle } from 'drizzle-orm/better-sqlite3'`,\n `import * as schema from './schema.js'`,\n `export const db = drizzle(new Database('data.db'), { schema })`,\n ],\n importPattern: /import\\s*\\{([^}]*)\\}\\s*from\\s*['\"]drizzle-orm\\/sqlite-core['\"]/,\n table: 'sqliteTable',\n columns: ['integer', 'text'],\n idColumn: `integer('id').primaryKey({ autoIncrement: true })`,\n createdAtColumn: [\n `text('created_at')`,\n ` .notNull()`,\n ` .$defaultFn(() => new Date().toISOString().split('T')[0])`,\n ],\n column: (name, type) => {\n switch (type) {\n case 'string':\n case 'text':\n return `text('${name}').notNull()`\n case 'number':\n return `integer('${name}').notNull()`\n case 'boolean':\n return `integer('${name}', { mode: 'boolean' }).notNull().default(false)`\n }\n },\n },\n postgresql: {\n module: 'drizzle-orm/pg-core',\n dbIndexExample: [\n `import pg from 'pg'`,\n `import { drizzle } from 'drizzle-orm/node-postgres'`,\n `import * as schema from './schema.js'`,\n `const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })`,\n `pool.on('error', (err) => console.warn('[pg] idle client error:', err.message))`,\n `export const db = drizzle(pool, { schema })`,\n ],\n importPattern: /import\\s*\\{([^}]*)\\}\\s*from\\s*['\"]drizzle-orm\\/pg-core['\"]/,\n table: 'pgTable',\n columns: ['boolean', 'integer', 'serial', 'text', 'timestamp'],\n idColumn: `serial('id').primaryKey()`,\n createdAtColumn: [`timestamp('created_at').notNull().defaultNow()`],\n column: (name, type) => {\n switch (type) {\n case 'string':\n case 'text':\n return `text('${name}').notNull()`\n case 'number':\n return `integer('${name}').notNull()`\n case 'boolean':\n return `boolean('${name}').notNull().default(false)`\n }\n },\n },\n}\n\n/** A `dialect:` value in `drizzle.config.ts`, mapped to what the generator does with it. */\nconst DIALECT_ALIASES: Record<string, ResourceDialect | undefined> = {\n sqlite: 'sqlite',\n turso: 'sqlite',\n postgresql: 'postgresql',\n}\n\nconst SCHEMA_IMPORT_DIALECTS: [RegExp, string][] = [\n [/from ['\"]drizzle-orm\\/sqlite-core['\"]/, 'sqlite'],\n [/from ['\"]drizzle-orm\\/pg-core['\"]/, 'postgresql'],\n [/from ['\"]drizzle-orm\\/mysql-core['\"]/, 'mysql'],\n [/from ['\"]drizzle-orm\\/singlestore-core['\"]/, 'singlestore'],\n]\n\n/**\n * The project's dialect: `drizzle.config.ts` says it outright; failing that, the core module the\n * schema already imports from does. A schema that imports from nothing (a fresh file) and no config\n * leaves the historical default, SQLite.\n *\n * @returns the dialect, or the raw name of one the generator cannot write code for.\n */\nfunction detectDialect(cwd: string, schemaSource: string): string {\n const config = readIfPresent(resolve(cwd, 'drizzle.config.ts'))\n if (config !== undefined) {\n const declared = /dialect\\s*:\\s*['\"]([a-z0-9-]+)['\"]/.exec(config)\n if (declared) return declared[1]\n }\n for (const [pattern, dialect] of SCHEMA_IMPORT_DIALECTS) {\n if (pattern.test(schemaSource)) return dialect\n }\n return 'sqlite'\n}\n\nfunction mapZodType(type: ResourceField['type']): string {\n switch (type) {\n case 'string':\n case 'text':\n return 'z.string()'\n case 'number':\n return 'z.number()'\n case 'boolean':\n return 'z.boolean()'\n }\n}\n\n// --- Template generators ---\n\nfunction generateSchemaEntry(\n resourceName: string,\n fields: ResourceField[],\n dialect: DialectSpec,\n): string {\n const [createdAtFirst, ...createdAtRest] = dialect.createdAtColumn\n const cols = [\n ` id: ${dialect.idColumn},`,\n ...fields.map((f) => ` ${f.name}: ${dialect.column(f.name, f.type)},`),\n ` createdAt: ${createdAtFirst}`,\n ...createdAtRest,\n ]\n cols[cols.length - 1] += ','\n return [\n ``,\n `export const ${resourceName} = ${dialect.table}('${resourceName}', {`,\n ...cols,\n `})`,\n ``,\n ].join('\\n')\n}\n\n/**\n * The schema source with the table builders the appended table uses imported. The generator used to\n * append `sqliteTable(...)` with no import at all, so the schema file stopped compiling.\n *\n * An existing named import from the dialect module gains the missing names; without one, an import\n * line goes on top. Names already imported are not repeated.\n */\nfunction withDialectImports(source: string, dialect: DialectSpec): string {\n const needed = [dialect.table, ...dialect.columns]\n const existing = dialect.importPattern.exec(source)\n if (existing) {\n const have = existing[1]\n .split(',')\n .map((n) => n.trim())\n .filter(Boolean)\n const merged = [...new Set([...have, ...needed])].sort((a, b) => a.localeCompare(b))\n return source.replace(existing[0], `import { ${merged.join(', ')} } from '${dialect.module}'`)\n }\n return `import { ${[...needed].sort((a, b) => a.localeCompare(b)).join(', ')} } from '${dialect.module}'\\n${source}`\n}\n\n/**\n * Query expressions per dialect. SQLite's synchronous drivers finish a query with `.all()`, `.get()`\n * or `.run()`; the Postgres drivers return a promise and have none of the three, so the Postgres\n * handlers await the builder and take the first row of `returning()`.\n */\ninterface QueryShapes {\n readonly async: boolean\n list(table: string): string\n insert(table: string): string\n findById(table: string): string\n updateById(table: string): string\n deleteById(table: string): string\n}\n\nconst QUERIES: Record<ResourceDialect, QueryShapes> = {\n sqlite: {\n async: false,\n list: (t) => `db.select().from(${t}).all()`,\n insert: (t) => `db.insert(${t}).values(body).returning().get()`,\n findById: (t) => `db.select().from(${t}).where(eq(${t}.id, params.id)).get()`,\n updateById: (t) => `db.update(${t}).set(body).where(eq(${t}.id, params.id)).returning().get()`,\n deleteById: (t) => `db.delete(${t}).where(eq(${t}.id, params.id)).run()`,\n },\n postgresql: {\n async: true,\n list: (t) => `await db.select().from(${t})`,\n insert: (t) => `(await db.insert(${t}).values(body).returning())[0]`,\n findById: (t) => `(await db.select().from(${t}).where(eq(${t}.id, params.id)))[0]`,\n updateById: (t) =>\n `(await db.update(${t}).set(body).where(eq(${t}.id, params.id)).returning())[0]`,\n deleteById: (t) => `await db.delete(${t}).where(eq(${t}.id, params.id))`,\n },\n}\n\ninterface RouteTemplateInput {\n resourceName: string\n fields: ResourceField[]\n queries: QueryShapes\n /** Project-relative path of the file being written, named by the placeholder policy. */\n displayPath: string\n}\n\nfunction generateRouteIndex({\n resourceName,\n fields,\n queries,\n displayPath,\n}: RouteTemplateInput): string {\n const bodyFields = fields.map((f) => ` ${f.name}: ${f.zodType},`).join('\\n')\n const asyncKw = queries.async ? 'async ' : ''\n return [\n `import { route, type AccessDecision } from 'theokit/server/define'`,\n `import { z } from 'zod'`,\n `import { db } from '../../db/index.js'`,\n `import { ${resourceName} } from '../../db/schema.js'`,\n ``,\n ...undecidedPolicyDeclaration(displayPath, 'these methods read and write a table'),\n ``,\n `export const GET = route()`,\n ` .policy(${UNDECIDED_POLICY_IDENT})`,\n ` .handler(${asyncKw}() => ${queries.list(resourceName)})`,\n ` .build()`,\n ``,\n `export const POST = route()`,\n ` .policy(${UNDECIDED_POLICY_IDENT})`,\n ` .body(`,\n ` z.object({`,\n bodyFields,\n ` }),`,\n ` )`,\n ` .status(201)`,\n ` .handler(${asyncKw}({ body }) => {`,\n ` const result = ${queries.insert(resourceName)}`,\n ` return result`,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateRouteId({\n resourceName,\n fields,\n queries,\n displayPath,\n}: RouteTemplateInput): string {\n const updateFields = fields.map((f) => ` ${f.name}: ${f.zodType}.optional(),`).join('\\n')\n const asyncKw = queries.async ? 'async ' : ''\n return [\n `import { route, type AccessDecision } from 'theokit/server/define'`,\n `import { z } from 'zod'`,\n `import { db } from '../../db/index.js'`,\n `import { ${resourceName} } from '../../db/schema.js'`,\n `import { eq } from 'drizzle-orm'`,\n ``,\n ...undecidedPolicyDeclaration(\n displayPath,\n 'these methods read, update and delete rows of a table',\n ),\n ``,\n `export const GET = route()`,\n ` .policy(${UNDECIDED_POLICY_IDENT})`,\n ` .params(z.object({ id: z.coerce.number() }))`,\n ` .handler(${asyncKw}({ params }) => {`,\n ` const item = ${queries.findById(resourceName)}`,\n ` if (!item) return new Response(JSON.stringify({ error: 'Not found' }), { status: 404 })`,\n ` return item`,\n ` })`,\n ` .build()`,\n ``,\n `export const PUT = route()`,\n ` .policy(${UNDECIDED_POLICY_IDENT})`,\n ` .params(z.object({ id: z.coerce.number() }))`,\n ` .body(`,\n ` z.object({`,\n updateFields,\n ` }),`,\n ` )`,\n ` .handler(${asyncKw}({ params, body }) => {`,\n ` const result = ${queries.updateById(resourceName)}`,\n ` if (!result) return new Response(JSON.stringify({ error: 'Not found' }), { status: 404 })`,\n ` return result`,\n ` })`,\n ` .build()`,\n ``,\n `export const DELETE = route()`,\n ` .policy(${UNDECIDED_POLICY_IDENT})`,\n ` .params(z.object({ id: z.coerce.number() }))`,\n ` .status(204)`,\n ` .handler(${asyncKw}({ params }) => {`,\n ` ${queries.deleteById(resourceName)}`,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateTestTemplate(resourceName: string, serverDir: string): string {\n return [\n `import { describe, it, expect } from 'vitest'`,\n ``,\n `describe('${resourceName} API', () => {`,\n ` it('should have a schema defined', async () => {`,\n ` const schema = await import('../${serverDir}/db/schema.js')`,\n ` expect(schema.${resourceName}).toBeDefined()`,\n ` })`,\n ``,\n ` it('should have route handlers', async () => {`,\n ` const index = await import('../${serverDir}/routes/${resourceName}/index.js')`,\n ` expect(index.GET).toBeDefined()`,\n ` expect(index.POST).toBeDefined()`,\n ` })`,\n `})`,\n ``,\n ].join('\\n')\n}\n\n// --- Orchestrator ---\n\n/**\n * Generate a CRUD resource: a table appended to `<serverDir>/db/schema.ts`, two route files under\n * `<serverDir>/routes/<name>/` and a test.\n *\n * @param serverDir - the project-relative `serverDir` from `theo.config.ts`. The generator used to\n * assume `server/`, so in the scaffold (`src/server`) it refused every time.\n */\nfunction readIfPresent(path: string): string | undefined {\n try {\n return readFileSync(path, 'utf-8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw err\n }\n}\n\n/** The files TypeScript resolves `../../db/index.js` to. */\nconst DB_INDEX_FILES = ['index.ts', 'index.tsx', 'index.js']\n\n/** Create `path` only if it does not exist; `false` when it already did. */\nfunction createExclusive(path: string, content: string): boolean {\n try {\n writeFileSync(path, content, { flag: 'wx' })\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false\n throw err\n }\n}\n\nexport function generateResource(\n cwd: string,\n name: string,\n fieldArgs: string[],\n serverDir = 'server',\n): GenerateResult {\n let fields: ResourceField[]\n try {\n fields = parseResourceFields(fieldArgs)\n } catch (err) {\n return { status: 'invalid_name', message: err instanceof Error ? err.message : String(err) }\n }\n\n const schemaRel = join(serverDir, 'db', 'schema.ts')\n const routeDirRel = join(serverDir, 'routes', name)\n const schemaPath = resolve(cwd, schemaRel)\n const routeIndexPath = resolve(cwd, routeDirRel, 'index.ts')\n const routeIdPath = resolve(cwd, routeDirRel, '[id].ts')\n const testPath = resolve(cwd, `tests/${name}.test.ts`)\n\n // Read rather than check-then-read, and create the new files with `wx` rather than\n // check-then-write: the answer can change between a check and the write that trusts it.\n const existingSchema = readIfPresent(schemaPath)\n if (existingSchema === undefined) {\n return {\n status: 'not_a_project',\n message:\n `${schemaRel} not found. \\`theokit generate resource\\` appends the table to the Drizzle ` +\n `schema under the configured serverDir (\"${serverDir}\"); create it first.`,\n }\n }\n if (existingSchema.includes(`export const ${name} =`)) {\n return {\n status: 'already_exists',\n filePath: schemaPath,\n kind: 'resource',\n name,\n message: `Table \"${name}\" already exists in ${schemaRel}`,\n }\n }\n\n const detected = detectDialect(cwd, existingSchema)\n const dialectName = DIALECT_ALIASES[detected]\n if (dialectName === undefined) {\n return {\n status: 'invalid_config',\n message:\n `\\`theokit generate resource\\` writes code for SQLite and PostgreSQL; this project uses ` +\n `\"${detected}\" (from drizzle.config.ts or the imports in ${schemaRel}). Nothing was written.`,\n }\n }\n const dialect = DIALECTS[dialectName]\n const queries = QUERIES[dialectName]\n\n // The routes import `db` from `<serverDir>/db/index.js`. Without the file the command reported\n // success and the next build failed with `Could not resolve` (usetheokit/theokit#1038). Which\n // driver to install is the project's choice, so the generator refuses rather than writing one.\n const dbIndexRel = join(serverDir, 'db', 'index.ts')\n if (!DB_INDEX_FILES.some((file) => existsSync(resolve(cwd, serverDir, 'db', file)))) {\n const example = dialect.dbIndexExample.map((line) => ' ' + line).join('\\n')\n return {\n status: 'not_a_project',\n message:\n `${dbIndexRel} not found. The routes \\`theokit generate resource\\` writes import \\`db\\` ` +\n `from it, so the build would fail to resolve it. Create it with \\`export const db\\`, for ` +\n `example (${dialectName}):\\n\\n${example}\\n\\n` +\n `Nothing was written.`,\n }\n }\n\n // 1. Create the route files first: an existing route refuses before the schema is touched.\n mkdirSync(dirname(routeIndexPath), { recursive: true })\n const template = { resourceName: name, fields, queries }\n if (\n !createExclusive(\n routeIndexPath,\n generateRouteIndex({ ...template, displayPath: join(routeDirRel, 'index.ts') }),\n )\n ) {\n return { status: 'already_exists', filePath: routeIndexPath, kind: 'resource', name }\n }\n writeFileSync(\n routeIdPath,\n generateRouteId({ ...template, displayPath: join(routeDirRel, '[id].ts') }),\n )\n\n // 2. Append the table, with the builders it uses imported.\n writeFileSync(\n schemaPath,\n withDialectImports(existingSchema, dialect) + generateSchemaEntry(name, fields, dialect),\n )\n\n // 3. Create the test file, keeping one the user already has.\n mkdirSync(dirname(testPath), { recursive: true })\n createExclusive(testPath, generateTestTemplate(name, serverDir))\n\n return { status: 'created', filePath: routeIndexPath, kind: 'resource', name }\n}\n","/**\n * The `theokit generate schedule` generator.\n *\n * A schedule must land where `theokit build` scans (`<agentsDir>/schedules`), so its directory is\n * read from the project config through `loadConfig`, the same reader the build uses. When the\n * config cannot be read the generator refuses by name instead of guessing a directory.\n *\n * A schedule runs the app's `chat` agent, so a project without one is refused too: a schedule\n * importing a module that does not exist would make `theokit build` fail on it.\n *\n * The schedule declares `defineCron('<last segment of the name>')`, so that segment is checked with\n * `defineCron`'s own rule and the scanner's own discovery: a name the build would reject, skip, or\n * find already used by another cron file is refused as `invalid_name` before anything is written.\n */\nimport { basename, dirname, extname, relative, resolve, sep } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { cronScanDirs, isDiscoverableCronFile, listCronFiles } from '../../server/cron/cron-scan.js'\nimport { CRON_NAME_RULE, isValidCronName } from '../../server/cron/define-cron.js'\nimport { findAgentFile } from '../../server/scan/agent-scan.js'\n\nimport { pathTraversalRefusal } from './generate-containment.js'\nimport type { GenerateResult } from './generate-types.js'\n\n/** Where the schedule goes and what it says, or the refusal that explains why it cannot be written. */\nexport async function resolveScheduleTarget(\n cwd: string,\n name: string,\n): Promise<{ filePath: string; content: string } | GenerateResult> {\n const malformed = cronNameRefusal(name)\n if (malformed !== undefined) return malformed\n let config: Awaited<ReturnType<typeof loadConfig>>\n try {\n config = await loadConfig(cwd)\n } catch (err) {\n return {\n status: 'invalid_config',\n message: `Cannot read ${resolve(cwd, 'theo.config.ts')}: ${(err as Error).message}`,\n }\n }\n const { agentsDir, serverDir } = config\n const agentsRoot = resolve(cwd, agentsDir)\n const cronDirs = cronScanDirs(cwd, serverDir, agentsDir)\n const filePath = resolve(cronDirs.schedules, `${name}.ts`)\n // Before the agent lookup: a chat agent missing from a directory outside the project is not\n // something to create, and the refusal must name the escape, not the missing file.\n const escaped = pathTraversalRefusal(cwd, filePath)\n if (escaped !== undefined) return escaped\n // The agent scanner's own rule, so the file found is the one the build serves as `chat`.\n const chatPath = findAgentFile(agentsRoot, 'chat')\n if (chatPath === undefined) {\n return {\n status: 'agent_not_found',\n message:\n `No \"chat\" agent in ${agentsRoot} (the build serves it from chat.{ts,tsx,js,jsx} or ` +\n 'chat/index.{ts,tsx,js,jsx}). A schedule runs the chat agent; create it first.',\n }\n }\n // The build scans both homes with one duplicate-name guard (build.ts, emitCronArtifacts).\n const taken = cronNameTaken(name, filePath, [cronDirs.crons, cronDirs.schedules])\n if (taken !== undefined) return taken\n return { filePath, content: generateScheduleTemplate(name, importSpecifier(filePath, chatPath)) }\n}\n\n/** The cron name a schedule called `name` declares: its last `/` segment. */\nexport function cronNameOf(name: string): string {\n return name.split('/').pop() ?? name\n}\n\n/** A refusal when the build would skip the file or `defineCron` would reject its name. */\nfunction cronNameRefusal(name: string): GenerateResult | undefined {\n const cronName = cronNameOf(name)\n if (!isDiscoverableCronFile(`${cronName}.ts`)) {\n return {\n status: 'invalid_name',\n message: `Invalid schedule name \"${name}\": the build does not discover a cron file named \"${cronName}.ts\".`,\n }\n }\n if (!isValidCronName(cronName)) {\n return {\n status: 'invalid_name',\n message: `Invalid schedule name \"${name}\": its cron name \"${cronName}\" is one defineCron rejects. ${CRON_NAME_RULE}`,\n }\n }\n return undefined\n}\n\n/**\n * A refusal when another cron file already carries this schedule's cron name. The generator names\n * a cron after its file, so a file of the same name in either cron home is the clash the build's\n * duplicate-name guard would fail on. The target itself is left to the `already_exists` answer.\n *\n * Compared by FILE name, while the build compares the name each file passes to `defineCron`, which\n * it learns only by importing the file. A hand-written `foo.ts` declaring `defineCron('bar')` is\n * not seen here, so schedule `bar` is written and the build then fails with\n * `DuplicateCronNameError`; and a `bar.ts` declaring another name refuses schedule `bar` although\n * the build would accept it. Importing every cron file to read its name would run user code at\n * generate time, which this generator does not do.\n */\nfunction cronNameTaken(\n name: string,\n filePath: string,\n cronDirs: readonly string[],\n): GenerateResult | undefined {\n const cronName = cronNameOf(name)\n const clash = listCronFiles(cronDirs).find(\n (path) => path !== filePath && basename(path, extname(path)) === cronName,\n )\n if (clash === undefined) return undefined\n return {\n status: 'invalid_name',\n message: `Invalid schedule name \"${name}\": the cron name \"${cronName}\" is already used by ${clash}. Cron names must be unique across server/crons/ and agents/schedules/.`,\n }\n}\n\n/**\n * The ESM specifier the schedule at `fromFile` uses to import `toFile` (`../chat.js`). A TypeScript\n * source is imported by its `.js` name, as TypeScript and tsx resolve it; a `.js` or `.jsx` file\n * keeps its own extension.\n */\nexport function importSpecifier(fromFile: string, toFile: string): string {\n const path = relative(dirname(fromFile), toFile)\n .split(sep)\n .join('/')\n .replace(/\\.tsx?$/, '.js')\n return path.startsWith('.') ? path : `./${path}`\n}\n\nfunction generateScheduleTemplate(name: string, chatSpecifier: string): string {\n const base = cronNameOf(name)\n return [\n `import { defineCron } from 'theokit/server/cron'`,\n `import { resolveProvider } from 'theokit/server/agent'`,\n `import { streamAgentTurnInProcess } from '@theokit/agents'`,\n ``,\n `import chat from '${chatSpecifier}'`,\n ``,\n `/**`,\n ` * A scheduled agent run, a first-class TheoKit cron. \\`theokit build\\` discovers it and translates the`,\n ` * schedule to your deploy target's native cron; \\`theokit start\\` runs it in-process.`,\n ` *`,\n ` * Each fire is one model run of your \\`chat\\` agent, so it spends tokens. Nobody is present to approve`,\n ` * a gated tool, so the run uses the \\`auto-reject\\` posture: every approval is answered \"no\" and the`,\n ` * gated tool does not run.`,\n ` *`,\n ` * Schedules are UTC (https://crontab.guru). \\`signal\\` aborts when the scheduler stops.`,\n ` */`,\n `export default defineCron('${base}', {`,\n ` schedule: '0 9 * * *', // every day at 09:00 UTC`,\n ` async handler({ traceId, scheduledAt, signal }) {`,\n ` let outcome = 'ok'`,\n ` try {`,\n ` const agent = chat as { model?: string; plugins?: readonly unknown[] }`,\n ` const { apiKey } = resolveProvider(agent.model, { plugins: agent.plugins })`,\n ` const run = streamAgentTurnInProcess(chat, apiKey, {`,\n ` message: \\`Scheduled run \"${base}\" at \\${scheduledAt.toISOString()}\\`,`,\n ` signal,`,\n ` approvals: {`,\n ` kind: 'auto-reject',`,\n ` reason: 'unattended schedule \"${base}\": nobody is present to approve',`,\n ` },`,\n ` })`,\n ` for await (const chunk of run) {`,\n ` // The SDK can report a failed run as a chunk rather than a rejection.`,\n ` if (chunk.type === 'error') {`,\n ` throw new Error(\\`[${base}] agent run failed: \\${chunk.errorText ?? 'no error text'}\\`)`,\n ` }`,\n ` }`,\n ` } catch (err) {`,\n ` outcome = \\`failed: \\${err instanceof Error ? err.message : String(err)}\\``,\n ` throw err`,\n ` } finally {`,\n ` // One traced line per fire, failed fires included: the scheduler's own error line has no trace id.`,\n ` console.log(\\`[${base}] fire \\${outcome} at \\${scheduledAt.toISOString()} (trace \\${traceId})\\`)`,\n ` }`,\n ` },`,\n `})`,\n ``,\n ].join('\\n')\n}\n","import type { CronDefinition, CronOptions } from './cron-types.js'\nimport { validateCronSchedule } from './cron-validate.js'\n\nconst NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/\n\n/** What {@link isValidCronName} requires, in words, for an error message. */\nexport const CRON_NAME_RULE =\n 'Must be 1-64 chars, lowercase alphanumeric + hyphen, starting with [a-z0-9].'\n\n/** Whether `defineCron` accepts `name`. The generator asks this before writing a cron. */\nexport function isValidCronName(name: string): boolean {\n return typeof name === 'string' && NAME_RE.test(name)\n}\n\nfunction validateName(name: string): void {\n if (!isValidCronName(name)) {\n throw new Error(`defineCron: invalid name \"${name}\". ${CRON_NAME_RULE}`)\n }\n}\n\n/**\n * Declare a time-triggered handler. Pure identity helper — no\n * registration side effect; the build-time scanner (T1.3) discovers\n * definitions by walking `server/crons/` and emits a manifest the\n * adapters translate at deploy.\n *\n * @example\n * ```ts\n * // server/crons/morning-summary.ts\n * export default defineCron('morning-summary', {\n * schedule: '0 9 * * *', // 09:00 UTC\n * async handler({ traceId, scheduledAt, signal }) {\n * // ...\n * },\n * })\n * ```\n */\nexport function defineCron(name: string, options: CronOptions): CronDefinition {\n validateName(name)\n validateCronSchedule(options.schedule)\n return {\n name,\n schedule: options.schedule,\n handler: options.handler,\n concurrency: options.concurrency ?? 'forbid',\n }\n}\n","/**\n * Shared types for the `theokit generate` CLI command family.\n *\n * Extracted to break the circular dependency between generate.ts ↔ generate-resource.ts\n * (architecture-remediation plan T1.1, 2026-06-12).\n */\n\nexport const VALID_TYPES = [\n 'route',\n 'action',\n 'page',\n 'ws',\n 'controller',\n 'agent',\n 'toolbox',\n 'workflow',\n 'eval',\n 'sandbox',\n 'schedule',\n 'memory',\n 'resource',\n] as const\nexport type GeneratorType = (typeof VALID_TYPES)[number]\n\nexport interface GenerateOptions {\n cwd: string\n type: string\n name: string\n fields?: string[]\n}\n\nexport type GenerateStatus =\n | 'created'\n | 'already_exists'\n | 'invalid_kind'\n | 'invalid_name'\n | 'not_a_project'\n | 'invalid_config'\n | 'agent_not_found'\n\nexport interface GenerateResult {\n status: GenerateStatus\n filePath?: string\n kind?: GeneratorType\n name?: string\n message?: string\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,aAAY,aAAAC,YAAW,iBAAAC,sBAAqB;AACrD,SAAS,OAAO,WAAAC,UAAS,WAAAC,gBAAe;;;ACIxC,SAAS,YAAY,UAAU,SAAS,WAAW;AASnD,SAAS,aAAa,KAAa,UAA2B;AAC5D,MAAI,SAAS,SAAS,IAAM,EAAG,QAAO;AACtC,QAAM,WAAW,SAAS,QAAQ,GAAG,GAAG,QAAQ;AAChD,SAAO,aAAa,MAAM,CAAC,WAAW,QAAQ,KAAK,SAAS,MAAM,GAAG,EAAE,CAAC,MAAM;AAChF;AAGO,SAAS,qBAAqB,KAAa,UAA8C;AAC9F,MAAI,aAAa,KAAK,QAAQ,EAAG,QAAO;AACxC,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,SAAS,2BAA2B,QAAQ,iCAAiC,QAAQ,GAAG,CAAC;AAAA,EAC3F;AACF;;;ACGO,IAAM,yBAAyB;AAQ/B,SAAS,2BAA2B,WAAmB,MAAwB;AACpF,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,MAAM,IAAI;AAAA,IACV;AAAA,IACA;AAAA,IACA,SAAS,sBAAsB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA,QAAQ,SAAS;AAAA,IACjB;AAAA,IACA;AAAA,EACF;AACF;;;ACpDA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,SAAS,MAAM,WAAAC,gBAAe;AAUvC,IAAM,sBAAsB,oBAAI,IAAI,CAAC,UAAU,QAAQ,UAAU,SAAS,CAAC;AAC3E,IAAM,kBAAkB,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I;AAClC,MAAI,YAAY,OAAW,QAAO;AAClC,QAAM,EAAE,KAAK,KAAK,IAAI;AAEtB,QAAM,OAAO,KAAK;AAGlB,MAAI,SAAS,YAAY;AACvB,UAAM,SAAS,MAAM,WAAW,GAAG;AACnC,QAAI,YAAY,OAAQ,QAAO;AAC/B,WAAO,iBAAiB,KAAK,MAAM,KAAK,UAAU,CAAC,GAAG,OAAO,SAAS;AAAA,EACxE;AAEA,QAAM,WAAW,MAAM,cAAc,KAAK,MAAM,IAAI;AACpD,MAAI,YAAY,SAAU,QAAO;AACjC,SAAO,YAAY,KAAK,MAAM,MAAM,QAAQ;AAC9C;AAGA,IAAM,eAGF;AAAA;AAAA;AAAA,EAGF,eAAe,CAAC,WACd,OAAO,WAAW;AAAA,EACpB,cAAc,CAAC,WAAW,OAAO,WAAW;AAAA;AAAA;AAAA,EAG5C,cAAc,CAAC,QAAQ,SAAS,OAAO,WAAW,iBAAiB,IAAI;AAAA,EACvE,gBAAgB,CAAC,WAAW,OAAO,WAAW;AAAA,EAC9C,iBAAiB,CAAC,WAAW,OAAO,WAAW;AACjD;AAMA,eAAsB,gBACpB,MACA,MACA,QACe;AACf,QAAM,SAAS,MAAM,SAAS,EAAE,KAAK,QAAQ,IAAI,GAAG,MAAM,MAAM,OAAO,CAAC;AACxE,MAAI,OAAO,WAAW,kBAAkB;AACtC,YAAQ,IAAI;AAAA,WAAS,OAAO,QAAQ;AAAA,CAA8B;AAAA,EACpE,WAAW,OAAO,WAAW,WAAW;AACtC,YAAQ,IAAI;AAAA,mBAAiB,IAAI,KAAK,OAAO,QAAQ;AAAA,CAAI;AAAA,EAC3D,OAAO;AACL,UAAM,IAAI,MAAM,aAAa,OAAO,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3D;AACF;","names":["existsSync","mkdirSync","writeFileSync","resolve","dirname","resolve","resolve","dirname","relative","resolve","sep","resolve","relative","dirname","sep","basename","resolve","existsSync","mkdirSync","dirname","writeFileSync"]}
@@ -2,7 +2,7 @@ import { a as TheoErrorCode, T as TheoErrorEnvelope } from './error-envelope-DG4
2
2
  import { IncomingMessage, ServerResponse } from 'node:http';
3
3
  import { P as PluginContext, W as WebOnRequestHook, g as WebPreHandlerHook, h as WebOnResponseHook, i as WebOnErrorHook } from './plugin-types-BUVfUQ0V.js';
4
4
  import { P as PluginRunner } from './plugin-runner-BVMOSxvb.js';
5
- import { J as JobBackend } from './job-backend-CgC8Xf33.js';
5
+ import { J as JobBackend } from './job-backend-WvUs5rO1.js';
6
6
  import { S as ServerRouteNode } from './match-DaKsL73w.js';
7
7
  import { L as LoadModule } from './module-loader-DCip7NoL.js';
8
8
  import { C as CsrfMode, D as DisallowedConfig } from './csrf-Dgot9qSM.js';
package/dist/index.d.ts CHANGED
@@ -215,7 +215,13 @@ declare const theoConfigSchema: z.ZodObject<{
215
215
  adapters: z.ZodOptional<z.ZodArray<z.ZodString>>;
216
216
  viteOptimizeDeps: z.ZodOptional<z.ZodArray<z.ZodString>>;
217
217
  jobs: z.ZodOptional<z.ZodObject<{
218
- backend: z.ZodCustom<unknown, unknown>;
218
+ backend: z.ZodCustom<object, object>;
219
+ worker: z.ZodPrefault<z.ZodObject<{
220
+ enabled: z.ZodDefault<z.ZodBoolean>;
221
+ pollIntervalMs: z.ZodDefault<z.ZodNumber>;
222
+ batchSize: z.ZodDefault<z.ZodNumber>;
223
+ lockSeconds: z.ZodDefault<z.ZodNumber>;
224
+ }, z.core.$strip>>;
219
225
  }, z.core.$strip>>;
220
226
  storage: z.ZodOptional<z.ZodObject<{
221
227
  servers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
@@ -254,6 +260,9 @@ declare const theoConfigSchema: z.ZodObject<{
254
260
  db: z.ZodOptional<z.ZodNumber>;
255
261
  maxRetriesPerRequest: z.ZodOptional<z.ZodNumber>;
256
262
  }, z.core.$strip>>>;
263
+ }, z.core.$strict>>;
264
+ cron: z.ZodOptional<z.ZodObject<{
265
+ lock: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodCustom<object, object>]>>;
257
266
  }, z.core.$strip>>;
258
267
  services: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
259
268
  runtime: z.ZodEnum<{
package/dist/index.js CHANGED
@@ -8,27 +8,26 @@ import {
8
8
  scanRoutes,
9
9
  theoConfigSchema,
10
10
  theoPlugin
11
- } from "./chunk-E5QTCOKC.js";
11
+ } from "./chunk-FEK25JUL.js";
12
12
  import "./chunk-7NRFZBAL.js";
13
13
  import "./chunk-SSYDEKWF.js";
14
- import "./chunk-D7STTNQN.js";
15
- import "./chunk-VPK7ABMB.js";
16
- import "./chunk-R4AMIBZL.js";
14
+ import "./chunk-BXQCJJPT.js";
15
+ import "./chunk-7MCEJVGV.js";
16
+ import "./chunk-4XZOUS5G.js";
17
17
  import "./chunk-OIGJOYX6.js";
18
18
  import "./chunk-U3SPBLJF.js";
19
19
  import "./chunk-WSOAN4KN.js";
20
20
  import "./chunk-ENSFCKP6.js";
21
21
  import "./chunk-OGLS76RN.js";
22
- import "./chunk-2Z7TANA4.js";
23
- import "./chunk-SYIQV4UH.js";
22
+ import "./chunk-PVCXREGE.js";
23
+ import "./chunk-36ZACTF3.js";
24
24
  import "./chunk-P6OS7652.js";
25
25
  import "./chunk-ZDUO4IYN.js";
26
26
  import "./chunk-IDWN2OSG.js";
27
27
  import "./chunk-47FFT43U.js";
28
28
  import "./chunk-NTDN54XO.js";
29
- import "./chunk-PVNMLZ5G.js";
30
- import "./chunk-ZDCCILMP.js";
31
- import "./chunk-CHTAWXC2.js";
29
+ import "./chunk-JO462JZM.js";
30
+ import "./chunk-IXXZBZF7.js";
32
31
  import "./chunk-AVQU5CQF.js";
33
32
  import "./chunk-VSLTKX5L.js";
34
33
  import "./chunk-SFGGRC35.js";
@@ -40,10 +39,13 @@ import "./chunk-V6Y2SMRG.js";
40
39
  import "./chunk-ACKBVBUI.js";
41
40
  import "./chunk-IZ3TIL6K.js";
42
41
  import "./chunk-TQEE36VD.js";
43
- import "./chunk-ICXXHV4V.js";
42
+ import "./chunk-54BIQFP4.js";
43
+ import "./chunk-ZICY2CD7.js";
44
44
  import "./chunk-YSJOZEI6.js";
45
45
  import "./chunk-Z4PJMZLM.js";
46
46
  import "./chunk-UMNXCU3K.js";
47
+ import "./chunk-TQTEKNOL.js";
48
+ import "./chunk-CHTAWXC2.js";
47
49
  import "./chunk-AHYOVVJ7.js";
48
50
  import "./chunk-SOYOYGWY.js";
49
51
  import "./chunk-ZWN3AODA.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config/define-config.ts","../src/config/config-builder.ts","../src/config/validate-structure.ts","../src/core/errors.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,SAAS,aAAaA,SAAkD;AAC7E,SAAOA;AACT;;;ACuCA,SAAS,kBAAkB,MAA0C;AACnE,QAAM,QAAQ,CAAC,UACb,kBAAkB,EAAE,GAAG,MAAM,GAAG,MAAM,CAAC;AACzC,SAAO;AAAA,IACL,MAAM,CAAC,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAAA,IACtC,WAAW,CAAC,UAAU,MAAM,EAAE,WAAW,MAAM,CAAC;AAAA,IAChD,QAAQ,CAAC,UAAU,MAAM,EAAE,QAAQ,MAAM,CAAC;AAAA,IAC1C,WAAW,CAAC,UAAU,MAAM,EAAE,WAAW,MAAM,CAAC;AAAA,IAChD,SAAS,CAAC,UAAU,MAAM,EAAE,SAAS,MAAM,CAAC;AAAA,IAC5C,MAAM,CAAC,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAAA,IACtC,MAAM,CAAC,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAAA,IACtC,cAAc,CAAC,UAAU,MAAM,EAAE,cAAc,MAAM,CAAC;AAAA,IACtD,KAAK,CAAC,UAAU,MAAM,EAAE,KAAK,MAAM,CAAC;AAAA,IACpC,KAAK,CA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,OAAO,SAAS,GAAG;AACrB,UAAM,IAAI,iBAAiB,QAAQ,OAAO;AAAA,EAC5C;AACF;","names":["config"]}
1
+ {"version":3,"sources":["../src/config/define-config.ts","../src/config/config-builder.ts","../src/config/validate-structure.ts","../src/core/errors.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,SAAS,aAAaA,SAAkD;AAC7E,SAAOA;AACT;;;ACuCA,SAAS,kBAAkB,MAA0C;AACnE,QAAM,QAAQ,CAAC,UACb,kBAAkB,EAAE,GAAG,MAAM,GAAG,MAAM,CAAC;AACzC,SAAO;AAAA,IACL,MAAM,CAAC,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAAA,IACtC,WAAW,CAAC,UAAU,MAAM,EAAE,WAAW,MAAM,CAAC;AAAA,IAChD,QAAQ,CAAC,UAAU,MAAM,EAAE,QAAQ,MAAM,CAAC;AAAA,IAC1C,WAAW,CAAC,UAAU,MAAM,EAAE,WAAW,MAAM,CAAC;AAAA,IAChD,SAAS,CAAC,UAAU,MAAM,EAAE,SAAS,MAAM,CAAC;AAAA,IAC5C,MAAM,CAAC,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAAA,IACtC,MAAM,CAAC,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAAA,IACtC,cAAc,CAAC,UAAU,MAAM,EAAE,cAAc,MAAM,CAAC;AAAA,IACtD,KAAK,CAAC,UAAU,MAAM,EAAE,KAAK,MAAM,CAAC;AAAA,IACpC,KAAK,CAAC,YAAY,MAAM,OAAO;AAAA,IAC/B,OAAO,MAAM,aAAa,IAAI;AAAA,EAChC;AACF;AAKO,SAAS,SAAwB;AACtC,SAAO,kBAAkB,CAAC,CAAC;AAC7B;;;ACnEA,SAAS,kBAAkB;AAC3B,SAAS,YAAY;;;ACLd,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EAEhB,YAAY,QAAkB,SAAiB;AAC7C,UAAM,aAAa,OAAO,IAAI,CAAC,MAAM,OAAO,CAAC,EAAE,EAAE,KAAK,IAAI;AAE1D;AAAA,MACE;AAAA;AAAA,UACa,OAAO;AAAA;AAAA,KACjB,aAAa;AAAA,EAAc,UAAU;AAAA,IAAO;AAAA,IACjD;AAEA,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACjB;AACF;;;ADHA,IAAM,iBAAmC;AAAA,EACvC;AAAA,IACE,MAAM;AAAA,IACN,cAAc;AAAA,EAChB;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,cAAc;AAAA,EAChB;AACF;AAIO,SAAS,yBAAyB,SAAiB,SAAS,OAAa;AAC9E,MAAI,CAAC,WAAW,OAAO,GAAG;AACxB,UAAM,IAAI,iBAAiB,CAAC,qCAAqC,OAAO,EAAE,GAAG,OAAO;AAAA,EACtF;AAEA,QAAM,SAAmB,CAAC;AAE1B,QAAM,eAAiC;AAAA,IACrC,EAAE,MAAM,QAAQ,cAAc,+BAA+B,MAAM,IAAI;AAAA,EACzE;AAEA,aAAW,QAAQ,cAAc;AAC/B,QAAI,CAAC,WAAW,KAAK,SAAS,KAAK,IAAI,CAAC,GAAG;AACzC,aAAO,KAAK,KAAK,YAAY;AAAA,IAC/B;AAAA,EACF;AAEA,aAAW,QAAQ,gBAAgB;AACjC,QAAI,CAAC,WAAW,KAAK,SAAS,KAAK,IAAI,CAAC,GAAG;AACzC,aAAO,KAAK,KAAK,YAAY;AAAA,IAC/B;AAAA,EACF;AAEA,MAAI,OAAO,SAAS,GAAG;AACrB,UAAM,IAAI,iBAAiB,QAAQ,OAAO;AAAA,EAC5C;AACF;","names":["config"]}
@@ -5,12 +5,12 @@ import {
5
5
  } from "./chunk-47MM2JUK.js";
6
6
  import {
7
7
  loadConfig
8
- } from "./chunk-OZB2TKGJ.js";
8
+ } from "./chunk-W2I6L4IJ.js";
9
9
  import "./chunk-3QPVEJ7D.js";
10
10
  import "./chunk-O5JZ6ROY.js";
11
- import "./chunk-NX3P5MLH.js";
11
+ import "./chunk-C2BRSL4W.js";
12
12
  import "./chunk-L4V5V2TI.js";
13
- import "./chunk-D2R5SJEL.js";
13
+ import "./chunk-MAJZ2L3A.js";
14
14
 
15
15
  // src/cli/commands/info.ts
16
16
  import { existsSync, readFileSync } from "fs";
@@ -103,4 +103,4 @@ export {
103
103
  buildInfo,
104
104
  infoCommand
105
105
  };
106
- //# sourceMappingURL=info-6NAUW5XY.js.map
106
+ //# sourceMappingURL=info-IPMW56PI.js.map
@@ -16,10 +16,10 @@ import {
16
16
  handleCspReport,
17
17
  handleCsrfReadiness,
18
18
  mountAgent
19
- } from "./chunk-RQKMY3JW.js";
19
+ } from "./chunk-XI4FALFZ.js";
20
20
  import {
21
21
  resolveProvider
22
- } from "./chunk-BINRCILF.js";
22
+ } from "./chunk-4JRXZTVQ.js";
23
23
  import {
24
24
  dispatchControllerRequest,
25
25
  incomingMessageToHandlerRequest,
@@ -31,7 +31,7 @@ import {
31
31
  import {
32
32
  TRACE_HEADER,
33
33
  extractTraceId
34
- } from "./chunk-MX63AWEK.js";
34
+ } from "./chunk-VXDTQO3S.js";
35
35
  import {
36
36
  logRequest
37
37
  } from "./chunk-C27VRUVN.js";
@@ -52,7 +52,8 @@ import {
52
52
  } from "./chunk-4WP7A7RX.js";
53
53
  import "./chunk-Z7CJHDLS.js";
54
54
  import "./chunk-O5JZ6ROY.js";
55
- import "./chunk-D2R5SJEL.js";
55
+ import "./chunk-MAJZ2L3A.js";
56
+ import "./chunk-NF7LXSXZ.js";
56
57
  import "./chunk-VQIUTCK2.js";
57
58
  export {
58
59
  ACTION_SCHEMAS_DIR,
@@ -87,4 +88,4 @@ export {
87
88
  scanWebSocketRoutes,
88
89
  sendError
89
90
  };
90
- //# sourceMappingURL=internal-api-R7TTYMCY.js.map
91
+ //# sourceMappingURL=internal-api-6RAOYIET.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  dispatchControllerRequest
3
- } from "./chunk-D7STTNQN.js";
3
+ } from "./chunk-BXQCJJPT.js";
4
4
  import {
5
5
  mountAgent
6
- } from "./chunk-R4AMIBZL.js";
6
+ } from "./chunk-4XZOUS5G.js";
7
7
  import {
8
8
  CSP_REPORT_PATH,
9
9
  CsrfReadinessStore,
@@ -18,11 +18,11 @@ import {
18
18
  executeAction,
19
19
  executeRoute,
20
20
  handleBatchRequest
21
- } from "./chunk-2Z7TANA4.js";
21
+ } from "./chunk-PVCXREGE.js";
22
22
  import {
23
23
  incomingMessageToHandlerRequest,
24
24
  sendError
25
- } from "./chunk-SYIQV4UH.js";
25
+ } from "./chunk-36ZACTF3.js";
26
26
  import "./chunk-P6OS7652.js";
27
27
  import "./chunk-ZDUO4IYN.js";
28
28
  import "./chunk-IDWN2OSG.js";
@@ -30,13 +30,11 @@ import "./chunk-47FFT43U.js";
30
30
  import {
31
31
  findSuggestion
32
32
  } from "./chunk-NTDN54XO.js";
33
- import "./chunk-PVNMLZ5G.js";
33
+ import "./chunk-JO462JZM.js";
34
34
  import {
35
35
  TRACE_HEADER,
36
- extractTraceId,
37
- logRequest
38
- } from "./chunk-ZDCCILMP.js";
39
- import "./chunk-CHTAWXC2.js";
36
+ extractTraceId
37
+ } from "./chunk-IXXZBZF7.js";
40
38
  import "./chunk-AVQU5CQF.js";
41
39
  import {
42
40
  createPluginRunnerFromConfig
@@ -65,12 +63,17 @@ import "./chunk-ACKBVBUI.js";
65
63
  import "./chunk-IZ3TIL6K.js";
66
64
  import {
67
65
  resolveProvider
68
- } from "./chunk-ICXXHV4V.js";
66
+ } from "./chunk-54BIQFP4.js";
67
+ import "./chunk-ZICY2CD7.js";
69
68
  import "./chunk-YSJOZEI6.js";
70
69
  import {
71
70
  generateNonce
72
71
  } from "./chunk-Z4PJMZLM.js";
73
72
  import "./chunk-UMNXCU3K.js";
73
+ import {
74
+ logRequest
75
+ } from "./chunk-TQTEKNOL.js";
76
+ import "./chunk-CHTAWXC2.js";
74
77
  import "./chunk-AHYOVVJ7.js";
75
78
  import "./chunk-SOYOYGWY.js";
76
79
  import "./chunk-ZWN3AODA.js";
@@ -108,4 +111,4 @@ export {
108
111
  scanWebSocketRoutes,
109
112
  sendError
110
113
  };
111
- //# sourceMappingURL=internal-api-A5HA7TYF.js.map
114
+ //# sourceMappingURL=internal-api-YGFPLQ4E.js.map
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Neutral `JobBackend` interface.
3
+ *
4
+ * Implementations ship in core:
5
+ * - `InMemoryJobBackend` (T2.2) — dev + tests; no external deps
6
+ * - `PostgresJobBackend` (T3.1) — production; requires `pg` peer dep
7
+ *
8
+ * Community packages (`@theokit/jobs-redis`, `@theokit/jobs-sqs`, etc.)
9
+ * implement this same interface to plug in alternate substrates without
10
+ * modifying TheoKit core.
11
+ */
12
+ interface JobEnqueueInput {
13
+ /** The job name (matches a `defineJob` declaration). */
14
+ name: string;
15
+ /** Validated input (already passed through Zod or equivalent at the queue-client layer). */
16
+ input: unknown;
17
+ /**
18
+ * Optional idempotency key, scoped to `name`: a second enqueue of the same (name, key) returns the
19
+ * first job's id instead of creating a job, including when the two calls race. The window is
20
+ * backend-specific: `PostgresJobBackend` holds the key while the row exists (until `ack`, or for
21
+ * good once the job has failed); `InMemoryJobBackend` holds it for 60 seconds.
22
+ */
23
+ idempotencyKey?: string;
24
+ /** Optional delay before the job becomes available for dispatch. */
25
+ delaySeconds?: number;
26
+ /** W3C Trace Context propagation per ADR/R0.5.9. */
27
+ traceparent?: string;
28
+ /**
29
+ * Maximum dispatch attempts stored with the job (default 1). The queue client has no access to
30
+ * the job definitions and leaves it unset; `createJobRunner` passes the definition's
31
+ * `maxAttempts` to `nack`, which takes precedence over this stored value.
32
+ */
33
+ maxAttempts?: number;
34
+ }
35
+ interface JobLease {
36
+ readonly jobId: string;
37
+ readonly name: string;
38
+ readonly input: unknown;
39
+ readonly attempts: number;
40
+ readonly maxAttempts: number;
41
+ readonly traceparent?: string;
42
+ readonly lockExpiresAt: Date;
43
+ /**
44
+ * Identifies THIS lease. Pass it back to `ack`/`nack` so a worker whose lease expired, and was
45
+ * handed to another worker, cannot finish the job on the new holder's behalf. Both first-party
46
+ * backends set it; optional so a backend written against the earlier contract still compiles.
47
+ */
48
+ readonly leaseToken?: string;
49
+ }
50
+ /** What `nack` is told about the failure. */
51
+ interface JobNackOptions extends JobLeaseFence {
52
+ /** The failure message. */
53
+ error: string;
54
+ /** The handler threw `NonRetryableError`: no retry, whatever the attempts left. */
55
+ nonRetryable?: boolean;
56
+ /**
57
+ * The retry ceiling from the job's definition. Takes precedence over the value stored at
58
+ * enqueue, which is 1 for every job enqueued through the queue client.
59
+ */
60
+ maxAttempts?: number;
61
+ }
62
+ /** Fences `ack`/`nack` to the lease that is finishing the job. */
63
+ interface JobLeaseFence {
64
+ /** The `leaseToken` of the `JobLease` being finished. Omitted, the call is not fenced. */
65
+ leaseToken?: string;
66
+ }
67
+ interface JobBackend {
68
+ /** Human-readable name for logging (e.g., "memory", "postgres"). */
69
+ readonly name: string;
70
+ /** Persist a job for later dispatch. Returns the generated jobId. */
71
+ enqueue(input: JobEnqueueInput): Promise<{
72
+ jobId: string;
73
+ }>;
74
+ /** Worker loop polls for the next available leases. */
75
+ dequeue(opts: {
76
+ batchSize?: number;
77
+ lockSeconds?: number;
78
+ }): Promise<JobLease[]>;
79
+ /**
80
+ * Mark a job complete (success). With `leaseToken`, rejects with `JobLeaseLostError` and leaves
81
+ * the job alone when that lease no longer holds it.
82
+ */
83
+ ack(jobId: string, fence?: JobLeaseFence): Promise<void>;
84
+ /**
85
+ * Mark a job failed; backend decides retry vs DLQ via attempts. With `leaseToken`, rejects with
86
+ * `JobLeaseLostError` and leaves the job alone when that lease no longer holds it.
87
+ */
88
+ nack(jobId: string, opts: JobNackOptions): Promise<void>;
89
+ /**
90
+ * Optional: return the existing jobId if `key` was enqueued within `ttlSeconds`. Pass `name` to
91
+ * scope the lookup to one job type, as `enqueue` deduplicates on (name, key); without it, a key
92
+ * shared by two job types may return either job.
93
+ */
94
+ idempotency?(key: string, ttlSeconds: number, name?: string): Promise<{
95
+ jobId: string;
96
+ } | null>;
97
+ }
98
+ /**
99
+ * Thrown from a job handler to opt out of retry policy. The runner nacks with
100
+ * `nonRetryable: true` and the backend never retries the job: `PostgresJobBackend`
101
+ * keeps it as failed with the error, `InMemoryJobBackend` drops it with a warning.
102
+ */
103
+ declare class NonRetryableError extends Error {
104
+ readonly code = "NON_RETRYABLE";
105
+ constructor(message: string);
106
+ }
107
+ /**
108
+ * `ack`/`nack` was called with a lease token that no longer holds the job: the lease expired and
109
+ * another worker leased the job again (or the job is gone). The job is left untouched, because the
110
+ * current holder owns its outcome. The runner logs it and moves on; a direct caller decides.
111
+ */
112
+ declare class JobLeaseLostError extends Error {
113
+ readonly code = "JOB_LEASE_LOST";
114
+ readonly jobId: string;
115
+ readonly operation: 'ack' | 'nack';
116
+ constructor(jobId: string, operation: 'ack' | 'nack');
117
+ }
118
+
119
+ export { type JobBackend as J, NonRetryableError as N, type JobEnqueueInput as a, type JobLease as b, type JobLeaseFence as c, JobLeaseLostError as d, type JobNackOptions as e };
@@ -3,14 +3,14 @@ import "tsx/esm";
3
3
  import {
4
4
  deepMerge,
5
5
  loadConfig
6
- } from "./chunk-OZB2TKGJ.js";
6
+ } from "./chunk-W2I6L4IJ.js";
7
7
  import "./chunk-3QPVEJ7D.js";
8
8
  import "./chunk-O5JZ6ROY.js";
9
- import "./chunk-NX3P5MLH.js";
9
+ import "./chunk-C2BRSL4W.js";
10
10
  import "./chunk-L4V5V2TI.js";
11
- import "./chunk-D2R5SJEL.js";
11
+ import "./chunk-MAJZ2L3A.js";
12
12
  export {
13
13
  deepMerge,
14
14
  loadConfig
15
15
  };
16
- //# sourceMappingURL=load-config-CLFWJOXN.js.map
16
+ //# sourceMappingURL=load-config-USRR4GXP.js.map
@@ -2,17 +2,18 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  createAgentSsrLoader
5
- } from "./chunk-UWV3B3RY.js";
5
+ } from "./chunk-XDLFOATW.js";
6
6
  import {
7
7
  extractAppResources,
8
8
  handleMcpJsonRpc
9
9
  } from "./chunk-BDH5GKFZ.js";
10
- import "./chunk-BINRCILF.js";
10
+ import "./chunk-4JRXZTVQ.js";
11
11
  import {
12
12
  scanAgents
13
13
  } from "./chunk-FU3LEX2I.js";
14
14
  import "./chunk-Z7CJHDLS.js";
15
15
  import "./chunk-3QPVEJ7D.js";
16
+ import "./chunk-NF7LXSXZ.js";
16
17
 
17
18
  // src/cli/commands/mcp.ts
18
19
  import { createInterface } from "readline";
@@ -46,7 +47,7 @@ async function serveMcpStdio(mod, name, appResources, streams) {
46
47
  // src/cli/commands/mcp.ts
47
48
  async function mcpCommand(name, deps = {}) {
48
49
  const projectRoot = deps.projectRoot ?? process.cwd();
49
- const agentsDir = deps.agentsDir ?? (await (await import("./load-config-CLFWJOXN.js")).loadConfig(projectRoot)).agentsDir;
50
+ const agentsDir = deps.agentsDir ?? (await (await import("./load-config-USRR4GXP.js")).loadConfig(projectRoot)).agentsDir;
50
51
  const agent = scanAgents(projectRoot, agentsDir).find((a) => a.name === name);
51
52
  if (!agent) {
52
53
  const names = scanAgents(projectRoot, agentsDir).map((a) => a.name).join(", ");
@@ -75,4 +76,4 @@ async function mcpCommand(name, deps = {}) {
75
76
  export {
76
77
  mcpCommand
77
78
  };
78
- //# sourceMappingURL=mcp-3NRZAQKY.js.map
79
+ //# sourceMappingURL=mcp-FBXEX45H.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli/commands/mcp.ts","../src/server/agent/mcp-stdio.ts"],"sourcesContent":["/**\n * `theokit mcp <agent>` — expose a scanned agent as an MCP server over stdio.\n *\n * The stdio sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`): a desktop MCP client\n * (e.g. Claude Desktop) spawns this command and speaks newline-delimited JSON-RPC over the pipe.\n * It reuses the framework's OWN `serveMcpStdio` / `handleMcpJsonRpc` (no LLM call, no runtime — a\n * TRANSPORT, like the HTTP route). `deps` is injectable so the routing is tested without Vite/stdin.\n */\nimport { createInterface } from 'node:readline'\n\nimport { extractAppResources } from '../../server/agent/mcp-app-resources.js'\nimport { type StdioStreams, serveMcpStdio } from '../../server/agent/mcp-stdio.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\n\nimport { createAgentSsrLoader } from './agent.js'\n\ninterface McpCommandDeps {\n projectRoot?: string\n /** Load a TS agent module; defaults to the framework's Vite SSR loader (same transpile as dev). */\n loadModule?: (filePath: string) => Promise<Record<string, unknown>>\n /** stdio streams; defaults to `readline(process.stdin)` + `process.stdout`. Injected in tests. */\n streams?: StdioStreams\n /** Agents dir name (config `agentsDir`); defaults to the loaded config's value (\"agents\"). Tests inject it. */\n agentsDir?: string\n}\n\nexport async function mcpCommand(name: string, deps: McpCommandDeps = {}): Promise<void> {\n const projectRoot = deps.projectRoot ?? process.cwd()\n // #95 follow-up — resolve agents dir from config (default \"agents\") so `agentsDir` is honored here too.\n const agentsDir =\n deps.agentsDir ??\n (await (await import('../../config/load-config.js')).loadConfig(projectRoot)).agentsDir\n const agent = scanAgents(projectRoot, agentsDir).find((a) => a.name === name)\n if (!agent) {\n const names = scanAgents(projectRoot, agentsDir)\n .map((a) => a.name)\n .join(', ')\n throw new Error(\n `theokit mcp: agent '${name}' not found. Available: ${names || '(none in agents/)'}`,\n )\n }\n\n let loadModule = deps.loadModule\n let dispose: (() => Promise<void>) | undefined\n if (!loadModule) {\n const loader = await createAgentSsrLoader(projectRoot)\n loadModule = loader.load\n dispose = loader.dispose\n }\n\n const streams =\n deps.streams ??\n ({\n lines: createInterface({ input: process.stdin }),\n write: (line: string) => process.stdout.write(line),\n } satisfies StdioStreams)\n\n try {\n const mod = await loadModule(agent.filePath)\n await serveMcpStdio(mod, agent.name, extractAppResources(mod), streams)\n } finally {\n if (dispose) await dispose()\n }\n}\n","/**\n * MCP stdio transport (M16 follow-up) — expose a TheoKit agent as an MCP server over stdin/stdout,\n * the sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`). A desktop MCP client (e.g.\n * Claude Desktop) spawns `theokit mcp <agent>` and speaks newline-delimited JSON-RPC over the pipe.\n *\n * This is a TRANSPORT over the framework's OWN {@link handleMcpJsonRpc} — it reuses the exact handler\n * the HTTP route uses; it calls no LLM, spawns no MCP client, and reimplements no runtime (G2 /\n * sdk-runtime.md). Distinct from the SDK's MCP CLIENT stdio (which spawns external MCP servers via\n * `mcpServers` command/args) — that stays SDK-side. Here TheoKit is the SERVER. The framework-side\n * placement of this server-exposure transport is recorded in ADR-0042 (refining ADR-0040's M16 note).\n */\nimport type { AppResource } from './mcp-app-resources.js'\nimport { handleMcpJsonRpc } from './mcp-handler.js'\n\n/**\n * Handle one newline-delimited JSON-RPC line. Returns the response line to write to stdout, or\n * `null` for a blank line (nothing to emit). A malformed JSON line yields a `-32700` (Parse error)\n * envelope — never throws, so the stdio loop never dies on bad input.\n */\nexport async function handleMcpStdioLine(\n line: string,\n mod: unknown,\n name: string,\n appResources: readonly AppResource[] = [],\n): Promise<string | null> {\n const trimmed = line.trim()\n if (trimmed.length === 0) return null\n let body: unknown\n try {\n body = JSON.parse(trimmed)\n } catch {\n return JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error' },\n })\n }\n const response = await handleMcpJsonRpc(mod, name, body, appResources)\n const payload: unknown = await response.json()\n return JSON.stringify(payload)\n}\n\n/** A minimal readable line source (an async iterable of lines) + a writable sink. */\nexport interface StdioStreams {\n /** Async iterable of newline-delimited input lines (e.g. `readline.createInterface({ input })`). */\n lines: AsyncIterable<string>\n /** Write a response line (the caller appends no newline). */\n write: (line: string) => void\n}\n\n/**\n * Drive the MCP stdio server loop: for each input line, dispatch via {@link handleMcpStdioLine} and\n * write the response line (with a trailing `\\n`). Returns when the input stream ends (EOF).\n */\nexport async function serveMcpStdio(\n mod: unknown,\n name: string,\n appResources: readonly AppResource[],\n streams: StdioStreams,\n): Promise<void> {\n for await (const line of streams.lines) {\n const out = await handleMcpStdio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A,EACF;AAEA,MAAI,aAAa,KAAK;AACtB,MAAI;AACJ,MAAI,CAAC,YAAY;AACf,UAAM,SAAS,MAAM,qBAAqB,WAAW;AACrD,iBAAa,OAAO;AACpB,cAAU,OAAO;AAAA,EACnB;AAEA,QAAM,UACJ,KAAK,WACJ;AAAA,IACC,OAAO,gBAAgB,EAAE,OAAO,QAAQ,MAAM,CAAC;AAAA,IAC/C,OAAO,CAAC,SAAiB,QAAQ,OAAO,MAAM,IAAI;AAAA,EACpD;AAEF,MAAI;AACF,UAAM,MAAM,MAAM,WAAW,MAAM,QAAQ;AAC3C,UAAM,cAAc,KAAK,MAAM,MAAM,oBAAoB,GAAG,GAAG,OAAO;AAAA,EACxE,UAAE;AACA,QAAI,QAAS,OAAM,QAAQ;AAAA,EAC7B;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/cli/commands/mcp.ts","../src/server/agent/mcp-stdio.ts"],"sourcesContent":["/**\n * `theokit mcp <agent>` — expose a scanned agent as an MCP server over stdio.\n *\n * The stdio sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`): a desktop MCP client\n * (e.g. Claude Desktop) spawns this command and speaks newline-delimited JSON-RPC over the pipe.\n * It reuses the framework's OWN `serveMcpStdio` / `handleMcpJsonRpc` (no LLM call, no runtime — a\n * TRANSPORT, like the HTTP route). `deps` is injectable so the routing is tested without Vite/stdin.\n */\nimport { createInterface } from 'node:readline'\n\nimport { extractAppResources } from '../../server/agent/mcp-app-resources.js'\nimport { type StdioStreams, serveMcpStdio } from '../../server/agent/mcp-stdio.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\n\nimport { createAgentSsrLoader } from './agent.js'\n\ninterface McpCommandDeps {\n projectRoot?: string\n /** Load a TS agent module; defaults to the framework's Vite SSR loader (same transpile as dev). */\n loadModule?: (filePath: string) => Promise<Record<string, unknown>>\n /** stdio streams; defaults to `readline(process.stdin)` + `process.stdout`. Injected in tests. */\n streams?: StdioStreams\n /** Agents dir name (config `agentsDir`); defaults to the loaded config's value (\"agents\"). Tests inject it. */\n agentsDir?: string\n}\n\nexport async function mcpCommand(name: string, deps: McpCommandDeps = {}): Promise<void> {\n const projectRoot = deps.projectRoot ?? process.cwd()\n // #95 follow-up — resolve agents dir from config (default \"agents\") so `agentsDir` is honored here too.\n const agentsDir =\n deps.agentsDir ??\n (await (await import('../../config/load-config.js')).loadConfig(projectRoot)).agentsDir\n const agent = scanAgents(projectRoot, agentsDir).find((a) => a.name === name)\n if (!agent) {\n const names = scanAgents(projectRoot, agentsDir)\n .map((a) => a.name)\n .join(', ')\n throw new Error(\n `theokit mcp: agent '${name}' not found. Available: ${names || '(none in agents/)'}`,\n )\n }\n\n let loadModule = deps.loadModule\n let dispose: (() => Promise<void>) | undefined\n if (!loadModule) {\n const loader = await createAgentSsrLoader(projectRoot)\n loadModule = loader.load\n dispose = loader.dispose\n }\n\n const streams =\n deps.streams ??\n ({\n lines: createInterface({ input: process.stdin }),\n write: (line: string) => process.stdout.write(line),\n } satisfies StdioStreams)\n\n try {\n const mod = await loadModule(agent.filePath)\n await serveMcpStdio(mod, agent.name, extractAppResources(mod), streams)\n } finally {\n if (dispose) await dispose()\n }\n}\n","/**\n * MCP stdio transport (M16 follow-up) — expose a TheoKit agent as an MCP server over stdin/stdout,\n * the sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`). A desktop MCP client (e.g.\n * Claude Desktop) spawns `theokit mcp <agent>` and speaks newline-delimited JSON-RPC over the pipe.\n *\n * This is a TRANSPORT over the framework's OWN {@link handleMcpJsonRpc} — it reuses the exact handler\n * the HTTP route uses; it calls no LLM, spawns no MCP client, and reimplements no runtime (G2 /\n * sdk-runtime.md). Distinct from the SDK's MCP CLIENT stdio (which spawns external MCP servers via\n * `mcpServers` command/args) — that stays SDK-side. Here TheoKit is the SERVER. The framework-side\n * placement of this server-exposure transport is recorded in ADR-0042 (refining ADR-0040's M16 note).\n */\nimport type { AppResource } from './mcp-app-resources.js'\nimport { handleMcpJsonRpc } from './mcp-handler.js'\n\n/**\n * Handle one newline-delimited JSON-RPC line. Returns the response line to write to stdout, or\n * `null` for a blank line (nothing to emit). A malformed JSON line yields a `-32700` (Parse error)\n * envelope — never throws, so the stdio loop never dies on bad input.\n */\nexport async function handleMcpStdioLine(\n line: string,\n mod: unknown,\n name: string,\n appResources: readonly AppResource[] = [],\n): Promise<string | null> {\n const trimmed = line.trim()\n if (trimmed.length === 0) return null\n let body: unknown\n try {\n body = JSON.parse(trimmed)\n } catch {\n return JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error' },\n })\n }\n const response = await handleMcpJsonRpc(mod, name, body, appResources)\n const payload: unknown = await response.json()\n return JSON.stringify(payload)\n}\n\n/** A minimal readable line source (an async iterable of lines) + a writable sink. */\nexport interface StdioStreams {\n /** Async iterable of newline-delimited input lines (e.g. `readline.createInterface({ input })`). */\n lines: AsyncIterable<string>\n /** Write a response line (the caller appends no newline). */\n write: (line: string) => void\n}\n\n/**\n * Drive the MCP stdio server loop: for each input line, dispatch via {@link handleMcpStdioLine} and\n * write the response line (with a trailing `\\n`). Returns when the input stream ends (EOF).\n */\nexport async function serveMcpStdio(\n mod: unknown,\n name: string,\n appResources: readonly AppResource[],\n streams: StdioStreams,\n): Promise<void> {\n for await (const line of streams.lines) {\n const out = await handleMcpStdioLine(line, mod, name, appResources)\n if (out !== null) streams.write(`${out}\\n`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,SAAS,uBAAuB;;;ACWhC,eAAsB,mBACpB,MACA,KACA,MACA,eAAuC,CAAC,GAChB;AACxB,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAO,KAAK,UAAU;AAAA,MACpB,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,OAAO,EAAE,MAAM,QAAQ,SAAS,cAAc;AAA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