@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
package/ui/app.js DELETED
@@ -1,1158 +0,0 @@
1
- if (!location.pathname.endsWith("/"))
2
- location.replace(location.pathname + "/" + location.search + location.hash);
3
-
4
- const app = document.querySelector("#app");
5
- const tabs = document.querySelectorAll(".tab");
6
- /** Ids of the registered panels: the server renders their tab buttons with `data-panel`. */
7
- const panelIds = new Set(Array.from(tabs, (button) => button.dataset?.panel).filter(Boolean));
8
- const state = {
9
- tab: "requests",
10
- requests: [],
11
- details: new Map(),
12
- mails: [],
13
- logs: [],
14
- routes: [],
15
- requestFilter: { q: "", status: "", method: "" },
16
- };
17
-
18
- async function api(path, init) {
19
- const response = await fetch(path, init);
20
- if (!response.ok && response.status !== 204) {
21
- let message = response.statusText || `Request failed (${response.status})`;
22
- try {
23
- message = (await response.json()).error || message;
24
- } catch {
25
- /* response has no JSON error */
26
- }
27
- throw new Error(message);
28
- }
29
- return response.status === 204 ? undefined : response.json();
30
- }
31
-
32
- function el(tag, attrs = {}, children = []) {
33
- const node = document.createElement(tag);
34
- for (const [key, value] of Object.entries(attrs)) {
35
- if (value == null) continue;
36
- if (key === "class") node.className = value;
37
- else if (key === "text") node.textContent = value;
38
- else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
39
- else node.setAttribute(key, value);
40
- }
41
- for (const child of Array.isArray(children) ? children : [children]) node.append(child);
42
- return node;
43
- }
44
-
45
- function errorView(error) {
46
- return el("p", { class: "error", text: `Could not load this view: ${error.message}` });
47
- }
48
- function empty(message) {
49
- return el("p", { class: "empty", text: message });
50
- }
51
- function time(value) {
52
- return value ? new Date(value).toLocaleTimeString() : "—";
53
- }
54
- function value(value) {
55
- return value == null ? "—" : String(value);
56
- }
57
- function sql(query) {
58
- return (
59
- query.sql ||
60
- `${query.collection || "collection"}.${query.command || "command"}\n${JSON.stringify(query.pipeline ?? {}, null, 2)}`
61
- );
62
- }
63
- function canExplain(query) {
64
- return query.driver === "postgres" && /^(select|with)\b/i.test((query.sql || "").trim());
65
- }
66
- function showTab(tab) {
67
- state.tab = tab;
68
- tabs.forEach((button) => button.classList.toggle("is-active", button.dataset.tab === tab));
69
- render();
70
- }
71
- function setTab(tab) {
72
- // A tab click opens the tab's first view, so a panel's hash route is dropped.
73
- if (hashPanel()) history.replaceState(null, "", location.pathname + location.search);
74
- showTab(tab);
75
- }
76
-
77
- function requestRow(request, selected) {
78
- const status = request.status == null ? "—" : String(request.status);
79
- return el(
80
- "button",
81
- {
82
- class: `row${selected ? " is-selected" : ""}`,
83
- type: "button",
84
- onclick: () => showRequest(request.id),
85
- },
86
- [
87
- el("div", { class: "row-top" }, [
88
- el("span", { class: "method", text: request.method }),
89
- el("span", { class: `status-${status[0]}`, text: status }),
90
- ]),
91
- el("div", { class: "path", text: request.path }),
92
- el("div", { class: "meta" }, [
93
- request.persisted
94
- ? el("span", { class: "badge", text: "saved" })
95
- : document.createTextNode(""),
96
- el("span", { text: `${value(request.durationMs)} ms` }),
97
- el("span", { text: `${request.queryCount} queries` }),
98
- request.warningCount
99
- ? el("span", { class: "badge", text: `⚠ ${request.warningCount}` })
100
- : document.createTextNode(""),
101
- ]),
102
- ],
103
- );
104
- }
105
-
106
- async function showRequest(id) {
107
- try {
108
- state.details.set(id, await api(`api/requests/${encodeURIComponent(id)}`));
109
- state.selectedRequest = id;
110
- render();
111
- } catch (error) {
112
- app.replaceChildren(errorView(error));
113
- }
114
- }
115
-
116
- function waterfall(request) {
117
- const entries = [
118
- ...request.phases.map((item) => ({
119
- label: item.name,
120
- at: item.startedAt,
121
- duration: item.durationMs,
122
- })),
123
- ...request.queries.map((item) => ({
124
- label: sql(item).replace(/\s+/g, " ").slice(0, 90),
125
- at: item.startedAt,
126
- duration: item.durationMs,
127
- })),
128
- ...request.cache.map((item) => ({
129
- label: `${item.type} ${item.key || item.keys?.join(", ") || ""}`.trim(),
130
- at: item.at,
131
- duration: item.durationMs || 0,
132
- })),
133
- ];
134
- if (!entries.length) return empty("No timed work recorded for this request.");
135
- const duration = Math.max(request.durationMs || 0, 1);
136
- const box = el("div", { class: "waterfall" });
137
- entries.forEach((entry) => {
138
- const start = Math.max(0, Math.min(100, ((entry.at - request.startedAt) / duration) * 100));
139
- const width = Math.max(0, Math.min(100 - start, (entry.duration / duration) * 100));
140
- const bar = el("span", { class: "bar" });
141
- bar.style.setProperty("--start", `${start}%`);
142
- bar.style.setProperty("--width", `${width}%`);
143
- box.append(
144
- el("div", { class: "waterfall-row" }, [
145
- el("div", { class: "waterfall-label", text: entry.label }),
146
- el("div", { class: "track" }, bar),
147
- ]),
148
- );
149
- });
150
- return box;
151
- }
152
-
153
- function queryRow(query, requestId) {
154
- const details = el("div", { class: "query" });
155
- const head = el("div", { class: "query-head" }, [
156
- el("span", {
157
- text: `${query.driver} · ${query.durationMs} ms · ${value(query.rowCount)} rows${query.error ? ` · ${query.error}` : ""}`,
158
- }),
159
- ]);
160
- if (canExplain(query) && requestId) {
161
- const button = el("button", {
162
- class: "explain",
163
- type: "button",
164
- text: "Explain",
165
- onclick: async () => {
166
- button.disabled = true;
167
- try {
168
- const result = await api(
169
- `api/requests/${encodeURIComponent(requestId)}/queries/${encodeURIComponent(query.id)}/explain`,
170
- { method: "POST" },
171
- );
172
- details.append(el("pre", { text: JSON.stringify(result.plan, null, 2) }));
173
- } catch (error) {
174
- details.append(el("p", { class: "error", text: error.message }));
175
- } finally {
176
- button.disabled = false;
177
- }
178
- },
179
- });
180
- head.append(button);
181
- }
182
- details.append(head, el("pre", { text: sql(query) }));
183
- if (query.bindings)
184
- details.append(el("pre", { text: `bindings: ${JSON.stringify(query.bindings, null, 2)}` }));
185
- return details;
186
- }
187
-
188
- function requestTools(request) {
189
- const status = el("span", { class: "meta" });
190
- const button = el("button", {
191
- type: "button",
192
- text: "Copy as curl",
193
- onclick: async () => {
194
- try {
195
- const { curl } = await api(`api/requests/${encodeURIComponent(request.id)}/curl`);
196
- await navigator.clipboard.writeText(curl);
197
- status.textContent = "Copied. Redacted values stay redacted.";
198
- } catch (error) {
199
- status.textContent = `Could not copy: ${error.message}`;
200
- }
201
- },
202
- });
203
- return el("div", { class: "toolbar" }, [button, status]);
204
- }
205
-
206
- /** The parts only the persisted request log keeps: the error, the redacted input and the response. */
207
- function recordSections(record) {
208
- const sections = [];
209
- if (record.error) {
210
- const where = [record.error.phase, record.error.file, record.error.site]
211
- .filter(Boolean)
212
- .join(" · ");
213
- sections.push(
214
- el("h3", { text: "Error" }),
215
- el("div", { class: "warning" }, [
216
- el("span", { text: `${record.error.name}: ${record.error.message}` }),
217
- where ? el("div", { class: "meta", text: where }) : document.createTextNode(""),
218
- ]),
219
- );
220
- if (record.error.stack) sections.push(el("pre", { text: record.error.stack }));
221
- }
222
- const input = {
223
- headers: record.headers,
224
- params: record.params,
225
- query: record.query,
226
- body: record.body,
227
- session: record.session,
228
- ip: record.ip,
229
- };
230
- sections.push(
231
- el("h3", { text: "Request (redacted)" }),
232
- el("pre", { text: JSON.stringify(input, null, 2) }),
233
- el("h3", { text: "Response" }),
234
- el("pre", { text: JSON.stringify({ status: record.status, ...record.response }, null, 2) }),
235
- );
236
- if (record.queries?.nPlusOne?.length)
237
- sections.push(
238
- el("h3", { text: `Queries (${record.queries.count})` }),
239
- el("pre", { text: JSON.stringify(record.queries, null, 2) }),
240
- );
241
- return sections;
242
- }
243
-
244
- function requestFilterQuery() {
245
- const params = new URLSearchParams();
246
- for (const [key, value] of Object.entries(state.requestFilter))
247
- if (value.trim()) params.set(key, value.trim());
248
- const text = params.toString();
249
- return text ? `?${text}` : "";
250
- }
251
-
252
- function requestFilterBar() {
253
- const field = (key, placeholder) =>
254
- el("input", {
255
- type: "search",
256
- placeholder,
257
- value: state.requestFilter[key],
258
- onchange: (event) => {
259
- state.requestFilter[key] = event.target.value;
260
- render();
261
- },
262
- });
263
- return el("div", { class: "toolbar" }, [
264
- field("q", "Search url or id"),
265
- field("status", "Status: 404 or 5xx"),
266
- field("method", "Method"),
267
- ]);
268
- }
269
-
270
- async function requestDetail(request) {
271
- const section = el("section", { class: "detail" }, [
272
- el("h2", {
273
- text: `${request.method} ${request.path} · ${value(request.status)} · ${value(request.durationMs)} ms`,
274
- }),
275
- ]);
276
- if (request.warnings.length) {
277
- section.append(el("h3", { text: "Warnings" }));
278
- request.warnings.forEach((warning) => {
279
- const children = [el("span", { text: warning.message })];
280
- if (warning.caller)
281
- children.push(
282
- document.createTextNode(" "),
283
- el("a", {
284
- href: `vscode://file/${warning.caller.file}:${warning.caller.line}:${warning.caller.column}`,
285
- text: `${warning.caller.file}:${warning.caller.line}`,
286
- }),
287
- );
288
- section.append(el("div", { class: "warning" }, children));
289
- });
290
- }
291
- section.append(requestTools(request));
292
- if (request.record) section.append(...recordSections(request.record));
293
- section.append(
294
- el("h3", { text: "Waterfall" }),
295
- waterfall(request),
296
- el("h3", { text: "Queries" }),
297
- );
298
- section.append(
299
- request.queries.length
300
- ? request.queries.map((query) => queryRow(query, request.id))
301
- : empty("No queries recorded."),
302
- );
303
- section.append(
304
- el("h3", { text: "Request logs" }),
305
- request.logs.length ? logsList(request.logs) : empty("No logs recorded."),
306
- );
307
- section.append(el("h3", { text: "Request mail" }));
308
- if (request.mails.length)
309
- request.mails.forEach((id) =>
310
- section.append(
311
- el("button", {
312
- class: "row",
313
- type: "button",
314
- text: `Mail ${id}`,
315
- onclick: () => {
316
- setTab("mail");
317
- showMail(id);
318
- },
319
- }),
320
- ),
321
- );
322
- else section.append(empty("No mail captured."));
323
- section.append(el("h3", { text: "AI runs" }), await requestAiView(request.id));
324
- return section;
325
- }
326
-
327
- async function requestsView() {
328
- const list = el("div", { class: "panel list" });
329
- try {
330
- state.requests = await api(`api/requests${requestFilterQuery()}`);
331
- } catch (error) {
332
- return errorView(error);
333
- }
334
- list.append(requestFilterBar());
335
- if (!state.requests.length) list.append(empty("No requests yet — make a request to your app"));
336
- else
337
- state.requests.forEach((item) =>
338
- list.append(requestRow(item, item.id === state.selectedRequest)),
339
- );
340
- const detail =
341
- state.selectedRequest && state.details.get(state.selectedRequest)
342
- ? await requestDetail(state.details.get(state.selectedRequest))
343
- : el("div", { class: "panel" }, empty("Select a request to inspect it."));
344
- return el("div", { class: "layout" }, [list, detail]);
345
- }
346
-
347
- function aiUsage(usage, cost) {
348
- const cacheSemantics =
349
- usage.inputIncludesCache === false
350
- ? "input excludes cache tokens"
351
- : "input includes cache tokens";
352
- return `${value(usage.input)} input · ${value(usage.output)} output · ${value(usage.cachedTokens)} cache read · ${value(usage.cacheWriteTokens)} cache write · ${cost == null ? "unpriced" : `$${cost.toFixed(6)} USD`} (${cacheSemantics})`;
353
- }
354
-
355
- function aiRunSummary(run) {
356
- return el("div", {}, [
357
- el("div", {
358
- class: "row-top",
359
- text: `${run.name} · ${run.status}${run.incomplete ? " · Incomplete / truncated" : ""} · ${run.duration} ms`,
360
- }),
361
- el("div", { class: "meta", text: run.models.join(", ") || "Model unreported" }),
362
- el("p", { text: aiUsage(run.usage, run.cost) }),
363
- el("div", {
364
- class: "meta",
365
- text: `${run.toolCalls} tool calls · ${run.retries} retries · ${value(run.cacheHits)} provider cache-hit trips · ${run.truncatedTrips} truncated trips · ${run.compactions} applied / ${run.skippedCompactions} skipped compactions · ${run.providerCompactions} provider compactions`,
366
- }),
367
- el("div", {
368
- class: "meta",
369
- text: `${run.traceId} · ${run.requestId ? `Request ${run.requestId}` : "Background / no request id"}`,
370
- }),
371
- ]);
372
- }
373
-
374
- function aiGuidance(data) {
375
- return empty(
376
- data.message ||
377
- "Install @warlock.js/ai and @warlock.js/ai-panoptic, restart warlock dev, and enable Panoptic observation.",
378
- );
379
- }
380
-
381
- async function requestAiView(requestId) {
382
- try {
383
- const data = await api(`api/ai?requestId=${encodeURIComponent(requestId)}`);
384
- if (!data.available) return aiGuidance(data);
385
- const section = el("div");
386
- if (!data.runs.length) section.append(empty("No AI runs collected for this request yet."));
387
- for (const run of data.runs) {
388
- section.append(
389
- el(
390
- "button",
391
- {
392
- class: "row",
393
- type: "button",
394
- onclick: () => {
395
- state.selectedAiRun = run.traceId;
396
- state.aiRequestId = requestId;
397
- setTab("ai");
398
- },
399
- },
400
- aiRunSummary(run),
401
- ),
402
- );
403
- }
404
- return section;
405
- } catch (error) {
406
- return errorView(error);
407
- }
408
- }
409
-
410
- function aiSpan(span, rootStartedAt) {
411
- const incomplete =
412
- span.status === "incomplete" ||
413
- span.error?.type === "AgentIncompleteError" ||
414
- span.error?.type === "AGENT_INCOMPLETE";
415
- const start = Date.parse(span.startedAt) - Date.parse(rootStartedAt);
416
- const section = el("details", { class: "ai-span", open: "" }, [
417
- el("summary", {
418
- text: `${span.type} ${span.name} · ${span.status}${incomplete ? " · Incomplete / truncated" : ""} · +${start} ms · ${span.duration} ms`,
419
- }),
420
- el("p", { class: "meta", text: `${span.startedAt} → ${span.endedAt}` }),
421
- el("pre", {
422
- text: JSON.stringify(
423
- { usage: span.usage, attributes: span.attributes, error: span.error },
424
- null,
425
- 2,
426
- ),
427
- }),
428
- ]);
429
- span.children.forEach((child) => section.append(aiSpan(child, rootStartedAt)));
430
- return section;
431
- }
432
-
433
- async function aiView() {
434
- const section = el("section", { class: "detail" }, el("h2", { text: "AI runs" }));
435
- const input = el("input", {
436
- type: "text",
437
- placeholder: "HTTP request id (empty for all runs)",
438
- "aria-label": "Filter AI runs by HTTP request id",
439
- value: state.aiRequestId || "",
440
- });
441
- section.append(
442
- el(
443
- "form",
444
- {
445
- class: "toolbar",
446
- onsubmit: (event) => {
447
- event.preventDefault();
448
- state.aiRequestId = input.value;
449
- state.selectedAiRun = undefined;
450
- render();
451
- },
452
- },
453
- [input, el("button", { type: "submit", text: "Filter / refresh" })],
454
- ),
455
- );
456
- const data = await api(
457
- `api/ai${state.aiRequestId ? `?requestId=${encodeURIComponent(state.aiRequestId)}` : ""}`,
458
- );
459
- if (!data.available) {
460
- section.append(aiGuidance(data));
461
- return section;
462
- }
463
- if (!data.runs.length) {
464
- section.append(
465
- empty(
466
- "No AI runs yet. Enable Panoptic observation and execute a flow; runs appear when collection completes.",
467
- ),
468
- );
469
- return section;
470
- }
471
- const costs = data.runs.filter((run) => run.cost != null);
472
- section.append(
473
- el("p", {
474
- text: `${data.aggregate.traces} runs · ${data.aggregate.usage.input} input tokens · ${data.aggregate.usage.output} output tokens · ${costs.length ? `$${costs.reduce((sum, run) => sum + run.cost, 0).toFixed(6)} USD (reported cost)` : "unpriced"}`,
475
- }),
476
- );
477
- const list = el("div", { class: "panel list" });
478
- for (const run of data.runs)
479
- list.append(
480
- el(
481
- "button",
482
- {
483
- class: `row${run.traceId === state.selectedAiRun ? " is-selected" : ""}`,
484
- type: "button",
485
- onclick: () => {
486
- state.selectedAiRun = run.traceId;
487
- render();
488
- },
489
- },
490
- aiRunSummary(run),
491
- ),
492
- );
493
- const detail = el("div", { class: "panel detail" });
494
- const selected = data.runs.find((run) => run.traceId === state.selectedAiRun);
495
- if (selected) {
496
- detail.append(aiRunSummary(selected));
497
- if (selected.requestId)
498
- detail.append(
499
- el("button", {
500
- type: "button",
501
- text: "Open HTTP request",
502
- onclick: async () => {
503
- state.tab = "requests";
504
- tabs.forEach((button) =>
505
- button.classList.toggle("is-active", button.dataset.tab === "requests"),
506
- );
507
- await showRequest(selected.requestId);
508
- },
509
- }),
510
- );
511
- try {
512
- const trace = await api(`api/ai/runs/${encodeURIComponent(selected.traceId)}`);
513
- detail.append(aiSpan(trace.root, trace.startedAt));
514
- } catch (error) {
515
- detail.append(errorView(error));
516
- }
517
- } else detail.append(empty("Select a run to inspect tools, retries and compaction metadata."));
518
- section.append(el("div", { class: "layout" }, [list, detail]));
519
- return section;
520
- }
521
-
522
- function agentRunSummary(run) {
523
- const cost = run.cost == null ? "unpriced" : `$${run.cost.toFixed(6)} USD`;
524
- return el("div", {}, [
525
- el("div", {
526
- class: "row-top",
527
- text: `${run.agent} · ${run.status} · ${value(run.durationMs)} ms`,
528
- }),
529
- el("div", { class: "meta", text: run.model }),
530
- el("p", {
531
- text: `${run.turns} turns · ${run.toolCalls} tool calls · ${run.refusals} refused · ${run.usage.input} input · ${run.usage.output} output · ${cost}`,
532
- }),
533
- el("div", {
534
- class: "meta",
535
- text: `${run.runId}${run.requestId ? ` · Request ${run.requestId}` : ""}`,
536
- }),
537
- ]);
538
- }
539
-
540
- function agentToolCall(call) {
541
- const lines = [
542
- `${call.name} · ${call.status} · ${call.durationMs} ms`,
543
- ...(call.refusal ? [`refused: ${call.refusal}`] : []),
544
- ...(call.error ? [`error: ${call.error.message}`] : []),
545
- ];
546
- return el("details", { class: "ai-span", open: call.refusal || call.error ? "" : null }, [
547
- el("summary", { text: lines.join(" · ") }),
548
- el("pre", {
549
- text: JSON.stringify({ input: call.input, output: call.output }, null, 2),
550
- }),
551
- ]);
552
- }
553
-
554
- function agentTurn(turn, trace) {
555
- const tokens = turn.toolsOffered.reduce((sum, tool) => sum + tool.tokens, 0);
556
- const cost = turn.cost == null ? "" : ` · $${turn.cost.toFixed(6)} USD`;
557
- const section = el("details", { class: "ai-span", open: "" }, [
558
- el("summary", {
559
- text: `turn ${turn.index} · ${value(turn.finishReason)} · ${Math.round(turn.durationMs)} ms · ${turn.usage.input} input · ${turn.usage.output} output${cost}`,
560
- }),
561
- el("p", {
562
- class: "meta",
563
- text: `starts from ${turn.input} · system prompt ${value(turn.systemPromptHash)} · tools ${turn.toolsHash}`,
564
- }),
565
- el("p", {
566
- class: "meta",
567
- text: `Tools offered (~${tokens} tokens): ${turn.toolsOffered.map((tool) => `${tool.name}@${tool.schemaHash.slice(0, 8)}`).join(", ") || "none"}`,
568
- }),
569
- ]);
570
- if (turn.text) section.append(el("pre", { text: turn.text }));
571
- turn.toolCalls.forEach((call) => section.append(agentToolCall(call)));
572
- turn.contract.forEach((event) =>
573
- section.append(
574
- el("p", {
575
- class: "meta",
576
- text: `contract: ${event.type}${event.tool ? ` ${event.tool}` : ""}${event.name ? ` ${event.name}` : ""}${event.reason ? ` (${event.reason})` : ""}`,
577
- }),
578
- ),
579
- );
580
- if (turn.error) section.append(el("p", { class: "error", text: turn.error.message }));
581
- return section;
582
- }
583
-
584
- function agentRequestDiff(trace, previous) {
585
- if (!previous) return empty("No earlier run of this agent to compare with.");
586
- const tools = (item) =>
587
- new Map(
588
- item.turns.flatMap((turn) => turn.toolsOffered).map((tool) => [tool.name, tool.schemaHash]),
589
- );
590
- const now = tools(trace);
591
- const before = tools(previous);
592
- const changed = [...now].filter(([name, hash]) => before.has(name) && before.get(name) !== hash);
593
- const added = [...now.keys()].filter((name) => !before.has(name));
594
- const removed = [...before.keys()].filter((name) => !now.has(name));
595
- const prompt = trace.systemPrompt?.hash === previous.systemPrompt?.hash ? "same" : "changed";
596
- const identical = prompt === "same" && !changed.length && !added.length && !removed.length;
597
- return el("p", {
598
- class: "meta",
599
- text: identical
600
- ? `Same system prompt and tool definitions as ${previous.runId}.`
601
- : `Against ${previous.runId}: system prompt ${prompt}; tools changed: ${changed.map(([name]) => name).join(", ") || "none"}; added: ${added.join(", ") || "none"}; removed: ${removed.join(", ") || "none"}.`,
602
- });
603
- }
604
-
605
- async function agentsView() {
606
- const section = el("section", { class: "detail" }, el("h2", { text: "Agent runs" }));
607
- const input = el("input", {
608
- type: "text",
609
- placeholder: "HTTP request id (empty for all runs)",
610
- "aria-label": "Filter agent runs by HTTP request id",
611
- value: state.agentRequestId || "",
612
- });
613
- section.append(
614
- el(
615
- "form",
616
- {
617
- class: "toolbar",
618
- onsubmit: (event) => {
619
- event.preventDefault();
620
- state.agentRequestId = input.value;
621
- state.selectedAgentRun = undefined;
622
- render();
623
- },
624
- },
625
- [input, el("button", { type: "submit", text: "Filter / refresh" })],
626
- ),
627
- );
628
- const data = await api(
629
- `api/ai/agent-runs${state.agentRequestId ? `?requestId=${encodeURIComponent(state.agentRequestId)}` : ""}`,
630
- );
631
- if (!data.available) {
632
- section.append(empty(data.message || "No agent traces yet."));
633
- return section;
634
- }
635
- if (!data.runs.length) {
636
- section.append(
637
- empty("No agent runs yet. Execute an agent in development; runs appear as turns finish."),
638
- );
639
- return section;
640
- }
641
- const list = el("div", { class: "panel list" });
642
- for (const run of data.runs)
643
- list.append(
644
- el(
645
- "button",
646
- {
647
- class: `row${run.runId === state.selectedAgentRun ? " is-selected" : ""}`,
648
- type: "button",
649
- onclick: () => {
650
- state.selectedAgentRun = run.runId;
651
- render();
652
- },
653
- },
654
- agentRunSummary(run),
655
- ),
656
- );
657
- const detail = el("div", { class: "panel detail" });
658
- const selected = data.runs.find((run) => run.runId === state.selectedAgentRun);
659
- if (selected) {
660
- detail.append(agentRunSummary(selected));
661
- try {
662
- const trace = await api(`api/ai/agent-runs/${encodeURIComponent(selected.runId)}`);
663
- const index = data.runs.indexOf(selected);
664
- const earlier = data.runs.slice(index + 1).find((run) => run.agent === selected.agent);
665
- const previous = earlier
666
- ? await api(`api/ai/agent-runs/${encodeURIComponent(earlier.runId)}`).catch(() => undefined)
667
- : undefined;
668
- detail.append(el("p", { class: "meta", text: `Input: ${trace.input}` }));
669
- if (trace.systemPrompt) {
670
- detail.append(
671
- el("details", { class: "ai-span" }, [
672
- el("summary", { text: `System prompt ${trace.systemPrompt.hash}` }),
673
- el("pre", {
674
- text: trace.systemPrompt.text ?? "Text not kept (only the hash is recorded).",
675
- }),
676
- ]),
677
- );
678
- }
679
- detail.append(agentRequestDiff(trace, previous));
680
- for (const [hash, schema] of Object.entries(trace.toolSchemas))
681
- detail.append(
682
- el("details", { class: "ai-span" }, [
683
- el("summary", { text: `Tool ${schema.name}@${hash.slice(0, 8)}` }),
684
- el("pre", { text: `${schema.description}\n\n${schema.schema ?? "Schema not kept."}` }),
685
- ]),
686
- );
687
- trace.turns.forEach((turn) => detail.append(agentTurn(turn, trace)));
688
- if (trace.error) detail.append(el("p", { class: "error", text: trace.error.message }));
689
- } catch (error) {
690
- detail.append(errorView(error));
691
- }
692
- } else detail.append(empty("Select a run to inspect its prompt, tools, calls and refusals."));
693
- section.append(el("div", { class: "layout" }, [list, detail]));
694
- return section;
695
- }
696
-
697
- function queriesView() {
698
- const requests = [...state.details.values()].sort((a, b) => b.startedAt - a.startedAt);
699
- // This session-only tab intentionally lists queries from request details fetched so far.
700
- const items = requests
701
- .flatMap((request) => request.queries.map((query) => ({ query, request })))
702
- .sort((a, b) => b.query.startedAt - a.query.startedAt);
703
- return el("section", { class: "card detail" }, [
704
- el("h2", { text: "Queries from inspected requests" }),
705
- items.length
706
- ? items.map(({ query, request }) => queryRow(query, request.id))
707
- : empty("Select requests to collect their queries in this session."),
708
- ]);
709
- }
710
-
711
- function mailDetail(mail) {
712
- const section = el("section", { class: "detail" }, [
713
- el("h2", { text: mail.subject || "(No subject)" }),
714
- ]);
715
- const table = el("table");
716
- const body = el("tbody");
717
- [
718
- ["From", mail.from],
719
- ["To", mail.to?.join(", ")],
720
- ["Cc", mail.cc?.join(", ")],
721
- ["Bcc", mail.bcc?.join(", ")],
722
- ].forEach(([name, item]) =>
723
- body.append(el("tr", {}, [el("th", { text: name }), el("td", { text: item || "—" })])),
724
- );
725
- Object.entries(mail.headers || {}).forEach(([name, item]) =>
726
- body.append(el("tr", {}, [el("th", { text: name }), el("td", { text: item })])),
727
- );
728
- table.append(body);
729
- section.append(table);
730
- const content = el("div");
731
- const htmlButton = el("button", { class: "toggle is-active", type: "button", text: "HTML" });
732
- const textButton = el("button", { class: "toggle", type: "button", text: "Text" });
733
- const show = (html) => {
734
- htmlButton.classList.toggle("is-active", html);
735
- textButton.classList.toggle("is-active", !html);
736
- content.replaceChildren(
737
- html
738
- ? el("iframe", {
739
- class: "mail-frame",
740
- sandbox: "",
741
- src: `api/mails/${encodeURIComponent(mail.id)}/html`,
742
- title: "HTML email body",
743
- })
744
- : el("pre", { text: mail.text || "No plain-text body." }),
745
- );
746
- };
747
- htmlButton.addEventListener("click", () => show(true));
748
- textButton.addEventListener("click", () => show(false));
749
- section.append(
750
- el("h3", { text: "Body" }),
751
- el("div", { class: "toolbar" }, [htmlButton, textButton]),
752
- content,
753
- );
754
- show(true);
755
- section.append(el("h3", { text: "Attachments" }));
756
- section.append(
757
- mail.attachments?.length
758
- ? el(
759
- "ul",
760
- { class: "attachments" },
761
- mail.attachments.map((file) =>
762
- el("li", {
763
- text: `${file.filename} · ${file.contentType || "unknown type"} · ${value(file.size)} bytes`,
764
- }),
765
- ),
766
- )
767
- : empty("No attachments."),
768
- );
769
- return section;
770
- }
771
-
772
- async function showMail(id) {
773
- try {
774
- state.selectedMail = await api(`api/mails/${encodeURIComponent(id)}`);
775
- render();
776
- } catch (error) {
777
- app.replaceChildren(errorView(error));
778
- }
779
- }
780
- async function mailView() {
781
- try {
782
- state.mails = await api("api/mails");
783
- } catch (error) {
784
- return errorView(error);
785
- }
786
- const list = el("div", { class: "panel list" });
787
- list.append(
788
- state.mails.length
789
- ? state.mails.map((mail) =>
790
- el(
791
- "button",
792
- {
793
- class: `row${state.selectedMail?.id === mail.id ? " is-selected" : ""}`,
794
- type: "button",
795
- onclick: () => showMail(mail.id),
796
- },
797
- [
798
- el("div", { class: "path", text: mail.subject || "(No subject)" }),
799
- el("div", {
800
- class: "meta",
801
- text: `${mail.to.join(", ")} · ${time(mail.capturedAt)}`,
802
- }),
803
- ],
804
- ),
805
- )
806
- : empty("No mail captured."),
807
- );
808
- return el("div", { class: "layout" }, [
809
- list,
810
- state.selectedMail
811
- ? mailDetail(state.selectedMail)
812
- : el("div", { class: "panel" }, empty("Select a message to inspect it.")),
813
- ]);
814
- }
815
-
816
- function logsList(logs) {
817
- const box = el("div");
818
- logs.forEach((log) => {
819
- const row = el("div", { class: "query" }, [
820
- el("div", { class: "query-head" }, [
821
- el("span", { class: `log-level log-${log.level}`, text: log.level }),
822
- el("span", { text: `${log.module} · ${log.action} · ${time(log.at)}` }),
823
- ]),
824
- el("div", { text: log.message }),
825
- ]);
826
- if (log.context !== undefined)
827
- row.append(
828
- el("details", {}, [
829
- el("summary", { text: "Context" }),
830
- el("pre", { text: JSON.stringify(log.context, null, 2) }),
831
- ]),
832
- );
833
- box.append(row);
834
- });
835
- return box;
836
- }
837
- async function logsView() {
838
- const section = el("section", { class: "card detail" }, [el("h2", { text: "Logs" })]);
839
- const level = el("select");
840
- ["", "debug", "info", "warn", "error", "success"].forEach((name) =>
841
- level.append(el("option", { value: name, text: name || "All levels" })),
842
- );
843
- const module = el("input", { placeholder: "Filter module" });
844
- const output = el("div");
845
- const load = async () => {
846
- try {
847
- const params = new URLSearchParams();
848
- if (level.value) params.set("level", level.value);
849
- if (module.value) params.set("module", module.value);
850
- state.logs = await api(`api/logs?${params}`);
851
- output.replaceChildren(state.logs.length ? logsList(state.logs) : empty("No logs found."));
852
- } catch (error) {
853
- output.replaceChildren(errorView(error));
854
- }
855
- };
856
- level.addEventListener("change", load);
857
- module.addEventListener("input", load);
858
- section.append(el("div", { class: "toolbar" }, [level, module]), output);
859
- await load();
860
- return section;
861
- }
862
-
863
- async function routesView() {
864
- try {
865
- state.routes = await api("api/routes");
866
- } catch (error) {
867
- return errorView(error);
868
- }
869
- const section = el("section", { class: "card detail" }, [el("h2", { text: "Routes" })]);
870
- const filter = el("input", { placeholder: "Filter routes" });
871
- const output = el("div");
872
- const draw = () => {
873
- const needle = filter.value.toLowerCase();
874
- const routes = state.routes.filter((route) =>
875
- `${route.method} ${route.path} ${route.name || ""} ${(route.middleware || []).join(" ")}`
876
- .toLowerCase()
877
- .includes(needle),
878
- );
879
- if (!routes.length) {
880
- output.replaceChildren(empty("No routes found."));
881
- return;
882
- }
883
- const table = el("table");
884
- table.append(
885
- el(
886
- "thead",
887
- {},
888
- el(
889
- "tr",
890
- {},
891
- ["Method", "Path", "Name", "Middleware"].map((name) => el("th", { text: name })),
892
- ),
893
- ),
894
- );
895
- table.append(
896
- el(
897
- "tbody",
898
- {},
899
- routes.map((route) =>
900
- el("tr", {}, [
901
- el("td", { text: route.method }),
902
- el("td", { text: route.path }),
903
- el("td", { text: route.name || "—" }),
904
- el("td", { text: (route.middleware || []).join(", ") || "—" }),
905
- ]),
906
- ),
907
- ),
908
- );
909
- output.replaceChildren(table);
910
- };
911
- filter.addEventListener("input", draw);
912
- section.append(el("div", { class: "toolbar" }, filter), output);
913
- draw();
914
- return section;
915
- }
916
-
917
- const DOCS_VIEWERS = [
918
- { id: "scalar", label: "Scalar", src: "docs" },
919
- { id: "swagger", label: "Swagger UI", src: "docs/swagger" },
920
- ];
921
- const DOCS_VIEWER_KEY = "warlock-devtools-docs-viewer";
922
-
923
- function savedDocsViewer() {
924
- try {
925
- const id = localStorage.getItem(DOCS_VIEWER_KEY);
926
- return DOCS_VIEWERS.find((viewer) => viewer.id === id) || DOCS_VIEWERS[0];
927
- } catch {
928
- return DOCS_VIEWERS[0];
929
- }
930
- }
931
-
932
- function saveDocsViewer(viewer) {
933
- try {
934
- localStorage.setItem(DOCS_VIEWER_KEY, viewer.id);
935
- } catch {
936
- // Storage can be blocked; the choice then lasts until the tab changes.
937
- }
938
- }
939
-
940
- function apiView() {
941
- const section = el("section");
942
- const frame = el("iframe", { class: "docs-frame", title: "API reference" });
943
- const buttons = DOCS_VIEWERS.map((viewer) =>
944
- el("button", {
945
- class: "toggle",
946
- type: "button",
947
- text: viewer.label,
948
- }),
949
- );
950
- const show = (viewer) => {
951
- frame.src = viewer.src;
952
- buttons.forEach((button, index) =>
953
- button.classList.toggle("is-active", DOCS_VIEWERS[index] === viewer),
954
- );
955
- };
956
- const pick = (viewer) => {
957
- saveDocsViewer(viewer);
958
- show(viewer);
959
- };
960
- buttons.forEach((button, index) =>
961
- button.addEventListener("click", () => pick(DOCS_VIEWERS[index])),
962
- );
963
- section.append(
964
- el("div", { class: "toolbar" }, [
965
- ...buttons,
966
- el("a", {
967
- class: "toolbar-link",
968
- href: "api/openapi.json",
969
- download: "openapi.json",
970
- text: "OpenAPI JSON",
971
- }),
972
- el("a", {
973
- class: "toolbar-link",
974
- href: "api/postman.json",
975
- download: "postman.json",
976
- text: "Postman collection",
977
- }),
978
- ]),
979
- frame,
980
- );
981
- show(savedDocsViewer());
982
- return section;
983
- }
984
-
985
- let renderVersion = 0;
986
-
987
- const SVG_NS = "http://www.w3.org/2000/svg";
988
-
989
- /** Like `el()`, for SVG elements (graphs drawn by panels). */
990
- function svg(tag, attrs = {}, children = []) {
991
- const node = document.createElementNS(SVG_NS, tag);
992
- for (const [key, attr] of Object.entries(attrs)) {
993
- if (attr == null) continue;
994
- if (key === "text") node.textContent = attr;
995
- else if (key.startsWith("on")) node.addEventListener(key.slice(2), attr);
996
- else node.setAttribute(key, attr);
997
- }
998
- for (const child of Array.isArray(children) ? children : [children]) node.append(child);
999
- return node;
1000
- }
1001
-
1002
- /** A panel's data URL: `""`, `"search?q=x"`, `"/flows/a"` and `"?page=2"` all resolve under `api/<id>`. */
1003
- function panelApiUrl(id, path = "") {
1004
- const suffix = !path || path.startsWith("/") || path.startsWith("?") ? path : `/${path}`;
1005
- return `api/${id}${suffix}`;
1006
- }
1007
-
1008
- /** The link to one of a panel's views: `#<id>` or `#<id>/<route>`. */
1009
- function panelHref(id, route = "") {
1010
- return `#${id}${route ? `/${route}` : ""}`;
1011
- }
1012
-
1013
- /** The panel that owns the location hash, if any. */
1014
- function hashPanel() {
1015
- const owner = location.hash.slice(1).split("/")[0];
1016
- return panelIds.has(owner) ? owner : undefined;
1017
- }
1018
-
1019
- /** The panel's part of the hash, as written: `#grimoire/flow/checkout` gives `flow/checkout`. */
1020
- function panelRoute(id) {
1021
- const hash = location.hash.slice(1);
1022
- return hash.startsWith(`${id}/`) ? hash.slice(id.length + 1) : "";
1023
- }
1024
-
1025
- function panelTitle(id) {
1026
- return (
1027
- Array.from(tabs)
1028
- .find((button) => button.dataset?.panel === id)
1029
- ?.textContent?.trim() || id
1030
- );
1031
- }
1032
-
1033
- const panelModules = new Map();
1034
-
1035
- /** Imports a panel's view module once per page load; a failed import is retried next time. */
1036
- function loadPanelModule(id) {
1037
- if (!panelModules.has(id)) {
1038
- const loading = import(new URL(`panels/${id}/view.js`, location.href).href);
1039
- loading.catch(() => panelModules.delete(id));
1040
- panelModules.set(id, loading);
1041
- }
1042
- return panelModules.get(id);
1043
- }
1044
-
1045
- /** What a panel's view module receives; see the devtools docs on registering a panel. */
1046
- function panelContext(id, root) {
1047
- return {
1048
- id,
1049
- root,
1050
- route: panelRoute(id),
1051
- api: (path, init) => api(panelApiUrl(id, path), init),
1052
- asset: (name) => `panels/${id}/${name}`,
1053
- href: (route) => panelHref(id, route),
1054
- navigate(route) {
1055
- const next = panelHref(id, route);
1056
- if (location.hash === next) render();
1057
- else location.hash = next;
1058
- },
1059
- refresh: () => render(),
1060
- el,
1061
- svg,
1062
- empty,
1063
- };
1064
- }
1065
-
1066
- async function panelView(id) {
1067
- let module;
1068
- try {
1069
- module = await loadPanelModule(id);
1070
- } catch (error) {
1071
- throw new Error(
1072
- `the ${panelTitle(id)} panel's view module did not load (${error.message}). Check the terminal running warlock dev.`,
1073
- { cause: error },
1074
- );
1075
- }
1076
- if (typeof module?.default !== "function")
1077
- throw new Error(`the ${panelTitle(id)} panel's view module has no default export function.`);
1078
- const root = el("section", { class: "panel", "data-panel": id });
1079
- return (await module.default(panelContext(id, root))) ?? root;
1080
- }
1081
-
1082
- /**
1083
- * A panel link (`#<id>/<route>`), typed, followed or reached with Back, opens
1084
- * that panel view; Back to an address without one shows the open panel's
1085
- * first view again.
1086
- */
1087
- function onHashChange() {
1088
- const panel = hashPanel();
1089
- if (panel) showTab(panel);
1090
- else if (panelIds.has(state.tab)) render();
1091
- }
1092
-
1093
- async function render() {
1094
- const version = ++renderVersion;
1095
- try {
1096
- const view =
1097
- state.tab === "ai"
1098
- ? await aiView()
1099
- : state.tab === "agents"
1100
- ? await agentsView()
1101
- : state.tab === "requests"
1102
- ? await requestsView()
1103
- : state.tab === "queries"
1104
- ? queriesView()
1105
- : state.tab === "mail"
1106
- ? await mailView()
1107
- : state.tab === "logs"
1108
- ? await logsView()
1109
- : state.tab === "routes"
1110
- ? await routesView()
1111
- : panelIds.has(state.tab)
1112
- ? await panelView(state.tab)
1113
- : apiView();
1114
- if (version === renderVersion) app.replaceChildren(view);
1115
- } catch (error) {
1116
- if (version === renderVersion) app.replaceChildren(errorView(error));
1117
- }
1118
- }
1119
-
1120
- tabs.forEach((button) => button.addEventListener("click", () => setTab(button.dataset.tab)));
1121
- document.querySelector("#clear").addEventListener("click", async () => {
1122
- try {
1123
- await api("api/requests", { method: "DELETE" });
1124
- state.requests = [];
1125
- state.details.clear();
1126
- state.selectedRequest = undefined;
1127
- state.selectedAiRun = undefined;
1128
- render();
1129
- } catch (error) {
1130
- app.prepend(errorView(error));
1131
- }
1132
- });
1133
- const events = new EventSource("api/stream");
1134
- for (const type of ["request", "mail", "log", "ai", "agent-trace"])
1135
- events.addEventListener(type, (event) => {
1136
- try {
1137
- const data = JSON.parse(event.data);
1138
- if (type === "ai" && (state.tab === "ai" || state.tab === "requests")) render();
1139
- if (type === "agent-trace" && state.tab === "agents") render();
1140
- if (type === "request") {
1141
- state.requests = [data, ...state.requests.filter((item) => item.id !== data.id)].slice(
1142
- 0,
1143
- 200,
1144
- );
1145
- if (state.tab === "requests") render();
1146
- }
1147
- if (type === "mail") {
1148
- state.mails = [data, ...state.mails.filter((item) => item.id !== data.id)].slice(0, 200);
1149
- }
1150
- if (type === "log") state.logs = [data, ...state.logs].slice(0, 200);
1151
- } catch {
1152
- /* malformed stream data is ignored */
1153
- }
1154
- });
1155
- window.addEventListener("hashchange", onHashChange);
1156
- const startPanel = hashPanel();
1157
- if (startPanel) showTab(startPanel);
1158
- else render();