theokit 0.81.0 → 0.83.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 (114) hide show
  1. package/README.md +42 -0
  2. package/dist/{actions-virtual-module-CA4YEAL3.js → actions-virtual-module-MPSG7MB5.js} +19 -19
  3. package/dist/{actions-virtual-module-QRTV4NHS.js → actions-virtual-module-TWOP4T6H.js} +2 -2
  4. package/dist/adapters/agent-mount.js +12 -12
  5. package/dist/{agent-OM47ZAIN.js → agent-QXJZG6R7.js} +2 -2
  6. package/dist/{app-typed-client-ZCLFXBEC.js → app-typed-client-BW6M6GM4.js} +21 -21
  7. package/dist/{app-typed-client-ZCMCBS45.js → app-typed-client-PIJJ6ABV.js} +2 -2
  8. package/dist/{build-TQAYRHJH.js → build-55ZYADOG.js} +2 -2
  9. package/dist/{chunk-C5H2JHDW.js → chunk-22WPUW6Q.js} +2 -2
  10. package/dist/{chunk-C5H2JHDW.js.map → chunk-22WPUW6Q.js.map} +1 -1
  11. package/dist/{chunk-W55B6BRC.js → chunk-2QOWKVJ6.js} +2 -2
  12. package/dist/{chunk-2Z3GHQ64.js → chunk-5EZJNG6M.js} +5 -5
  13. package/dist/{chunk-JUJI3FZM.js → chunk-6NIKAL47.js} +3 -3
  14. package/dist/{chunk-JUJI3FZM.js.map → chunk-6NIKAL47.js.map} +1 -1
  15. package/dist/{chunk-APUYC5BE.js → chunk-6QNGLLJX.js} +3 -3
  16. package/dist/{chunk-TQTEKNOL.js → chunk-AP2E5WHS.js} +1 -5
  17. package/dist/{chunk-TQTEKNOL.js.map → chunk-AP2E5WHS.js.map} +1 -1
  18. package/dist/{chunk-MSSUMKFR.js → chunk-BSH3OSJ5.js} +21 -1
  19. package/dist/chunk-BSH3OSJ5.js.map +1 -0
  20. package/dist/{chunk-CFJN5JHJ.js → chunk-CIMKVK5O.js} +7 -7
  21. package/dist/{chunk-YH5CDWLU.js → chunk-CNOCBSTV.js} +22 -1
  22. package/dist/chunk-CNOCBSTV.js.map +1 -0
  23. package/dist/{chunk-U3SPBLJF.js → chunk-DIPCJ5VE.js} +1 -5
  24. package/dist/chunk-DIPCJ5VE.js.map +1 -0
  25. package/dist/{chunk-JZLNZOEL.js → chunk-F6YBS77T.js} +2 -2
  26. package/dist/{chunk-KSEPYAMJ.js → chunk-K3MYB4LO.js} +5 -5
  27. package/dist/{chunk-QKWBT7IY.js → chunk-MDTPLIOU.js} +2 -2
  28. package/dist/{chunk-ICLIUEST.js → chunk-PH753JOS.js} +34 -10
  29. package/dist/chunk-PH753JOS.js.map +1 -0
  30. package/dist/{chunk-QEVTZ3IH.js → chunk-SI2DLU7R.js} +30 -30
  31. package/dist/{chunk-SHBPXX5E.js → chunk-SI6W733S.js} +3 -3
  32. package/dist/{chunk-36ZACTF3.js → chunk-TEH6RKDC.js} +7 -15
  33. package/dist/{chunk-36ZACTF3.js.map → chunk-TEH6RKDC.js.map} +1 -1
  34. package/dist/{chunk-HWRZUQPE.js → chunk-V3RGGV5P.js} +7 -7
  35. package/dist/{chunk-LXV5IEBB.js → chunk-WHQN35LA.js} +2 -2
  36. package/dist/{chunk-AL5JHX7X.js → chunk-YAGGFI7B.js} +61 -13
  37. package/dist/chunk-YAGGFI7B.js.map +1 -0
  38. package/dist/{chunk-42TYMRBG.js → chunk-YATQI5XC.js} +46 -32
  39. package/dist/{chunk-42TYMRBG.js.map → chunk-YATQI5XC.js.map} +1 -1
  40. package/dist/{chunk-4XZOUS5G.js → chunk-Z7G5F7YF.js} +5 -5
  41. package/dist/{chunk-7HGZ3CKL.js → chunk-ZSMB75Z2.js} +1 -5
  42. package/dist/{chunk-7HGZ3CKL.js.map → chunk-ZSMB75Z2.js.map} +1 -1
  43. package/dist/cli/index.js +6 -6
  44. package/dist/client/index.js +3 -3
  45. package/dist/{dev-CDCYJTDM.js → dev-PIB34ZYF.js} +5 -5
  46. package/dist/{dev-emit-BR6ERY63.js → dev-emit-VCXNCJND.js} +2 -2
  47. package/dist/{index-BGIX-H9s.d.ts → index-BHUYAnjZ.d.ts} +2 -5
  48. package/dist/index.js +19 -19
  49. package/dist/{internal-api-JFA4JI3Z.js → internal-api-EPAFPRDC.js} +31 -31
  50. package/dist/{internal-api-KQQHFTCG.js → internal-api-SKPCSHTV.js} +2 -2
  51. package/dist/{job-backend-BRfDfojf.d.ts → job-backend-CPASsVEt.d.ts} +11 -0
  52. package/dist/{mcp-4OM4QSYT.js → mcp-RFCVZ76T.js} +2 -2
  53. package/dist/{preview-AAV5CDIH.js → preview-T4BVZIN2.js} +3 -3
  54. package/dist/server/agent/index.d.ts +7 -2
  55. package/dist/server/agent/index.js +1 -1
  56. package/dist/server/auth/index.d.ts +17 -8
  57. package/dist/server/auth/index.js +5 -3
  58. package/dist/server/cron/index.js +5 -5
  59. package/dist/server/http/index.d.ts +2 -2
  60. package/dist/server/http/index.js +11 -15
  61. package/dist/server/index.d.ts +8 -15
  62. package/dist/server/index.js +79 -83
  63. package/dist/server/index.js.map +1 -1
  64. package/dist/server/jobs/index.d.ts +28 -3
  65. package/dist/server/jobs/index.js +10 -8
  66. package/dist/server/observability/index.d.ts +1 -5
  67. package/dist/server/observability/index.js +1 -3
  68. package/dist/server/scan/index.d.ts +1 -3
  69. package/dist/server/scan/index.js +1 -3
  70. package/dist/server/storage/index.js +3 -3
  71. package/dist/server/webhook/index.d.ts +45 -1
  72. package/dist/server/webhook/index.js +7 -1
  73. package/dist/{server-boundary-JA3UOKJS.js → server-boundary-5UV5OLUQ.js} +2 -2
  74. package/dist/{server-boundary-OJ6YIPQT.js → server-boundary-IJTLASGW.js} +19 -19
  75. package/dist/{start-ZMKPC4TF.js → start-DBGV5FUN.js} +4 -4
  76. package/dist/testing/index.d.ts +31 -0
  77. package/dist/testing/index.js +205 -0
  78. package/dist/testing/index.js.map +1 -0
  79. package/dist/vite-plugin/index.js +19 -19
  80. package/dist/{vite-plugin-CK5E4PA5.js → vite-plugin-WW3DFQPT.js} +4 -4
  81. package/package.json +8 -4
  82. package/dist/chunk-AL5JHX7X.js.map +0 -1
  83. package/dist/chunk-ICLIUEST.js.map +0 -1
  84. package/dist/chunk-MSSUMKFR.js.map +0 -1
  85. package/dist/chunk-U3SPBLJF.js.map +0 -1
  86. package/dist/chunk-YH5CDWLU.js.map +0 -1
  87. /package/dist/{actions-virtual-module-CA4YEAL3.js.map → actions-virtual-module-MPSG7MB5.js.map} +0 -0
  88. /package/dist/{actions-virtual-module-QRTV4NHS.js.map → actions-virtual-module-TWOP4T6H.js.map} +0 -0
  89. /package/dist/{agent-OM47ZAIN.js.map → agent-QXJZG6R7.js.map} +0 -0
  90. /package/dist/{app-typed-client-ZCLFXBEC.js.map → app-typed-client-BW6M6GM4.js.map} +0 -0
  91. /package/dist/{app-typed-client-ZCMCBS45.js.map → app-typed-client-PIJJ6ABV.js.map} +0 -0
  92. /package/dist/{build-TQAYRHJH.js.map → build-55ZYADOG.js.map} +0 -0
  93. /package/dist/{chunk-W55B6BRC.js.map → chunk-2QOWKVJ6.js.map} +0 -0
  94. /package/dist/{chunk-2Z3GHQ64.js.map → chunk-5EZJNG6M.js.map} +0 -0
  95. /package/dist/{chunk-APUYC5BE.js.map → chunk-6QNGLLJX.js.map} +0 -0
  96. /package/dist/{chunk-CFJN5JHJ.js.map → chunk-CIMKVK5O.js.map} +0 -0
  97. /package/dist/{chunk-JZLNZOEL.js.map → chunk-F6YBS77T.js.map} +0 -0
  98. /package/dist/{chunk-KSEPYAMJ.js.map → chunk-K3MYB4LO.js.map} +0 -0
  99. /package/dist/{chunk-QKWBT7IY.js.map → chunk-MDTPLIOU.js.map} +0 -0
  100. /package/dist/{chunk-QEVTZ3IH.js.map → chunk-SI2DLU7R.js.map} +0 -0
  101. /package/dist/{chunk-SHBPXX5E.js.map → chunk-SI6W733S.js.map} +0 -0
  102. /package/dist/{chunk-HWRZUQPE.js.map → chunk-V3RGGV5P.js.map} +0 -0
  103. /package/dist/{chunk-LXV5IEBB.js.map → chunk-WHQN35LA.js.map} +0 -0
  104. /package/dist/{chunk-4XZOUS5G.js.map → chunk-Z7G5F7YF.js.map} +0 -0
  105. /package/dist/{dev-CDCYJTDM.js.map → dev-PIB34ZYF.js.map} +0 -0
  106. /package/dist/{dev-emit-BR6ERY63.js.map → dev-emit-VCXNCJND.js.map} +0 -0
  107. /package/dist/{internal-api-JFA4JI3Z.js.map → internal-api-EPAFPRDC.js.map} +0 -0
  108. /package/dist/{internal-api-KQQHFTCG.js.map → internal-api-SKPCSHTV.js.map} +0 -0
  109. /package/dist/{mcp-4OM4QSYT.js.map → mcp-RFCVZ76T.js.map} +0 -0
  110. /package/dist/{preview-AAV5CDIH.js.map → preview-T4BVZIN2.js.map} +0 -0
  111. /package/dist/{server-boundary-JA3UOKJS.js.map → server-boundary-5UV5OLUQ.js.map} +0 -0
  112. /package/dist/{server-boundary-OJ6YIPQT.js.map → server-boundary-IJTLASGW.js.map} +0 -0
  113. /package/dist/{start-ZMKPC4TF.js.map → start-DBGV5FUN.js.map} +0 -0
  114. /package/dist/{vite-plugin-CK5E4PA5.js.map → vite-plugin-WW3DFQPT.js.map} +0 -0
package/README.md CHANGED
@@ -85,8 +85,44 @@ export const GET = route()
85
85
  | `./client/core` | The framework-agnostic client (no React) |
86
86
  | `./react-query` | The TanStack Query adapter over `theoFetch` |
87
87
  | `./vite-plugin` | The plugin that makes all of the above work |
88
+ | `./testing` | `startTestServer`: boot the app as a real process from a test |
88
89
  | `./boot`, `./adapters/web-shim`, `./adapters/ws-shim` | Runtime shims |
89
90
 
91
+ ## OIDC discovery
92
+
93
+ `discoverOidcProvider(issuer)` from `theokit/server/auth` fetches and caches a provider's
94
+ metadata. The issuer and every endpoint it returns (`authorization_endpoint`, `token_endpoint`,
95
+ and `userinfo_endpoint`, `jwks_uri`, `end_session_endpoint` when present) must be https, or http
96
+ on a loopback host (`localhost`, `[::1]`, `127.0.0.0/8`; never `0.0.0.0`). Endpoints need not
97
+ share the issuer's host. Otherwise it throws `OidcInsecureEndpointError` (`code:
98
+ 'oidc_insecure_endpoint'`, with `field` and `url`), and the failure is not cached.
99
+ `isSafeOidcUrl(url)` applies the same rule.
100
+
101
+ ## Testing
102
+
103
+ `theokit/testing` starts the app's own `theokit dev` (or `theokit start`) on a free port and resolves
104
+ once `/__theo/ready` answers. No stdout parsing, no `npx`, no hand-rolled process-group kill.
105
+
106
+ ```ts
107
+ import { afterAll, beforeAll, expect, it } from 'vitest'
108
+ import { startTestServer, type TestServer } from 'theokit/testing'
109
+
110
+ let server: TestServer
111
+ beforeAll(async () => {
112
+ server = await startTestServer({ cwd: process.cwd() }) // mode: 'dev' by default
113
+ })
114
+ afterAll(async () => {
115
+ await server.close()
116
+ })
117
+
118
+ it('is healthy', async () => {
119
+ expect((await fetch(`${server.origin}/__theo/health`)).status).toBe(200)
120
+ })
121
+ ```
122
+
123
+ If the child exits or the deadline (`timeoutMs`, default 60 s) passes, `startTestServer` throws
124
+ `TestServerBootError` with the child's output. `mode: 'start'` expects a prior `theokit build`.
125
+
90
126
  ## Storage
91
127
 
92
128
  `theo.config.ts > storage` declares servers and databases; route code gets a cached client from
@@ -175,6 +211,12 @@ The job commits or rolls back with the row, and workers cannot see it before the
175
211
  backend with `enqueueInTransaction` (`PostgresJobBackend` has it); any other backend rejects with
176
212
  `TransactionalEnqueueUnsupportedError` instead of enqueueing outside the transaction.
177
213
 
214
+ To take back a queued job in a transaction, call
215
+ `ctx.queue.cancelInTransaction(client, 'process-task', { idempotencyKey })`. It removes the job
216
+ only while no worker ever leased it and resolves `true` if it removed one; a leased job (even with
217
+ an expired lease) or a failed one is left alone. A backend without `cancelInTransaction` rejects
218
+ with `TransactionalCancelUnsupportedError`.
219
+
178
220
  `theokit start` and `theokit dev` run a job worker in the same process whenever jobs are declared
179
221
  and a backend is set: it polls the backend, runs each job and backs off while the backend is
180
222
  unreachable. On `SIGTERM`, `start` stops polling and waits for the job in progress before closing
@@ -1,38 +1,38 @@
1
- import "./chunk-SHBPXX5E.js";
2
- import "./chunk-4XZOUS5G.js";
1
+ import "./chunk-SI6W733S.js";
2
+ import "./chunk-Z7G5F7YF.js";
3
+ import "./chunk-4Z5XO4O4.js";
4
+ import {
5
+ scanServerActionsEnriched
6
+ } from "./chunk-ZSMB75Z2.js";
7
+ import "./chunk-A6UFN6QQ.js";
3
8
  import "./chunk-WSOAN4KN.js";
4
9
  import "./chunk-ENSFCKP6.js";
5
- import "./chunk-HWRZUQPE.js";
6
- import "./chunk-36ZACTF3.js";
10
+ import "./chunk-DV34VG3N.js";
11
+ import "./chunk-V3RGGV5P.js";
12
+ import "./chunk-TEH6RKDC.js";
13
+ import "./chunk-V6Y2SMRG.js";
7
14
  import "./chunk-P6OS7652.js";
8
15
  import "./chunk-ZDUO4IYN.js";
9
16
  import "./chunk-IDWN2OSG.js";
10
- import "./chunk-YH5CDWLU.js";
17
+ import "./chunk-AHYOVVJ7.js";
18
+ import "./chunk-SOYOYGWY.js";
19
+ import "./chunk-CNOCBSTV.js";
20
+ import "./chunk-ZWN3AODA.js";
11
21
  import "./chunk-NTDN54XO.js";
12
22
  import "./chunk-JO462JZM.js";
13
23
  import "./chunk-IXXZBZF7.js";
14
24
  import "./chunk-AVQU5CQF.js";
25
+ import "./chunk-UMNXCU3K.js";
26
+ import "./chunk-AP2E5WHS.js";
27
+ import "./chunk-CHTAWXC2.js";
15
28
  import "./chunk-VSLTKX5L.js";
16
29
  import "./chunk-SFGGRC35.js";
17
- import "./chunk-4Z5XO4O4.js";
18
- import {
19
- scanServerActionsEnriched
20
- } from "./chunk-7HGZ3CKL.js";
21
- import "./chunk-A6UFN6QQ.js";
22
- import "./chunk-DV34VG3N.js";
23
- import "./chunk-V6Y2SMRG.js";
24
30
  import "./chunk-ACKBVBUI.js";
25
31
  import "./chunk-IZ3TIL6K.js";
26
32
  import "./chunk-54BIQFP4.js";
27
33
  import "./chunk-ZICY2CD7.js";
28
34
  import "./chunk-YSJOZEI6.js";
29
35
  import "./chunk-Z4PJMZLM.js";
30
- import "./chunk-UMNXCU3K.js";
31
- import "./chunk-TQTEKNOL.js";
32
- import "./chunk-CHTAWXC2.js";
33
- import "./chunk-AHYOVVJ7.js";
34
- import "./chunk-SOYOYGWY.js";
35
- import "./chunk-ZWN3AODA.js";
36
36
  import "./chunk-XTHN6JBX.js";
37
37
 
38
38
  // src/vite-plugin/actions-virtual-module.ts
@@ -236,4 +236,4 @@ export const actions = manifest
236
236
  export {
237
237
  actionsVirtualModule
238
238
  };
239
- //# sourceMappingURL=actions-virtual-module-CA4YEAL3.js.map
239
+ //# sourceMappingURL=actions-virtual-module-MPSG7MB5.js.map
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
- import "./chunk-MSSUMKFR.js";
3
+ import "./chunk-BSH3OSJ5.js";
4
4
  import "./chunk-4JRXZTVQ.js";
5
5
  import "./chunk-FNJVSFEC.js";
6
6
  import "./chunk-WSMLSIS5.js";
@@ -219,4 +219,4 @@ export const actions = manifest
219
219
  export {
220
220
  actionsVirtualModule
221
221
  };
222
- //# sourceMappingURL=actions-virtual-module-QRTV4NHS.js.map
222
+ //# sourceMappingURL=actions-virtual-module-TWOP4T6H.js.map
@@ -3,20 +3,25 @@ import {
3
3
  createSubjectResolverFromFactory,
4
4
  matchAgentAuxRoute,
5
5
  serveMatchedAuxRoute
6
- } from "../chunk-APUYC5BE.js";
6
+ } from "../chunk-6QNGLLJX.js";
7
7
  import {
8
8
  mountAgent
9
- } from "../chunk-4XZOUS5G.js";
10
- import "../chunk-36ZACTF3.js";
9
+ } from "../chunk-Z7G5F7YF.js";
10
+ import {
11
+ scanAgents
12
+ } from "../chunk-A6UFN6QQ.js";
13
+ import "../chunk-TEH6RKDC.js";
14
+ import "../chunk-V6Y2SMRG.js";
11
15
  import "../chunk-P6OS7652.js";
12
16
  import "../chunk-IDWN2OSG.js";
17
+ import "../chunk-SOYOYGWY.js";
18
+ import "../chunk-ZWN3AODA.js";
13
19
  import "../chunk-JO462JZM.js";
14
20
  import "../chunk-IXXZBZF7.js";
15
21
  import "../chunk-AVQU5CQF.js";
16
- import {
17
- scanAgents
18
- } from "../chunk-A6UFN6QQ.js";
19
- import "../chunk-V6Y2SMRG.js";
22
+ import "../chunk-UMNXCU3K.js";
23
+ import "../chunk-AP2E5WHS.js";
24
+ import "../chunk-CHTAWXC2.js";
20
25
  import "../chunk-ACKBVBUI.js";
21
26
  import "../chunk-IZ3TIL6K.js";
22
27
  import "../chunk-RN5NDLUS.js";
@@ -24,11 +29,6 @@ import {
24
29
  resolveProvider
25
30
  } from "../chunk-54BIQFP4.js";
26
31
  import "../chunk-ZICY2CD7.js";
27
- import "../chunk-UMNXCU3K.js";
28
- import "../chunk-TQTEKNOL.js";
29
- import "../chunk-CHTAWXC2.js";
30
- import "../chunk-SOYOYGWY.js";
31
- import "../chunk-ZWN3AODA.js";
32
32
  import "../chunk-XTHN6JBX.js";
33
33
  export {
34
34
  createAgentSubjectResolver,
@@ -3,7 +3,7 @@ import "tsx/esm";
3
3
  import {
4
4
  agentCommand,
5
5
  createAgentSsrLoader
6
- } from "./chunk-QKWBT7IY.js";
6
+ } from "./chunk-MDTPLIOU.js";
7
7
  import "./chunk-4JRXZTVQ.js";
8
8
  import "./chunk-FU3LEX2I.js";
9
9
  import "./chunk-Z7CJHDLS.js";
@@ -13,4 +13,4 @@ export {
13
13
  agentCommand,
14
14
  createAgentSsrLoader
15
15
  };
16
- //# sourceMappingURL=agent-OM47ZAIN.js.map
16
+ //# sourceMappingURL=agent-QXJZG6R7.js.map
@@ -1,42 +1,42 @@
1
1
  import {
2
2
  scanControllerModules
3
- } from "./chunk-SHBPXX5E.js";
4
- import "./chunk-4XZOUS5G.js";
3
+ } from "./chunk-SI6W733S.js";
4
+ import "./chunk-Z7G5F7YF.js";
5
+ import "./chunk-4Z5XO4O4.js";
6
+ import {
7
+ generateManifest
8
+ } from "./chunk-ZSMB75Z2.js";
9
+ import "./chunk-A6UFN6QQ.js";
5
10
  import "./chunk-WSOAN4KN.js";
6
11
  import "./chunk-ENSFCKP6.js";
7
- import "./chunk-HWRZUQPE.js";
8
- import "./chunk-36ZACTF3.js";
12
+ import {
13
+ HTTP_METHODS
14
+ } from "./chunk-DV34VG3N.js";
15
+ import "./chunk-V3RGGV5P.js";
16
+ import "./chunk-TEH6RKDC.js";
17
+ import "./chunk-V6Y2SMRG.js";
9
18
  import "./chunk-P6OS7652.js";
10
19
  import "./chunk-ZDUO4IYN.js";
11
20
  import "./chunk-IDWN2OSG.js";
12
- import "./chunk-YH5CDWLU.js";
21
+ import "./chunk-AHYOVVJ7.js";
22
+ import "./chunk-SOYOYGWY.js";
23
+ import "./chunk-CNOCBSTV.js";
24
+ import "./chunk-ZWN3AODA.js";
13
25
  import "./chunk-NTDN54XO.js";
14
26
  import "./chunk-JO462JZM.js";
15
27
  import "./chunk-IXXZBZF7.js";
16
28
  import "./chunk-AVQU5CQF.js";
29
+ import "./chunk-UMNXCU3K.js";
30
+ import "./chunk-AP2E5WHS.js";
31
+ import "./chunk-CHTAWXC2.js";
17
32
  import "./chunk-VSLTKX5L.js";
18
33
  import "./chunk-SFGGRC35.js";
19
- import "./chunk-4Z5XO4O4.js";
20
- import {
21
- generateManifest
22
- } from "./chunk-7HGZ3CKL.js";
23
- import "./chunk-A6UFN6QQ.js";
24
- import {
25
- HTTP_METHODS
26
- } from "./chunk-DV34VG3N.js";
27
- import "./chunk-V6Y2SMRG.js";
28
34
  import "./chunk-ACKBVBUI.js";
29
35
  import "./chunk-IZ3TIL6K.js";
30
36
  import "./chunk-54BIQFP4.js";
31
37
  import "./chunk-ZICY2CD7.js";
32
38
  import "./chunk-YSJOZEI6.js";
33
39
  import "./chunk-Z4PJMZLM.js";
34
- import "./chunk-UMNXCU3K.js";
35
- import "./chunk-TQTEKNOL.js";
36
- import "./chunk-CHTAWXC2.js";
37
- import "./chunk-AHYOVVJ7.js";
38
- import "./chunk-SOYOYGWY.js";
39
- import "./chunk-ZWN3AODA.js";
40
40
  import "./chunk-XTHN6JBX.js";
41
41
 
42
42
  // src/vite-plugin/app-typed-client.ts
@@ -429,4 +429,4 @@ export {
429
429
  generateClientDts,
430
430
  shouldReemitForFile
431
431
  };
432
- //# sourceMappingURL=app-typed-client-ZCLFXBEC.js.map
432
+ //# sourceMappingURL=app-typed-client-BW6M6GM4.js.map
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
- import "./chunk-MSSUMKFR.js";
3
+ import "./chunk-BSH3OSJ5.js";
4
4
  import "./chunk-4JRXZTVQ.js";
5
5
  import {
6
6
  scanControllerModules
@@ -412,4 +412,4 @@ export {
412
412
  generateClientDts,
413
413
  shouldReemitForFile
414
414
  };
415
- //# sourceMappingURL=app-typed-client-ZCMCBS45.js.map
415
+ //# sourceMappingURL=app-typed-client-PIJJ6ABV.js.map
@@ -411,7 +411,7 @@ async function buildCommand(options) {
411
411
  `);
412
412
  }
413
413
  async function runAdapterBuild(target, config, cwd, adapter) {
414
- const { theoPluginAsync } = await import("./vite-plugin-CK5E4PA5.js");
414
+ const { theoPluginAsync } = await import("./vite-plugin-WW3DFQPT.js");
415
415
  const { default: react } = await import("@vitejs/plugin-react");
416
416
  const ctx = {
417
417
  // `react()` may return Plugin or Plugin[] depending on version; spread the
@@ -506,4 +506,4 @@ function relativize3(absPath, root) {
506
506
  export {
507
507
  buildCommand
508
508
  };
509
- //# sourceMappingURL=build-TQAYRHJH.js.map
509
+ //# sourceMappingURL=build-55ZYADOG.js.map
@@ -2,7 +2,7 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  jobBackendFromConfig
5
- } from "./chunk-W55B6BRC.js";
5
+ } from "./chunk-2QOWKVJ6.js";
6
6
  import {
7
7
  extractTraceContext,
8
8
  generateNewTraceContext
@@ -549,4 +549,4 @@ export {
549
549
  prepareJobBackend,
550
550
  startJobWorker
551
551
  };
552
- //# sourceMappingURL=chunk-C5H2JHDW.js.map
552
+ //# sourceMappingURL=chunk-22WPUW6Q.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server/cache-bootstrap.ts","../src/server/cron/cron-runtime-node.ts","../src/cli/commands/resolve-listen-port.ts","../src/cli/commands/start/bootstrap-stages.ts","../src/cli/commands/start/cron-bootstrap.ts","../src/cli/commands/start/job-bootstrap.ts","../src/server/jobs/job-backend.ts","../src/server/jobs/job-runner.ts","../src/server/jobs/job-worker.ts"],"sourcesContent":["import type { NormalizedCacheConfig } from '../cache/engine-singleton.js'\n\n/**\n * Initialize the singleton cache engine from `theo.config.ts > cache` (#352).\n *\n * Until this existed, `initCacheEngine` had no production caller while\n * `getCacheEngine` had three — so `revalidateTag`, `updateTag` and\n * `revalidatePath`, all exported publicly, threw \"Cache engine not initialized\"\n * in every application. The subsystem was not unreachable code; it was a bridge\n * with one half published and the other half never built.\n *\n * Three states a boot legitimately reaches, each handled by a guard rather than\n * by a `catch`, because `initCacheEngine` throws on all three and absorbing the\n * throws would absorb the real double-init bug with them:\n *\n * - no `cache` key at all — the framework stays backward compatible, no engine\n * - `enabled: false` — an explicit opt-out, not an error\n * - already initialized — HMR, a second server in one process, a test booting\n * twice in one worker\n *\n * Unlike `configureStorageManagerFromConfig`, its sibling in the CLI bootstrap,\n * a malformed config is NOT\n * degraded into a warning here, and the divergence is deliberate. Warning and\n * continuing would boot an application whose `revalidateTag` still throws — the\n * exact defect this function exists to remove, restored silently and now\n * attributable to nothing.\n */\nexport async function initCacheEngineFromConfig(cacheConfig: unknown): Promise<void> {\n if (cacheConfig === undefined || cacheConfig === null) return\n\n const { initCacheEngine, isCacheEngineInitialized } = await import('../cache/engine-singleton.js')\n if (isCacheEngineInitialized()) return\n\n const { cacheSchema } = await import('../config/schemas/index.js')\n const parsed = cacheSchema.parse(cacheConfig)\n if (!parsed.enabled) return\n\n initCacheEngine({\n enabled: parsed.enabled,\n // The schema accepts `'memory'` or a caller-supplied adapter instance, which\n // it cannot type beyond `unknown` without importing the adapter contract\n // into the config layer.\n storage: parsed.storage as NormalizedCacheConfig['storage'],\n maxEntries: parsed.maxEntries,\n defaults: parsed.defaults,\n })\n}\n","import { CronExpressionParser } from 'cron-parser'\n\nimport { generateNewTraceContext } from '../observability/trace-context-propagation.js'\n\nimport type { CronLock } from './cron-lock.js'\nimport type { CronContext, CronDefinition } from './cron-types.js'\n\n/**\n * In-process cron scheduler, run by `theokit start` (and by `theokit dev --crons`).\n *\n * Algorithm:\n * - For each cron, compute `nextFireAt = cron-parser.next()`.\n * - Schedule a `setTimeout(handler, nextFireAt - now)`.\n * - After handler invocation (sync return or Promise scheduled), recompute\n * next fire from CURRENT time (drift-free vs scheduled time).\n *\n * Per-cron isolation (EC-109):\n * - Each cron's handler invocation is fire-and-forget (`void` scheduled).\n * A hanging handler does NOT block the scheduler loop nor other crons.\n * - `concurrency: 'forbid'` (default) tracks an in-flight flag per-cron;\n * subsequent ticks skip + warn while the in-flight flag is set.\n * - `concurrency: 'allow'` runs handlers concurrently — caller's responsibility.\n *\n * Several processes (replicas) each run this scheduler under `theokit start`. Without a `lock`,\n * each one fires every tick. With one, each tick asks the lock first and only the process that\n * gets `true` runs the handler (usetheokit/theokit#1016). A lock that fails skips the tick and logs\n * the error: running unguarded would repeat the side effect on every replica, which is the defect\n * the lock exists for.\n *\n * Serverless targets use platform-native triggers (T1.5 adapter translators), which fire once.\n */\n\nexport interface CronSchedulerOptions {\n /** Shared lock deciding which process runs each tick. Absent: this process runs every tick. */\n lock?: CronLock\n}\n\nexport interface CronScheduler {\n start(): void\n stop(): void\n}\n\ninterface CronJobState {\n readonly def: CronDefinition\n inFlight: boolean\n timer: NodeJS.Timeout | null\n abortController: AbortController | null\n lockToken?: number\n}\n\nexport function createCronScheduler(\n definitions: readonly CronDefinition[],\n options: CronSchedulerOptions = {},\n): CronScheduler {\n const lock = options.lock\n const candidate = lock as { acquire?: unknown } | null | undefined\n if (candidate !== undefined && typeof candidate?.acquire !== 'function') {\n throw new TypeError(\n 'createCronScheduler: `lock` must be an object with an `acquire(name, scheduledAt)` method returning Promise<boolean>.',\n )\n }\n const states: CronJobState[] = definitions.map((def) => ({\n def,\n inFlight: false,\n timer: null,\n abortController: null,\n }))\n\n let started = false\n\n /** Run the tick if the lock (when there is one) gives it to this process. */\n const fireIfLockAllows = (state: CronJobState, scheduledAt: Date): void => {\n if (lock === undefined) {\n runTick(state, scheduledAt)\n scheduleNext(state)\n return\n }\n state.timer = null\n // Schedule the next tick now: an acquire that never settles must not stop this cron.\n scheduleNext(state)\n const token = (state.lockToken = (state.lockToken ?? 0) + 1)\n const superseded = (): boolean => state.lockToken !== token || !started\n // A synchronous throw from `acquire` is treated like a rejection.\n void Promise.resolve()\n .then(() => lock.acquire(state.def.name, scheduledAt))\n .then(\n (won) => {\n if (!won) return\n if (superseded()) {\n console.warn(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()} ` +\n '— the cron lock answered after the next tick was already scheduled.',\n )\n return\n }\n runTick(state, scheduledAt)\n },\n (err: unknown) => {\n console.error(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()}: ` +\n 'the cron lock could not be acquired:',\n err instanceof Error ? err.message : err,\n )\n },\n )\n }\n\n const runTick = (state: CronJobState, scheduledAt: Date): void => {\n state.timer = null\n\n if (state.inFlight && state.def.concurrency === 'forbid') {\n console.warn(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()} ` +\n '— previous handler still running (concurrency: forbid).',\n )\n return\n }\n\n state.inFlight = true\n state.abortController = new AbortController()\n const traceCtx = generateNewTraceContext()\n const ctx: CronContext = {\n traceId: traceCtx.trace_id,\n scheduledAt,\n signal: state.abortController.signal,\n }\n\n // Fire-and-forget: EC-109 — never await here so a hanging handler\n // can't block the scheduler loop or other crons.\n void Promise.resolve()\n .then(() => state.def.handler(ctx))\n .catch((err: unknown) => {\n console.error(\n `[theokit:cron] \"${state.def.name}\" handler error:`,\n err instanceof Error ? err.message : err,\n )\n })\n .finally(() => {\n state.inFlight = false\n })\n }\n\n const scheduleNext = (state: CronJobState): void => {\n if (!started) return\n const interval = CronExpressionParser.parse(state.def.schedule, {\n tz: 'UTC',\n currentDate: new Date(),\n })\n const next = interval.next().toDate()\n const delayMs = Math.max(0, next.getTime() - Date.now())\n state.timer = setTimeout(() => {\n fireIfLockAllows(state, next)\n }, delayMs)\n // setTimeout returns a Timeout object; in Node, .unref() is available but\n // we DO want this to keep the event loop alive in dev — explicit no-unref.\n }\n\n return {\n start(): void {\n if (started) return\n started = true\n for (const state of states) {\n scheduleNext(state)\n }\n },\n stop(): void {\n started = false\n for (const state of states) {\n if (state.timer) {\n clearTimeout(state.timer)\n state.timer = null\n }\n state.abortController?.abort()\n state.abortController = null\n }\n },\n }\n}\n","/**\n * The port a command listens on: an explicit flag, then `PORT`, then `config.port`.\n *\n * The flag is a person typing now, the environment is where the process was put (`PORT` is what\n * every container platform injects, usetheokit/theokit#402), and the config is the project's default.\n * `theokit start` and `theokit dev` both resolve it here, so they cannot drift again\n * (usetheokit/theokit#1134: `dev` ignored `PORT` and listened on `config.port`).\n *\n * A `PORT` that is not an integer is ignored rather than turned into `NaN`.\n */\nexport function resolveListenPort(\n flag: number | undefined,\n env: NodeJS.ProcessEnv,\n configPort: number,\n): number {\n if (flag !== undefined) return flag\n const fromEnv = Number.parseInt(env.PORT ?? '', 10)\n return Number.isInteger(fromEnv) ? fromEnv : configPort\n}\n","/**\n * Bootstrap stages extracted from `start.ts` per T4.2 (architecture-cleanup, ADR-0017).\n *\n * The full goal of T4.2 is a ≤30-LOC `startCommand` spine + 6-8 stage files. This\n * file ships the first batch: the configure-from-config bootstrap helpers + the\n * SSR entry resolver. They are stand-alone, side-effect-free at module load, and\n * already individually testable.\n *\n * Remaining stages (request-handler extraction, graceful-shutdown extraction,\n * signal-handlers extraction) are deferred to a follow-up sprint — see plan\n * ks.\n */\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\n\ninterface SdkAgentRegistry {\n configure?: (opts: { maxAgents?: number; idleTimeoutMs?: number }) => void\n}\ninterface SdkModule {\n Agent?: { registry?: SdkAgentRegistry }\n}\n\n/**\n * Configure SDK's Agent.registry from `theo.config.ts > agents.registry`.\n * Lazy at boot; EC-3 sync flag flip prevents race under concurrent boot.\n * Silent no-op when registry config is absent or SDK is uninstalled.\n */\nexport async function configureAgentRegistryFromConfig(\n registryConfig: { maxAgents: number; idleTimeoutMs: number } | undefined,\n): Promise<void> {\n if (registryConfig === undefined) return\n try {\n const sdk = (await import('@theokit/sdk').catch(() => null)) as SdkModule | null\n const sdkConfigure = sdk?.Agent?.registry?.configure\n if (sdkConfigure === undefined) return\n const { configureAgentRegistryOnce } =\n await import('../../../server/agent/configure-agent-registry.js')\n configureAgentRegistryOnce(\n {\n configure: (opts) => {\n sdkConfigure(opts)\n },\n },\n registryConfig,\n )\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.agent_registry_skip', {\n event: 'bootstrap.agent_registry_skip',\n message: msg,\n })\n }\n}\n\n/**\n * Configure the StorageManager from `theo.config.ts > storage` (ADR-0007).\n * Manager enforces configure-once internally (D3); this helper bridges the\n * config to the singleton with actionable error handling.\n */\nexport async function configureStorageManagerFromConfig(storageConfig: unknown): Promise<void> {\n if (storageConfig === undefined || storageConfig === null) return\n try {\n const { getStorageManager } = await import('../../../server/storage/storage-manager.js')\n const { storageSchema } = await import('../../../config/schema.js')\n // Re-validate at boot so a malformed config from a non-Zod source\n // (test fixtures, dynamic configs) surfaces a clear error early.\n const parsed = storageSchema.parse(storageConfig)\n getStorageManager().configure(parsed)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.storage_skip', {\n event: 'bootstrap.storage_skip',\n message: msg,\n })\n }\n}\n\nconst SSR_EXTENSIONS = ['.mjs', '.js'] as const\n\n/**\n * Resolve the SSR entry-server module path. tsup may emit `.mjs` or `.js`\n * depending on output format. Try `.mjs` first (modern default) then fall\n * back to `.js`. Returns null when neither exists — SSR stays disabled.\n *\n * Exported so unit tests can pin the resolution order without booting the\n * full CLI.\n */\nexport function resolveSsrEntry(distDir: string): string | null {\n for (const ext of SSR_EXTENSIONS) {\n const path = resolve(distDir, `server/entry-server${ext}`)\n\n if (existsSync(path)) return path\n }\n return null\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { CronManifest } from '../../../server/cron/cron-manifest.js'\nimport type { CronDefinition } from '../../../server/cron/cron-types.js'\n\n/**\n * Reads the cron manifest `theokit build` writes and re-loads each handler so\n * `theokit start` can drive the in-process scheduler.\n *\n * The build prints \"Cron → in-process scheduler (theokit start)\" for\n * `target: node`, but nothing on the serving side ever read `dist/crons.json`\n * — the crons were declared, validated, written, and then never ran\n * (theokit#324).\n *\n * The manifest names WHICH files hold a cron; the definition itself is taken\n * from the module, which is the source `defineCron` produced. Trusting the\n * manifest's copy of the schedule would let a stale build silently run a cron\n * on the wrong cadence.\n */\nexport async function loadCronDefinitions(\n manifestPath: string,\n projectRoot: string,\n loadModule: (filePath: string) => unknown,\n): Promise<CronDefinition[]> {\n if (!existsSync(manifestPath)) return []\n\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as CronManifest\n return loadCronModules(\n manifest.crons.map((entry) => resolve(projectRoot, entry.filePath)),\n loadModule,\n )\n}\n\n/**\n * Import each file and take its `defineCron` default export, refusing a file without one. Shared\n * with `theokit dev --crons`, which lists the files itself and loads them through Vite.\n */\nexport async function loadCronModules(\n filePaths: readonly string[],\n loadModule: (filePath: string) => unknown,\n): Promise<CronDefinition[]> {\n const definitions: CronDefinition[] = []\n for (const filePath of filePaths) {\n const mod = (await loadModule(filePath)) as { default?: unknown }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `\"${filePath}\" is listed as a cron but has no valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`. ' +\n 'Re-run `theokit build` if the file changed since the last build.',\n )\n }\n definitions.push(exported)\n }\n return definitions\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.schedule === 'string' &&\n typeof candidate.handler === 'function'\n )\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../../../config/schema.js'\nimport { jobBackendFromConfig } from '../../../server/jobs/job-backend-from-config.js'\nimport type { JobBackend } from '../../../server/jobs/job-backend.js'\nimport type { JobManifest } from '../../../server/jobs/job-manifest.js'\nimport { createJobRunner } from '../../../server/jobs/job-runner.js'\nimport type { JobDefinition } from '../../../server/jobs/job-types.js'\nimport { createJobWorker, type JobWorker } from '../../../server/jobs/job-worker.js'\n\n/**\n * Reads the job manifest `theokit build` writes and re-loads each definition, the jobs twin of\n * `loadCronDefinitions`. The manifest names WHICH files hold a job; the definition comes from the\n * module, so a stale build cannot run a handler the source no longer has.\n *\n * Before usetheokit/theokit#1010 nothing on the serving side read `jobs.json`.\n */\nexport async function loadJobDefinitions(\n manifestPath: string,\n projectRoot: string,\n loadModule: (filePath: string) => unknown,\n): Promise<JobDefinition[]> {\n if (!existsSync(manifestPath)) return []\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as JobManifest\n return loadJobModules(\n manifest.jobs.map((entry) => resolve(projectRoot, entry.filePath)),\n loadModule,\n )\n}\n\n/** Import each file and take its `defineJob` default export, refusing a file without one. */\nexport async function loadJobModules(\n filePaths: readonly string[],\n loadModule: (filePath: string) => unknown,\n): Promise<JobDefinition[]> {\n const definitions: JobDefinition[] = []\n for (const filePath of filePaths) {\n const mod = (await loadModule(filePath)) as { default?: unknown }\n if (!isJobDefinition(mod.default)) {\n throw new Error(\n `\"${filePath}\" is listed as a job but has no valid default export. ` +\n \"Expected `export default defineJob(name, { handler })` from 'theokit/server/jobs'. \" +\n 'Re-run `theokit build` if the file changed since the last build.',\n )\n }\n definitions.push(mod.default)\n }\n return definitions\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.handler === 'function' &&\n typeof candidate.maxAttempts === 'number'\n )\n}\n\n/**\n * `migrate()` of the configured `jobs.backend` rejected at boot. The process must not serve: every\n * route would answer 2xx while the outbox dropped each job it enqueued (usetheokit/theokit#1072).\n */\nclass JobBackendSetupError extends Error {\n readonly code = 'JOB_BACKEND_SETUP_FAILED'\n readonly backend: string\n constructor(backend: string, cause: unknown) {\n const reason = describeCause(cause)\n super(\n `jobs.backend (${backend}) could not create its storage at boot: ${reason}. ` +\n 'Jobs enqueued now would be lost, so the server did not start. Check that the database ' +\n 'in theo.config.ts is reachable and that its user may create tables.',\n { cause },\n )\n this.name = 'JobBackendSetupError'\n this.backend = backend\n }\n}\n\n/**\n * The text of a setup failure. `pg` connecting to `localhost` tries every address it resolves to\n * and rejects with an `AggregateError` whose own message is empty, which printed \"could not create\n * its storage at boot: .\" on a CI runner. The attempts are listed instead, and an error without a\n * message falls back to its code.\n */\nfunction describeCause(cause: unknown): string {\n if (cause instanceof AggregateError && cause.message === '') {\n return cause.errors.map(describeCause).join('; ')\n }\n if (cause instanceof Error) {\n const code = (cause as { code?: unknown }).code\n if (cause.message !== '') return cause.message\n return typeof code === 'string' ? code : cause.name\n }\n return String(cause)\n}\n\n/**\n * Run `migrate()` on the configured `jobs.backend`, when it has one, before anything can enqueue\n * or dequeue. `theokit start` and `theokit dev` call it at boot whether or not this process runs\n * the worker: a web-only process enqueues into the same table.\n *\n * It used to be the app's job, and nothing told the app: the README configured a\n * `PostgresJobBackend` without the call, and a fresh database answered 2xx while every job was\n * dropped. Calling it from `theo.config.ts` instead made `theokit build` need a database.\n */\nexport async function prepareJobBackend(config: Pick<TheoConfig, 'jobs'>): Promise<void> {\n const backend = jobBackendFromConfig(config)\n if (backend?.migrate === undefined) return\n try {\n await backend.migrate()\n } catch (err) {\n throw new JobBackendSetupError(backend.name, err)\n }\n}\n\nexport interface JobWorkerBootstrap {\n /** The running worker, or `undefined` when none was started (see `summary`). */\n readonly worker: JobWorker | undefined\n /** One line for the boot log saying what happens to the declared jobs, or `undefined` if none. */\n readonly summary: string | undefined\n}\n\n/**\n * Start the in-process job worker when there is something to run and somewhere to run it from.\n *\n * - no declared jobs: no worker. A worker with no definitions would lease other processes' jobs\n * and fail them as \"No job definition\".\n * - jobs but no `jobs.backend`: no worker, and the summary says the jobs cannot run.\n * - `jobs.worker.enabled: false`: no worker, said in the summary, so a web-only process is visibly\n * one.\n */\nexport function startJobWorker(\n config: Pick<TheoConfig, 'jobs'>,\n definitions: readonly JobDefinition[],\n): JobWorkerBootstrap {\n if (definitions.length === 0) return { worker: undefined, summary: undefined }\n const declared = `Jobs: ${String(definitions.length)} declared`\n const backend: JobBackend | undefined = jobBackendFromConfig(config)\n if (backend === undefined) {\n return {\n worker: undefined,\n summary:\n `${declared}, NOT running: theo.config.ts sets no jobs.backend, so ctx.queue is absent ` +\n 'and nothing can enqueue or run them.',\n }\n }\n const options = config.jobs?.worker\n if (options?.enabled === false) {\n return {\n worker: undefined,\n summary: `${declared}, worker disabled (jobs.worker.enabled: false); another process must run them.`,\n }\n }\n const worker = createJobWorker(createJobRunner(backend, definitions), {\n pollIntervalMs: options?.pollIntervalMs,\n batchSize: options?.batchSize,\n lockSeconds: options?.lockSeconds,\n })\n worker.start()\n return {\n worker,\n summary: `${declared}, worker polling the ${backend.name} backend in-process`,\n }\n}\n","/**\n * Neutral `JobBackend` interface.\n *\n * Implementations ship in core:\n * - `InMemoryJobBackend` (T2.2) — dev + tests; no external deps\n * - `PostgresJobBackend` (T3.1) — production; requires `pg` peer dep\n *\n * Community packages (`@theokit/jobs-redis`, `@theokit/jobs-sqs`, etc.)\n * implement this same interface to plug in alternate substrates without\n * modifying TheoKit core.\n */\n\nimport type { PoolLike } from '../storage/storage-types.js'\n\nexport interface JobEnqueueInput {\n /** The job name (matches a `defineJob` declaration). */\n name: string\n /** Validated input (already passed through Zod or equivalent at the queue-client layer). */\n input: unknown\n /**\n * Optional idempotency key, scoped to `name`: a second enqueue of the same (name, key) returns the\n * first job's id instead of creating a job, including when the two calls race. The window is\n * backend-specific: `PostgresJobBackend` holds the key while the row exists (until `ack`, or for\n * good once the job has failed); `InMemoryJobBackend` holds it for 60 seconds.\n */\n idempotencyKey?: string\n /** Optional delay before the job becomes available for dispatch. */\n delaySeconds?: number\n /** W3C Trace Context propagation per ADR/R0.5.9. */\n traceparent?: string\n /**\n * Maximum dispatch attempts stored with the job (default 1). The queue client has no access to\n * the job definitions and leaves it unset; `createJobRunner` passes the definition's\n * `maxAttempts` to `nack`, which takes precedence over this stored value.\n */\n maxAttempts?: number\n}\n\nexport interface JobLease {\n readonly jobId: string\n readonly name: string\n readonly input: unknown\n readonly attempts: number\n readonly maxAttempts: number\n readonly traceparent?: string\n readonly lockExpiresAt: Date\n /**\n * Identifies THIS lease. Pass it back to `ack`/`nack` so a worker whose lease expired, and was\n * handed to another worker, cannot finish the job on the new holder's behalf. Both first-party\n * backends set it; optional so a backend written against the earlier contract still compiles.\n */\n readonly leaseToken?: string\n}\n\n/** What `nack` is told about the failure. */\nexport interface JobNackOptions extends JobLeaseFence {\n /** The failure message. */\n error: string\n /** The handler threw `NonRetryableError`: no retry, whatever the attempts left. */\n nonRetryable?: boolean\n /**\n * The retry ceiling from the job's definition. Takes precedence over the value stored at\n * enqueue, which is 1 for every job enqueued through the queue client.\n */\n maxAttempts?: number\n}\n\n/** Fences `ack`/`nack` to the lease that is finishing the job. */\nexport interface JobLeaseFence {\n /** The `leaseToken` of the `JobLease` being finished. Omitted, the call is not fenced. */\n leaseToken?: string\n}\n\nexport interface JobBackend {\n /** Human-readable name for logging (e.g., \"memory\", \"postgres\"). */\n readonly name: string\n\n /** Persist a job for later dispatch. Returns the generated jobId. */\n enqueue(input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /** Worker loop polls for the next available leases. */\n dequeue(opts: { batchSize?: number; lockSeconds?: number }): Promise<JobLease[]>\n\n /**\n * Mark a job complete (success). With `leaseToken`, rejects with `JobLeaseLostError` and leaves\n * the job alone when that lease no longer holds it.\n */\n ack(jobId: string, fence?: JobLeaseFence): Promise<void>\n\n /**\n * Mark a job failed; backend decides retry vs DLQ via attempts. With `leaseToken`, rejects with\n * `JobLeaseLostError` and leaves the job alone when that lease no longer holds it.\n */\n nack(jobId: string, opts: JobNackOptions): Promise<void>\n\n /**\n * Optional: keep a lease for `lockSeconds` more, counted from now, and return the new deadline.\n * A handler that is still making progress calls it (through `ctx.extendLease`) so a job that may\n * run for a long time does not need a long lock for every job. Rejects with `JobLeaseLostError`\n * (`operation: 'extend'`) when `leaseToken` no longer holds the job: the lease expired and was\n * handed on, or the job is gone (usetheokit/theokit#1132). A backend that leaves it out cannot\n * have its leases extended, and `ctx.extendLease` says so.\n */\n extendLease?(jobId: string, opts: { leaseToken: string; lockSeconds: number }): Promise<Date>\n\n /**\n * Optional: persist a job through `client`, a connection inside a transaction the caller opened,\n * so the job commits or rolls back with the caller's writes (usetheokit/theokit#1077). Only a\n * backend whose jobs live in the caller's database can offer it; `ctx.queue.enqueueInTransaction`\n * refuses a backend without it rather than enqueueing outside the transaction.\n */\n enqueueInTransaction?(client: PoolLike, input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /**\n * Optional: resolve when the backend's store answers, reject when it does not. `GET /__theo/ready`\n * calls it under `theokit start` and `theokit dev`, so an unreachable job store answers 503\n * (usetheokit/theokit#1071). A backend with nothing remote to reach leaves it out.\n */\n ping?(): Promise<void>\n\n /**\n * Optional: create or upgrade whatever storage the backend needs (a table, an index). Must be\n * idempotent and safe to run from several processes at once. `theokit start` and `theokit dev`\n * call it once at boot, before serving a request or starting the worker, and refuse to boot when\n * it rejects (usetheokit/theokit#1072). A backend that needs no setup leaves it out.\n */\n migrate?(): Promise<void>\n\n /**\n * Optional: return the existing jobId if `key` was enqueued within `ttlSeconds`. Pass `name` to\n * scope the lookup to one job type, as `enqueue` deduplicates on (name, key); without it, a key\n * shared by two job types may return either job.\n */\n idempotency?(key: string, ttlSeconds: number, name?: string): Promise<{ jobId: string } | null>\n}\n\n/**\n * Thrown from a job handler to opt out of retry policy. The runner nacks with\n * `nonRetryable: true` and the backend never retries the job: `PostgresJobBackend`\n * keeps it as failed with the error, `InMemoryJobBackend` drops it with a warning.\n */\nexport class NonRetryableError extends Error {\n readonly code = 'NON_RETRYABLE'\n constructor(message: string) {\n super(message)\n this.name = 'NonRetryableError'\n }\n}\n\n/**\n * `ack`/`nack` was called with a lease token that no longer holds the job: the lease expired and\n * another worker leased the job again (or the job is gone). The job is left untouched, because the\n * current holder owns its outcome. The runner logs it and moves on; a direct caller decides.\n */\nexport class JobLeaseLostError extends Error {\n readonly code = 'JOB_LEASE_LOST'\n readonly jobId: string\n readonly operation: 'ack' | 'nack' | 'extend'\n constructor(jobId: string, operation: 'ack' | 'nack' | 'extend') {\n super(\n `Cannot ${operation} job \"${jobId}\": its lease expired and another worker holds it now, ` +\n 'or the job no longer exists. The current holder decides its outcome.',\n )\n this.name = 'JobLeaseLostError'\n this.jobId = jobId\n this.operation = operation\n }\n}\n\n/**\n * `ctx.extendLease` was called on a job whose backend has no `extendLease`. The lease keeps its\n * original deadline and `ctx.signal` aborts when it passes.\n */\nexport class JobLeaseExtensionUnsupportedError extends Error {\n readonly code = 'JOB_LEASE_EXTENSION_UNSUPPORTED'\n readonly backend: string\n constructor(backend: string) {\n super(\n `The \"${backend}\" job backend cannot extend a lease. Give the worker a lockSeconds longer ` +\n 'than the longest job, or use a backend that implements extendLease.',\n )\n this.name = 'JobLeaseExtensionUnsupportedError'\n this.backend = backend\n }\n}\n","import { createLogger } from '../observability/logger.js'\nimport {\n extractTraceContext,\n generateNewTraceContext,\n} from '../observability/trace-context-propagation.js'\n\nimport {\n type JobBackend,\n JobLeaseExtensionUnsupportedError,\n type JobLease,\n JobLeaseLostError,\n NonRetryableError,\n} from './job-backend.js'\nimport type { JobContext, JobDefinition } from './job-types.js'\n\n/**\n * Job runner — pulls leases from a backend and invokes the matching\n * handler. Each invocation wires up `JobContext` with:\n * - `traceId` extracted from the lease's `traceparent` header (W3C\n * Trace Context per R0.5.9), OR a fresh generated trace_id when\n * the upstream had no traceparent OR it was malformed.\n * - `attempt` from the lease.\n * - `signal` that aborts when the lease times out.\n *\n * `tick()` runs one dequeue+dispatch cycle and returns when all leases\n * have been ack'd or nack'd. `createJobWorker` (`job-worker.ts`) is the loop\n * around it, with idle polling and error backoff; `theokit start` and\n * `theokit dev` run one.\n *\n * EC-6 (trace continuity edge): when a lease has no traceparent OR a\n * malformed one, the handler still gets a valid traceId (generated) —\n * never null/undefined. The job MAY itself enqueue child jobs that\n * continue the new trace_id.\n */\n\nconst runnerLogger = createLogger({ context: { component: 'theokit:jobs:runner' } })\n\n/**\n * Run an ack or nack, fenced by the lease. A lost lease means another worker owns the job now, so\n * its outcome is not ours to write: log it and move on. Any other failure propagates.\n */\nasync function finish(\n lease: JobLease,\n outcome: 'ack' | 'nack',\n write: () => Promise<void>,\n): Promise<void> {\n try {\n await write()\n } catch (err) {\n if (!(err instanceof JobLeaseLostError)) throw err\n runnerLogger.warn('job lease lost before the outcome was written; the new holder decides it', {\n jobId: lease.jobId,\n job: lease.name,\n attempt: lease.attempts,\n outcome,\n code: err.code,\n })\n }\n}\n\nexport interface JobRunner {\n /** Run one dequeue+dispatch cycle. */\n tick(opts?: { batchSize?: number; lockSeconds?: number }): Promise<number>\n}\n\nexport function createJobRunner(\n backend: JobBackend,\n definitions: readonly JobDefinition[],\n): JobRunner {\n const byName = new Map<string, JobDefinition>()\n for (const def of definitions) {\n byName.set(def.name, def)\n }\n\n const runOne = async (lease: JobLease, lockSeconds: number): Promise<void> => {\n const def = byName.get(lease.name)\n if (!def) {\n // Job name not registered in this runner's definition set. Nack\n // permanently — the lease can't be processed by this runner.\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: `No job definition for \"${lease.name}\"`,\n nonRetryable: true,\n leaseToken: lease.leaseToken,\n }),\n )\n return\n }\n\n // Resolve trace ID from lease's traceparent, or fall back to fresh.\n let traceId: string\n if (lease.traceparent) {\n const headers = new Headers({ traceparent: lease.traceparent })\n const ctx = extractTraceContext(headers)\n traceId = ctx?.trace_id ?? generateNewTraceContext().trace_id\n } else {\n traceId = generateNewTraceContext().trace_id\n }\n\n // Optional Zod validation on input.\n let parsedInput: unknown = lease.input\n if (def.inputSchema) {\n try {\n parsedInput = def.inputSchema.parse(lease.input)\n } catch (err) {\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: `Input validation failed: ${err instanceof Error ? err.message : String(err)}`,\n nonRetryable: true,\n leaseToken: lease.leaseToken,\n }),\n )\n return\n }\n }\n\n const abortController = new AbortController()\n // Auto-abort when the lease expires. `extendLease` moves the deadline, so the timer is re-armed.\n let lockTimer: ReturnType<typeof setTimeout> | undefined\n const armLockTimer = (expiresAt: Date): void => {\n lockTimer = setTimeout(\n () => {\n abortController.abort()\n },\n Math.max(0, expiresAt.getTime() - Date.now()),\n )\n }\n armLockTimer(lease.lockExpiresAt)\n\n const jobCtx: JobContext = {\n traceId,\n input: parsedInput,\n signal: abortController.signal,\n attempt: lease.attempts,\n async extendLease(seconds = lockSeconds) {\n if (backend.extendLease === undefined || lease.leaseToken === undefined) {\n throw new JobLeaseExtensionUnsupportedError(backend.name)\n }\n try {\n const until = await backend.extendLease(lease.jobId, {\n leaseToken: lease.leaseToken,\n lockSeconds: seconds,\n })\n clearTimeout(lockTimer)\n armLockTimer(until)\n } catch (err) {\n // Another worker holds the job now: this handler must stop.\n if (err instanceof JobLeaseLostError) abortController.abort()\n throw err\n }\n },\n }\n\n let failure: unknown\n let failed = false\n try {\n await def.handler(jobCtx)\n } catch (err) {\n failed = true\n failure = err\n } finally {\n clearTimeout(lockTimer)\n }\n // The outcome is written outside the handler's try, so a failed ack is never mistaken for a\n // failed handler and nacked.\n if (!failed) {\n await finish(lease, 'ack', () => backend.ack(lease.jobId, { leaseToken: lease.leaseToken }))\n return\n }\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: failure instanceof Error ? failure.message : String(failure),\n nonRetryable: failure instanceof NonRetryableError,\n leaseToken: lease.leaseToken,\n // The definition is the source of truth: a job enqueued through the queue client was stored\n // with the backend default of 1 (usetheokit/theokit#1013).\n maxAttempts: def.maxAttempts,\n }),\n )\n }\n\n return {\n async tick(opts) {\n const lockSeconds = opts?.lockSeconds ?? 30\n const leases = await backend.dequeue({ batchSize: opts?.batchSize ?? 10, lockSeconds })\n // Process leases sequentially — caller controls concurrency via\n // batchSize and tick frequency.\n for (const lease of leases) {\n await runOne(lease, lockSeconds)\n }\n return leases.length\n },\n }\n}\n","import { createLogger } from '../observability/logger.js'\n\nimport type { JobRunner } from './job-runner.js'\n\n/**\n * The loop around `JobRunner.tick()`.\n *\n * `tick()` runs one dequeue-and-dispatch cycle and left the loop to its caller, and `theokit start`\n * never wrote one, so jobs were enqueued into a backend nothing drained (usetheokit/theokit#1010).\n * This is that loop, shared by `theokit start`, `theokit dev` and anyone running a worker process\n * of their own:\n *\n * - a tick that leased jobs is followed by another at once, so a backlog drains at full speed;\n * - an empty tick waits `pollIntervalMs` before asking again;\n * - a tick that throws (the database is down) is logged and retried with exponential backoff\n * capped at `maxErrorBackoffMs`, so an outage neither kills the process nor spins;\n * - `stop()` lets the tick in progress finish (its jobs are acked or nacked) and resolves after it.\n * A wait in progress is cut short.\n */\nexport interface JobWorkerOptions {\n /** Wait after a tick that leased nothing. Default 1000 ms. */\n pollIntervalMs?: number\n /** Leases per tick, passed to `tick()`. Default 10. */\n batchSize?: number\n /** Lease duration per job, passed to `tick()`. Default 30 s. */\n lockSeconds?: number\n /** Ceiling of the backoff after consecutive failed ticks. Default 30 000 ms. */\n maxErrorBackoffMs?: number\n}\n\nexport interface JobWorker {\n /** Start polling. A second call is a no-op. */\n start(): void\n /** Stop polling; resolves once the tick in progress, if any, has finished. */\n stop(): Promise<void>\n}\n\nconst workerLogger = createLogger({ context: { component: 'theokit:jobs:worker' } })\n\nexport function createJobWorker(runner: JobRunner, options: JobWorkerOptions = {}): JobWorker {\n const pollIntervalMs = options.pollIntervalMs ?? 1000\n const maxErrorBackoffMs = options.maxErrorBackoffMs ?? 30_000\n const tickOptions = { batchSize: options.batchSize ?? 10, lockSeconds: options.lockSeconds ?? 30 }\n\n let running = false\n let loop: Promise<void> | undefined\n let wake: (() => void) | undefined\n\n const wait = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(done, ms)\n function done(): void {\n clearTimeout(timer)\n wake = undefined\n resolve()\n }\n wake = done\n })\n\n const run = async (): Promise<void> => {\n let failures = 0\n while (running) {\n try {\n const leased = await runner.tick(tickOptions)\n failures = 0\n if (leased > 0) continue\n await wait(pollIntervalMs)\n } catch (err) {\n failures++\n const delayMs = Math.min(pollIntervalMs * 2 ** failures, maxErrorBackoffMs)\n workerLogger.error('job worker tick failed; retrying', {\n error: err instanceof Error ? err.message : String(err),\n consecutiveFailures: failures,\n retryInMs: delayMs,\n })\n await wait(delayMs)\n }\n }\n }\n\n return {\n start() {\n if (running) return\n running = true\n loop = run()\n },\n async stop() {\n running = false\n wake?.()\n await loop\n loop = undefined\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,eAAsB,0BAA0B,aAAqC;AACnF,MAAI,gBAAgB,UAAa,gBAAgB,KAAM;AAEvD,QAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAAO,gCAA8B;AACjG,MAAI,yBAAyB,EAAG;AAEhC,QAAM,EAAE,YAAY,IAAI,MAAM,OAAO,uBAA4B;AACjE,QAAM,SAAS,YAAY,MAAM,WAAW;AAC5C,MAAI,CAAC,OAAO,QAAS;AAErB,kBAAgB;AAAA,IACd,SAAS,OAAO;AAAA;AAAA;AAAA;AAAA,IAIhB,SAAS,OAAO;AAAA,IAChB,YAAY,OAAO;AAAA,IACnB,UAAU,OAAO;AAAA,EACnB,CAAC;AACH;;;AC9CA,SAAS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SAAS,OAAU;AAC7E,QAAM,WAAW,SAAS,OAAO,YAAY,MAAM,CAAC;AACpD,QAAM,UAAkC,qBAAqB,MAAM;AACnE,MAAI,YAAY,QAAW;AACzB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SACE,GAAG,QAAQ;AAAA,IAEf;AAAA,EACF;AACA,QAAM,UAAU,OAAO,MAAM;AAC7B,MAAI,SAAS,YAAY,OAAO;AAC9B,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SAAS,GAAG,QAAQ;AAAA,IACtB;AAAA,EACF;AACA,QAAM,SAAS,gBAAgB,gBAAgB,SAAS,WAAW,GAAG;AAAA,IACpE,gBAAgB,SAAS;AAAA,IACzB,WAAW,SAAS;AAAA,IACpB,aAAa,SAAS;AAAA,EACxB,CAAC;AACD,SAAO,MAAM;AACb,SAAO;AAAA,IACL;AAAA,IACA,SAAS,GAAG,QAAQ,wBAAwB,QAAQ,IAAI;AAAA,EAC1D;AACF;","names":["existsSync","resolve","existsSync","readFileSync","resolve","resolve","existsSync","readFileSync","resolve"]}
1
+ {"version":3,"sources":["../src/server/cache-bootstrap.ts","../src/server/cron/cron-runtime-node.ts","../src/cli/commands/resolve-listen-port.ts","../src/cli/commands/start/bootstrap-stages.ts","../src/cli/commands/start/cron-bootstrap.ts","../src/cli/commands/start/job-bootstrap.ts","../src/server/jobs/job-backend.ts","../src/server/jobs/job-runner.ts","../src/server/jobs/job-worker.ts"],"sourcesContent":["import type { NormalizedCacheConfig } from '../cache/engine-singleton.js'\n\n/**\n * Initialize the singleton cache engine from `theo.config.ts > cache` (#352).\n *\n * Until this existed, `initCacheEngine` had no production caller while\n * `getCacheEngine` had three — so `revalidateTag`, `updateTag` and\n * `revalidatePath`, all exported publicly, threw \"Cache engine not initialized\"\n * in every application. The subsystem was not unreachable code; it was a bridge\n * with one half published and the other half never built.\n *\n * Three states a boot legitimately reaches, each handled by a guard rather than\n * by a `catch`, because `initCacheEngine` throws on all three and absorbing the\n * throws would absorb the real double-init bug with them:\n *\n * - no `cache` key at all — the framework stays backward compatible, no engine\n * - `enabled: false` — an explicit opt-out, not an error\n * - already initialized — HMR, a second server in one process, a test booting\n * twice in one worker\n *\n * Unlike `configureStorageManagerFromConfig`, its sibling in the CLI bootstrap,\n * a malformed config is NOT\n * degraded into a warning here, and the divergence is deliberate. Warning and\n * continuing would boot an application whose `revalidateTag` still throws — the\n * exact defect this function exists to remove, restored silently and now\n * attributable to nothing.\n */\nexport async function initCacheEngineFromConfig(cacheConfig: unknown): Promise<void> {\n if (cacheConfig === undefined || cacheConfig === null) return\n\n const { initCacheEngine, isCacheEngineInitialized } = await import('../cache/engine-singleton.js')\n if (isCacheEngineInitialized()) return\n\n const { cacheSchema } = await import('../config/schemas/index.js')\n const parsed = cacheSchema.parse(cacheConfig)\n if (!parsed.enabled) return\n\n initCacheEngine({\n enabled: parsed.enabled,\n // The schema accepts `'memory'` or a caller-supplied adapter instance, which\n // it cannot type beyond `unknown` without importing the adapter contract\n // into the config layer.\n storage: parsed.storage as NormalizedCacheConfig['storage'],\n maxEntries: parsed.maxEntries,\n defaults: parsed.defaults,\n })\n}\n","import { CronExpressionParser } from 'cron-parser'\n\nimport { generateNewTraceContext } from '../observability/trace-context-propagation.js'\n\nimport type { CronLock } from './cron-lock.js'\nimport type { CronContext, CronDefinition } from './cron-types.js'\n\n/**\n * In-process cron scheduler, run by `theokit start` (and by `theokit dev --crons`).\n *\n * Algorithm:\n * - For each cron, compute `nextFireAt = cron-parser.next()`.\n * - Schedule a `setTimeout(handler, nextFireAt - now)`.\n * - After handler invocation (sync return or Promise scheduled), recompute\n * next fire from CURRENT time (drift-free vs scheduled time).\n *\n * Per-cron isolation (EC-109):\n * - Each cron's handler invocation is fire-and-forget (`void` scheduled).\n * A hanging handler does NOT block the scheduler loop nor other crons.\n * - `concurrency: 'forbid'` (default) tracks an in-flight flag per-cron;\n * subsequent ticks skip + warn while the in-flight flag is set.\n * - `concurrency: 'allow'` runs handlers concurrently — caller's responsibility.\n *\n * Several processes (replicas) each run this scheduler under `theokit start`. Without a `lock`,\n * each one fires every tick. With one, each tick asks the lock first and only the process that\n * gets `true` runs the handler (usetheokit/theokit#1016). A lock that fails skips the tick and logs\n * the error: running unguarded would repeat the side effect on every replica, which is the defect\n * the lock exists for.\n *\n * Serverless targets use platform-native triggers (T1.5 adapter translators), which fire once.\n */\n\nexport interface CronSchedulerOptions {\n /** Shared lock deciding which process runs each tick. Absent: this process runs every tick. */\n lock?: CronLock\n}\n\nexport interface CronScheduler {\n start(): void\n stop(): void\n}\n\ninterface CronJobState {\n readonly def: CronDefinition\n inFlight: boolean\n timer: NodeJS.Timeout | null\n abortController: AbortController | null\n lockToken?: number\n}\n\nexport function createCronScheduler(\n definitions: readonly CronDefinition[],\n options: CronSchedulerOptions = {},\n): CronScheduler {\n const lock = options.lock\n const candidate = lock as { acquire?: unknown } | null | undefined\n if (candidate !== undefined && typeof candidate?.acquire !== 'function') {\n throw new TypeError(\n 'createCronScheduler: `lock` must be an object with an `acquire(name, scheduledAt)` method returning Promise<boolean>.',\n )\n }\n const states: CronJobState[] = definitions.map((def) => ({\n def,\n inFlight: false,\n timer: null,\n abortController: null,\n }))\n\n let started = false\n\n /** Run the tick if the lock (when there is one) gives it to this process. */\n const fireIfLockAllows = (state: CronJobState, scheduledAt: Date): void => {\n if (lock === undefined) {\n runTick(state, scheduledAt)\n scheduleNext(state)\n return\n }\n state.timer = null\n // Schedule the next tick now: an acquire that never settles must not stop this cron.\n scheduleNext(state)\n const token = (state.lockToken = (state.lockToken ?? 0) + 1)\n const superseded = (): boolean => state.lockToken !== token || !started\n // A synchronous throw from `acquire` is treated like a rejection.\n void Promise.resolve()\n .then(() => lock.acquire(state.def.name, scheduledAt))\n .then(\n (won) => {\n if (!won) return\n if (superseded()) {\n console.warn(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()} ` +\n '— the cron lock answered after the next tick was already scheduled.',\n )\n return\n }\n runTick(state, scheduledAt)\n },\n (err: unknown) => {\n console.error(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()}: ` +\n 'the cron lock could not be acquired:',\n err instanceof Error ? err.message : err,\n )\n },\n )\n }\n\n const runTick = (state: CronJobState, scheduledAt: Date): void => {\n state.timer = null\n\n if (state.inFlight && state.def.concurrency === 'forbid') {\n console.warn(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()} ` +\n '— previous handler still running (concurrency: forbid).',\n )\n return\n }\n\n state.inFlight = true\n state.abortController = new AbortController()\n const traceCtx = generateNewTraceContext()\n const ctx: CronContext = {\n traceId: traceCtx.trace_id,\n scheduledAt,\n signal: state.abortController.signal,\n }\n\n // Fire-and-forget: EC-109 — never await here so a hanging handler\n // can't block the scheduler loop or other crons.\n void Promise.resolve()\n .then(() => state.def.handler(ctx))\n .catch((err: unknown) => {\n console.error(\n `[theokit:cron] \"${state.def.name}\" handler error:`,\n err instanceof Error ? err.message : err,\n )\n })\n .finally(() => {\n state.inFlight = false\n })\n }\n\n const scheduleNext = (state: CronJobState): void => {\n if (!started) return\n const interval = CronExpressionParser.parse(state.def.schedule, {\n tz: 'UTC',\n currentDate: new Date(),\n })\n const next = interval.next().toDate()\n const delayMs = Math.max(0, next.getTime() - Date.now())\n state.timer = setTimeout(() => {\n fireIfLockAllows(state, next)\n }, delayMs)\n // setTimeout returns a Timeout object; in Node, .unref() is available but\n // we DO want this to keep the event loop alive in dev — explicit no-unref.\n }\n\n return {\n start(): void {\n if (started) return\n started = true\n for (const state of states) {\n scheduleNext(state)\n }\n },\n stop(): void {\n started = false\n for (const state of states) {\n if (state.timer) {\n clearTimeout(state.timer)\n state.timer = null\n }\n state.abortController?.abort()\n state.abortController = null\n }\n },\n }\n}\n","/**\n * The port a command listens on: an explicit flag, then `PORT`, then `config.port`.\n *\n * The flag is a person typing now, the environment is where the process was put (`PORT` is what\n * every container platform injects, usetheokit/theokit#402), and the config is the project's default.\n * `theokit start` and `theokit dev` both resolve it here, so they cannot drift again\n * (usetheokit/theokit#1134: `dev` ignored `PORT` and listened on `config.port`).\n *\n * A `PORT` that is not an integer is ignored rather than turned into `NaN`.\n */\nexport function resolveListenPort(\n flag: number | undefined,\n env: NodeJS.ProcessEnv,\n configPort: number,\n): number {\n if (flag !== undefined) return flag\n const fromEnv = Number.parseInt(env.PORT ?? '', 10)\n return Number.isInteger(fromEnv) ? fromEnv : configPort\n}\n","/**\n * Bootstrap stages extracted from `start.ts` per T4.2 (architecture-cleanup, ADR-0017).\n *\n * The full goal of T4.2 is a ≤30-LOC `startCommand` spine + 6-8 stage files. This\n * file ships the first batch: the configure-from-config bootstrap helpers + the\n * SSR entry resolver. They are stand-alone, side-effect-free at module load, and\n * already individually testable.\n *\n * Remaining stages (request-handler extraction, graceful-shutdown extraction,\n * signal-handlers extraction) are deferred to a follow-up sprint — see plan\n * ks.\n */\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\n\ninterface SdkAgentRegistry {\n configure?: (opts: { maxAgents?: number; idleTimeoutMs?: number }) => void\n}\ninterface SdkModule {\n Agent?: { registry?: SdkAgentRegistry }\n}\n\n/**\n * Configure SDK's Agent.registry from `theo.config.ts > agents.registry`.\n * Lazy at boot; EC-3 sync flag flip prevents race under concurrent boot.\n * Silent no-op when registry config is absent or SDK is uninstalled.\n */\nexport async function configureAgentRegistryFromConfig(\n registryConfig: { maxAgents: number; idleTimeoutMs: number } | undefined,\n): Promise<void> {\n if (registryConfig === undefined) return\n try {\n const sdk = (await import('@theokit/sdk').catch(() => null)) as SdkModule | null\n const sdkConfigure = sdk?.Agent?.registry?.configure\n if (sdkConfigure === undefined) return\n const { configureAgentRegistryOnce } =\n await import('../../../server/agent/configure-agent-registry.js')\n configureAgentRegistryOnce(\n {\n configure: (opts) => {\n sdkConfigure(opts)\n },\n },\n registryConfig,\n )\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.agent_registry_skip', {\n event: 'bootstrap.agent_registry_skip',\n message: msg,\n })\n }\n}\n\n/**\n * Configure the StorageManager from `theo.config.ts > storage` (ADR-0007).\n * Manager enforces configure-once internally (D3); this helper bridges the\n * config to the singleton with actionable error handling.\n */\nexport async function configureStorageManagerFromConfig(storageConfig: unknown): Promise<void> {\n if (storageConfig === undefined || storageConfig === null) return\n try {\n const { getStorageManager } = await import('../../../server/storage/storage-manager.js')\n const { storageSchema } = await import('../../../config/schema.js')\n // Re-validate at boot so a malformed config from a non-Zod source\n // (test fixtures, dynamic configs) surfaces a clear error early.\n const parsed = storageSchema.parse(storageConfig)\n getStorageManager().configure(parsed)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.storage_skip', {\n event: 'bootstrap.storage_skip',\n message: msg,\n })\n }\n}\n\nconst SSR_EXTENSIONS = ['.mjs', '.js'] as const\n\n/**\n * Resolve the SSR entry-server module path. tsup may emit `.mjs` or `.js`\n * depending on output format. Try `.mjs` first (modern default) then fall\n * back to `.js`. Returns null when neither exists — SSR stays disabled.\n *\n * Exported so unit tests can pin the resolution order without booting the\n * full CLI.\n */\nexport function resolveSsrEntry(distDir: string): string | null {\n for (const ext of SSR_EXTENSIONS) {\n const path = resolve(distDir, `server/entry-server${ext}`)\n\n if (existsSync(path)) return path\n }\n return null\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { CronManifest } from '../../../server/cron/cron-manifest.js'\nimport type { CronDefinition } from '../../../server/cron/cron-types.js'\n\n/**\n * Reads the cron manifest `theokit build` writes and re-loads each handler so\n * `theokit start` can drive the in-process scheduler.\n *\n * The build prints \"Cron → in-process scheduler (theokit start)\" for\n * `target: node`, but nothing on the serving side ever read `dist/crons.json`\n * — the crons were declared, validated, written, and then never ran\n * (theokit#324).\n *\n * The manifest names WHICH files hold a cron; the definition itself is taken\n * from the module, which is the source `defineCron` produced. Trusting the\n * manifest's copy of the schedule would let a stale build silently run a cron\n * on the wrong cadence.\n */\nexport async function loadCronDefinitions(\n manifestPath: string,\n projectRoot: string,\n loadModule: (filePath: string) => unknown,\n): Promise<CronDefinition[]> {\n if (!existsSync(manifestPath)) return []\n\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as CronManifest\n return loadCronModules(\n manifest.crons.map((entry) => resolve(projectRoot, entry.filePath)),\n loadModule,\n )\n}\n\n/**\n * Import each file and take its `defineCron` default export, refusing a file without one. Shared\n * with `theokit dev --crons`, which lists the files itself and loads them through Vite.\n */\nexport async function loadCronModules(\n filePaths: readonly string[],\n loadModule: (filePath: string) => unknown,\n): Promise<CronDefinition[]> {\n const definitions: CronDefinition[] = []\n for (const filePath of filePaths) {\n const mod = (await loadModule(filePath)) as { default?: unknown }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `\"${filePath}\" is listed as a cron but has no valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`. ' +\n 'Re-run `theokit build` if the file changed since the last build.',\n )\n }\n definitions.push(exported)\n }\n return definitions\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.schedule === 'string' &&\n typeof candidate.handler === 'function'\n )\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../../../config/schema.js'\nimport { jobBackendFromConfig } from '../../../server/jobs/job-backend-from-config.js'\nimport type { JobBackend } from '../../../server/jobs/job-backend.js'\nimport type { JobManifest } from '../../../server/jobs/job-manifest.js'\nimport { createJobRunner } from '../../../server/jobs/job-runner.js'\nimport type { JobDefinition } from '../../../server/jobs/job-types.js'\nimport { createJobWorker, type JobWorker } from '../../../server/jobs/job-worker.js'\n\n/**\n * Reads the job manifest `theokit build` writes and re-loads each definition, the jobs twin of\n * `loadCronDefinitions`. The manifest names WHICH files hold a job; the definition comes from the\n * module, so a stale build cannot run a handler the source no longer has.\n *\n * Before usetheokit/theokit#1010 nothing on the serving side read `jobs.json`.\n */\nexport async function loadJobDefinitions(\n manifestPath: string,\n projectRoot: string,\n loadModule: (filePath: string) => unknown,\n): Promise<JobDefinition[]> {\n if (!existsSync(manifestPath)) return []\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as JobManifest\n return loadJobModules(\n manifest.jobs.map((entry) => resolve(projectRoot, entry.filePath)),\n loadModule,\n )\n}\n\n/** Import each file and take its `defineJob` default export, refusing a file without one. */\nexport async function loadJobModules(\n filePaths: readonly string[],\n loadModule: (filePath: string) => unknown,\n): Promise<JobDefinition[]> {\n const definitions: JobDefinition[] = []\n for (const filePath of filePaths) {\n const mod = (await loadModule(filePath)) as { default?: unknown }\n if (!isJobDefinition(mod.default)) {\n throw new Error(\n `\"${filePath}\" is listed as a job but has no valid default export. ` +\n \"Expected `export default defineJob(name, { handler })` from 'theokit/server/jobs'. \" +\n 'Re-run `theokit build` if the file changed since the last build.',\n )\n }\n definitions.push(mod.default)\n }\n return definitions\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.handler === 'function' &&\n typeof candidate.maxAttempts === 'number'\n )\n}\n\n/**\n * `migrate()` of the configured `jobs.backend` rejected at boot. The process must not serve: every\n * route would answer 2xx while the outbox dropped each job it enqueued (usetheokit/theokit#1072).\n */\nclass JobBackendSetupError extends Error {\n readonly code = 'JOB_BACKEND_SETUP_FAILED'\n readonly backend: string\n constructor(backend: string, cause: unknown) {\n const reason = describeCause(cause)\n super(\n `jobs.backend (${backend}) could not create its storage at boot: ${reason}. ` +\n 'Jobs enqueued now would be lost, so the server did not start. Check that the database ' +\n 'in theo.config.ts is reachable and that its user may create tables.',\n { cause },\n )\n this.name = 'JobBackendSetupError'\n this.backend = backend\n }\n}\n\n/**\n * The text of a setup failure. `pg` connecting to `localhost` tries every address it resolves to\n * and rejects with an `AggregateError` whose own message is empty, which printed \"could not create\n * its storage at boot: .\" on a CI runner. The attempts are listed instead, and an error without a\n * message falls back to its code.\n */\nfunction describeCause(cause: unknown): string {\n if (cause instanceof AggregateError && cause.message === '') {\n return cause.errors.map(describeCause).join('; ')\n }\n if (cause instanceof Error) {\n const code = (cause as { code?: unknown }).code\n if (cause.message !== '') return cause.message\n return typeof code === 'string' ? code : cause.name\n }\n return String(cause)\n}\n\n/**\n * Run `migrate()` on the configured `jobs.backend`, when it has one, before anything can enqueue\n * or dequeue. `theokit start` and `theokit dev` call it at boot whether or not this process runs\n * the worker: a web-only process enqueues into the same table.\n *\n * It used to be the app's job, and nothing told the app: the README configured a\n * `PostgresJobBackend` without the call, and a fresh database answered 2xx while every job was\n * dropped. Calling it from `theo.config.ts` instead made `theokit build` need a database.\n */\nexport async function prepareJobBackend(config: Pick<TheoConfig, 'jobs'>): Promise<void> {\n const backend = jobBackendFromConfig(config)\n if (backend?.migrate === undefined) return\n try {\n await backend.migrate()\n } catch (err) {\n throw new JobBackendSetupError(backend.name, err)\n }\n}\n\nexport interface JobWorkerBootstrap {\n /** The running worker, or `undefined` when none was started (see `summary`). */\n readonly worker: JobWorker | undefined\n /** One line for the boot log saying what happens to the declared jobs, or `undefined` if none. */\n readonly summary: string | undefined\n}\n\n/**\n * Start the in-process job worker when there is something to run and somewhere to run it from.\n *\n * - no declared jobs: no worker. A worker with no definitions would lease other processes' jobs\n * and fail them as \"No job definition\".\n * - jobs but no `jobs.backend`: no worker, and the summary says the jobs cannot run.\n * - `jobs.worker.enabled: false`: no worker, said in the summary, so a web-only process is visibly\n * one.\n */\nexport function startJobWorker(\n config: Pick<TheoConfig, 'jobs'>,\n definitions: readonly JobDefinition[],\n): JobWorkerBootstrap {\n if (definitions.length === 0) return { worker: undefined, summary: undefined }\n const declared = `Jobs: ${String(definitions.length)} declared`\n const backend: JobBackend | undefined = jobBackendFromConfig(config)\n if (backend === undefined) {\n return {\n worker: undefined,\n summary:\n `${declared}, NOT running: theo.config.ts sets no jobs.backend, so ctx.queue is absent ` +\n 'and nothing can enqueue or run them.',\n }\n }\n const options = config.jobs?.worker\n if (options?.enabled === false) {\n return {\n worker: undefined,\n summary: `${declared}, worker disabled (jobs.worker.enabled: false); another process must run them.`,\n }\n }\n const worker = createJobWorker(createJobRunner(backend, definitions), {\n pollIntervalMs: options?.pollIntervalMs,\n batchSize: options?.batchSize,\n lockSeconds: options?.lockSeconds,\n })\n worker.start()\n return {\n worker,\n summary: `${declared}, worker polling the ${backend.name} backend in-process`,\n }\n}\n","/**\n * Neutral `JobBackend` interface.\n *\n * Implementations ship in core:\n * - `InMemoryJobBackend` (T2.2) — dev + tests; no external deps\n * - `PostgresJobBackend` (T3.1) — production; requires `pg` peer dep\n *\n * Community packages (`@theokit/jobs-redis`, `@theokit/jobs-sqs`, etc.)\n * implement this same interface to plug in alternate substrates without\n * modifying TheoKit core.\n */\n\nimport type { PoolLike } from '../storage/storage-types.js'\n\nexport interface JobEnqueueInput {\n /** The job name (matches a `defineJob` declaration). */\n name: string\n /** Validated input (already passed through Zod or equivalent at the queue-client layer). */\n input: unknown\n /**\n * Optional idempotency key, scoped to `name`: a second enqueue of the same (name, key) returns the\n * first job's id instead of creating a job, including when the two calls race. The window is\n * backend-specific: `PostgresJobBackend` holds the key while the row exists (until `ack`, or for\n * good once the job has failed); `InMemoryJobBackend` holds it for 60 seconds.\n */\n idempotencyKey?: string\n /** Optional delay before the job becomes available for dispatch. */\n delaySeconds?: number\n /** W3C Trace Context propagation per ADR/R0.5.9. */\n traceparent?: string\n /**\n * Maximum dispatch attempts stored with the job (default 1). The queue client has no access to\n * the job definitions and leaves it unset; `createJobRunner` passes the definition's\n * `maxAttempts` to `nack`, which takes precedence over this stored value.\n */\n maxAttempts?: number\n}\n\nexport interface JobLease {\n readonly jobId: string\n readonly name: string\n readonly input: unknown\n readonly attempts: number\n readonly maxAttempts: number\n readonly traceparent?: string\n readonly lockExpiresAt: Date\n /**\n * Identifies THIS lease. Pass it back to `ack`/`nack` so a worker whose lease expired, and was\n * handed to another worker, cannot finish the job on the new holder's behalf. Both first-party\n * backends set it; optional so a backend written against the earlier contract still compiles.\n */\n readonly leaseToken?: string\n}\n\n/** What `nack` is told about the failure. */\nexport interface JobNackOptions extends JobLeaseFence {\n /** The failure message. */\n error: string\n /** The handler threw `NonRetryableError`: no retry, whatever the attempts left. */\n nonRetryable?: boolean\n /**\n * The retry ceiling from the job's definition. Takes precedence over the value stored at\n * enqueue, which is 1 for every job enqueued through the queue client.\n */\n maxAttempts?: number\n}\n\n/** Fences `ack`/`nack` to the lease that is finishing the job. */\nexport interface JobLeaseFence {\n /** The `leaseToken` of the `JobLease` being finished. Omitted, the call is not fenced. */\n leaseToken?: string\n}\n\nexport interface JobBackend {\n /** Human-readable name for logging (e.g., \"memory\", \"postgres\"). */\n readonly name: string\n\n /** Persist a job for later dispatch. Returns the generated jobId. */\n enqueue(input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /** Worker loop polls for the next available leases. */\n dequeue(opts: { batchSize?: number; lockSeconds?: number }): Promise<JobLease[]>\n\n /**\n * Mark a job complete (success). With `leaseToken`, rejects with `JobLeaseLostError` and leaves\n * the job alone when that lease no longer holds it.\n */\n ack(jobId: string, fence?: JobLeaseFence): Promise<void>\n\n /**\n * Mark a job failed; backend decides retry vs DLQ via attempts. With `leaseToken`, rejects with\n * `JobLeaseLostError` and leaves the job alone when that lease no longer holds it.\n */\n nack(jobId: string, opts: JobNackOptions): Promise<void>\n\n /**\n * Optional: keep a lease for `lockSeconds` more, counted from now, and return the new deadline.\n * A handler that is still making progress calls it (through `ctx.extendLease`) so a job that may\n * run for a long time does not need a long lock for every job. Rejects with `JobLeaseLostError`\n * (`operation: 'extend'`) when `leaseToken` no longer holds the job: the lease expired and was\n * handed on, or the job is gone (usetheokit/theokit#1132). A backend that leaves it out cannot\n * have its leases extended, and `ctx.extendLease` says so.\n */\n extendLease?(jobId: string, opts: { leaseToken: string; lockSeconds: number }): Promise<Date>\n\n /**\n * Optional: persist a job through `client`, a connection inside a transaction the caller opened,\n * so the job commits or rolls back with the caller's writes (usetheokit/theokit#1077). Only a\n * backend whose jobs live in the caller's database can offer it; `ctx.queue.enqueueInTransaction`\n * refuses a backend without it rather than enqueueing outside the transaction.\n */\n enqueueInTransaction?(client: PoolLike, input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /**\n * Optional: remove the job `(name, idempotencyKey)` through `client`, a connection inside the\n * caller's transaction, while no worker ever leased it. Resolves `true` when it removed one and\n * `false` when there was none or a worker has leased it (even with an expired lease) or it\n * failed, because a run may be going on for it (usetheokit/theokit#2118). A backend whose jobs\n * live elsewhere leaves it out, as with `enqueueInTransaction`.\n */\n cancelInTransaction?(\n client: PoolLike,\n input: { name: string; idempotencyKey: string },\n ): Promise<boolean>\n\n /**\n * Optional: resolve when the backend's store answers, reject when it does not. `GET /__theo/ready`\n * calls it under `theokit start` and `theokit dev`, so an unreachable job store answers 503\n * (usetheokit/theokit#1071). A backend with nothing remote to reach leaves it out.\n */\n ping?(): Promise<void>\n\n /**\n * Optional: create or upgrade whatever storage the backend needs (a table, an index). Must be\n * idempotent and safe to run from several processes at once. `theokit start` and `theokit dev`\n * call it once at boot, before serving a request or starting the worker, and refuse to boot when\n * it rejects (usetheokit/theokit#1072). A backend that needs no setup leaves it out.\n */\n migrate?(): Promise<void>\n\n /**\n * Optional: return the existing jobId if `key` was enqueued within `ttlSeconds`. Pass `name` to\n * scope the lookup to one job type, as `enqueue` deduplicates on (name, key); without it, a key\n * shared by two job types may return either job.\n */\n idempotency?(key: string, ttlSeconds: number, name?: string): Promise<{ jobId: string } | null>\n}\n\n/**\n * Thrown from a job handler to opt out of retry policy. The runner nacks with\n * `nonRetryable: true` and the backend never retries the job: `PostgresJobBackend`\n * keeps it as failed with the error, `InMemoryJobBackend` drops it with a warning.\n */\nexport class NonRetryableError extends Error {\n readonly code = 'NON_RETRYABLE'\n constructor(message: string) {\n super(message)\n this.name = 'NonRetryableError'\n }\n}\n\n/**\n * `ack`/`nack` was called with a lease token that no longer holds the job: the lease expired and\n * another worker leased the job again (or the job is gone). The job is left untouched, because the\n * current holder owns its outcome. The runner logs it and moves on; a direct caller decides.\n */\nexport class JobLeaseLostError extends Error {\n readonly code = 'JOB_LEASE_LOST'\n readonly jobId: string\n readonly operation: 'ack' | 'nack' | 'extend'\n constructor(jobId: string, operation: 'ack' | 'nack' | 'extend') {\n super(\n `Cannot ${operation} job \"${jobId}\": its lease expired and another worker holds it now, ` +\n 'or the job no longer exists. The current holder decides its outcome.',\n )\n this.name = 'JobLeaseLostError'\n this.jobId = jobId\n this.operation = operation\n }\n}\n\n/**\n * `ctx.extendLease` was called on a job whose backend has no `extendLease`. The lease keeps its\n * original deadline and `ctx.signal` aborts when it passes.\n */\nexport class JobLeaseExtensionUnsupportedError extends Error {\n readonly code = 'JOB_LEASE_EXTENSION_UNSUPPORTED'\n readonly backend: string\n constructor(backend: string) {\n super(\n `The \"${backend}\" job backend cannot extend a lease. Give the worker a lockSeconds longer ` +\n 'than the longest job, or use a backend that implements extendLease.',\n )\n this.name = 'JobLeaseExtensionUnsupportedError'\n this.backend = backend\n }\n}\n","import { createLogger } from '../observability/logger.js'\nimport {\n extractTraceContext,\n generateNewTraceContext,\n} from '../observability/trace-context-propagation.js'\n\nimport {\n type JobBackend,\n JobLeaseExtensionUnsupportedError,\n type JobLease,\n JobLeaseLostError,\n NonRetryableError,\n} from './job-backend.js'\nimport type { JobContext, JobDefinition } from './job-types.js'\n\n/**\n * Job runner — pulls leases from a backend and invokes the matching\n * handler. Each invocation wires up `JobContext` with:\n * - `traceId` extracted from the lease's `traceparent` header (W3C\n * Trace Context per R0.5.9), OR a fresh generated trace_id when\n * the upstream had no traceparent OR it was malformed.\n * - `attempt` from the lease.\n * - `signal` that aborts when the lease times out.\n *\n * `tick()` runs one dequeue+dispatch cycle and returns when all leases\n * have been ack'd or nack'd. `createJobWorker` (`job-worker.ts`) is the loop\n * around it, with idle polling and error backoff; `theokit start` and\n * `theokit dev` run one.\n *\n * EC-6 (trace continuity edge): when a lease has no traceparent OR a\n * malformed one, the handler still gets a valid traceId (generated) —\n * never null/undefined. The job MAY itself enqueue child jobs that\n * continue the new trace_id.\n */\n\nconst runnerLogger = createLogger({ context: { component: 'theokit:jobs:runner' } })\n\n/**\n * Run an ack or nack, fenced by the lease. A lost lease means another worker owns the job now, so\n * its outcome is not ours to write: log it and move on. Any other failure propagates.\n */\nasync function finish(\n lease: JobLease,\n outcome: 'ack' | 'nack',\n write: () => Promise<void>,\n): Promise<void> {\n try {\n await write()\n } catch (err) {\n if (!(err instanceof JobLeaseLostError)) throw err\n runnerLogger.warn('job lease lost before the outcome was written; the new holder decides it', {\n jobId: lease.jobId,\n job: lease.name,\n attempt: lease.attempts,\n outcome,\n code: err.code,\n })\n }\n}\n\nexport interface JobRunner {\n /** Run one dequeue+dispatch cycle. */\n tick(opts?: { batchSize?: number; lockSeconds?: number }): Promise<number>\n}\n\nexport function createJobRunner(\n backend: JobBackend,\n definitions: readonly JobDefinition[],\n): JobRunner {\n const byName = new Map<string, JobDefinition>()\n for (const def of definitions) {\n byName.set(def.name, def)\n }\n\n const runOne = async (lease: JobLease, lockSeconds: number): Promise<void> => {\n const def = byName.get(lease.name)\n if (!def) {\n // Job name not registered in this runner's definition set. Nack\n // permanently — the lease can't be processed by this runner.\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: `No job definition for \"${lease.name}\"`,\n nonRetryable: true,\n leaseToken: lease.leaseToken,\n }),\n )\n return\n }\n\n // Resolve trace ID from lease's traceparent, or fall back to fresh.\n let traceId: string\n if (lease.traceparent) {\n const headers = new Headers({ traceparent: lease.traceparent })\n const ctx = extractTraceContext(headers)\n traceId = ctx?.trace_id ?? generateNewTraceContext().trace_id\n } else {\n traceId = generateNewTraceContext().trace_id\n }\n\n // Optional Zod validation on input.\n let parsedInput: unknown = lease.input\n if (def.inputSchema) {\n try {\n parsedInput = def.inputSchema.parse(lease.input)\n } catch (err) {\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: `Input validation failed: ${err instanceof Error ? err.message : String(err)}`,\n nonRetryable: true,\n leaseToken: lease.leaseToken,\n }),\n )\n return\n }\n }\n\n const abortController = new AbortController()\n // Auto-abort when the lease expires. `extendLease` moves the deadline, so the timer is re-armed.\n let lockTimer: ReturnType<typeof setTimeout> | undefined\n const armLockTimer = (expiresAt: Date): void => {\n lockTimer = setTimeout(\n () => {\n abortController.abort()\n },\n Math.max(0, expiresAt.getTime() - Date.now()),\n )\n }\n armLockTimer(lease.lockExpiresAt)\n\n const jobCtx: JobContext = {\n traceId,\n input: parsedInput,\n signal: abortController.signal,\n attempt: lease.attempts,\n async extendLease(seconds = lockSeconds) {\n if (backend.extendLease === undefined || lease.leaseToken === undefined) {\n throw new JobLeaseExtensionUnsupportedError(backend.name)\n }\n try {\n const until = await backend.extendLease(lease.jobId, {\n leaseToken: lease.leaseToken,\n lockSeconds: seconds,\n })\n clearTimeout(lockTimer)\n armLockTimer(until)\n } catch (err) {\n // Another worker holds the job now: this handler must stop.\n if (err instanceof JobLeaseLostError) abortController.abort()\n throw err\n }\n },\n }\n\n let failure: unknown\n let failed = false\n try {\n await def.handler(jobCtx)\n } catch (err) {\n failed = true\n failure = err\n } finally {\n clearTimeout(lockTimer)\n }\n // The outcome is written outside the handler's try, so a failed ack is never mistaken for a\n // failed handler and nacked.\n if (!failed) {\n await finish(lease, 'ack', () => backend.ack(lease.jobId, { leaseToken: lease.leaseToken }))\n return\n }\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: failure instanceof Error ? failure.message : String(failure),\n nonRetryable: failure instanceof NonRetryableError,\n leaseToken: lease.leaseToken,\n // The definition is the source of truth: a job enqueued through the queue client was stored\n // with the backend default of 1 (usetheokit/theokit#1013).\n maxAttempts: def.maxAttempts,\n }),\n )\n }\n\n return {\n async tick(opts) {\n const lockSeconds = opts?.lockSeconds ?? 30\n const leases = await backend.dequeue({ batchSize: opts?.batchSize ?? 10, lockSeconds })\n // Process leases sequentially — caller controls concurrency via\n // batchSize and tick frequency.\n for (const lease of leases) {\n await runOne(lease, lockSeconds)\n }\n return leases.length\n },\n }\n}\n","import { createLogger } from '../observability/logger.js'\n\nimport type { JobRunner } from './job-runner.js'\n\n/**\n * The loop around `JobRunner.tick()`.\n *\n * `tick()` runs one dequeue-and-dispatch cycle and left the loop to its caller, and `theokit start`\n * never wrote one, so jobs were enqueued into a backend nothing drained (usetheokit/theokit#1010).\n * This is that loop, shared by `theokit start`, `theokit dev` and anyone running a worker process\n * of their own:\n *\n * - a tick that leased jobs is followed by another at once, so a backlog drains at full speed;\n * - an empty tick waits `pollIntervalMs` before asking again;\n * - a tick that throws (the database is down) is logged and retried with exponential backoff\n * capped at `maxErrorBackoffMs`, so an outage neither kills the process nor spins;\n * - `stop()` lets the tick in progress finish (its jobs are acked or nacked) and resolves after it.\n * A wait in progress is cut short.\n */\nexport interface JobWorkerOptions {\n /** Wait after a tick that leased nothing. Default 1000 ms. */\n pollIntervalMs?: number\n /** Leases per tick, passed to `tick()`. Default 10. */\n batchSize?: number\n /** Lease duration per job, passed to `tick()`. Default 30 s. */\n lockSeconds?: number\n /** Ceiling of the backoff after consecutive failed ticks. Default 30 000 ms. */\n maxErrorBackoffMs?: number\n}\n\nexport interface JobWorker {\n /** Start polling. A second call is a no-op. */\n start(): void\n /** Stop polling; resolves once the tick in progress, if any, has finished. */\n stop(): Promise<void>\n}\n\nconst workerLogger = createLogger({ context: { component: 'theokit:jobs:worker' } })\n\nexport function createJobWorker(runner: JobRunner, options: JobWorkerOptions = {}): JobWorker {\n const pollIntervalMs = options.pollIntervalMs ?? 1000\n const maxErrorBackoffMs = options.maxErrorBackoffMs ?? 30_000\n const tickOptions = { batchSize: options.batchSize ?? 10, lockSeconds: options.lockSeconds ?? 30 }\n\n let running = false\n let loop: Promise<void> | undefined\n let wake: (() => void) | undefined\n\n const wait = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(done, ms)\n function done(): void {\n clearTimeout(timer)\n wake = undefined\n resolve()\n }\n wake = done\n })\n\n const run = async (): Promise<void> => {\n let failures = 0\n while (running) {\n try {\n const leased = await runner.tick(tickOptions)\n failures = 0\n if (leased > 0) continue\n await wait(pollIntervalMs)\n } catch (err) {\n failures++\n const delayMs = Math.min(pollIntervalMs * 2 ** failures, maxErrorBackoffMs)\n workerLogger.error('job worker tick failed; retrying', {\n error: err instanceof Error ? err.message : String(err),\n consecutiveFailures: failures,\n retryInMs: delayMs,\n })\n await wait(delayMs)\n }\n }\n }\n\n return {\n start() {\n if (running) return\n running = true\n loop = run()\n },\n async stop() {\n running = false\n wake?.()\n await loop\n loop = undefined\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,eAAsB,0BAA0B,aAAqC;AACnF,MAAI,gBAAgB,UAAa,gBAAgB,KAAM;AAEvD,QAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAAO,gCAA8B;AACjG,MAAI,yBAAyB,EAAG;AAEhC,QAAM,EAAE,YAAY,IAAI,MAAM,OAAO,uBAA4B;AACjE,QAAM,SAAS,YAAY,MAAM,WAAW;AAC5C,MAAI,CAAC,OAAO,QAAS;AAErB,kBAAgB;AAAA,IACd,SAAS,OAAO;AAAA;AAAA;AAAA;AAAA,IAIhB,SAAS,OAAO;AAAA,IAChB,YAAY,OAAO;AAAA,IACnB,UAAU,OAAO;AAAA,EACnB,CAAC;AACH;;;AC9CA,SAAS,4BAA4B;AAkD9B,SAAS,oBACd,aACA,UAAgC,CAAC,GAClB;AACf,QAAM,OAAO,QAAQ;AACrB,QAAM,YAAY;AAClB,MAAI,cAAc,UAAa,OAAO,WAAW,YAAY,YAAY;AACvE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,SAAyB,YAAY,IAAI,CAAC,SAAS;AAAA,IACvD;AAAA,IACA,UAAU;AAAA,IACV,OA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,MACL,QAAQ;AAAA,MACR,SAAS,GAAG,QAAQ;AAAA,IACtB;AAAA,EACF;AACA,QAAM,SAAS,gBAAgB,gBAAgB,SAAS,WAAW,GAAG;AAAA,IACpE,gBAAgB,SAAS;AAAA,IACzB,WAAW,SAAS;AAAA,IACpB,aAAa,SAAS;AAAA,EACxB,CAAC;AACD,SAAO,MAAM;AACb,SAAO;AAAA,IACL;AAAA,IACA,SAAS,GAAG,QAAQ,wBAAwB,QAAQ,IAAI;AAAA,EAC1D;AACF;","names":["existsSync","resolve","existsSync","readFileSync","resolve","resolve","existsSync","readFileSync","resolve"]}
@@ -26,7 +26,7 @@ import {
26
26
  parseAgentRequestBody,
27
27
  readAgentPolicy,
28
28
  subjectFromContext
29
- } from "./chunk-MSSUMKFR.js";
29
+ } from "./chunk-BSH3OSJ5.js";
30
30
  import {
31
31
  getApprovalRegistry
32
32
  } from "./chunk-4JRXZTVQ.js";
@@ -954,4 +954,4 @@ export {
954
954
  applyNonceToInlineScripts,
955
955
  setupSsrDevMiddleware
956
956
  };
957
- //# sourceMappingURL=chunk-W55B6BRC.js.map
957
+ //# sourceMappingURL=chunk-2QOWKVJ6.js.map
@@ -1,9 +1,6 @@
1
1
  import {
2
2
  writeAtomic
3
- } from "./chunk-LXV5IEBB.js";
4
- import {
5
- generateNewTraceContext
6
- } from "./chunk-UMNXCU3K.js";
3
+ } from "./chunk-WHQN35LA.js";
7
4
  import {
8
5
  importUserModule
9
6
  } from "./chunk-AHYOVVJ7.js";
@@ -13,6 +10,9 @@ import {
13
10
  import {
14
11
  compareByCodeUnit
15
12
  } from "./chunk-ZWN3AODA.js";
13
+ import {
14
+ generateNewTraceContext
15
+ } from "./chunk-UMNXCU3K.js";
16
16
 
17
17
  // src/server/cron/cron-validate.ts
18
18
  import { CronExpressionParser } from "cron-parser";
@@ -436,4 +436,4 @@ export {
436
436
  scanCrons,
437
437
  scanCronDirs
438
438
  };
439
- //# sourceMappingURL=chunk-2Z3GHQ64.js.map
439
+ //# sourceMappingURL=chunk-5EZJNG6M.js.map
@@ -442,8 +442,8 @@ async function handleSubscribe(request, platform, config) {
442
442
  headers: { "content-type": "text/plain; charset=utf-8" }
443
443
  });
444
444
  }
445
- async function handleChannelWebhook(request, urlPath, config) {
446
- const parsed = parseChannelPath(urlPath);
445
+ async function handleChannelWebhook(request, target, config) {
446
+ const parsed = typeof target === "string" ? parseChannelPath(target) : target;
447
447
  if (parsed === null) {
448
448
  return jsonError(
449
449
  400,
@@ -542,4 +542,4 @@ export {
542
542
  streamAgentTurnInProcess,
543
543
  InProcessApprovalRequiredError
544
544
  };
545
- //# sourceMappingURL=chunk-JUJI3FZM.js.map
545
+ //# sourceMappingURL=chunk-6NIKAL47.js.map