theokit 0.46.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/dist/{actions-virtual-module-LLDDAQWY.js → actions-virtual-module-2VVLVXHY.js} +6 -6
  2. package/dist/{actions-virtual-module-67K4POQ2.js → actions-virtual-module-Z5LXAX7E.js} +8 -7
  3. package/dist/actions-virtual-module-Z5LXAX7E.js.map +1 -0
  4. package/dist/{agent-WFULT3OB.js → agent-Y3JKRROD.js} +4 -4
  5. package/dist/{app-typed-client-S3VR4ZA3.js → app-typed-client-N4I4RBLT.js} +6 -6
  6. package/dist/app-typed-client-N4I4RBLT.js.map +1 -0
  7. package/dist/{app-typed-client-N5WUE2CP.js → app-typed-client-NI3CM2FA.js} +8 -7
  8. package/dist/app-typed-client-NI3CM2FA.js.map +1 -0
  9. package/dist/{aws-lambda-473QCOL6.js → aws-lambda-7SUTORXM.js} +3 -3
  10. package/dist/boot/index.js +1 -1
  11. package/dist/{build-YQ6MXOV6.js → build-SJQDRD2B.js} +10 -10
  12. package/dist/{bun-OQUCL3XW.js → bun-TLYZCEGE.js} +3 -3
  13. package/dist/{chunk-HEK4SET7.js → chunk-5JJCNEUS.js} +2 -2
  14. package/dist/chunk-5JJCNEUS.js.map +1 -0
  15. package/dist/chunk-6E5WKMDS.js +67 -0
  16. package/dist/chunk-6E5WKMDS.js.map +1 -0
  17. package/dist/{chunk-TDNNBLGW.js → chunk-6GGWS7J3.js} +1 -1
  18. package/dist/chunk-6GGWS7J3.js.map +1 -0
  19. package/dist/{chunk-FZG3JYB3.js → chunk-7ZOQN7UH.js} +1 -1
  20. package/dist/{chunk-B7ONQ4QJ.js → chunk-AOGYAXPY.js} +3 -3
  21. package/dist/{chunk-QPVXGC7O.js → chunk-CUYEA62B.js} +1 -1
  22. package/dist/{chunk-QPVXGC7O.js.map → chunk-CUYEA62B.js.map} +1 -1
  23. package/dist/{chunk-OXCALO3W.js → chunk-D3425YDV.js} +2 -2
  24. package/dist/{chunk-SMP2T335.js → chunk-DGQO372T.js} +2 -2
  25. package/dist/{chunk-C34PMLSN.js → chunk-DV34VG3N.js} +2 -10
  26. package/dist/chunk-DV34VG3N.js.map +1 -0
  27. package/dist/{chunk-U3H53IIN.js → chunk-FO55VGMQ.js} +3 -3
  28. package/dist/{chunk-VFU7DTUL.js → chunk-GEHX6CAE.js} +10 -8
  29. package/dist/chunk-GEHX6CAE.js.map +1 -0
  30. package/dist/{chunk-GDN3PXFH.js → chunk-HBU2GIMZ.js} +1 -1
  31. package/dist/chunk-HBU2GIMZ.js.map +1 -0
  32. package/dist/{chunk-7SABX4DJ.js → chunk-IZ3TIL6K.js} +28 -2
  33. package/dist/{chunk-7SABX4DJ.js.map → chunk-IZ3TIL6K.js.map} +1 -1
  34. package/dist/{chunk-L4Y6RJ4E.js → chunk-KSZGBUTI.js} +2 -2
  35. package/dist/{chunk-226KMIGZ.js → chunk-MNIQ5F3Y.js} +2 -10
  36. package/dist/chunk-MNIQ5F3Y.js.map +1 -0
  37. package/dist/{chunk-KBGGQK4I.js → chunk-O3JIAU3V.js} +4 -4
  38. package/dist/{chunk-UYMCKHML.js → chunk-O5W7XSUX.js} +40 -40
  39. package/dist/chunk-O5W7XSUX.js.map +1 -0
  40. package/dist/{chunk-EIRQM55C.js → chunk-OJLL4YD6.js} +5 -46
  41. package/dist/chunk-OJLL4YD6.js.map +1 -0
  42. package/dist/{chunk-6LNIGF5P.js → chunk-ORKNVORZ.js} +1 -1
  43. package/dist/chunk-ORKNVORZ.js.map +1 -0
  44. package/dist/{chunk-KPKLIUUL.js → chunk-TNI4MARH.js} +3 -3
  45. package/dist/{chunk-6KDXP472.js → chunk-UDPJP42U.js} +4 -4
  46. package/dist/{chunk-HGZL5EOI.js → chunk-VQIUTCK2.js} +28 -2
  47. package/dist/chunk-VQIUTCK2.js.map +1 -0
  48. package/dist/{chunk-6VDYQ4I6.js → chunk-VTJMND23.js} +4 -4
  49. package/dist/{chunk-6VDYQ4I6.js.map → chunk-VTJMND23.js.map} +1 -1
  50. package/dist/{chunk-37ZO643S.js → chunk-XALU5LCU.js} +3 -3
  51. package/dist/{chunk-SEELKQUM.js → chunk-Y2KHTD2W.js} +6 -2
  52. package/dist/chunk-Y2KHTD2W.js.map +1 -0
  53. package/dist/{chunk-SZU6BOMV.js → chunk-YRRWQDKK.js} +22 -18
  54. package/dist/chunk-YRRWQDKK.js.map +1 -0
  55. package/dist/{chunk-5AMXBU2R.js → chunk-ZALJIZH2.js} +13 -13
  56. package/dist/chunk-ZALJIZH2.js.map +1 -0
  57. package/dist/cli/index.js +31 -9
  58. package/dist/cli/index.js.map +1 -1
  59. package/dist/client/index.d.ts +1 -1
  60. package/dist/client/index.js +1 -1
  61. package/dist/{cloudflare-4YT5CK3P.js → cloudflare-JTBKOX3F.js} +3 -3
  62. package/dist/{deno-deploy-YYN6BNLF.js → deno-deploy-3ESNGYZU.js} +3 -3
  63. package/dist/{dev-YNO26JS3.js → dev-6TWDBX6G.js} +12 -12
  64. package/dist/{dev-emit-J7V6GWSK.js → dev-emit-7ZZRTYF3.js} +3 -3
  65. package/dist/{dev-emit-F54Y5TIU.js → dev-emit-E5Z26AMV.js} +3 -3
  66. package/dist/devtools/entry.js.map +1 -1
  67. package/dist/doctor-Y53QTUSP.js +56 -0
  68. package/dist/doctor-Y53QTUSP.js.map +1 -0
  69. package/dist/{error-envelope-BsNzzAV5.d.ts → error-envelope-DG47lt8E.d.ts} +4 -4
  70. package/dist/{generate-GXWPUVS7.js → generate-WQSNW4F6.js} +1 -1
  71. package/dist/{generate-GXWPUVS7.js.map → generate-WQSNW4F6.js.map} +1 -1
  72. package/dist/{index-BeAsvfPr.d.ts → index-BEtEv6ZH.d.ts} +2 -2
  73. package/dist/index.d.ts +5 -5
  74. package/dist/index.js +9 -8
  75. package/dist/index.js.map +1 -1
  76. package/dist/{info-ICDTPJDC.js → info-QB7Q3SHP.js} +5 -5
  77. package/dist/{internal-api-S7WK2WCY.js → internal-api-REGN3WMX.js} +11 -9
  78. package/dist/{internal-api-NO24QAXC.js → internal-api-XQA2L663.js} +6 -6
  79. package/dist/load-config-JKJ73TOD.js +14 -0
  80. package/dist/{mcp-3S6A4A4Q.js → mcp-CO4AGAXV.js} +5 -5
  81. package/dist/{netlify-2WZUQYI3.js → netlify-OFJUYXTZ.js} +3 -3
  82. package/dist/node-ND4MJU3Z.js +10 -0
  83. package/dist/{openapi-NIYA2VBG.js → openapi-5CZCL7YP.js} +7 -7
  84. package/dist/registry-QTSMLOVG.js +23 -0
  85. package/dist/{routes-2RD4S5PZ.js → routes-GWAWUVVQ.js} +6 -6
  86. package/dist/{schema-S553QCAU.js → schema-2JEG6TTU.js} +3 -3
  87. package/dist/server/agent/index.d.ts +90 -1
  88. package/dist/server/agent/index.js +14 -2
  89. package/dist/server/cost/index.d.ts +1 -0
  90. package/dist/server/cost/index.js +3 -1
  91. package/dist/server/http/index.d.ts +2 -2
  92. package/dist/server/http/index.js +2 -2
  93. package/dist/server/index.d.ts +499 -6
  94. package/dist/server/index.js +491 -12
  95. package/dist/server/index.js.map +1 -1
  96. package/dist/server/observability/index.d.ts +4 -4
  97. package/dist/server/observability/index.js +1 -1
  98. package/dist/server/rate-limit/index.js +2 -2
  99. package/dist/server/scan/index.js +2 -2
  100. package/dist/{server-error-to-envelope-UM7DEVM4.js → server-error-to-envelope-2MQOME5Q.js} +2 -2
  101. package/dist/{server-error-to-envelope-UUXDSLAZ.js → server-error-to-envelope-4TGCDQ2S.js} +2 -2
  102. package/dist/{services-typed-client-EO4RFNTZ.js → services-typed-client-II7LKXKO.js} +2 -2
  103. package/dist/sessions-gc-H4WC4IXB.js +38 -0
  104. package/dist/sessions-gc-H4WC4IXB.js.map +1 -0
  105. package/dist/{start-TVT7BZ4V.js → start-IO3ZYGEX.js} +13 -13
  106. package/dist/start-IO3ZYGEX.js.map +1 -0
  107. package/dist/{static-25H5K42R.js → static-HTT2WNIT.js} +3 -3
  108. package/dist/{theo-cloud-JL2KXHIS.js → theo-cloud-ZTQLXGPS.js} +2 -2
  109. package/dist/theo-cloud-ZTQLXGPS.js.map +1 -0
  110. package/dist/{vercel-FP3C6LN6.js → vercel-72HFEMJ3.js} +3 -3
  111. package/dist/vite-plugin/index.js +9 -8
  112. package/dist/{vite-plugin-K64KQZSU.js → vite-plugin-NQ6F7FGV.js} +12 -12
  113. package/package.json +6 -7
  114. package/dist/actions-virtual-module-67K4POQ2.js.map +0 -1
  115. package/dist/app-typed-client-N5WUE2CP.js.map +0 -1
  116. package/dist/app-typed-client-S3VR4ZA3.js.map +0 -1
  117. package/dist/chunk-226KMIGZ.js.map +0 -1
  118. package/dist/chunk-5AMXBU2R.js.map +0 -1
  119. package/dist/chunk-6LNIGF5P.js.map +0 -1
  120. package/dist/chunk-C34PMLSN.js.map +0 -1
  121. package/dist/chunk-EIRQM55C.js.map +0 -1
  122. package/dist/chunk-GDN3PXFH.js.map +0 -1
  123. package/dist/chunk-HEK4SET7.js.map +0 -1
  124. package/dist/chunk-HGZL5EOI.js.map +0 -1
  125. package/dist/chunk-SEELKQUM.js.map +0 -1
  126. package/dist/chunk-SZU6BOMV.js.map +0 -1
  127. package/dist/chunk-TDNNBLGW.js.map +0 -1
  128. package/dist/chunk-UYMCKHML.js.map +0 -1
  129. package/dist/chunk-VFU7DTUL.js.map +0 -1
  130. package/dist/load-config-ICCNMO74.js +0 -14
  131. package/dist/node-CMAYKDCM.js +0 -10
  132. package/dist/registry-72YH7ZJM.js +0 -23
  133. package/dist/start-TVT7BZ4V.js.map +0 -1
  134. package/dist/theo-cloud-JL2KXHIS.js.map +0 -1
  135. /package/dist/{actions-virtual-module-LLDDAQWY.js.map → actions-virtual-module-2VVLVXHY.js.map} +0 -0
  136. /package/dist/{agent-WFULT3OB.js.map → agent-Y3JKRROD.js.map} +0 -0
  137. /package/dist/{aws-lambda-473QCOL6.js.map → aws-lambda-7SUTORXM.js.map} +0 -0
  138. /package/dist/{build-YQ6MXOV6.js.map → build-SJQDRD2B.js.map} +0 -0
  139. /package/dist/{bun-OQUCL3XW.js.map → bun-TLYZCEGE.js.map} +0 -0
  140. /package/dist/{chunk-FZG3JYB3.js.map → chunk-7ZOQN7UH.js.map} +0 -0
  141. /package/dist/{chunk-B7ONQ4QJ.js.map → chunk-AOGYAXPY.js.map} +0 -0
  142. /package/dist/{chunk-OXCALO3W.js.map → chunk-D3425YDV.js.map} +0 -0
  143. /package/dist/{chunk-SMP2T335.js.map → chunk-DGQO372T.js.map} +0 -0
  144. /package/dist/{chunk-U3H53IIN.js.map → chunk-FO55VGMQ.js.map} +0 -0
  145. /package/dist/{chunk-L4Y6RJ4E.js.map → chunk-KSZGBUTI.js.map} +0 -0
  146. /package/dist/{chunk-KBGGQK4I.js.map → chunk-O3JIAU3V.js.map} +0 -0
  147. /package/dist/{chunk-KPKLIUUL.js.map → chunk-TNI4MARH.js.map} +0 -0
  148. /package/dist/{chunk-6KDXP472.js.map → chunk-UDPJP42U.js.map} +0 -0
  149. /package/dist/{chunk-37ZO643S.js.map → chunk-XALU5LCU.js.map} +0 -0
  150. /package/dist/{cloudflare-4YT5CK3P.js.map → cloudflare-JTBKOX3F.js.map} +0 -0
  151. /package/dist/{deno-deploy-YYN6BNLF.js.map → deno-deploy-3ESNGYZU.js.map} +0 -0
  152. /package/dist/{dev-YNO26JS3.js.map → dev-6TWDBX6G.js.map} +0 -0
  153. /package/dist/{dev-emit-J7V6GWSK.js.map → dev-emit-7ZZRTYF3.js.map} +0 -0
  154. /package/dist/{dev-emit-F54Y5TIU.js.map → dev-emit-E5Z26AMV.js.map} +0 -0
  155. /package/dist/{info-ICDTPJDC.js.map → info-QB7Q3SHP.js.map} +0 -0
  156. /package/dist/{internal-api-S7WK2WCY.js.map → internal-api-REGN3WMX.js.map} +0 -0
  157. /package/dist/{internal-api-NO24QAXC.js.map → internal-api-XQA2L663.js.map} +0 -0
  158. /package/dist/{load-config-ICCNMO74.js.map → load-config-JKJ73TOD.js.map} +0 -0
  159. /package/dist/{mcp-3S6A4A4Q.js.map → mcp-CO4AGAXV.js.map} +0 -0
  160. /package/dist/{netlify-2WZUQYI3.js.map → netlify-OFJUYXTZ.js.map} +0 -0
  161. /package/dist/{node-CMAYKDCM.js.map → node-ND4MJU3Z.js.map} +0 -0
  162. /package/dist/{openapi-NIYA2VBG.js.map → openapi-5CZCL7YP.js.map} +0 -0
  163. /package/dist/{registry-72YH7ZJM.js.map → registry-QTSMLOVG.js.map} +0 -0
  164. /package/dist/{routes-2RD4S5PZ.js.map → routes-GWAWUVVQ.js.map} +0 -0
  165. /package/dist/{schema-S553QCAU.js.map → schema-2JEG6TTU.js.map} +0 -0
  166. /package/dist/{server-error-to-envelope-UM7DEVM4.js.map → server-error-to-envelope-2MQOME5Q.js.map} +0 -0
  167. /package/dist/{server-error-to-envelope-UUXDSLAZ.js.map → server-error-to-envelope-4TGCDQ2S.js.map} +0 -0
  168. /package/dist/{services-typed-client-EO4RFNTZ.js.map → services-typed-client-II7LKXKO.js.map} +0 -0
  169. /package/dist/{static-25H5K42R.js.map → static-HTT2WNIT.js.map} +0 -0
  170. /package/dist/{vercel-FP3C6LN6.js.map → vercel-72HFEMJ3.js.map} +0 -0
  171. /package/dist/{vite-plugin-K64KQZSU.js.map → vite-plugin-NQ6F7FGV.js.map} +0 -0
@@ -98,7 +98,19 @@ var ERROR_NAME_TO_CODE = /* @__PURE__ */ new Map([
98
98
  // RouterConventionError reaches the wire only during dev-error overlay;
99
99
  // INTERNAL_SERVER_ERROR is appropriate, but we add a HintExt-shaped ext
100
100
  // with the migration guidance for the devtools display.
101
- ["RouterConventionError", "INTERNAL_SERVER_ERROR"]
101
+ ["RouterConventionError", "INTERNAL_SERVER_ERROR"],
102
+ // M80 — the agent errors, which this table contained NONE of.
103
+ //
104
+ // The consequence was concrete: a `GuardrailViolationError` — thrown when a prompt-injection or
105
+ // PII guard BLOCKS — crossed as HTTP 500, indistinguishable from a real server failure. Retry
106
+ // middleware then re-submitted the very input the guard had just rejected.
107
+ //
108
+ // The status codes say what actually happened: the request was refused (400), the caller has
109
+ // spent its budget (429), or a human must approve before this proceeds (403). None of the three
110
+ // is "the server broke", and none should be retried by a generic 5xx policy.
111
+ ["GuardrailViolationError", "BAD_REQUEST"],
112
+ ["CostBudgetExceededError", "TOO_MANY_REQUESTS"],
113
+ ["InProcessApprovalRequiredError", "FORBIDDEN"]
102
114
  ]);
103
115
  var META_EXTRACTORS = /* @__PURE__ */ new Map([
104
116
  [
@@ -121,6 +133,20 @@ var META_EXTRACTORS = /* @__PURE__ */ new Map([
121
133
  migrationUrl: e.migrationUrl
122
134
  };
123
135
  }
136
+ ],
137
+ [
138
+ // M80 — so telemetry can count blocks PER GUARD without parsing the message. A count derived
139
+ // from message text breaks the first time somebody improves the wording, and the improvement
140
+ // looks harmless right up until the dashboard goes flat.
141
+ //
142
+ // Read from the class's own public fields rather than the SDK's `metadata`: that type is
143
+ // provider-transport shaped (`provider`, `endpoint`, `statusCode`, `retryAfter`), and an
144
+ // agent-domain fact does not belong in it.
145
+ "GuardrailViolationError",
146
+ (err) => {
147
+ const e = err;
148
+ return { guardName: e.guardName, phase: e.phase };
149
+ }
124
150
  ]
125
151
  ]);
126
152
  var EXT_BUILDERS = /* @__PURE__ */ new Map([
@@ -168,4 +194,4 @@ export {
168
194
  fromUnknown,
169
195
  serverErrorToEnvelope
170
196
  };
171
- //# sourceMappingURL=chunk-7SABX4DJ.js.map
197
+ //# sourceMappingURL=chunk-IZ3TIL6K.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/contracts/theo-error.ts","../src/core/contracts/server-error-to-envelope.ts"],"mappings":";AAqCO,IAAM,YAAN,cAAwC,MAAM;AAAA,EACjC,OAAO;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAA8B;AACxC,UAAM,KAAK,SAAS,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,MAAS;AAChF,SAAK,OAAO,KAAK;AACjB,SAAK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wB;AAAA,EAChF;AAAA,IACE;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,IACR;AAAA,EACF;AACF,CAAC;AAcM,SAAS,sBAAsB,OAAmC;AACvE,MAAI,iBAAiB,WAAW;AAC9B,WAAO,MAAM;AAAA,EACf;AACA,MAAI,EAAE,iBAAiB,QAAQ;AAC7B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,OAAO,UAAU,WAAW,QAAQ;AAAA,IAC/C;AAAA,EACF;AACA,QAAM,OAAO,MAAM;AACnB,QAAM,OAAO,mBAAmB,IAAI,IAAI,KAAK;AAC7C,QAAM,YAAY,gBAAgB,IAAI,IAAI;AAC1C,QAAM,QAAQ,YAAY,UAAU,KAAK,IAAI;AAC7C,QAAM,OAAgC,EAAE,KAAK;AAC7C,MAAI,OAAO;AACT,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC1C,UAAI,MAAM,OAAW,MAAK,CAAC,IAAI;AAAA,IACjC;AAAA,EACF;AACA,QAAM,aAAa,aAAa,IAAI,IAAI;AACxC,QAAM,MAAM,aAAa,WAAW,KAAK,IAAI;AAC7C,SAAO;AAAA,IACL;AAAA,IACA,SAAS,MAAM;AAAA,IACf,OAAQ,MAAsC;AAAA,IAC9C;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/core/contracts/theo-error.ts","../src/core/contracts/server-error-to-envelope.ts"],"mappings":";AAqCO,IAAM,YAAN,cAAwC,MAAM;AAAA,EACjC,OAAO;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAA8B;AACxC,UAAM,KAAK,SAAS,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,MAAS;AAChF,SAAK,OAAO,KAAK;AACjB,SAAK,OAAO,KAAK;AACjB,SAAK,MAAM,KAAK;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,WAAoC;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524,4 @@ export {
524
524
  writeManifest,
525
525
  loadManifest
526
526
  };
527
- //# sourceMappingURL=chunk-L4Y6RJ4E.js.map
527
+ //# sourceMappingURL=chunk-KSZGBUTI.js.map
@@ -178,15 +178,7 @@ function matchRoute(url, routes) {
178
178
  }
179
179
 
180
180
  // src/core/contracts/http-methods.ts
181
- var HTTP_METHODS = [
182
- "GET",
183
- "POST",
184
- "PUT",
185
- "PATCH",
186
- "DELETE",
187
- "HEAD",
188
- "OPTIONS"
189
- ];
181
+ var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
190
182
  var HTTP_METHOD_LOWERCASE = HTTP_METHODS.map((m) => m.toLowerCase());
191
183
 
192
184
  // src/server/scan/scan.ts
@@ -416,4 +408,4 @@ export {
416
408
  scanServerRoutes,
417
409
  scanWebSocketRoutes
418
410
  };
419
- //# sourceMappingURL=chunk-226KMIGZ.js.map
411
+ //# sourceMappingURL=chunk-MNIQ5F3Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/scan/action-scan.ts","../src/server/scan/match.ts","../src/core/contracts/http-methods.ts","../src/server/scan/scan.ts","../src/server/scan/detect-http-methods.ts","../src/server/scan/errors.ts","../src/server/scan/ws-scan.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: walks `serverDir/actions/` derived from cwd.\n * No HTTP input ever reaches these fs calls.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport { extname, join, relative } from 'node:path'\n\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nexport interface ActionNode {\n filePath: string\n actionPath: string\n}\n\n/**\n * Enriched manifest entry per plan g3-server-actions-and-useaction v1.2\n * § Phase 1 / T1.4 + ADR D4. Consumed by virtual module `@theo/actions`\n * (T3.1) and G4 devtools \"Actions\" tab (T5.1).\n */\nexport interface ActionManifestEntry {\n name: string\n filePath: string\n urlPath: string\n accept: 'form' | 'json'\n hasInput: boolean\n /**\n * P#4 plugin-forms shared-schema convention (per plan p4-plugin-forms v1.1 T1.1).\n * When present, points to an isomorphic schema file at\n * `<serverDir>/actions/schemas/<basename>.ts` exporting `export const schema = z.object(...)`.\n * Virtual module emits `import {schema} from '<schemaFilePath>'` + attaches as\n * `actions.X.__zodSchema` so client-side <TheoForm> can drive zodResolver.\n * Undefined when convention not followed (graceful degrade — TheoForm still\n * works via explicit `schema={...}` prop escape hatch).\n */\n schemaFilePath?: string\n}\n\n/**\n * EC-2: structured error for scan-time defects (name collision, reserved\n * identifier, etc.). Throw at scan time to fail loud — silent shadowing is\n * a security/correctness footgun.\n */\nexport class ActionScanError extends Error {\n readonly code: 'NAME_COLLISION' | 'RESERVED_NAME'\n readonly conflictingPaths: readonly string[]\n\n constructor(\n code: 'NAME_COLLISION' | 'RESERVED_NAME',\n message: string,\n conflictingPaths: readonly string[],\n ) {\n super(message)\n // T4.1 fix: identify class by name so serverErrorToEnvelope boundary\n // translator can route via class-name lookup (without this, runtime\n // `err.name` defaults to 'Error' and the meta.name diagnostic is wrong).\n this.name = 'ActionScanError'\n this.code = code\n this.conflictingPaths = conflictingPaths\n }\n}\n\nconst ACTION_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst TEST_FILE_RE = /\\.(test|spec)\\.(ts|tsx|js|jsx)$/\nconst RESERVED_NAMES = new Set(['index', 'constructor', '__proto__', 'prototype', 'hasOwnProperty'])\n\n/**\n * Backward-compatible: original simple-shape scanner used by existing\n * consumers. Preserved verbatim; new consumers should call\n * `scanServerActionsEnriched`.\n */\nexport function scanServerActions(serverDir: string): ActionNode[] {\n const actionsDir = join(serverDir, 'actions')\n if (!existsSync(actionsDir) || !statSync(actionsDir).isDirectory()) {\n return []\n }\n\n const results: ActionNode[] = []\n walkSourceFiles(actionsDir, { extensions: ACTION_EXTENSIONS }, (absPath) => {\n if (TEST_FILE_RE.test(absPath)) return\n let rel = relative(actionsDir, absPath)\n rel = rel.replace(/\\\\/g, '/')\n rel = rel.slice(0, -extname(rel).length)\n results.push({\n filePath: absPath,\n actionPath: rel,\n })\n })\n return results\n}\n\n/**\n * Enriched scan: light AST detection of `accept: 'form'|'json'` + `input:`\n * presence via regex-after-comment-stripping (EC-9). Throws ActionScanError\n * on file/dir name collision (EC-2) or reserved JS identifier names.\n *\n * Output `ActionManifestEntry[]` is sorted by `name` for deterministic\n * `.theokit/actions-manifest.json` emission.\n */\nexport function scanServerActionsEnriched(serverDir: string): ActionManifestEntry[] {\n const actionsDir = join(serverDir, 'actions')\n if (!existsSync(actionsDir) || !statSync(actionsDir).isDirectory()) {\n return []\n }\n\n const seenNames = new Set<string>()\n const entries: ActionManifestEntry[] = []\n\n // Collect first; collision-check after the full walk.\n walkSourceFiles(actionsDir, { extensions: ACTION_EXTENSIONS }, (absPath) => {\n if (TEST_FILE_RE.test(absPath)) return\n const rel = relative(actionsDir, absPath).replace(/\\\\/g, '/')\n // P#4 plugin-forms — `schemas/` subdir holds isomorphic zod schemas\n // for the shared-schema convention (T1.1). NOT executable actions; skip.\n if (rel.startsWith('schemas/')) return\n const name = rel.slice(0, -extname(rel).length)\n\n const basename = name.includes('/') ? (name.split('/').pop() ?? name) : name\n if (RESERVED_NAMES.has(basename)) {\n throw new ActionScanError(\n 'RESERVED_NAME',\n `Reserved JS identifier \"${basename}\" cannot be an action name (${absPath})`,\n [absPath],\n )\n }\n // File-level collision (one file appearing twice) is impossible via the\n // walker; per-export collision check happens inside the export loop below.\n const source = readFileSync(absPath, 'utf8')\n const stripped = stripComments(source)\n const accept = /\\baccept\\s*:\\s*['\"]form['\"]/.test(stripped) ? 'form' : 'json'\n const hasInput = /\\binput\\s*:\\s*z\\./.test(stripped) || /\\binput\\s*:\\s*\\w+\\(/.test(stripped)\n\n // T7.1 wire fix — extract exports so the urlPath includes the second\n // segment required by action-middleware (`/api/__actions/<file>/<export>`).\n // Each named action export becomes its own manifest entry.\n // Proxy key on the EXPORT name (so consumers write `actions.saveMemory(input)`).\n // URL keeps the runtime 2-segment shape `/api/__actions/<file>/<export>`\n // expected by action-middleware. Cross-file export collisions become a\n // scan error to surface the ambiguity early.\n const exportNames = extractActionExportNames(stripped)\n // P#4 plugin-forms shared-schema convention: check for\n // `<actionsDir>/schemas/<basename>.ts` (or .tsx/.js/.jsx).\n // Skip when actions live in subdirs (`schemas/` is flat by convention).\n const schemaFilePath = name.includes('/') ? undefined : detectSchemaFile(actionsDir, basename)\n for (const exportName of exportNames) {\n const proxyKey = exportName === 'default' ? name : exportName\n if (seenNames.has(proxyKey)) {\n throw new ActionScanError(\n 'NAME_COLLISION',\n `Duplicate action proxy key \"${proxyKey}\" (two files export the same name)`,\n [absPath],\n )\n }\n seenNames.add(proxyKey)\n const entry: ActionManifestEntry = {\n name: proxyKey,\n filePath: absPath,\n urlPath: `/api/__actions/${name}/${exportName}`,\n accept,\n hasInput,\n }\n if (schemaFilePath !== undefined) {\n entry.schemaFilePath = schemaFilePath\n }\n entries.push(entry)\n }\n })\n\n // EC-2: detect file vs dir collisions (e.g., foo.ts AND foo/bar.ts).\n // After walk completes, any name that has children prefixed `name/` triggers collision.\n for (const entry of entries) {\n const childPrefix = `${entry.name}/`\n const conflictingChild = entries.find((other) => other.name.startsWith(childPrefix))\n if (conflictingChild) {\n throw new ActionScanError(\n 'NAME_COLLISION',\n `Action \"${entry.name}\" conflicts with directory of same name containing \"${conflictingChild.name}\"`,\n [entry.filePath, conflictingChild.filePath],\n )\n }\n }\n\n entries.sort((a, b) => {\n if (a.name < b.name) return -1\n if (a.name > b.name) return 1\n return 0\n })\n return entries\n}\n\n/**\n * Strip JavaScript line + block comments from source. Simple state machine\n * (does not parse strings — false positives if a comment marker appears\n * inside a string literal, but that's an acceptable trade-off for v1 vs\n * full AST parse).\n */\n/**\n * Extract action export names via regex over comment-stripped source.\n * Matches `export const <name> = defineAction(...)`, `export default\n * defineAction(...)`, and `export function <name>(...)` forms. Returns\n * `['default']` when no named action exports are found (best-effort fallback\n * for default-export shapes the regex misses).\n */\nfunction extractActionExportNames(stripped: string): string[] {\n const names = new Set<string>()\n const namedRe = /\\bexport\\s+(?:const|let|var|function\\*?)\\s+([a-zA-Z_$][\\w$]*)\\s*[=(]/g\n let m: RegExpExecArray | null\n while ((m = namedRe.exec(stripped)) !== null) {\n const name = m[1]\n if (typeof name === 'string' && name.length > 0) names.add(name)\n }\n if (/\\bexport\\s+default\\s+defineAction\\b/.test(stripped)) {\n names.add('default')\n }\n if (names.size === 0) names.add('default')\n return [...names]\n}\n\n/**\n * P#4 plugin-forms shared-schema convention helper (per plan p4-plugin-forms v1.1 T1.1).\n * Returns the resolved path to `<actionsDir>/schemas/<basename>.<ext>` if it exists.\n * Tries `.ts`, `.tsx`, `.js`, `.jsx` in that order. Returns undefined when no match.\n */\nfunction detectSchemaFile(actionsDir: string, basename: string): string | undefined {\n const schemasDir = join(actionsDir, 'schemas')\n if (!existsSync(schemasDir)) return undefined\n for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {\n const candidate = join(schemasDir, `${basename}${ext}`)\n if (existsSync(candidate)) return candidate\n }\n return undefined\n}\n\nfunction stripComments(source: string): string {\n let out = ''\n let i = 0\n while (i < source.length) {\n const ch = source[i]\n const next = source[i + 1]\n if (ch === '/' && next === '/') {\n // Line comment: skip until newline\n while (i < source.length && source[i] !== '\\n') i++\n continue\n }\n if (ch === '/' && next === '*') {\n // Block comment: skip until */\n i += 2\n while (i < source.length - 1 && !(source[i] === '*' && source[i + 1] === '/')) i++\n i += 2\n continue\n }\n out += ch\n i++\n }\n return out\n}\n","export interface ServerRouteNode {\n filePath: string\n routePath: string\n paramNames: string[]\n pattern: RegExp\n /** HTTP methods (uppercase) the route file exports. Optional for backward\n * compatibility with manifests generated before G1. Empty array means the\n * file has no HTTP exports (util-only); undefined means \"not detected\". */\n methods?: string[]\n}\n\nexport function compilePattern(routePath: string): {\n pattern: RegExp\n paramNames: string[]\n} {\n const paramNames: string[] = []\n // Single pass: handle both catch-all (:...name) and regular (:name) params\n const regexStr = routePath.replace(/:(?:\\.\\.\\.)?([^/]+)/g, (match: string, name: string) => {\n paramNames.push(name)\n // Catch-all matches across slashes, regular matches single segment\n return match.startsWith(':...') ? '(.+)' : '([^/]+)'\n })\n // `regexStr` is derived from a developer-authored route path (build-time\n // input, not HTTP-controlled). The `security/detect-non-literal-regexp`\n // rule cannot see this constraint — disable narrowly.\n // eslint-disable-next-line security/detect-non-literal-regexp -- route pattern from build-time scan, never HTTP input\n return { pattern: new RegExp(`^${regexStr}$`), paramNames }\n}\n\nexport function matchRoute(\n url: string,\n routes: ServerRouteNode[],\n): { route: ServerRouteNode; params: Record<string, string> } | null {\n // Strip query string and trailing slash\n let path = url.split('?')[0]\n if (path.length > 1 && path.endsWith('/')) {\n path = path.slice(0, -1)\n }\n\n for (const route of routes) {\n const match = route.pattern.exec(path)\n if (match) {\n const params: Record<string, string> = {}\n route.paramNames.forEach((name, i) => {\n params[name] = match[i + 1]\n })\n return { route, params }\n }\n }\n return null\n}\n","/**\n * Canonical HTTP method set used by the typed client codegen + Proxy runtime.\n * Kept here (under `server/scan/`) because the SCAN is the first consumer —\n * `vite-plugin/app-typed-client.ts` (Phase 2) and `client/app-client.ts` (Phase 3)\n * import from here to ensure a single source of truth.\n *\n * Lowercase variants are derived via `.toLowerCase()` at call sites; we do not\n * export them separately to avoid drift between the two lists.\n */\n\nexport const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const\n\nexport type HttpMethod = (typeof HTTP_METHODS)[number]\n\nexport const HTTP_METHOD_LOWERCASE = HTTP_METHODS.map((m) => m.toLowerCase()) as readonly string[]\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: walks `serverDir/routes/` derived from cwd.\n * No HTTP input ever reaches these fs calls.\n */\nimport { existsSync, statSync } from 'node:fs'\nimport { basename, extname, join, relative } from 'node:path'\n\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport { detectExportedHttpMethods } from './detect-http-methods.js'\nimport { RouterConventionError } from './errors.js'\nimport { compilePattern, type ServerRouteNode } from './match.js'\n\nconst ROUTE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\n\n// EC-4: Co-located unit/spec tests must be silently skipped by the scanner,\n// BEFORE the dotted-basename check fires. Matches `*.test.ts|tsx|js|jsx`\n// and `*.spec.ts|tsx|js|jsx`.\nconst TEST_OR_SPEC_RE = /\\.(test|spec)\\.[jt]sx?$/\n\nfunction isTestOrSpecFile(filePath: string): boolean {\n return TEST_OR_SPEC_RE.test(basename(filePath))\n}\n\nfunction hasDotOutsideBrackets(segment: string): boolean {\n let depth = 0\n for (const ch of segment) {\n if (ch === '[') depth++\n else if (ch === ']') depth--\n else if (ch === '.' && depth === 0) return true\n }\n return false\n}\n\nfunction splitDottedSegmentOutsideBrackets(segment: string): string[] {\n const parts: string[] = []\n let current = ''\n let depth = 0\n for (const ch of segment) {\n if (ch === '[') {\n depth++\n current += ch\n } else if (ch === ']') {\n depth--\n current += ch\n } else if (ch === '.' && depth === 0) {\n if (current) parts.push(current)\n current = ''\n } else {\n current += ch\n }\n }\n if (current) parts.push(current)\n return parts\n}\n\nfunction buildDirectoryNestedSuggestion(filePath: string, routesDir: string): string {\n const rel = relative(routesDir, filePath).replace(/\\\\/g, '/')\n const ext = extname(rel)\n const withoutExt = rel.slice(0, -ext.length)\n const segments = withoutExt.split('/').flatMap(splitDottedSegmentOutsideBrackets)\n return `routes/${segments.join('/')}${ext}`\n}\n\nfunction assertNoDottedSegment(filePath: string, routesDir: string): void {\n const rel = relative(routesDir, filePath).replace(/\\\\/g, '/')\n const ext = extname(rel)\n const withoutExt = rel.slice(0, -ext.length)\n const segments = withoutExt.split('/')\n for (const seg of segments) {\n if (hasDotOutsideBrackets(seg)) {\n throw new RouterConventionError({\n file: filePath,\n suggestion: buildDirectoryNestedSuggestion(filePath, routesDir),\n })\n }\n }\n}\n\nfunction fileToRoutePath(filePath: string, routesDir: string): string {\n let rel = relative(routesDir, filePath)\n // Strip extension\n const ext = extname(rel)\n rel = rel.slice(0, -ext.length)\n // Normalize separators\n rel = rel.replace(/\\\\/g, '/')\n // Strip index suffix\n if (rel.endsWith('/index')) {\n rel = rel.slice(0, -6)\n } else if (rel === 'index') {\n rel = ''\n }\n // Replace [...param] with :...param (catch-all, before regular params).\n // Replace [param] with :param. Inputs are file paths bounded by the\n // OS filename limit; the bracket capture is bounded by `]`.\n rel = rel.replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, ':...$1')\n // eslint-disable-next-line sonarjs/slow-regex -- bounded by `]`; input is a single filename\n rel = rel.replace(/\\[([^\\]]+)\\]/g, ':$1')\n return `/api/${rel}`\n}\n\nexport function scanServerRoutes(serverDir: string): ServerRouteNode[] {\n const routesDir = join(serverDir, 'routes')\n if (!existsSync(routesDir) || !statSync(routesDir).isDirectory()) {\n return []\n }\n\n const results: ServerRouteNode[] = []\n walkSourceFiles(routesDir, { extensions: ROUTE_EXTENSIONS }, (absPath) => {\n // EC-4: skip co-located test/spec files BEFORE the dotted-basename check\n if (isTestOrSpecFile(absPath)) return\n\n // G6 T1.1: reject dotted basenames (legacy convention that produced wrong\n // paramNames due to greedy `:(?:\\.\\.\\.)?([^/]+)` regex in compilePattern).\n assertNoDottedSegment(absPath, routesDir)\n\n const routePath = fileToRoutePath(absPath, routesDir)\n const { pattern, paramNames } = compilePattern(routePath)\n const methods = detectExportedHttpMethods(absPath)\n results.push({\n filePath: absPath,\n routePath,\n paramNames,\n pattern,\n methods,\n })\n })\n\n // T1.4 / EC-2 — refuse to scan if a user route collides with the reserved\n // batch endpoint path. User must rename or disable batching.\n const conflicting = results.find((r) => r.routePath === '/api/__theo_batch__')\n if (conflicting) {\n throw new Error(\n `Server route ${conflicting.filePath} resolves to '/api/__theo_batch__' which is reserved for the batch endpoint. Rename the route or disable batching in theo.config.ts.`,\n )\n }\n\n // Sort: static first, then dynamic, then catch-all last\n const isCatchAll = (route: ServerRouteNode) => route.routePath.includes(':...')\n results.sort((a, b) => {\n const aStatic = a.paramNames.length === 0\n const bStatic = b.paramNames.length === 0\n const aCatchAll = isCatchAll(a)\n const bCatchAll = isCatchAll(b)\n\n // Static routes first\n if (aStatic && !bStatic) return -1\n if (!aStatic && bStatic) return 1\n // Catch-all routes last\n if (aCatchAll && !bCatchAll) return 1\n if (!aCatchAll && bCatchAll) return -1\n return a.routePath.localeCompare(b.routePath)\n })\n\n return results\n}\n","/**\n * Detect which HTTP-method named exports a route file declares.\n *\n * Uses the TypeScript compiler API (not regex) per G1 edge-case review EC-4:\n * regex over file content emits false positives for `// export const GET = ...`\n * in comments and `` `export const GET = ...` `` in template literals. AST\n * walking avoids both classes of bug.\n *\n * `typescript` ships as CommonJS with internal dynamic `require('fs')`.\n * When loaded via ESM `import`, the dynamic requires fail at module-bootstrap.\n * We use `createRequire(import.meta.url)` to keep the package on its native\n * CJS path. The type-only namespace import gives us the AST helpers shape.\n *\n * Returns the set of HTTP methods (uppercase) the file exports. Empty array\n * means the file has no HTTP exports (the route file is util-only).\n */\n\nimport { readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\n\nimport type * as TS from 'typescript'\n\nimport { HTTP_METHODS, type HttpMethod } from '../../core/contracts/http-methods.js'\n\nconst require_ = createRequire(import.meta.url)\n\nconst ts = require_('typescript') as typeof TS\n\nconst HTTP_METHOD_NAMES = new Set<string>(HTTP_METHODS)\n\nfunction hasExportModifier(modifiers: readonly TS.Modifier[] | undefined): boolean {\n if (!modifiers) return false\n for (const m of modifiers) {\n if (m.kind === ts.SyntaxKind.ExportKeyword) return true\n }\n return false\n}\n\n// An AST visitor over the export forms (const / function / named export) is inherently branchy;\n// the complexity is in the grammar it walks, not in tangled logic. Splitting it would scatter one\n// cohesive dispatch across helpers for no readability gain.\n// eslint-disable-next-line complexity -- AST visitor, see above\nfunction collectFromStatement(stmt: TS.Statement, found: Set<HttpMethod>): void {\n // `export const GET = ...` / `export function GET ...` / `export async function GET ...`\n if (ts.isVariableStatement(stmt) && hasExportModifier(ts.getModifiers(stmt))) {\n for (const decl of stmt.declarationList.declarations) {\n if (ts.isIdentifier(decl.name) && HTTP_METHOD_NAMES.has(decl.name.text)) {\n found.add(decl.name.text as HttpMethod)\n }\n }\n return\n }\n\n if (\n (ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt)) &&\n hasExportModifier(ts.getModifiers(stmt))\n ) {\n if (stmt.name && HTTP_METHOD_NAMES.has(stmt.name.text)) {\n found.add(stmt.name.text as HttpMethod)\n }\n return\n }\n\n // `export { GET }` / `export { handler as GET } from './shared'` (EC-5)\n if (ts.isExportDeclaration(stmt) && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {\n for (const spec of stmt.exportClause.elements) {\n // spec.name is the exported (re-)name; spec.propertyName is the original (when renamed)\n if (HTTP_METHOD_NAMES.has(spec.name.text)) {\n found.add(spec.name.text as HttpMethod)\n }\n }\n }\n}\n\nexport function detectExportedHttpMethods(filePath: string, content?: string): HttpMethod[] {\n // `filePath` is a route module the framework itself discovered by globbing the project — never\n // user input at runtime. Reading it by a computed path is the whole job of a source scanner.\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- framework-controlled path\n const src = content ?? readFileSync(filePath, 'utf-8')\n const sourceFile = ts.createSourceFile(\n filePath,\n src,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ false,\n ts.ScriptKind.TS,\n )\n const found = new Set<HttpMethod>()\n for (const stmt of sourceFile.statements) {\n collectFromStatement(stmt, found)\n }\n return [...found].sort((a, b) => a.localeCompare(b))\n}\n","/**\n * Router-convention errors thrown by the server-route scanner.\n *\n * Plan: .claude/knowledge-base/plans/g6-router-convention-plan.md v1.1\n *\n * theokit 0.4.0+ enforces directory-nested file-system routing\n * (`auth/[provider]/login.ts`) and REJECTS dotted-basename routes\n * (`auth.[provider].login.ts`) because the legacy regex extracted the\n * dotted basename incorrectly — `params.provider` was undefined at request\n * time. Decision recorded in the plan above (`g6-router-convention-plan.md`) and CHANGELOG 0.4.0\n * (no standalone ADR was cut for this router-convention change).\n */\n\n/**\n * Canonical migration guide URL. T4.2 establishes this as the authoritative\n * landing page. EC-3: error message uses this constant so the URL never\n * drifts from the doc location.\n */\nexport const ROUTER_MIGRATION_GUIDE_URL = 'https://theokit.dev/migration/0.3-to-0.4-router'\n\ninterface RouterConventionErrorOptions {\n /** Absolute path of the offending route file. */\n file: string\n /** Suggested directory-nested replacement path (relative, e.g. `routes/auth/[provider]/login.ts`). */\n suggestion: string\n /** Migration guide URL (defaults to `ROUTER_MIGRATION_GUIDE_URL`). */\n migrationUrl?: string\n}\n\n/**\n * Thrown by `scanServerRoutes` when a route file uses the legacy\n * dotted-basename convention (`auth.[provider].login.ts`).\n *\n * The error is FAIL-FAST by design — running with a route that has wrong\n * `paramNames` produces silent 404s at request time, which is strictly\n * worse than a build-time error.\n */\nexport class RouterConventionError extends Error {\n override readonly name = 'RouterConventionError'\n readonly file: string\n readonly suggestion: string\n readonly migrationUrl: string\n\n constructor(opts: RouterConventionErrorOptions) {\n const migrationUrl = opts.migrationUrl ?? ROUTER_MIGRATION_GUIDE_URL\n const message = [\n `Router convention violation: dotted route basename is not supported in theokit 0.4+.`,\n ``,\n ` File: ${opts.file}`,\n ` Use directory-nested form: ${opts.suggestion}`,\n ``,\n `Migration guide: ${migrationUrl}`,\n `Run \\`theokit migrate router\\` to convert all dotted basenames automatically.`,\n ].join('\\n')\n super(message)\n this.file = opts.file\n this.suggestion = opts.suggestion\n this.migrationUrl = migrationUrl\n }\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: walks `serverDir/ws/` derived from cwd.\n * No HTTP input ever reaches these fs calls.\n */\nimport { existsSync, statSync } from 'node:fs'\nimport { extname, join, relative } from 'node:path'\n\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nconst WS_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\n\nexport interface WebSocketRouteNode {\n filePath: string\n wsPath: string\n}\n\nexport function scanWebSocketRoutes(serverDir: string): WebSocketRouteNode[] {\n const wsDir = join(serverDir, 'ws')\n if (!existsSync(wsDir) || !statSync(wsDir).isDirectory()) {\n return []\n }\n\n const results: WebSocketRouteNode[] = []\n walkSourceFiles(wsDir, { extensions: WS_EXTENSIONS }, (absPath) => {\n let rel = relative(wsDir, absPath)\n rel = rel.replace(/\\\\/g, '/')\n rel = rel.slice(0, -extname(rel).length)\n if (rel.endsWith('/index')) rel = rel.slice(0, -6)\n else if (rel === 'index') rel = ''\n results.push({\n filePath: absPath,\n wsPath: `/ws/${rel}`,\n })\n })\n return results\n}\n"],"mappings":";;;;;;;AAIA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,SAAS,MAAM,gBAAgB;AAqCjC,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YACE,MACA,SACA,kBACA;AACA,UAAM,OAAO;AAIb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,mBAAmB;AAAA,EAC1B;AACF;AAEA,IAAM,oBAAoB,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAChE,IAAM,eAAe;AACrB,IAAM,iBAAiB,oBAAI,IAAI,CAAC,SAAS,eAAe,aAAa,aAAa,gBAAgB,CAAC;AAO5F,SAAS,kBAAkB,WAAiC;AACjE,QAAM,aAAa,KAAK,WAAW,SAAS;AAC5C,MAAI,CAAC,WAAW,UAAU,KAAK,CAAC,SAAS,UAAU,EAAE,YAAY,GAAG;AAClE,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,UAAwB,CAAC;AAC/B,kBAAgB,YAAY,EAAE,YAAY,kBAAkB,GAAG,CAAC,YAAY;AAC1E,QAAI,aAAa,KAAK,OAAO,EAAG;AAChC,QAAI,MAAM,SAAS,YAAY,OAAO;AACtC,UAAM,IAAI,QAAQ,OAAO,GAAG;AAC5B,UAAM,IAAI,MAAM,GAAG,CAAC,QAAQ,GAAG,EAAE,MAAM;AACvC,YAAQ,KAAK;AAAA,MACX,UA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GAAG,EAAE;AAAA,aACxC,QAAQ,QAAS,OAAM;AAChC,YAAQ,KAAK;AAAA,MACX,UAAU;AAAA,MACV,QAAQ,OAAO,GAAG;AAAA,IACpB,CAAC;AAAA,EACH,CAAC;AACD,SAAO;AACT;","names":["basename","existsSync","statSync","extname","join","relative","readFileSync","readFileSync","relative","extname","join","existsSync","statSync","existsSync","statSync","extname","join","relative","join","existsSync","statSync","relative","extname"]}
@@ -39,13 +39,13 @@ var SpanImpl = class {
39
39
  }
40
40
  };
41
41
  var NoopSpan = class {
42
- // eslint-disable-next-line @typescript-eslint/no-empty-function -- Null Object, ver acima
42
+ // eslint-disable-next-line @typescript-eslint/no-empty-function -- Null Object, see above
43
43
  setAttribute() {
44
44
  }
45
- // eslint-disable-next-line @typescript-eslint/no-empty-function -- Null Object, ver acima
45
+ // eslint-disable-next-line @typescript-eslint/no-empty-function -- Null Object, see above
46
46
  setStatus() {
47
47
  }
48
- // eslint-disable-next-line @typescript-eslint/no-empty-function -- Null Object, ver acima
48
+ // eslint-disable-next-line @typescript-eslint/no-empty-function -- Null Object, see above
49
49
  end() {
50
50
  }
51
51
  };
@@ -350,4 +350,4 @@ export {
350
350
  createObservabilityPlugin,
351
351
  defineObservabilityAdapter
352
352
  };
353
- //# sourceMappingURL=chunk-KBGGQK4I.js.map
353
+ //# sourceMappingURL=chunk-O3JIAU3V.js.map
@@ -2,11 +2,11 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  loadEnv
5
- } from "./chunk-GDN3PXFH.js";
5
+ } from "./chunk-HBU2GIMZ.js";
6
6
  import {
7
7
  getApprovalRegistry,
8
8
  resolveProvider
9
- } from "./chunk-TDNNBLGW.js";
9
+ } from "./chunk-6GGWS7J3.js";
10
10
  import {
11
11
  scanAgents
12
12
  } from "./chunk-LNVMHQ2Z.js";
@@ -19,6 +19,7 @@ import {
19
19
 
20
20
  // src/server/agent/render-terminal.ts
21
21
  import { createInterface } from "readline";
22
+ import { TerminalPresenter, fromWireChunk } from "@theokit/presenter";
22
23
  var ANSI = {
23
24
  dim: "\x1B[2m",
24
25
  red: "\x1B[31m",
@@ -29,37 +30,22 @@ var ANSI = {
29
30
  function paint(text, color, tty) {
30
31
  return tty ? `${ANSI[color]}${text}${ANSI.reset}` : text;
31
32
  }
32
- function display(value) {
33
- return typeof value === "string" ? value : JSON.stringify(value ?? {});
34
- }
35
- function renderChunkLine(chunk, tty) {
36
- switch (chunk.type) {
37
- case "text-delta":
38
- return chunk.delta;
39
- case "text-end":
40
- case "finish":
41
- return "\n";
42
- case "reasoning-delta":
43
- return paint(chunk.delta, "dim", tty);
44
- case "reasoning-end":
45
- return "\n";
46
- case "tool-input-available":
47
- return paint(`
48
- \u25B8 ${chunk.toolName}(${display(chunk.input)})
49
- `, "cyan", tty);
50
- case "tool-output-available":
51
- return paint(` \u2713 ${display(chunk.output)}
52
- `, "green", tty);
53
- case "tool-output-error":
54
- return paint(` \u2717 ${chunk.errorText}
55
- `, "red", tty);
56
- case "error":
57
- return paint(`
58
- \u2717 ${chunk.errorText}
59
- `, "red", tty);
60
- default:
61
- return chunk.type === "data-checkpoint" ? paint("\n\u2387 checkpoint saved \u2014 resume with the same session id\n", "dim", tty) : "";
62
- }
33
+ var ROW_COLOR = {
34
+ text: void 0,
35
+ reasoning: "dim",
36
+ tool: "cyan",
37
+ "tool-result": "green",
38
+ "tool-error": "red",
39
+ error: "red",
40
+ status: "dim",
41
+ finish: "dim"
42
+ };
43
+ function paintRow(row, tty) {
44
+ const color = ROW_COLOR[row.kind];
45
+ const body = color === void 0 ? row.text : paint(row.text, color, tty);
46
+ return row.kind === "text" ? body : `
47
+ ${body}
48
+ `;
63
49
  }
64
50
  async function renderAgentStreamToTerminal(chunks, opts) {
65
51
  const tty = opts.stdout.isTTY;
@@ -67,6 +53,7 @@ async function renderAgentStreamToTerminal(chunks, opts) {
67
53
  if (s) opts.stdout.write(s);
68
54
  };
69
55
  const toolNames = /* @__PURE__ */ new Map();
56
+ const presenter = new TerminalPresenter({ maxPreview: 88 });
70
57
  let sawError = false;
71
58
  for await (const chunk of chunks) {
72
59
  if (chunk.type === "tool-approval-request") {
@@ -78,7 +65,13 @@ async function renderAgentStreamToTerminal(chunks, opts) {
78
65
  toolNames.set(chunk.toolCallId, chunk.toolName);
79
66
  }
80
67
  if (chunk.type === "error") sawError = true;
81
- write(renderChunkLine(chunk, tty));
68
+ if (chunk.type === "data-checkpoint") {
69
+ write(paint("\n\u2387 checkpoint saved \u2014 resume with the same session id\n", "dim", tty));
70
+ continue;
71
+ }
72
+ for (const event of fromWireChunk(chunk, toolNames)) {
73
+ for (const row of presenter.present(event)) write(paintRow(row, tty));
74
+ }
82
75
  }
83
76
  return { sawError };
84
77
  }
@@ -145,17 +138,24 @@ async function runAgentInTerminal(mod, apiKey, input) {
145
138
 
146
139
  // src/cli/commands/agent.ts
147
140
  async function agentCommand(name, message, deps = {}) {
148
- if (!message || message.trim().length === 0) {
149
- throw new Error('theokit agent: a message is required. Usage: theokit agent <name> "<message>"');
141
+ const interactive = message === void 0 || message.trim().length === 0;
142
+ if (interactive && deps.startInteractive === void 0) {
143
+ throw new Error(
144
+ 'theokit agent: no message given and no interactive surface is wired. Pass a message (`theokit agent <name> "<message>"`), or supply `startInteractive` to run a session.'
145
+ );
150
146
  }
151
147
  const projectRoot = deps.projectRoot ?? process.cwd();
152
- const agentsDir = deps.agentsDir ?? (await (await import("./load-config-ICCNMO74.js")).loadConfig(projectRoot)).agentsDir;
148
+ const agentsDir = deps.agentsDir ?? (await (await import("./load-config-JKJ73TOD.js")).loadConfig(projectRoot)).agentsDir;
153
149
  const agents = scanAgents(projectRoot, agentsDir);
154
150
  const agent = agents.find((a) => a.name === name);
155
151
  if (!agent) {
156
152
  const names = agents.map((a) => a.name).join(", ") || `(none found in ${agentsDir}/)`;
157
153
  throw new Error(`theokit agent: '${name}' not found. Available agents: ${names}`);
158
154
  }
155
+ if (interactive) {
156
+ const startInteractive = deps.startInteractive;
157
+ return await startInteractive(agent.name);
158
+ }
159
159
  const runAgent = deps.runAgent ?? runAgentInTerminal;
160
160
  const apiKey = deps.resolveApiKey?.() ?? (() => {
161
161
  loadEnv({ cwd: projectRoot, mode: "development" });
@@ -178,8 +178,8 @@ async function agentCommand(name, message, deps = {}) {
178
178
  async function createAgentSsrLoader(projectRoot) {
179
179
  const { createServer } = await import("vite");
180
180
  const react = (await import("@vitejs/plugin-react")).default;
181
- const { theoPluginAsync } = await import("./vite-plugin-K64KQZSU.js");
182
- const { loadConfig } = await import("./load-config-ICCNMO74.js");
181
+ const { theoPluginAsync } = await import("./vite-plugin-NQ6F7FGV.js");
182
+ const { loadConfig } = await import("./load-config-JKJ73TOD.js");
183
183
  const config = await loadConfig(projectRoot);
184
184
  const theoPlugins = await theoPluginAsync({
185
185
  root: projectRoot,
@@ -212,4 +212,4 @@ export {
212
212
  agentCommand,
213
213
  createAgentSsrLoader
214
214
  };
215
- //# sourceMappingURL=chunk-UYMCKHML.js.map
215
+ //# sourceMappingURL=chunk-O5W7XSUX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/agent/run-terminal-agent.ts","../src/server/agent/render-terminal.ts","../src/cli/commands/agent.ts"],"sourcesContent":["/**\n * M5 (theokit-ai-first) — run a compiled agent in the terminal, reusing the M4 harness.\n *\n * The web `mountAgent` renders `streamAgentUIMessages` to an HTTP `Response` and resolves HITL\n * approvals via the approve route. This is its terminal sibling: SAME `compileAgentModule` + SAME\n * `streamAgentUIMessages` + SAME in-process approval registry — only the render surface (stdout) and\n * the approval input (a readline prompt) differ (ADR 0039 D2). In a single-process CLI the stream's\n * `awaitApproval` (→ `registry.register`) and the terminal prompt (→ `registry.resolve`) share the one\n * in-process registry — the M4 singleton's exact fit. No new runtime, no LLM call, no tool dispatch.\n */\nimport {\n compileAgentModule,\n streamAgentUIMessages,\n type HumanInTheLoopOptions,\n} from '@theokit/agents'\n\nimport { getApprovalRegistry, type ApprovalRegistry } from './approval-registry.js'\nimport {\n promptTerminalApproval,\n renderAgentStreamToTerminal,\n type TerminalOut,\n} from './render-terminal.js'\n\ninterface RunTerminalAgentInput {\n message: string\n /** Resume key; a fresh id per run when omitted. */\n sessionId?: string\n /** Injectable sink (defaults to `process.stdout` at the CLI entry). */\n stdout?: TerminalOut\n /** Injectable shared registry (defaults to the process singleton). */\n registry?: ApprovalRegistry\n /** Injectable approval prompt (defaults to the readline prompt over the process streams). */\n promptApproval?: (req: { toolName: string; timeoutMs?: number }) => Promise<boolean>\n /** Labels a fail-fast `AgentDefinitionError` (the file path). */\n source?: string\n}\n\n/**\n * Compile the module (M4, gathers `@Mixin` toolboxes), stream it, and render to the terminal. When the\n * agent has `@HumanInTheLoop`-gated tools, the terminal prompts and resolves the shared registry —\n * approve runs the tool, deny/timeout/non-TTY denies and the run continues.\n */\nexport async function runAgentInTerminal(\n mod: unknown,\n apiKey: string,\n input: RunTerminalAgentInput,\n): Promise<{ sawError: boolean }> {\n const compiled = compileAgentModule(mod, input.source)\n const stdout = input.stdout ?? process.stdout\n const registry = input.registry ?? getApprovalRegistry()\n const sessionId = input.sessionId ?? crypto.randomUUID()\n const promptApproval =\n input.promptApproval ??\n ((req: { toolName: string; timeoutMs?: number }) =>\n promptTerminalApproval(req, { input: process.stdin, output: process.stdout }, req.timeoutMs))\n\n // Mirror mount-agent's HITL wiring; absent ⇒ the non-HITL stream path (M2), unchanged.\n const gated = compiled.hitl\n const hitl =\n gated && gated.size > 0\n ? {\n gated,\n awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions) =>\n registry.register(approvalId, {\n timeoutMs: opts.timeout ?? 300_000,\n onTimeout: opts.onTimeout ?? 'abort',\n }),\n }\n : undefined\n\n const chunks = streamAgentUIMessages(compiled, apiKey, {\n message: input.message,\n sessionId,\n hitl,\n })\n return renderAgentStreamToTerminal(chunks, {\n stdout,\n onApproval: async ({ approvalId, toolName }) => {\n // The renderer paused here (the SDK run is paused in its awaited pre_tool_call hook); prompt,\n // then resolve the SAME registry the stream registered into — the run resumes with the decision.\n // The prompt shares the gated tool's timeout so it can never outlive the registry-settled run.\n const timeoutMs = gated?.get(toolName)?.timeout ?? 300_000\n const approved = await promptApproval({ toolName, timeoutMs })\n registry.resolve(approvalId, approved)\n },\n })\n}\n","/**\n * M5 (theokit-ai-first) — the terminal render surface for the M4 agent harness.\n *\n * Consumes the M4 `UIMessageChunk` stream (`streamAgentUIMessages`) and writes it to the terminal:\n * streaming text, a dim reasoning line, tool call / result rows, a checkpoint notice, errors.\n *\n * ## M70 — this file used to be the evidence of the gap it now closes\n *\n * It switched on wire chunks BY HAND and never touched `TerminalPresenter`, even though that\n * presenter exists for exactly this. Not a consumer's idiosyncrasy — a structural one: the\n * presenter's only source translators consumed raw SDK messages, and this surface receives\n * `WireChunk`, already translated. There was no door between them, so our own terminal renderer\n * re-implemented the mapping and the shared presenter had no production consumer at all.\n *\n * The pipeline is now `WireChunk → fromWireChunk → TerminalPresenter`. The presenter returns DATA\n * (`TerminalRow[]`) carrying a semantic `kind`, and this file decides the styling — which is the\n * split the presenter was designed for (format there, render here).\n * On a HITL `tool-approval-request` it delegates to the injected `onApproval` (the entry wires that to\n * a readline prompt + the approval registry). This is the ONLY new code M5 adds — no runtime, no LLM\n * call, no tool dispatch (ADR 0039 D2). I/O is INJECTED (`stdout`, prompt streams) so the whole\n * surface is deterministically testable without a TTY (ADR 0039 D4 / ADR-M5a).\n */\nimport { createInterface } from 'node:readline'\nimport type { Readable, Writable } from 'node:stream'\n\nimport { TerminalPresenter, fromWireChunk } from '@theokit/presenter'\nimport type { TerminalRow } from '@theokit/presenter'\nimport type { WireChunk as UIMessageChunk } from '@theokit/presenter/wire'\n\n/** ANSI helpers — applied only on a TTY so a captured (non-TTY) sink stays plain-text for tests. */\nconst ANSI = {\n dim: '\\x1b[2m',\n red: '\\x1b[31m',\n cyan: '\\x1b[36m',\n green: '\\x1b[32m',\n reset: '\\x1b[0m',\n}\nfunction paint(text: string, color: keyof typeof ANSI, tty: boolean | undefined): string {\n return tty ? `${ANSI[color]}${text}${ANSI.reset}` : text\n}\n\n/** A stdout-like sink; `isTTY` gates color (Node's `process.stdout` carries it, a test sink does not). */\nexport type TerminalOut = Writable & { isTTY?: boolean }\n\ninterface TerminalRenderOptions {\n stdout: TerminalOut\n /** Resolve a HITL approval (the entry prompts + resolves the registry). */\n onApproval: (req: { approvalId: string; toolName: string }) => Promise<void>\n}\n\n/** Semantic row kind → the ANSI colour this surface paints it with. */\nconst ROW_COLOR: Record<TerminalRow['kind'], keyof typeof ANSI | undefined> = {\n text: undefined,\n reasoning: 'dim',\n tool: 'cyan',\n 'tool-result': 'green',\n 'tool-error': 'red',\n error: 'red',\n status: 'dim',\n finish: 'dim',\n}\n\n/**\n * Paint one presented row for this terminal.\n *\n * The presenter decided WHAT the line says and what kind it is; this decides how it looks here. A\n * `text` row is written raw so streaming deltas concatenate into a paragraph — every other kind is\n * a discrete line and gets its own newline.\n */\nfunction paintRow(row: TerminalRow, tty: boolean | undefined): string {\n const color = ROW_COLOR[row.kind]\n const body = color === undefined ? row.text : paint(row.text, color, tty)\n return row.kind === 'text' ? body : `\\n${body}\\n`\n}\n\n/**\n * Render the `UIMessageChunk` stream to `stdout`. Sequential: one chunk → its line(s). The SDK run is\n * already paused inside the awaited `pre_tool_call` hook when a `tool-approval-request` arrives, so a\n * blocking `await onApproval(...)` here is correct — no frame buffer, no concurrency. Returns whether\n * an `error` chunk was seen so the caller can signal a non-zero exit (fail-loud, not silent exit 0).\n */\nexport async function renderAgentStreamToTerminal(\n chunks: AsyncIterable<UIMessageChunk>,\n opts: TerminalRenderOptions,\n): Promise<{ sawError: boolean }> {\n const tty = opts.stdout.isTTY\n const write = (s: string): void => {\n if (s) opts.stdout.write(s)\n }\n // toolCallId → toolName. Needed twice, for the same reason: the wire drops the name after the\n // call. The approval prompt's chunk carries only ids, and `tool-output-available` carries only\n // `toolCallId` — which is why `fromWireChunk` takes this map rather than inventing a name.\n const toolNames = new Map<string, string>()\n const presenter = new TerminalPresenter({ maxPreview: 88 })\n let sawError = false\n\n for await (const chunk of chunks) {\n if (chunk.type === 'tool-approval-request') {\n const toolName = toolNames.get(chunk.toolCallId)\n await opts.onApproval({ approvalId: chunk.approvalId, toolName: toolName ?? 'tool' })\n continue\n }\n if (chunk.type === 'tool-input-available' && chunk.toolCallId) {\n toolNames.set(chunk.toolCallId, chunk.toolName)\n }\n if (chunk.type === 'error') sawError = true\n\n // The checkpoint notice stays here, deliberately. It is a FRAMEWORK signal carried as a\n // `data-*` part, not agent output, so it never enters the canonical event — the same line the\n // forward mapping drew for HITL. Routing it through the presenter would mean widening the\n // canonical event to carry framework concerns.\n if (chunk.type === 'data-checkpoint') {\n write(paint('\\n\\u2387 checkpoint saved — resume with the same session id\\n', 'dim', tty))\n continue\n }\n\n for (const event of fromWireChunk(chunk, toolNames)) {\n for (const row of presenter.present(event)) write(paintRow(row, tty))\n }\n }\n return { sawError }\n}\n\n/** Injectable I/O for the approval prompt (defaults to the process streams at the CLI entry). */\ninterface PromptIO {\n input: Readable & { isTTY?: boolean }\n output: Writable & { isTTY?: boolean }\n}\n\n/**\n * Prompt `Approve <tool>? (y/N)` and resolve to the decision. A non-interactive environment (piped /\n * CI — either stream is not a TTY) AUTO-DENIES without prompting (ADR-M5b fail-safe: a decision that\n * cannot be obtained is a deny, never an auto-approve; mirrors HITL `onTimeout: 'abort'`).\n *\n * `timeoutMs` (the gated tool's `@HumanInTheLoop` timeout) auto-denies + closes the prompt when the\n * human walks away — WITHOUT it the readline question would outlive the SDK run (the registry settles\n * the run at its own timeout but readline has no timer), hanging the CLI on a now-irrelevant prompt.\n */\nexport function promptTerminalApproval(\n req: { toolName: string },\n io: PromptIO,\n timeoutMs?: number,\n): Promise<boolean> {\n if (!io.input.isTTY || !io.output.isTTY) {\n io.output.write(`\\n⚠ Non-interactive terminal — auto-denying approval for '${req.toolName}'.\\n`)\n return Promise.resolve(false)\n }\n return new Promise<boolean>((resolve) => {\n const rl = createInterface({ input: io.input, output: io.output })\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (approved: boolean): void => {\n if (timer) clearTimeout(timer)\n rl.close()\n resolve(approved)\n }\n if (timeoutMs !== undefined && timeoutMs > 0) {\n timer = setTimeout(() => {\n io.output.write(`\\n⚠ Approval timed out — denying '${req.toolName}'.\\n`)\n settle(false)\n }, timeoutMs)\n }\n rl.question(`\\n❔ Approve ${req.toolName}? (y/N) `, (answer) => {\n const a = answer.trim().toLowerCase()\n settle(a === 'y' || a === 'yes')\n })\n })\n}\n","/**\n * M5 (theokit-ai-first) — `theokit agent <name> [message]`: run a scanned agent in the terminal.\n *\n * Scans the top-level `agents/` directory (M2), loads the matched `agents/<name>.ts` through the\n * framework's OWN Vite pipeline (the SAME transpile `theokit dev` uses — legacy `@Agent`/`@Tool`\n * decorators need it; Node's native loader can't transpile TS), resolves the provider apiKey, and\n * runs it in the terminal via the M4 harness (`runAgentInTerminal`). A dev-time surface (ADR 0039 D1),\n * not a CLI product. `deps` is injectable so the fail-fast branches are tested without Vite/an LLM.\n */\nimport { loadEnv } from '../../config/load-env.js'\nimport { resolveProvider } from '../../server/agent/provider-resolver.js'\nimport { runAgentInTerminal } from '../../server/agent/run-terminal-agent.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\n\ninterface AgentCommandDeps {\n projectRoot?: string\n /** Load a TS agent module; defaults to a fresh minimal Vite SSR server (framework transpile). */\n loadModule?: (filePath: string) => Promise<Record<string, unknown>>\n runAgent?: typeof runAgentInTerminal\n resolveApiKey?: () => string\n /** Agents dir name (config `agentsDir`); defaults to the loaded config's value (\"agents\"). Tests inject it. */\n agentsDir?: string\n /**\n * M83 — the interactive surface, when one is wired.\n *\n * Injected rather than imported: the terminal app lives in `@theokit/tui`, and importing it here\n * would make every `theokit` install carry an Ink runtime for a command most users pass a message\n * to. Absent ⇒ a message is still required, and the error now says why rather than reciting usage.\n */\n startInteractive?: (agentName: string) => Promise<{ sawError: boolean }>\n}\n\nexport async function agentCommand(\n name: string,\n message: string | undefined,\n deps: AgentCommandDeps = {},\n): Promise<{ sawError: boolean }> {\n // M83 — an absent message means INTERACTIVE, not an error.\n //\n // Refusing here is what left the command-routing primitive without a production consumer in this\n // repo: a router exists to route what a user types over a session, and a command that takes one\n // message and exits never types twice. The refusal also made the first thing a new user runs —\n // `theokit agent chat` — fail with usage text, which reads as \"this is broken\", not as \"pass an\n // argument\".\n //\n // The interactive loop itself is the surface's job (`@theokit/tui`); what changes here is that the\n // CLI stops refusing, and reports which mode it entered so the caller is never guessing.\n const interactive = message === undefined || message.trim().length === 0\n if (interactive && deps.startInteractive === undefined) {\n throw new Error(\n 'theokit agent: no message given and no interactive surface is wired. Pass a message ' +\n '(`theokit agent <name> \"<message>\"`), or supply `startInteractive` to run a session.',\n )\n }\n const projectRoot = deps.projectRoot ?? process.cwd()\n // #95 follow-up — resolve the agents dir from config (default \"agents\") so `agentsDir: \"core/agents\"`\n // is honored in the terminal, same as dev. Tests inject `agentsDir` to skip the config load.\n const agentsDir =\n deps.agentsDir ??\n (await (await import('../../config/load-config.js')).loadConfig(projectRoot)).agentsDir\n const agents = scanAgents(projectRoot, agentsDir)\n const agent = agents.find((a) => a.name === name)\n if (!agent) {\n const names = agents.map((a) => a.name).join(', ') || `(none found in ${agentsDir}/)`\n throw new Error(`theokit agent: '${name}' not found. Available agents: ${names}`)\n }\n\n // M83 — hand off to the interactive surface once the agent NAME is resolved, and not before: a\n // typo'd name must fail the same way in both modes, with the list of what exists.\n if (interactive) {\n // Non-null by construction: the guard at the top of this function refuses interactive mode when\n // no surface is wired, so reaching here means one was.\n const startInteractive = deps.startInteractive as (n: string) => Promise<{ sawError: boolean }>\n return await startInteractive(agent.name)\n }\n\n const runAgent = deps.runAgent ?? runAgentInTerminal\n // Load .env into process.env BEFORE resolving the provider key — parity with `theokit dev`\n // (dev.ts loadEnv), so an app with OPENROUTER_API_KEY in .env works here too (review H1). Skipped\n // when the key is injected (tests) — a temp project has no .env anyway.\n const apiKey =\n deps.resolveApiKey?.() ??\n (() => {\n loadEnv({ cwd: projectRoot, mode: 'development' })\n return resolveProvider().apiKey\n })()\n\n let loadModule = deps.loadModule\n let dispose: (() => Promise<void>) | undefined\n if (!loadModule) {\n const loader = await createAgentSsrLoader(projectRoot)\n loadModule = loader.load\n dispose = loader.dispose\n }\n\n try {\n const mod = await loadModule(agent.filePath)\n return await runAgent(mod, apiKey, { message, source: agent.filePath })\n } finally {\n if (dispose) await dispose()\n }\n}\n\n/**\n * A minimal middleware-mode Vite server built from the SAME `theoPluginAsync` plugin set `theokit dev`\n * uses (`cli/commands/dev.ts`) — so a class-decorated `agents/<name>.ts` transpiles identically. No\n * HTTP listen, no service orchestration, silent — just `ssrLoadModule`. Caller MUST `dispose()`.\n */\nexport async function createAgentSsrLoader(projectRoot: string): Promise<{\n load: (p: string) => Promise<Record<string, unknown>>\n dispose: () => Promise<void>\n}> {\n const { createServer } = await import('vite')\n const react = (await import('@vitejs/plugin-react')).default\n const { theoPluginAsync } = await import('../../vite-plugin/index.js')\n const { loadConfig } = await import('../../config/load-config.js')\n // Pass the project's ssr/services/optimizeDeps config through, exactly as dev.ts does — so an app\n // that customizes ssr.noExternal transpiles here identically to `theokit dev` (review L1).\n const config = await loadConfig(projectRoot)\n const theoPlugins = await theoPluginAsync({\n root: projectRoot,\n ssr: config.ssr,\n services: config.services,\n viteOptimizeDeps: config.viteOptimizeDeps,\n // #95 — honor config `serverDir` so the terminal SSR loader transpiles under the same root as dev.\n serverDir: config.serverDir,\n // #95 follow-up — honor config `agentsDir`.\n agentsDir: config.agentsDir,\n })\n const server = await createServer({\n root: projectRoot,\n plugins: [react(), ...theoPlugins],\n server: { middlewareMode: true },\n appType: 'custom',\n logLevel: 'silent',\n })\n return {\n load: (p) => server.ssrLoadModule(p) as Promise<Record<string, unknown>>,\n dispose: async () => {\n // Surface a cleanup failure instead of swallowing it (error-handling.md) — non-fatal, the run\n // already finished, so warn rather than throw past the CLI boundary.\n await server.close().catch((err: unknown) => {\n console.warn('[theokit agent] Vite server cleanup error:', err)\n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OAAO;AAAA;AAAA,IAElB,WAAW,OAAO;AAAA,EACpB,CAAC;AACD,QAAM,SAAS,MAAM,aAAa;AAAA,IAChC,MAAM;AAAA,IACN,SAAS,CAAC,MAAM,GAAG,GAAG,WAAW;AAAA,IACjC,QAAQ,EAAE,gBAAgB,KAAK;AAAA,IAC/B,SAAS;AAAA,IACT,UAAU;AAAA,EACZ,CAAC;AACD,SAAO;AAAA,IACL,MAAM,CAAC,MAAM,OAAO,cAAc,CAAC;AAAA,IACnC,SAAS,YAAY;AAGnB,YAAM,OAAO,MAAM,EAAE,MAAM,CAAC,QAAiB;AAC3C,gBAAQ,KAAK,8CAA8C,GAAG;AAAA,MAChE,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
@@ -2,7 +2,7 @@ import {
2
2
  dispatchCsrfWarn,
3
3
  incomingMessageToWebRequest,
4
4
  sendError
5
- } from "./chunk-37ZO643S.js";
5
+ } from "./chunk-XALU5LCU.js";
6
6
  import {
7
7
  enforceCsrf,
8
8
  validateCsrfRequest
@@ -162,10 +162,10 @@ function createInProcessApprovalRegistry() {
162
162
  function buildAgentHitl(compiled) {
163
163
  const gated = compiled.hitl;
164
164
  if (gated === void 0 || gated.size === 0) return void 0;
165
- const registry2 = getApprovalRegistry();
165
+ const registry = getApprovalRegistry();
166
166
  return {
167
167
  gated,
168
- awaitApproval: (approvalId, opts, toolName) => registry2.register(approvalId, {
168
+ awaitApproval: (approvalId, opts, toolName) => registry.register(approvalId, {
169
169
  timeoutMs: opts.timeout ?? 3e5,
170
170
  onTimeout: opts.onTimeout ?? "abort",
171
171
  toolName,
@@ -385,46 +385,6 @@ function resolveSessionBaseDir(projectRoot) {
385
385
  return `${trimTrailingSlashes(projectRoot)}/.data/agent-sessions`;
386
386
  }
387
387
 
388
- // src/server/agent/provider-resolver.ts
389
- var DEFAULT_REGISTRY = [
390
- {
391
- name: "openrouter",
392
- envKey: "OPENROUTER_API_KEY",
393
- baseUrl: "https://openrouter.ai/api/v1",
394
- priority: 1
395
- },
396
- {
397
- name: "openai",
398
- envKey: "OPENAI_API_KEY",
399
- baseUrl: "https://api.openai.com/v1",
400
- priority: 2
401
- },
402
- {
403
- name: "anthropic",
404
- envKey: "ANTHROPIC_API_KEY",
405
- baseUrl: "https://api.anthropic.com",
406
- priority: 3
407
- }
408
- ];
409
- var registry = [...DEFAULT_REGISTRY];
410
- function resolveProvider() {
411
- const sorted = [...registry].sort((a, b) => a.priority - b.priority);
412
- for (const desc of sorted) {
413
- const apiKey = process.env[desc.envKey];
414
- if (apiKey && apiKey.length > 0) {
415
- return {
416
- name: desc.name,
417
- apiKey,
418
- baseUrl: desc.baseUrl
419
- };
420
- }
421
- }
422
- const envKeys = sorted.map((p) => p.envKey).join(" OR ");
423
- throw new Error(
424
- `No LLM provider API key found in environment. Set one of: ${envKeys}. Get a free OpenRouter key at https://openrouter.ai/keys (recommended \u2014 one key, many models).`
425
- );
426
- }
427
-
428
388
  export {
429
389
  scanControllerModules,
430
390
  dispatchControllerRequest,
@@ -438,7 +398,6 @@ export {
438
398
  getRunEventCache,
439
399
  mintRunId,
440
400
  parseAgentRequestBody,
441
- mountAgent,
442
- resolveProvider
401
+ mountAgent
443
402
  };
444
- //# sourceMappingURL=chunk-EIRQM55C.js.map
403
+ //# sourceMappingURL=chunk-OJLL4YD6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/http/controller-dispatch.ts","../src/server/agent/mount-agent.ts","../src/server/agent/build-agent-streamer.ts","../src/server/agent/approval-registry.ts","../src/server/agent/durable-ui-message-stream-response.ts","../src/server/agent/run-event-cache.ts"],"mappings":";;;;;;;;;;;AAIA,SAAS,mBAAgC;AAEzC,SAAS,YAAY;AAErB,SAAS,wBAAwB,yBAA0C;AAyB3E,IAAM,yBAAyB,oBAAI,IAAI,CAAC,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAQlE,SAAS,oBAAoB,KAAuB;AACzD,QAAM,QAAkB,CAAC;AACzB,QAAM,OAAO,CAAC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,QAAM,WAAWC,oBAAmB,KAAK,MAAM;AAK/C,MAAI,SAAS,gBAAgB;AAC3B,UAAM,UAAU,MAAMC,sBAAqB,SAAS,gBAAgB,SAAS,cAAc,CAAC,CAAC;AAC7F,QAAI,YAAY,OAAW,UAAS,SAAS,EAAE,SAAS,YAAY,KAAK;AAAA,EAC3E;AAEA,MAAI,OAAgB;AACpB,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK;AAAA,EAC5B,QAAQ;AAAA,EAER;AAEA,QAAM,QAAQ,sBAAsB,IAAI;AACxC,MAAI,UAAU,MAAM;AAClB,WAAO,UAAU,KAAK,eAAe,yDAAyD;AAAA,EAChG;AAMA,QAAM,OAAO,eAAe,QAAQ;AAMpC,QAAM,QAAQ,UAAU;AACxB,SAAO;AAAA,IACLC,uBAAsB,UAAU,QAAQ;AAAA,MACtC,GAAG;AAAA,MACH;AAAA,MACA,QAAQ,QAAQ;AAAA,MAChB,KAAK,oBAAoB,UAAU,WAAW;AAAA,MAC9C,SAAS,sBAAsB,WAAW;AAAA,IAC5C,CAAC;AAAA,IACD,EAAE,OAAO,OAAO,iBAAiB,EAAE;AAAA,EACrC;AACF;AAOA,SAAS,oBACP,UACA,aACoB;AACpB,QAAM,WAAW,SAAS,gBAAgB,UAAU,KAAK;AACzD,SAAO,gBAAgB,UAAa,UAAU,cAAc;AAC9D;AAGA,SAAS,oBAAoB,OAAuB;AAClD,MAAI,MAAM,MAAM;AAChB,SAAO,MAAM,KAAK,MAAM,MAAM,CAAC,MAAM,IAAK,QAAO;AACjD,SAAO,MAAM,MAAM,GAAG,GAAG;AAC3B;AASO,SAAS,sBAAsB,aAAqD;AACzF,MAAI,gBAAgB,OAAW,QAAO;AAKtC,SAAO,GAAG,oBAAoB,WAAW,CAAC;AAC5C;","names":["compileAgentModule","resolveEnabledSkills","streamAgentUIMessages","compileAgentModule","resolveEnabledSkills","streamAgentUIMessages"]}
@@ -43,4 +43,4 @@ export {
43
43
  emitControllerArtifacts,
44
44
  describeControllerArtifacts
45
45
  };
46
- //# sourceMappingURL=chunk-6LNIGF5P.js.map
46
+ //# sourceMappingURL=chunk-ORKNVORZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/build/emit-controllers.ts"],"sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\n\nimport { transformControllerSource } from '@theokit/http'\n\nimport { findControllerFiles } from '../../../server/http/controller-dispatch.js'\n\n/**\n * theokit#123 — compile `server/controllers/**` into `dist` so production can serve them.\n *\n * ## Why production needed anything at all\n *\n * #122 made decorator controllers first-class in `theokit dev`, where a Vite `enforce:'pre'` swc\n * transform compiles them on the fly — parameter decorators (`@Body`/`@Param`/`@Query`) emit\n * metadata esbuild cannot produce. `theokit start` has no Vite and no transform, so an uncompiled\n * `.controller.ts` simply cannot load, and controller routes 404'd in production while working in\n * dev. That split is the whole issue.\n *\n * ## Why compile at BUILD time rather than load with swc at runtime\n *\n * `loadControllerWithSwc` would work in production and was the smaller diff. It is refused on\n * purpose: `@swc/core` is a peer dependency and a native binary, so that path makes every deployed\n * app carry a compiler it only needs once, and turns a missing optional peer into a runtime 404\n * instead of a build failure. Compilation belongs where the rest of the build already is — and it\n * is what the issue's root-cause note asks for.\n *\n * ## Why NOT in `generateManifest`\n *\n * ADR-5 keeps controllers out of the manifest, and that is preserved here: the manifest is the\n * deploy-adapter contract, and adding a parallel route source to it would ripple through every\n * adapter. This emits a SEPARATE artifact (`dist/controllers.json` + `dist/controllers/*.mjs`) that\n * only the Node start path reads. An adapter that knows nothing about controllers keeps working\n * exactly as before.\n */\n\n/** The build artifact `theokit start` reads to find compiled controllers. */\ninterface ControllerBuildManifest {\n version: 1\n /** Emitted module paths, relative to `distDir`, in scan order. */\n modules: string[]\n}\n\nexport const CONTROLLER_MANIFEST_FILE = 'controllers.json'\nconst CONTROLLER_OUT_DIR = 'controllers'\n\n/**\n * Compile every controller under `<serverDir>/controllers` into `<distDir>/controllers`.\n *\n * No controllers ⇒ **no artifact at all** (not an empty one). `theokit start` treats a missing\n * manifest as \"this app has no controllers\" and skips the whole branch, so a routes-only app pays\n * nothing and its `dist` is byte-identical to before — the ADR-5 posture, kept.\n */\nexport async function emitControllerArtifacts(opts: {\n serverDir: string\n distDir: string\n}): Promise<ControllerBuildManifest | null> {\n const controllersDir = resolve(opts.serverDir, CONTROLLER_OUT_DIR)\n const files = findControllerFiles(controllersDir)\n if (files.length === 0) return null\n\n const outDir = resolve(opts.distDir, CONTROLLER_OUT_DIR)\n mkdirSync(outDir, { recursive: true })\n\n const modules: string[] = []\n for (const file of files) {\n // Errors are NOT caught. A controller that fails to compile must fail the BUILD — swallowing it\n // here would ship an app whose routes 404 at runtime with nothing pointing back at the cause,\n // which is the exact failure mode this issue reports (error-handling.md § 2).\n const code = await transformControllerSource(readFileSync(file, 'utf-8'), file)\n\n // Mirror the source tree under `dist/controllers` so two files with the same basename in\n // different folders cannot overwrite each other.\n const rel = relative(controllersDir, file).replace(/\\.controller\\.ts$/, '.controller.mjs')\n const outPath = join(outDir, rel)\n mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, code)\n modules.push(`${CONTROLLER_OUT_DIR}/${rel.split('\\\\').join('/')}`)\n }\n\n const manifest: ControllerBuildManifest = { version: 1, modules }\n writeFileSync(\n resolve(opts.distDir, CONTROLLER_MANIFEST_FILE),\n JSON.stringify(manifest, null, 2) + '\\n',\n )\n return manifest\n}\n\n/** Human-facing summary for the build log (mirrors the cron/job emitters). */\nexport function describeControllerArtifacts(manifest: ControllerBuildManifest | null): string {\n if (manifest === null) return 'controllers: none'\n const names = manifest.modules.map((m) => basename(m, '.mjs')).join(', ')\n return `controllers: ${manifest.modules.length} compiled (${names})`\n}\n"],"mappings":";;;;;;;AAAA,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,UAAU,SAAS,MAAM,UAAU,eAAe;AAE3D,SAAS,iCAAiC;AAuCnC,IAAM,2BAA2B;AACxC,IAAM,qBAAqB;AAS3B,eAAsB,wBAAwB,MAGF;AAC1C,QAAM,iBAAiB,QAAQ,KAAK,WAAW,kBAAkB;AACjE,QAAM,QAAQ,oBAAoB,cAAc;AAChD,MAAI,MAAM,WAAW,EAAG,QAAO;AAE/B,QAAM,SAAS,QAAQ,KAAK,SAAS,kBAAkB;AACvD,YAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;AAErC,QAAM,UAAoB,CAAC;AAC3B,aAAW,QAAQ,OAAO;AAIxB,UAAM,OAAO,MAAM,0BAA0B,aAAa,MAAM,OAAO,GAAG,IAAI;AAI9E,UAAM,MAAM,SAAS,gBAAgB,IAAI,EAAE,QAAQ,qBAAqB,iBAAiB;AACzF,UAAM,UAAU,KAAK,QAAQ,GAAG;AAChC,cAAU,QAAQ,OAAO,GAAG,EAAE,WAAW,KAAK,CAAC;AAC/C,kBAAc,SAAS,IAAI;AAC3B,YAAQ,KAAK,GAAG,kBAAkB,IAAI,IAAI,MAAM,IAAI,EAAE,KAAK,GAAG,CAAC,EAAE;AAAA,EACnE;AAEA,QAAM,WAAoC,EAAE,SAAS,GAAG,QAAQ;AAChE;AAAA,IACE,QAAQ,KAAK,SAAS,wBAAwB;AAAA,IAC9C,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI;AAAA,EACtC;AACA,SAAO;AACT;AAGO,SAAS,4BAA4B,UAAkD;AAC5F,MAAI,aAAa,KAAM,QAAO;AAC9B,QAAM,QAAQ,SAAS,QAAQ,IAAI,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,EAAE,KAAK,IAAI;AACxE,SAAO,gBAAgB,SAAS,QAAQ,MAAM,cAAc,KAAK;AACnE;","names":[]}
@@ -90,7 +90,7 @@ function createRateLimiter(config, opts = {}) {
90
90
  return resultFromState(state, config);
91
91
  }
92
92
  throw new Error(
93
- "createRateLimiter: async RateLimitStore implementations are not supported by this sync fa\xE7ade. Use the InMemoryStore default or build a custom middleware around the async store directly."
93
+ "createRateLimiter: async RateLimitStore implementations are not supported by this sync facade. Use the InMemoryStore default or build a custom middleware around the async store directly."
94
94
  );
95
95
  };
96
96
  }
@@ -124,7 +124,7 @@ function createRateLimiterWeb(config, opts = {}) {
124
124
  return resultFromState(state, config);
125
125
  }
126
126
  throw new Error(
127
- "createRateLimiterWeb: async RateLimitStore implementations are not supported by this sync fa\xE7ade. Use the InMemoryStore default or build a custom middleware around the async store directly."
127
+ "createRateLimiterWeb: async RateLimitStore implementations are not supported by this sync facade. Use the InMemoryStore default or build a custom middleware around the async store directly."
128
128
  );
129
129
  };
130
130
  }
@@ -134,4 +134,4 @@ export {
134
134
  createRateLimiter,
135
135
  createRateLimiterWeb
136
136
  };
137
- //# sourceMappingURL=chunk-KPKLIUUL.js.map
137
+ //# sourceMappingURL=chunk-TNI4MARH.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  InMemoryStore
3
- } from "./chunk-KPKLIUUL.js";
3
+ } from "./chunk-TNI4MARH.js";
4
4
  import {
5
5
  parseCookieHeader
6
6
  } from "./chunk-4FWBKX6G.js";
@@ -53,7 +53,7 @@ function createRouteRateLimiter(config) {
53
53
  const store = cfg.store ?? new InMemoryStore();
54
54
  if (!(store instanceof InMemoryStore)) {
55
55
  throw new Error(
56
- "createRouteRateLimiter: async RateLimitStore implementations require a dedicated async middleware path. Use the InMemoryStore default for the sync fa\xE7ade."
56
+ "createRouteRateLimiter: async RateLimitStore implementations require a dedicated async middleware path. Use the InMemoryStore default for the sync facade."
57
57
  );
58
58
  }
59
59
  const inMemoryStore = store;
@@ -124,7 +124,7 @@ function createRouteRateLimiterWeb(config) {
124
124
  const store = cfg.store ?? new InMemoryStore();
125
125
  if (!(store instanceof InMemoryStore)) {
126
126
  throw new Error(
127
- "createRouteRateLimiterWeb: async RateLimitStore implementations require a dedicated async middleware path. Use the InMemoryStore default for the Web fa\xE7ade."
127
+ "createRouteRateLimiterWeb: async RateLimitStore implementations require a dedicated async middleware path. Use the InMemoryStore default for the Web facade."
128
128
  );
129
129
  }
130
130
  const inMemoryStore = store;
@@ -182,4 +182,4 @@ export {
182
182
  deriveKeyFromRequest,
183
183
  createRouteRateLimiterWeb
184
184
  };
185
- //# sourceMappingURL=chunk-6KDXP472.js.map
185
+ //# sourceMappingURL=chunk-UDPJP42U.js.map