@warlock.js/devtools 5.55.0 → 5.57.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 (240) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +26 -13
  3. package/cjs/ai-source-DTpxumMA.cjs +381 -0
  4. package/cjs/ai-source-DTpxumMA.cjs.map +1 -0
  5. package/cjs/auth-DzU0gHDG.cjs +1655 -0
  6. package/cjs/auth-DzU0gHDG.cjs.map +1 -0
  7. package/cjs/boot-Dy5OqgTM.cjs +138 -0
  8. package/cjs/boot-Dy5OqgTM.cjs.map +1 -0
  9. package/cjs/capture-CqIiaznN.cjs +1342 -0
  10. package/cjs/capture-CqIiaznN.cjs.map +1 -0
  11. package/cjs/cascade-store-pHjKeSFm.cjs +863 -0
  12. package/cjs/cascade-store-pHjKeSFm.cjs.map +1 -0
  13. package/cjs/collector-CJbQbzzK.cjs +271 -0
  14. package/cjs/collector-CJbQbzzK.cjs.map +1 -0
  15. package/cjs/contracts-CVmplkNb.cjs +112 -0
  16. package/cjs/contracts-CVmplkNb.cjs.map +1 -0
  17. package/cjs/current-request-id-BoJJb3y7.cjs +37 -0
  18. package/cjs/current-request-id-BoJJb3y7.cjs.map +1 -0
  19. package/cjs/errors-CyZp5yS-.cjs +177 -0
  20. package/cjs/errors-CyZp5yS-.cjs.map +1 -0
  21. package/cjs/histogram-BaI-PnCv.cjs +102 -0
  22. package/cjs/histogram-BaI-PnCv.cjs.map +1 -0
  23. package/cjs/http-DCfXQvw-.cjs +870 -0
  24. package/cjs/http-DCfXQvw-.cjs.map +1 -0
  25. package/cjs/index.cjs +2 -1
  26. package/cjs/insights-BKtqxdnP.cjs +811 -0
  27. package/cjs/insights-BKtqxdnP.cjs.map +1 -0
  28. package/cjs/ip-DbNhPOzi.cjs +153 -0
  29. package/cjs/ip-DbNhPOzi.cjs.map +1 -0
  30. package/cjs/migrations-w7GMsrQw.cjs +297 -0
  31. package/cjs/migrations-w7GMsrQw.cjs.map +1 -0
  32. package/cjs/openapi-CC7OAUc6.cjs +52 -0
  33. package/cjs/openapi-CC7OAUc6.cjs.map +1 -0
  34. package/cjs/options-CWqFC5__.cjs +181 -0
  35. package/cjs/options-CWqFC5__.cjs.map +1 -0
  36. package/cjs/panels-Rcmeitu3.cjs +318 -0
  37. package/cjs/panels-Rcmeitu3.cjs.map +1 -0
  38. package/cjs/process-panel-DEOnLxoT.cjs +48 -0
  39. package/cjs/process-panel-DEOnLxoT.cjs.map +1 -0
  40. package/cjs/production/index.cjs +238 -0
  41. package/cjs/production/index.cjs.map +1 -0
  42. package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +52 -0
  43. package/cjs/server-ykxsOwob.cjs +184 -0
  44. package/cjs/server-ykxsOwob.cjs.map +1 -0
  45. package/cjs/{src-Xwm3Eel9.cjs → src-UPtTCI2j.cjs} +210 -293
  46. package/cjs/src-UPtTCI2j.cjs.map +1 -0
  47. package/cjs/store-aq207T8v.cjs +9 -0
  48. package/cjs/stream-route-CJTABkUy.cjs +875 -0
  49. package/cjs/stream-route-CJTABkUy.cjs.map +1 -0
  50. package/esm/devtools-connector.d.mts +16 -13
  51. package/esm/devtools-connector.d.mts.map +1 -1
  52. package/esm/devtools-connector.mjs +127 -18
  53. package/esm/devtools-connector.mjs.map +1 -1
  54. package/esm/index.d.mts +4 -2
  55. package/esm/index.mjs +2 -1
  56. package/esm/options.mjs +2 -1
  57. package/esm/options.mjs.map +1 -1
  58. package/esm/panel-tokens.d.mts +13 -0
  59. package/esm/panel-tokens.d.mts.map +1 -0
  60. package/esm/panel-tokens.mjs +45 -0
  61. package/esm/panel-tokens.mjs.map +1 -0
  62. package/esm/panels.mjs +73 -8
  63. package/esm/panels.mjs.map +1 -1
  64. package/esm/production/auth/common-passwords.mjs +303 -0
  65. package/esm/production/auth/common-passwords.mjs.map +1 -0
  66. package/esm/production/auth/default-crypto.mjs +19 -0
  67. package/esm/production/auth/default-crypto.mjs.map +1 -0
  68. package/esm/production/auth/helpers.mjs +77 -0
  69. package/esm/production/auth/helpers.mjs.map +1 -0
  70. package/esm/production/auth/index.mjs +6 -0
  71. package/esm/production/auth/passkeys.mjs +96 -0
  72. package/esm/production/auth/passkeys.mjs.map +1 -0
  73. package/esm/production/auth/service.mjs +1166 -0
  74. package/esm/production/auth/service.mjs.map +1 -0
  75. package/esm/production/boot.mjs +138 -0
  76. package/esm/production/boot.mjs.map +1 -0
  77. package/esm/production/capture/dev-stats.mjs +83 -0
  78. package/esm/production/capture/dev-stats.mjs.map +1 -0
  79. package/esm/production/capture/engine.mjs +442 -0
  80. package/esm/production/capture/engine.mjs.map +1 -0
  81. package/esm/production/capture/explain.mjs +271 -0
  82. package/esm/production/capture/explain.mjs.map +1 -0
  83. package/esm/production/capture/filter.mjs +24 -0
  84. package/esm/production/capture/filter.mjs.map +1 -0
  85. package/esm/production/capture/index.mjs +7 -0
  86. package/esm/production/capture/production-capture.mjs +134 -0
  87. package/esm/production/capture/production-capture.mjs.map +1 -0
  88. package/esm/production/capture/redact.mjs +109 -0
  89. package/esm/production/capture/redact.mjs.map +1 -0
  90. package/esm/production/capture/stats-stores.mjs +300 -0
  91. package/esm/production/capture/stats-stores.mjs.map +1 -0
  92. package/esm/production/cli/actions.mjs +151 -0
  93. package/esm/production/cli/actions.mjs.map +1 -0
  94. package/esm/production/cli/index.d.mts +17 -0
  95. package/esm/production/cli/index.d.mts.map +1 -0
  96. package/esm/production/cli/index.mjs +86 -0
  97. package/esm/production/cli/index.mjs.map +1 -0
  98. package/esm/production/contracts.d.mts +592 -0
  99. package/esm/production/contracts.d.mts.map +1 -0
  100. package/esm/production/contracts.mjs +95 -0
  101. package/esm/production/contracts.mjs.map +1 -0
  102. package/esm/production/errors.d.mts +31 -0
  103. package/esm/production/errors.d.mts.map +1 -0
  104. package/esm/production/errors.mjs +142 -0
  105. package/esm/production/errors.mjs.map +1 -0
  106. package/esm/production/http/access.mjs +124 -0
  107. package/esm/production/http/access.mjs.map +1 -0
  108. package/esm/production/http/auth-routes.mjs +280 -0
  109. package/esm/production/http/auth-routes.mjs.map +1 -0
  110. package/esm/production/http/client.mjs +57 -0
  111. package/esm/production/http/client.mjs.map +1 -0
  112. package/esm/production/http/constants.mjs +11 -0
  113. package/esm/production/http/constants.mjs.map +1 -0
  114. package/esm/production/http/context.mjs +14 -0
  115. package/esm/production/http/context.mjs.map +1 -0
  116. package/esm/production/http/cookie.mjs +39 -0
  117. package/esm/production/http/cookie.mjs.map +1 -0
  118. package/esm/production/http/headers.mjs +25 -0
  119. package/esm/production/http/headers.mjs.map +1 -0
  120. package/esm/production/http/index.mjs +10 -0
  121. package/esm/production/http/ip.mjs +130 -0
  122. package/esm/production/http/ip.mjs.map +1 -0
  123. package/esm/production/http/mount.mjs +300 -0
  124. package/esm/production/http/mount.mjs.map +1 -0
  125. package/esm/production/http/state.mjs +54 -0
  126. package/esm/production/http/state.mjs.map +1 -0
  127. package/esm/production/index.d.mts +6 -0
  128. package/esm/production/index.mjs +5 -0
  129. package/esm/production/insights/cap-report.mjs +67 -0
  130. package/esm/production/insights/cap-report.mjs.map +1 -0
  131. package/esm/production/insights/health.mjs +88 -0
  132. package/esm/production/insights/health.mjs.map +1 -0
  133. package/esm/production/insights/index.mjs +10 -0
  134. package/esm/production/insights/insights.mjs +167 -0
  135. package/esm/production/insights/insights.mjs.map +1 -0
  136. package/esm/production/insights/instance.mjs +24 -0
  137. package/esm/production/insights/instance.mjs.map +1 -0
  138. package/esm/production/insights/jobs.mjs +100 -0
  139. package/esm/production/insights/jobs.mjs.map +1 -0
  140. package/esm/production/insights/reporter.mjs +59 -0
  141. package/esm/production/insights/reporter.mjs.map +1 -0
  142. package/esm/production/insights/resources.mjs +139 -0
  143. package/esm/production/insights/resources.mjs.map +1 -0
  144. package/esm/production/insights/writer.mjs +72 -0
  145. package/esm/production/insights/writer.mjs.map +1 -0
  146. package/esm/production/openapi.mjs +52 -0
  147. package/esm/production/openapi.mjs.map +1 -0
  148. package/esm/production/options.d.mts +60 -0
  149. package/esm/production/options.d.mts.map +1 -0
  150. package/esm/production/options.mjs +170 -0
  151. package/esm/production/options.mjs.map +1 -0
  152. package/esm/production/stats/histogram.mjs +67 -0
  153. package/esm/production/stats/histogram.mjs.map +1 -0
  154. package/esm/production/stats/merge.mjs +106 -0
  155. package/esm/production/stats/merge.mjs.map +1 -0
  156. package/esm/production/store/cascade-store.mjs +322 -0
  157. package/esm/production/store/cascade-store.mjs.map +1 -0
  158. package/esm/production/store/index.mjs +5 -0
  159. package/esm/production/store/mapping.mjs +258 -0
  160. package/esm/production/store/mapping.mjs.map +1 -0
  161. package/esm/production/store/memory-store.mjs +291 -0
  162. package/esm/production/store/memory-store.mjs.map +1 -0
  163. package/esm/production/store/migrations.d.mts +11 -0
  164. package/esm/production/store/migrations.d.mts.map +1 -0
  165. package/esm/production/store/migrations.mjs +29 -0
  166. package/esm/production/store/migrations.mjs.map +1 -0
  167. package/esm/production/store/models/account.migration.mjs +34 -0
  168. package/esm/production/store/models/account.migration.mjs.map +1 -0
  169. package/esm/production/store/models/account.model.mjs +13 -0
  170. package/esm/production/store/models/account.model.mjs.map +1 -0
  171. package/esm/production/store/models/audit.migration.mjs +30 -0
  172. package/esm/production/store/models/audit.migration.mjs.map +1 -0
  173. package/esm/production/store/models/audit.model.mjs +13 -0
  174. package/esm/production/store/models/audit.model.mjs.map +1 -0
  175. package/esm/production/store/models/base.mjs +27 -0
  176. package/esm/production/store/models/base.mjs.map +1 -0
  177. package/esm/production/store/models/index.mjs +17 -0
  178. package/esm/production/store/models/invite.migration.mjs +26 -0
  179. package/esm/production/store/models/invite.migration.mjs.map +1 -0
  180. package/esm/production/store/models/invite.model.mjs +13 -0
  181. package/esm/production/store/models/invite.model.mjs.map +1 -0
  182. package/esm/production/store/models/report.migration.mjs +20 -0
  183. package/esm/production/store/models/report.migration.mjs.map +1 -0
  184. package/esm/production/store/models/report.model.mjs +13 -0
  185. package/esm/production/store/models/report.model.mjs.map +1 -0
  186. package/esm/production/store/models/sample.migration.mjs +25 -0
  187. package/esm/production/store/models/sample.migration.mjs.map +1 -0
  188. package/esm/production/store/models/sample.model.mjs +13 -0
  189. package/esm/production/store/models/sample.model.mjs.map +1 -0
  190. package/esm/production/store/models/session.migration.mjs +31 -0
  191. package/esm/production/store/models/session.migration.mjs.map +1 -0
  192. package/esm/production/store/models/session.model.mjs +13 -0
  193. package/esm/production/store/models/session.model.mjs.map +1 -0
  194. package/esm/production/store/models/state.migration.mjs +26 -0
  195. package/esm/production/store/models/state.migration.mjs.map +1 -0
  196. package/esm/production/store/models/state.model.mjs +13 -0
  197. package/esm/production/store/models/state.model.mjs.map +1 -0
  198. package/esm/query-shape.mjs +14 -1
  199. package/esm/query-shape.mjs.map +1 -1
  200. package/esm/server/explain-route.mjs +26 -1
  201. package/esm/server/explain-route.mjs.map +1 -1
  202. package/esm/server/index.mjs +9 -4
  203. package/esm/server/index.mjs.map +1 -1
  204. package/esm/server/insights-routes.mjs +62 -0
  205. package/esm/server/insights-routes.mjs.map +1 -0
  206. package/esm/server/log-routes.mjs +32 -5
  207. package/esm/server/log-routes.mjs.map +1 -1
  208. package/esm/server/openapi-routes.mjs +3 -2
  209. package/esm/server/openapi-routes.mjs.map +1 -1
  210. package/esm/server/requests-routes.mjs +125 -0
  211. package/esm/server/requests-routes.mjs.map +1 -1
  212. package/esm/server/session-routes.mjs +42 -0
  213. package/esm/server/session-routes.mjs.map +1 -0
  214. package/esm/server/stream-route.mjs +81 -11
  215. package/esm/server/stream-route.mjs.map +1 -1
  216. package/esm/server/ui-assets.mjs +34 -25
  217. package/esm/server/ui-assets.mjs.map +1 -1
  218. package/esm/sources/log-source.mjs +14 -1
  219. package/esm/sources/log-source.mjs.map +1 -1
  220. package/esm/types.d.mts +208 -3
  221. package/esm/types.d.mts.map +1 -1
  222. package/esm/ui-root.mjs +9 -4
  223. package/esm/ui-root.mjs.map +1 -1
  224. package/llms-full.txt +166 -21
  225. package/llms.txt +2 -2
  226. package/package.json +32 -8
  227. package/skills/SKILL.md +166 -21
  228. package/ui/dashboard/assets/app.css +3 -0
  229. package/ui/dashboard/assets/app.js +50 -0
  230. package/ui/dashboard/build-info.json +21 -0
  231. package/ui/dashboard/index.html +16 -0
  232. package/ui/panels/processes.js +12 -3
  233. package/cjs/ai-source-Dz_3tlZ5.cjs +0 -703
  234. package/cjs/ai-source-Dz_3tlZ5.cjs.map +0 -1
  235. package/cjs/server-B11ShQYE.cjs +0 -628
  236. package/cjs/server-B11ShQYE.cjs.map +0 -1
  237. package/cjs/src-Xwm3Eel9.cjs.map +0 -1
  238. package/ui/app.css +0 -376
  239. package/ui/app.js +0 -1158
  240. package/ui/index.html +0 -28
@@ -0,0 +1,875 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-Zuuoy_Rh.cjs");
2
+ const require_panels = require("./panels-Rcmeitu3.cjs");
3
+ const require_ai_source = require("./ai-source-DTpxumMA.cjs");
4
+ const require_errors = require("./errors-CyZp5yS-.cjs");
5
+ let node_fs = require("node:fs");
6
+ let node_path = require("node:path");
7
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
8
+ let _warlock_js_logger = require("@warlock.js/logger");
9
+
10
+ //#region ../../packages/devtools/src/server/ai-routes.ts
11
+ /** Read-only AI metadata, inside the same development/loopback guard as every panel. */
12
+ function registerAiRoutes(server, deps) {
13
+ server.get("/api/ai", async (request, reply) => {
14
+ reply.header("Cache-Control", "no-store");
15
+ const source = deps.ai;
16
+ if (!source?.available) return {
17
+ available: false,
18
+ message: source?.message ?? "Install @warlock.js/ai and @warlock.js/ai-panoptic, then restart warlock dev. Import @warlock.js/ai-panoptic and enable ai.config({ panoptic: { observeAll: true } }). If already installed, check that both packages are compatible and can be loaded.",
19
+ runs: []
20
+ };
21
+ const filter = request.query.requestId === void 0 ? void 0 : { requestId: request.query.requestId };
22
+ return {
23
+ available: true,
24
+ runs: source.store.query(filter).map(source.summarize),
25
+ aggregate: source.store.aggregate(filter)
26
+ };
27
+ });
28
+ server.get("/api/ai/agent-runs", async (request, reply) => {
29
+ reply.header("Cache-Control", "no-store");
30
+ const source = deps.agentTraces;
31
+ if (!source?.available()) return {
32
+ available: false,
33
+ message: require_ai_source.AGENT_TRACE_INSTALL_GUIDANCE,
34
+ runs: []
35
+ };
36
+ return {
37
+ available: true,
38
+ runs: source.list(request.query.requestId === void 0 ? void 0 : { requestId: request.query.requestId })
39
+ };
40
+ });
41
+ server.get("/api/ai/agent-runs/:id", async (request, reply) => {
42
+ reply.header("Cache-Control", "no-store");
43
+ const trace = deps.agentTraces?.get(request.params.id);
44
+ if (!trace) return reply.code(404).send();
45
+ return trace;
46
+ });
47
+ server.get("/api/ai/runs/:id", async (request, reply) => {
48
+ reply.header("Cache-Control", "no-store");
49
+ const source = deps.ai;
50
+ const trace = source?.available ? source.store.get(request.params.id) : void 0;
51
+ if (!trace) return reply.code(404).send();
52
+ return trace;
53
+ });
54
+ }
55
+
56
+ //#endregion
57
+ //#region ../../packages/devtools/src/server/explain-route.ts
58
+ /**
59
+ * The value the logger's redaction substitutes for a censored leaf
60
+ * (`logger/src/redact/redact.ts`, `DEFAULT_CENSOR`). Not exported from
61
+ * `@warlock.js/logger`, so matched by literal here.
62
+ */
63
+ const REDACTED_PLACEHOLDER = "[REDACTED]";
64
+ function isExplainableSql(sql) {
65
+ return /^\s*(select|with)\b/i.test(sql ?? "");
66
+ }
67
+ /** Registers the EXPLAIN route: Postgres `SELECT`/`WITH` queries only. */
68
+ function registerExplainRoute(server, deps) {
69
+ server.post("/api/requests/:requestId/queries/:queryId/explain", async (request, reply) => {
70
+ const query = deps.collector.getRequest(request.params.requestId)?.queries.find((item) => item.id === request.params.queryId);
71
+ if (!query) {
72
+ reply.code(404).send();
73
+ return;
74
+ }
75
+ if (query.driver !== "postgres" || !isExplainableSql(query.sql) || !deps.explain) {
76
+ reply.code(400).send({ error: "Only Postgres SELECT or WITH queries can be explained" });
77
+ return;
78
+ }
79
+ if (query.bindings?.some((binding) => binding === REDACTED_PLACEHOLDER)) {
80
+ reply.code(400).send({ error: "bindings redacted" });
81
+ return;
82
+ }
83
+ try {
84
+ return { plan: await deps.explain(query) };
85
+ } catch (error) {
86
+ reply.code(500).send({ error: error instanceof Error ? error.message : String(error) });
87
+ }
88
+ });
89
+ }
90
+ /**
91
+ * Registers `POST /api/queries/:shapeId/explain`: EXPLAIN for a query shape,
92
+ * run by the process that kept an example of it (development and production).
93
+ * A failure answers `{ error, code, ref?, instance? }` with the code's status.
94
+ */
95
+ function registerShapeExplainRoute(server, deps) {
96
+ const explainShape = deps.explainShape;
97
+ if (!explainShape) return;
98
+ server.post("/api/queries/:shapeId/explain", async (request, reply) => {
99
+ try {
100
+ return await explainShape(request.params.shapeId);
101
+ } catch (error) {
102
+ if (error instanceof require_errors.DevtoolsApiError) {
103
+ reply.code(error.statusCode).send(error.toBody());
104
+ return;
105
+ }
106
+ const failure = new require_errors.DevtoolsApiError("server.error", { ref: require_errors.createErrorRef() });
107
+ _warlock_js_logger.log.error("devtools", "explain", `EXPLAIN route failed (ref ${failure.ref}): ${error instanceof Error ? error.message : String(error)}`);
108
+ reply.code(failure.statusCode).send(failure.toBody());
109
+ }
110
+ });
111
+ }
112
+
113
+ //#endregion
114
+ //#region ../../packages/devtools/src/server/insights-routes.ts
115
+ const QUERY_SORTS = [
116
+ "total",
117
+ "p95",
118
+ "count",
119
+ "n+1"
120
+ ];
121
+ const ROUTE_SORTS = [
122
+ "total",
123
+ "p95",
124
+ "count",
125
+ "errors"
126
+ ];
127
+ /**
128
+ * Reads `?instance=&sort=&limit=`. A sort outside `sorts` or a limit that is
129
+ * not a whole number from 1 to 500 answers `input.invalid`.
130
+ */
131
+ function parseInsightQuery(query, sorts) {
132
+ const result = { instance: query.instance || "all" };
133
+ if (sorts && query.sort !== void 0 && query.sort !== "") {
134
+ if (!sorts.includes(query.sort)) throw new require_errors.DevtoolsApiError("input.invalid");
135
+ result.sort = query.sort;
136
+ }
137
+ if (query.limit !== void 0 && query.limit !== "") {
138
+ const limit = Number(query.limit);
139
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500) throw new require_errors.DevtoolsApiError("input.invalid");
140
+ result.limit = limit;
141
+ }
142
+ return result;
143
+ }
144
+ /**
145
+ * The read-only routes of the Resources, Queries (statistics), Routes
146
+ * (statistics), Health, Errors, Logs (production) and Jobs tabs, over
147
+ * `deps.insights`: `GET /api/instances`, `/api/resources`,
148
+ * `/api/queries/stats`, `/api/routes/stats`, `/api/health`, `/api/errors`,
149
+ * `/api/jobs`. Each takes `?instance=<id|all>` (default `all`). Without
150
+ * `deps.insights` nothing is registered.
151
+ */
152
+ function registerInsightsRoutes(server, deps) {
153
+ const insights = deps.insights;
154
+ if (!insights) return;
155
+ const route = (path, sorts, read) => {
156
+ server.get(path, async (request, reply) => {
157
+ const query = parseInsightQuery(request.query, sorts);
158
+ reply.header("Cache-Control", "no-store");
159
+ return read(query);
160
+ });
161
+ };
162
+ route("/api/instances", void 0, () => insights.instances());
163
+ route("/api/resources", void 0, (query) => insights.resources(query));
164
+ route("/api/queries/stats", QUERY_SORTS, (query) => insights.queryStats(query));
165
+ route("/api/routes/stats", ROUTE_SORTS, (query) => insights.routeStats(query));
166
+ route("/api/health", void 0, (query) => insights.health(query));
167
+ route("/api/errors", void 0, (query) => insights.errors(query));
168
+ route("/api/jobs", void 0, (query) => insights.jobs(query));
169
+ }
170
+
171
+ //#endregion
172
+ //#region ../../packages/devtools/src/server/log-routes.ts
173
+ /**
174
+ * Registers the log listing route, filterable by `level` and `module`. In
175
+ * production it answers from the insights (every instance, no `context`);
176
+ * in development it answers from the collector's logs, which keep `context`.
177
+ */
178
+ function registerLogRoutes(server, deps) {
179
+ server.get("/api/logs", async (request, reply) => {
180
+ const { level, module } = request.query;
181
+ if (deps.mode === "production" && deps.insights) {
182
+ const query = parseInsightQuery(request.query);
183
+ reply.header("Cache-Control", "no-store");
184
+ return deps.insights.logs({
185
+ ...query,
186
+ ...level ? { level } : {},
187
+ ...module ? { module } : {}
188
+ });
189
+ }
190
+ return deps.collector.listLogs({
191
+ level,
192
+ module
193
+ }).map((entry) => ({
194
+ level: entry.level,
195
+ module: entry.module,
196
+ action: entry.action,
197
+ message: entry.message,
198
+ at: entry.at,
199
+ requestId: null,
200
+ instance: null,
201
+ context: entry.context
202
+ }));
203
+ });
204
+ }
205
+
206
+ //#endregion
207
+ //#region ../../packages/devtools/src/server/mail-routes.ts
208
+ const MAIL_HTML_CSP = "sandbox; default-src 'none'; img-src data: https: http:; style-src 'unsafe-inline'";
209
+ /** Registers the mailbox list, single-mail detail, and mail HTML routes. */
210
+ function registerMailRoutes(server, deps) {
211
+ server.get("/api/mails", async () => deps.collector.listMails());
212
+ server.get("/api/mails/:id", async (request, reply) => {
213
+ const mail = deps.collector.getMail(request.params.id);
214
+ if (!mail) {
215
+ reply.code(404).send();
216
+ return;
217
+ }
218
+ const { html, ...rest } = mail;
219
+ return rest;
220
+ });
221
+ server.get("/api/mails/:id/html", async (request, reply) => {
222
+ const mail = deps.collector.getMail(request.params.id);
223
+ if (!mail || !mail.html) {
224
+ reply.code(404).send();
225
+ return;
226
+ }
227
+ reply.header("Content-Security-Policy", MAIL_HTML_CSP).header("X-Content-Type-Options", "nosniff").header("Content-Type", "text/html; charset=utf-8").send(mail.html);
228
+ });
229
+ }
230
+
231
+ //#endregion
232
+ //#region ../../packages/devtools/src/server/ui-assets.ts
233
+ const uiFile = (name) => () => node_path.default.join(require_ai_source.resolveUiRoot(), name);
234
+ /**
235
+ * The only assets that can be requested. The request's asset name is looked
236
+ * up here and never joined into a filesystem path.
237
+ */
238
+ const UI_ASSETS = {
239
+ "app.js": {
240
+ contentType: "text/javascript; charset=utf-8",
241
+ file: uiFile("dashboard/assets/app.js")
242
+ },
243
+ "app.css": {
244
+ contentType: "text/css; charset=utf-8",
245
+ file: uiFile("dashboard/assets/app.css")
246
+ },
247
+ "scalar.js": {
248
+ contentType: "text/javascript; charset=utf-8",
249
+ file: uiFile("vendor/scalar/standalone.js")
250
+ },
251
+ "swagger-ui-bundle.js": {
252
+ contentType: "text/javascript; charset=utf-8",
253
+ file: uiFile("vendor/swagger-ui/swagger-ui-bundle.js")
254
+ },
255
+ "swagger-ui.css": {
256
+ contentType: "text/css; charset=utf-8",
257
+ file: uiFile("vendor/swagger-ui/swagger-ui.css")
258
+ },
259
+ "docs-swagger.js": {
260
+ contentType: "text/javascript; charset=utf-8",
261
+ file: uiFile("docs-swagger.js")
262
+ }
263
+ };
264
+ /** Sends `file` with `contentType` and no caching. */
265
+ function sendFile(reply, file, contentType) {
266
+ reply.header("Cache-Control", "no-store").header("Content-Type", contentType).send((0, node_fs.readFileSync)(file));
267
+ }
268
+ const NOT_BUILT_HTML = "<!doctype html><title>Warlock Devtools</title><p>The devtools dashboard has not been built. Run <code>pnpm --filter @warlock.js/devtools build:ui</code>.</p>";
269
+ /**
270
+ * Serves the static dashboard: the built `ui/dashboard/index.html` at the
271
+ * dashboard root and the whitelisted assets (`app.js`, `app.css`, the
272
+ * vendored Scalar bundle as `scalar.js`, and the vendored Swagger UI files
273
+ * plus their init script). The asset name is matched against a fixed
274
+ * whitelist — never joined into a filesystem path — so no request can
275
+ * traverse outside it. Before the first `build:ui` the root answers 503 with
276
+ * a note that says how to build. `notFound` answers an unknown asset (the
277
+ * production gate passes its uniform 404, so the public asset route answers
278
+ * like any unknown URL of the app); without it the answer is a bare 404.
279
+ */
280
+ function registerUiAssets(server, options = {}) {
281
+ const serveIndex = (request, reply) => {
282
+ const [pathname = "", search] = (request.originalUrl ?? request.url).split("?");
283
+ if (!pathname.endsWith("/")) {
284
+ const base = (request.routeOptions.url ?? pathname).replace(/\/+$/, "");
285
+ reply.code(308).header("Cache-Control", "no-store").redirect(`${base}/${search === void 0 ? "" : `?${search}`}`, 308);
286
+ return;
287
+ }
288
+ const index = node_path.default.join(require_ai_source.resolveUiRoot(), "dashboard", "index.html");
289
+ if (!(0, node_fs.existsSync)(index)) {
290
+ reply.code(503).header("Cache-Control", "no-store").header("Content-Type", "text/html; charset=utf-8").send(NOT_BUILT_HTML);
291
+ return;
292
+ }
293
+ reply.header("Cache-Control", "no-store").header("Content-Type", "text/html; charset=utf-8").send((0, node_fs.readFileSync)(index));
294
+ };
295
+ server.get("/", serveIndex);
296
+ server.get("/assets/:name", (request, reply) => {
297
+ const asset = Object.hasOwn(UI_ASSETS, request.params.name) ? UI_ASSETS[request.params.name] : void 0;
298
+ const file = asset?.file();
299
+ if (!asset || !file || !(0, node_fs.existsSync)(file)) {
300
+ if (options.notFound) {
301
+ options.notFound(request, reply);
302
+ return;
303
+ }
304
+ reply.code(404).header("Cache-Control", "no-store").send();
305
+ return;
306
+ }
307
+ sendFile(reply, file, asset.contentType);
308
+ });
309
+ }
310
+
311
+ //#endregion
312
+ //#region ../../packages/devtools/src/server/openapi-routes.ts
313
+ /**
314
+ * Registers the API docs: `GET /api/openapi.json` returns the document core
315
+ * builds from the registered routes (`deps.getOpenApiDocument`), and
316
+ * `GET /docs` serves the page that renders it with Scalar and
317
+ * `GET /docs/swagger` the same document in Swagger UI;
318
+ * `GET /api/postman.json` returns the Postman collection core builds
319
+ * (`deps.getPostmanCollection`). The pages use relative URLs, so it works under whatever base path the dashboard is
320
+ * mounted on.
321
+ */
322
+ function registerOpenApiRoutes(server, deps) {
323
+ server.get("/api/openapi.json", async (_request, reply) => {
324
+ if (!deps.getOpenApiDocument) return reply.code(503).header("Cache-Control", "no-store").send({ error: "The OpenAPI document is not available: the host did not provide a generator." });
325
+ reply.header("Cache-Control", "no-store");
326
+ return deps.getOpenApiDocument();
327
+ });
328
+ server.get("/api/postman.json", async (_request, reply) => {
329
+ if (!deps.getPostmanCollection) return reply.code(503).header("Cache-Control", "no-store").send({ error: "The Postman collection is not available: the host did not provide a generator." });
330
+ reply.header("Cache-Control", "no-store");
331
+ return deps.getPostmanCollection();
332
+ });
333
+ const frameable = (reply) => reply.header("X-Frame-Options", "SAMEORIGIN").header("Content-Security-Policy", "frame-ancestors 'self'");
334
+ server.get("/docs", (_request, reply) => {
335
+ sendFile(frameable(reply), node_path.default.join(require_ai_source.resolveUiRoot(), "docs.html"), "text/html; charset=utf-8");
336
+ });
337
+ server.get("/docs/swagger", (_request, reply) => {
338
+ sendFile(frameable(reply), node_path.default.join(require_ai_source.resolveUiRoot(), "docs-swagger.html"), "text/html; charset=utf-8");
339
+ });
340
+ }
341
+
342
+ //#endregion
343
+ //#region ../../packages/devtools/src/server/panel-routes.ts
344
+ /**
345
+ * Mounts each panel's data routes at `/api/<id><route path>` and its view
346
+ * module and assets at `/panels/<id>/<name>`. Callers register this inside
347
+ * the devtools scope, so the guard covers every one of them. A file is
348
+ * served only when its name is listed by the panel; the request never
349
+ * becomes a filesystem path.
350
+ */
351
+ function registerPanelRoutes(server, panels) {
352
+ const byId = new Map(panels.map((panel) => [panel.id, panel]));
353
+ for (const panel of panels) for (const route of panel.routes) server.route({
354
+ method: route.method,
355
+ url: `/api/${panel.id}${route.path}`,
356
+ handler: async (request, reply) => {
357
+ const input = {
358
+ params: request.params ?? {},
359
+ query: request.query ?? {},
360
+ body: request.body
361
+ };
362
+ const result = await route.handler(input);
363
+ reply.header("cache-control", "no-store");
364
+ if (result === void 0) return reply.code(204).send();
365
+ return result;
366
+ }
367
+ });
368
+ server.get("/panels/:id/:name", (request, reply) => {
369
+ const panel = byId.get(request.params.id);
370
+ const name = request.params.name;
371
+ const file = panel === void 0 ? void 0 : name === "view.js" ? panel.view : Object.hasOwn(panel.assets, name) ? panel.assets[name] : void 0;
372
+ if (file === void 0) {
373
+ reply.code(404).header("Cache-Control", "no-store").send();
374
+ return;
375
+ }
376
+ reply.header("X-Content-Type-Options", "nosniff");
377
+ sendFile(reply, file, require_panels.panelContentType(name));
378
+ });
379
+ }
380
+
381
+ //#endregion
382
+ //#region ../../packages/devtools/src/request-history.ts
383
+ /** The list row filters run over, from an in-memory summary. */
384
+ function summaryToRow(summary) {
385
+ return {
386
+ id: summary.id,
387
+ time: new Date(summary.startedAt).toISOString(),
388
+ method: summary.method,
389
+ url: summary.path,
390
+ ...summary.route ? { route: summary.route } : {},
391
+ status: summary.status ?? 0,
392
+ durationMs: summary.durationMs ?? 0
393
+ };
394
+ }
395
+ /** An in-memory-shaped list row from a persisted one. */
396
+ function rowToSummary(row) {
397
+ return {
398
+ id: row.id,
399
+ method: row.method,
400
+ path: row.url,
401
+ route: row.route,
402
+ status: row.status,
403
+ startedAt: Date.parse(row.time),
404
+ durationMs: row.durationMs,
405
+ queryCount: row.queryCount ?? 0,
406
+ warningCount: row.nPlusOneCount ?? 0,
407
+ persisted: true
408
+ };
409
+ }
410
+ /**
411
+ * Merge the live ring buffer with the persisted log, newest first, without
412
+ * duplicates: a request in both is shown from memory (it has the full
413
+ * timeline). Persisted rows fill in what a restart or the ring buffer's size
414
+ * evicted.
415
+ */
416
+ function mergeRequestHistory(live, persisted, limit) {
417
+ const seen = new Set(live.map((summary) => summary.id));
418
+ const merged = [...live];
419
+ for (const row of persisted) {
420
+ if (seen.has(row.id)) continue;
421
+ seen.add(row.id);
422
+ merged.push(rowToSummary(row));
423
+ }
424
+ return merged.sort((first, second) => second.startedAt - first.startedAt).slice(0, limit);
425
+ }
426
+ const FILTER_KEYS = [
427
+ "status",
428
+ "route",
429
+ "method",
430
+ "since",
431
+ "until",
432
+ "q"
433
+ ];
434
+ /** The request log filter in a `GET /api/requests` query string. */
435
+ function filterFromQuery(query) {
436
+ const filter = {};
437
+ for (const key of FILTER_KEYS) {
438
+ const value = query[key];
439
+ if (typeof value === "string" && value.trim() !== "") filter[key] = value.trim();
440
+ }
441
+ const limit = Number(query.limit);
442
+ if (Number.isInteger(limit) && limit > 0) filter.limit = limit;
443
+ return filter;
444
+ }
445
+ /** Whether a filter narrows anything. */
446
+ function hasFilter(filter) {
447
+ return FILTER_KEYS.some((key) => filter[key] !== void 0);
448
+ }
449
+ function toLogLevel(level) {
450
+ return level === "debug" || level === "info" || level === "warn" || level === "success" ? level : "error";
451
+ }
452
+ /**
453
+ * A request detail rebuilt from a persisted record, in the shape of an
454
+ * in-memory one: phases, logs and N+1 warnings carry over; query-by-query
455
+ * and cache detail live only in memory, so those lists are empty. `record`
456
+ * has everything the log kept.
457
+ */
458
+ function recordToDetail(record) {
459
+ const startedAt = Date.parse(record.time);
460
+ const warnings = (record.queries?.nPlusOne ?? []).map((finding) => ({
461
+ type: "n+1",
462
+ message: `${finding.query} ran ${finding.count} times`,
463
+ shape: finding.query,
464
+ count: finding.count
465
+ }));
466
+ return {
467
+ id: record.id,
468
+ method: record.method,
469
+ path: record.url,
470
+ route: record.route.pattern,
471
+ status: record.status,
472
+ startedAt,
473
+ durationMs: record.durationMs,
474
+ error: record.error?.message,
475
+ phases: (record.phases ?? []).map((phase) => ({
476
+ name: phase.name,
477
+ startedAt,
478
+ durationMs: phase.durationMs
479
+ })),
480
+ queries: [],
481
+ cache: [],
482
+ logs: (record.logs ?? []).map((entry) => ({
483
+ level: toLogLevel(entry.level),
484
+ module: entry.module,
485
+ action: entry.action,
486
+ message: entry.message,
487
+ at: entry.at,
488
+ ...entry.context ? { context: entry.context } : {}
489
+ })),
490
+ mails: [],
491
+ warnings,
492
+ persisted: true,
493
+ record
494
+ };
495
+ }
496
+
497
+ //#endregion
498
+ //#region ../../packages/devtools/src/server/requests-routes.ts
499
+ const STATUS_FILTER = /^(?:[1-5]\d\d|[1-5]xx)$/i;
500
+ const METHOD_FILTER = /^[A-Za-z]{1,16}$/;
501
+ const RELATIVE_SINCE = /^(\d+)(s|m|h|d)$/;
502
+ const UNIT_MS = {
503
+ s: 1e3,
504
+ m: 6e4,
505
+ h: 36e5,
506
+ d: 864e5
507
+ };
508
+ const DEFAULT_SAMPLE_LIMIT = 200;
509
+ const MAX_SAMPLE_LIMIT = 1e3;
510
+ /** A time bound as epoch ms: a number, an ISO date, or (for `since`) a duration back such as `15m`. */
511
+ function parseTimeBound(value, allowRelative) {
512
+ if (/^\d+$/.test(value)) return Number(value);
513
+ const relative = allowRelative ? RELATIVE_SINCE.exec(value) : null;
514
+ if (relative) return Date.now() - Number(relative[1]) * UNIT_MS[relative[2]];
515
+ const parsed = Date.parse(value);
516
+ if (Number.isNaN(parsed)) throw new require_errors.DevtoolsApiError("request.invalid-filter");
517
+ return parsed;
518
+ }
519
+ /** The stored-sample filter in a `GET /api/requests` query string; throws `request.invalid-filter`. */
520
+ function sampleFilterFromQuery(query, filter, fallbackLimit) {
521
+ const result = { limit: Math.min(MAX_SAMPLE_LIMIT, filter.limit ?? fallbackLimit) };
522
+ if (filter.status !== void 0) {
523
+ const status = String(filter.status);
524
+ if (!STATUS_FILTER.test(status)) throw new require_errors.DevtoolsApiError("request.invalid-filter");
525
+ result.status = status.toLowerCase();
526
+ }
527
+ if (filter.method !== void 0) {
528
+ if (!METHOD_FILTER.test(String(filter.method))) throw new require_errors.DevtoolsApiError("request.invalid-filter");
529
+ result.method = String(filter.method);
530
+ }
531
+ if (filter.route !== void 0) result.route = String(filter.route);
532
+ if (filter.q !== void 0) result.q = String(filter.q);
533
+ if (filter.since !== void 0) result.since = parseTimeBound(String(filter.since), true);
534
+ if (filter.until !== void 0) result.until = parseTimeBound(String(filter.until), false);
535
+ const instance = query.instance;
536
+ if (typeof instance === "string" && instance.trim() !== "" && instance !== "all") result.instance = instance.trim();
537
+ return result;
538
+ }
539
+ function sendApiError(reply, error) {
540
+ reply.code(error.statusCode).send(error.toBody());
541
+ }
542
+ /**
543
+ * Production: the same four routes over the request source (stored samples
544
+ * and this process's memory), merged with the persisted request log the way
545
+ * development merges it with the ring buffer.
546
+ */
547
+ function registerProductionRequestsRoutes(server, deps) {
548
+ const source = deps.requests;
549
+ if (!source) return;
550
+ server.get("/api/requests", async (request, reply) => {
551
+ const { requestLog, options } = deps;
552
+ try {
553
+ const filter = filterFromQuery(request.query);
554
+ const sampleFilter = sampleFilterFromQuery(request.query, filter, DEFAULT_SAMPLE_LIMIT);
555
+ const limit = Math.min(MAX_SAMPLE_LIMIT, filter.limit ?? options.maxRequests);
556
+ let persisted = [];
557
+ if (requestLog) try {
558
+ requestLog.compile(filter);
559
+ persisted = await requestLog.list({
560
+ ...filter,
561
+ limit
562
+ });
563
+ } catch (error) {
564
+ if (error instanceof Error && /^Invalid /.test(error.message)) throw new require_errors.DevtoolsApiError("request.invalid-filter");
565
+ }
566
+ const samples = await source.list({
567
+ ...sampleFilter,
568
+ limit
569
+ });
570
+ return mergeRequestHistory(samples, persisted, limit);
571
+ } catch (error) {
572
+ if (error instanceof require_errors.DevtoolsApiError) {
573
+ sendApiError(reply, error);
574
+ return;
575
+ }
576
+ throw error;
577
+ }
578
+ });
579
+ server.get("/api/requests/:id", async (request, reply) => {
580
+ const { id } = request.params;
581
+ const persisted = await deps.requestLog?.get(id).catch(() => void 0);
582
+ const found = await source.get(id);
583
+ if (found) {
584
+ if ("phases" in found) return persisted ? {
585
+ ...found,
586
+ record: persisted
587
+ } : found;
588
+ if (persisted) return {
589
+ ...recordToDetail(persisted),
590
+ ...found.instance === void 0 ? {} : { instance: found.instance },
591
+ partial: true
592
+ };
593
+ return found;
594
+ }
595
+ if (!persisted) {
596
+ sendApiError(reply, new require_errors.DevtoolsApiError("request.not-found"));
597
+ return;
598
+ }
599
+ return recordToDetail(persisted);
600
+ });
601
+ server.get("/api/requests/:id/curl", async (request, reply) => {
602
+ const { id } = request.params;
603
+ const baseUrl = `${request.protocol}://${request.headers.host ?? "localhost"}`;
604
+ const persisted = await deps.requestLog?.get(id).catch(() => void 0);
605
+ if (persisted && deps.requestLog) return { curl: deps.requestLog.curl(persisted, baseUrl) };
606
+ const found = await source.get(id);
607
+ if (!found) {
608
+ sendApiError(reply, new require_errors.DevtoolsApiError("request.not-found"));
609
+ return;
610
+ }
611
+ return { curl: `curl -X ${found.method} '${baseUrl}${found.path.replace(/'/g, `'\\''`)}'` };
612
+ });
613
+ server.delete("/api/requests", async (_request, reply) => {
614
+ await source.clear();
615
+ deps.collector.clear();
616
+ reply.code(204).send();
617
+ });
618
+ }
619
+ /**
620
+ * Registers the request list, single-request detail, "copy as curl", and
621
+ * clear routes.
622
+ *
623
+ * With core's persistent request log available, the list and the detail also
624
+ * read the JSON-lines history, so requests survive a restart. The list
625
+ * accepts `status` (404 or 5xx), `route`, `method`, `since`, `until`, `q`
626
+ * and `limit` query parameters.
627
+ */
628
+ function registerRequestsRoutes(server, deps) {
629
+ if (deps.requests) {
630
+ registerProductionRequestsRoutes(server, deps);
631
+ return;
632
+ }
633
+ server.get("/api/requests", async (request, reply) => {
634
+ const { requestLog, collector, options } = deps;
635
+ if (!requestLog) return collector.listRequests();
636
+ try {
637
+ const filter = filterFromQuery(request.query);
638
+ const matches = requestLog.compile(filter);
639
+ const live = hasFilter(filter) ? collector.listRequests().filter((summary) => matches(summaryToRow(summary))) : collector.listRequests();
640
+ const limit = filter.limit ?? options.maxRequests;
641
+ const persisted = await requestLog.list({
642
+ ...filter,
643
+ limit
644
+ });
645
+ return mergeRequestHistory(live, persisted, limit);
646
+ } catch (error) {
647
+ if (error instanceof Error && /^Invalid /.test(error.message)) {
648
+ reply.code(400).send({ error: error.message });
649
+ return;
650
+ }
651
+ return collector.listRequests();
652
+ }
653
+ });
654
+ server.get("/api/requests/:id", async (request, reply) => {
655
+ const { id } = request.params;
656
+ const persisted = await deps.requestLog?.get(id).catch(() => void 0);
657
+ const found = deps.collector.getRequest(id);
658
+ if (found) return persisted ? {
659
+ ...found,
660
+ record: persisted
661
+ } : found;
662
+ if (!persisted) {
663
+ reply.code(404).send();
664
+ return;
665
+ }
666
+ return recordToDetail(persisted);
667
+ });
668
+ server.get("/api/requests/:id/curl", async (request, reply) => {
669
+ const { id } = request.params;
670
+ const baseUrl = `${request.protocol}://${request.headers.host ?? "localhost"}`;
671
+ const persisted = await deps.requestLog?.get(id).catch(() => void 0);
672
+ if (persisted && deps.requestLog) return { curl: deps.requestLog.curl(persisted, baseUrl) };
673
+ const live = deps.collector.getRequest(id);
674
+ if (!live) {
675
+ reply.code(404).send();
676
+ return;
677
+ }
678
+ return { curl: `curl -X ${live.method} '${baseUrl}${live.path.replace(/'/g, `'\\''`)}'` };
679
+ });
680
+ server.delete("/api/requests", async (_request, reply) => {
681
+ deps.collector.clear();
682
+ if (deps.ai?.available) deps.ai.store.clear();
683
+ reply.code(204).send();
684
+ });
685
+ }
686
+
687
+ //#endregion
688
+ //#region ../../packages/devtools/src/server/route-routes.ts
689
+ /** Registers the route map, sourced from core's router via `deps.listRoutes`. */
690
+ function registerRouteRoutes(server, deps) {
691
+ server.get("/api/routes", async () => deps.listRoutes ? deps.listRoutes() : []);
692
+ }
693
+
694
+ //#endregion
695
+ //#region ../../packages/devtools/src/server/stream-route.ts
696
+ const PING_INTERVAL_MS = 15e3;
697
+ /** How long a browser waits before it reconnects a dropped stream. */
698
+ const RETRY_MS = 5e3;
699
+ /** The log entry as the production stream sends it: no context (it may hold values). */
700
+ function withoutContext(entry) {
701
+ return {
702
+ level: entry.level,
703
+ module: entry.module,
704
+ action: entry.action,
705
+ message: entry.message,
706
+ at: entry.at
707
+ };
708
+ }
709
+ /**
710
+ * Registers the SSE stream: one `event: <type>\ndata: <json>\n\n` frame per
711
+ * collector event, plus a `: ping` comment every 15s to keep intermediaries
712
+ * from closing an idle connection. The reply is hijacked so Fastify never
713
+ * tries to serialize or close the response itself.
714
+ *
715
+ * The first frames are `retry: 5000` and an `event: hello` with the mode,
716
+ * instance and role. In production (`deps.streamSession` set) the session and
717
+ * the open state are checked again at every ping and the stream ends when
718
+ * either fails; log entries carry no context; mail, AI and agent events flow
719
+ * only when those tabs are enabled.
720
+ */
721
+ function registerStreamRoute(server, deps) {
722
+ server.get("/api/stream", async (request, reply) => {
723
+ const session = deps.streamSession ? await deps.streamSession(request) : null;
724
+ const enabled = new Set(deps.builtInPanels ?? []);
725
+ const instanceId = deps.instance?.id;
726
+ const mode = deps.mode ?? "development";
727
+ reply.hijack();
728
+ const res = reply.raw;
729
+ res.writeHead(200, {
730
+ ...session?.headers,
731
+ "Content-Type": "text/event-stream",
732
+ "Cache-Control": "no-store",
733
+ Connection: "keep-alive",
734
+ "X-Accel-Buffering": "no"
735
+ });
736
+ const write = (frame) => {
737
+ if (!res.writableEnded && !res.destroyed) res.write(frame);
738
+ };
739
+ write(`retry: ${RETRY_MS}\n\n`);
740
+ const hello = {
741
+ mode,
742
+ instance: instanceId ?? null,
743
+ role: session?.role ?? (mode === "development" ? "admin" : null)
744
+ };
745
+ write(`event: hello\ndata: ${JSON.stringify(hello)}\n\n`);
746
+ const dispose = deps.collector.subscribe((event) => {
747
+ if (event.type === "hello") return;
748
+ if (session !== null) {
749
+ if (event.type === "mail" && !enabled.has("mail")) return;
750
+ if (event.type === "log") {
751
+ if (!session.logLevels.includes(event.data.level)) return;
752
+ const row = withoutContext(event.data);
753
+ write(`event: log\ndata: ${JSON.stringify(instanceId !== void 0 ? {
754
+ ...row,
755
+ instance: instanceId
756
+ } : row)}\n\n`);
757
+ return;
758
+ }
759
+ }
760
+ const data = event.type === "request" && instanceId !== void 0 ? {
761
+ ...event.data,
762
+ instance: instanceId
763
+ } : event.data;
764
+ write(`event: ${event.type}\ndata: ${JSON.stringify(data)}\n\n`);
765
+ });
766
+ const aiAllowed = session === null || enabled.has("ai");
767
+ const agentsAllowed = session === null || enabled.has("agents");
768
+ const disposeAi = aiAllowed && deps.ai?.available ? deps.ai.subscribe((event) => {
769
+ write(`event: ai\ndata: ${JSON.stringify(event)}\n\n`);
770
+ }) : void 0;
771
+ const disposeAgentTraces = agentsAllowed ? deps.agentTraces?.subscribe((event) => {
772
+ write(`event: agent-trace\ndata: ${JSON.stringify(event)}\n\n`);
773
+ }) : void 0;
774
+ let closed = false;
775
+ const close = () => {
776
+ if (closed) return;
777
+ closed = true;
778
+ clearInterval(pingTimer);
779
+ dispose();
780
+ disposeAi?.();
781
+ disposeAgentTraces?.();
782
+ session?.release();
783
+ if (!res.writableEnded && !res.destroyed) res.end();
784
+ };
785
+ const pingTimer = setInterval(() => {
786
+ if (session === null) {
787
+ write(": ping\n\n");
788
+ return;
789
+ }
790
+ session.revalidate().then((stillValid) => {
791
+ if (closed) return;
792
+ if (stillValid) write(": ping\n\n");
793
+ else close();
794
+ }, () => close());
795
+ }, PING_INTERVAL_MS);
796
+ pingTimer.unref();
797
+ request.raw.on("close", close);
798
+ res.on("error", close);
799
+ });
800
+ }
801
+
802
+ //#endregion
803
+ Object.defineProperty(exports, "registerAiRoutes", {
804
+ enumerable: true,
805
+ get: function () {
806
+ return registerAiRoutes;
807
+ }
808
+ });
809
+ Object.defineProperty(exports, "registerExplainRoute", {
810
+ enumerable: true,
811
+ get: function () {
812
+ return registerExplainRoute;
813
+ }
814
+ });
815
+ Object.defineProperty(exports, "registerInsightsRoutes", {
816
+ enumerable: true,
817
+ get: function () {
818
+ return registerInsightsRoutes;
819
+ }
820
+ });
821
+ Object.defineProperty(exports, "registerLogRoutes", {
822
+ enumerable: true,
823
+ get: function () {
824
+ return registerLogRoutes;
825
+ }
826
+ });
827
+ Object.defineProperty(exports, "registerMailRoutes", {
828
+ enumerable: true,
829
+ get: function () {
830
+ return registerMailRoutes;
831
+ }
832
+ });
833
+ Object.defineProperty(exports, "registerOpenApiRoutes", {
834
+ enumerable: true,
835
+ get: function () {
836
+ return registerOpenApiRoutes;
837
+ }
838
+ });
839
+ Object.defineProperty(exports, "registerPanelRoutes", {
840
+ enumerable: true,
841
+ get: function () {
842
+ return registerPanelRoutes;
843
+ }
844
+ });
845
+ Object.defineProperty(exports, "registerRequestsRoutes", {
846
+ enumerable: true,
847
+ get: function () {
848
+ return registerRequestsRoutes;
849
+ }
850
+ });
851
+ Object.defineProperty(exports, "registerRouteRoutes", {
852
+ enumerable: true,
853
+ get: function () {
854
+ return registerRouteRoutes;
855
+ }
856
+ });
857
+ Object.defineProperty(exports, "registerShapeExplainRoute", {
858
+ enumerable: true,
859
+ get: function () {
860
+ return registerShapeExplainRoute;
861
+ }
862
+ });
863
+ Object.defineProperty(exports, "registerStreamRoute", {
864
+ enumerable: true,
865
+ get: function () {
866
+ return registerStreamRoute;
867
+ }
868
+ });
869
+ Object.defineProperty(exports, "registerUiAssets", {
870
+ enumerable: true,
871
+ get: function () {
872
+ return registerUiAssets;
873
+ }
874
+ });
875
+ //# sourceMappingURL=stream-route-CJTABkUy.cjs.map