@aiwg/cli 2026.10.15 → 2026.10.16

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 (180) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +23 -9
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/cli/handlers/daemon.js +17 -1
  26. package/dist/src/cli/handlers/doctor-args.js +10 -5
  27. package/dist/src/cli/handlers/doctor-help.js +4 -1
  28. package/dist/src/cli/handlers/index.js +2 -2
  29. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  30. package/dist/src/cli/handlers/models.js +3 -2
  31. package/dist/src/cli/handlers/regenerate.js +8 -16
  32. package/dist/src/cli/handlers/sessions.js +7 -7
  33. package/dist/src/cli/handlers/subcommands.js +8 -0
  34. package/dist/src/cli/handlers/update.js +157 -0
  35. package/dist/src/cli/handlers/use.js +14 -4
  36. package/dist/src/cli/handlers/utilities.js +3 -560
  37. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  38. package/dist/src/cli/services/deployment-verification.js +0 -1
  39. package/dist/src/config/aiwg-config.js +2 -1
  40. package/dist/src/config/authorization-cli.js +7 -3
  41. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  42. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  43. package/dist/src/config/framework-aliases.js +12 -0
  44. package/dist/src/config/host-resource-report.d.mts +19 -0
  45. package/dist/src/config/host-resource-report.mjs +80 -0
  46. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  47. package/dist/src/config/host-resource-runtime.mjs +293 -0
  48. package/dist/src/config/installed-selection.js +22 -0
  49. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  50. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  51. package/dist/src/decision/heldout/access.js +74 -0
  52. package/dist/src/decision/heldout/calibration.js +1 -0
  53. package/dist/src/decision/heldout/collector.js +8 -1
  54. package/dist/src/effects/verifiers/file.js +22 -5
  55. package/dist/src/extensions/claude-attribution.js +82 -0
  56. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  57. package/dist/src/extensions/commands/daemon.js +109 -0
  58. package/dist/src/extensions/commands/definitions.js +5 -89
  59. package/dist/src/gates/heldout.js +17 -7
  60. package/dist/src/lint/check-patterns.js +163 -0
  61. package/dist/src/lint/checks.js +268 -0
  62. package/dist/src/lint/reference-resolution.js +54 -0
  63. package/dist/src/lint/runner.js +3 -465
  64. package/dist/src/mcp/helpers.mjs +11 -1
  65. package/dist/src/memory/project-registry.js +44 -4
  66. package/dist/src/models/worker-plan.js +36 -5
  67. package/dist/src/models/wrapper-deployment.js +25 -12
  68. package/dist/src/models/wrapper-enforcement.js +47 -7
  69. package/dist/src/network-analysis/research.js +2 -1
  70. package/dist/src/policy/hitl-check.js +14 -4
  71. package/dist/src/policy/hitl-consume.js +54 -0
  72. package/dist/src/policy/hitl-receipt.js +2 -0
  73. package/dist/src/policy/hitl.js +11 -3
  74. package/dist/src/providers/provider-context-contracts.js +162 -0
  75. package/dist/src/providers/provider-definition-schema.js +136 -0
  76. package/dist/src/providers/provider-definitions.js +8 -1298
  77. package/dist/src/providers/provider-seeds-1.js +360 -0
  78. package/dist/src/providers/provider-seeds-2.js +387 -0
  79. package/dist/src/providers/provider-seeds-3.js +262 -0
  80. package/dist/src/research/clients/arxiv.js +4 -30
  81. package/dist/src/research/clients/base.js +48 -22
  82. package/dist/src/research/identity.js +34 -2
  83. package/dist/src/research/query-cli.js +3 -87
  84. package/dist/src/research/query-options.js +87 -0
  85. package/dist/src/research/reference-match.js +70 -24
  86. package/dist/src/research/services/acquisition.js +9 -7
  87. package/dist/src/research/services/citation.js +5 -2
  88. package/dist/src/research/types.js +2 -0
  89. package/dist/src/serve/mission-conductor.js +48 -4
  90. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  91. package/dist/src/sessions/adapters/grok-build.js +14 -7
  92. package/dist/src/sessions/workspace-discovery.js +5 -5
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +16 -46
  94. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  95. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  96. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  97. package/dist/src/smiths/context-pipeline/generator.js +9 -10
  98. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  99. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  100. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  101. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  102. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  103. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  104. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  105. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  106. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  107. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  108. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  109. package/package.json +10 -1
  110. package/schemas/decision/D29Study.v10.schema.json +65 -0
  111. package/tools/agents/deploy-agents.mjs +10 -0
  112. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  113. package/tools/agents/providers/context-write.mjs +4 -0
  114. package/tools/agents/providers/pi.mjs +3 -1
  115. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  116. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  117. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  118. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  119. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  120. package/tools/daemon/README.md +511 -0
  121. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  122. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  123. package/tools/daemon/agent-supervisor.mjs +299 -0
  124. package/tools/daemon/automation-engine.mjs +310 -0
  125. package/tools/daemon/autonomous-engine.mjs +346 -0
  126. package/tools/daemon/behavior-loader.mjs +316 -0
  127. package/tools/daemon/behavior.mjs +174 -0
  128. package/tools/daemon/concierge/intent-router.mjs +401 -0
  129. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  130. package/tools/daemon/concierge/response-translator.mjs +462 -0
  131. package/tools/daemon/config.mjs +377 -0
  132. package/tools/daemon/cron-scheduler.mjs +178 -0
  133. package/tools/daemon/daemon-main.mjs +1169 -0
  134. package/tools/daemon/event-router.mjs +84 -0
  135. package/tools/daemon/file-watcher.mjs +383 -0
  136. package/tools/daemon/index.mjs +1181 -0
  137. package/tools/daemon/init-profile.mjs +124 -0
  138. package/tools/daemon/ipc-client.mjs +197 -0
  139. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  140. package/tools/daemon/ipc-server.mjs +275 -0
  141. package/tools/daemon/maintenance-owner.mjs +79 -0
  142. package/tools/daemon/memory-manager.mjs +386 -0
  143. package/tools/daemon/message-router.mjs +194 -0
  144. package/tools/daemon/provider-watcher.mjs +585 -0
  145. package/tools/daemon/pty-adapter.mjs +420 -0
  146. package/tools/daemon/repl-chat.mjs +359 -0
  147. package/tools/daemon/resource-bounds.mjs +88 -0
  148. package/tools/daemon/sandbox-transport.mjs +295 -0
  149. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  150. package/tools/daemon/task-store.mjs +450 -0
  151. package/tools/daemon/tmux-manager.mjs +324 -0
  152. package/tools/daemon/update-policy.mjs +517 -0
  153. package/tools/daemon/web-server.mjs +399 -0
  154. package/tools/daemon/web-ui/index.html +585 -0
  155. package/tools/daemon/web-ui/styles.css +156 -0
  156. package/tools/docker/Dockerfile.daemon +35 -0
  157. package/tools/docker/container-manager.mjs +291 -0
  158. package/tools/messaging/adapter-registry.mjs +230 -0
  159. package/tools/messaging/adapters/base.mjs +326 -0
  160. package/tools/messaging/adapters/discord.mjs +462 -0
  161. package/tools/messaging/adapters/slack.mjs +402 -0
  162. package/tools/messaging/adapters/telegram.mjs +552 -0
  163. package/tools/messaging/chat-handler.mjs +297 -0
  164. package/tools/messaging/command-router.mjs +269 -0
  165. package/tools/messaging/event-bus.mjs +199 -0
  166. package/tools/messaging/index.mjs +456 -0
  167. package/tools/messaging/message-formatter.mjs +320 -0
  168. package/tools/messaging/room-manager.mjs +277 -0
  169. package/tools/messaging/types.mjs +94 -0
  170. package/tools/providers/pi-bridge-policy.mjs +4 -0
  171. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  172. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  173. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  174. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  175. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  176. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  177. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  178. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  179. package/tools/ralph-external/session-launcher.mjs +7 -7
  180. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,399 @@
1
+ /**
2
+ * Daemon Web Server — HTTP + SSE for operator interface
3
+ *
4
+ * Lightweight HTTP server using Node.js built-in `http` module.
5
+ * Serves the web UI dashboard and provides REST API + SSE endpoints
6
+ * for live data streaming.
7
+ *
8
+ * @implements #519
9
+ * @tests @test/unit/web-server.test.mjs
10
+ */
11
+
12
+ import http from 'node:http';
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { EventEmitter } from 'node:events';
18
+
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+ const WEB_UI_DIR = path.join(__dirname, 'web-ui');
21
+
22
+ const MIME_TYPES = {
23
+ '.html': 'text/html',
24
+ '.css': 'text/css',
25
+ '.js': 'application/javascript',
26
+ '.json': 'application/json',
27
+ '.png': 'image/png',
28
+ '.svg': 'image/svg+xml',
29
+ '.ico': 'image/x-icon',
30
+ };
31
+
32
+ export class WebServer extends EventEmitter {
33
+ /**
34
+ * @param {object} options
35
+ * @param {number} [options.port=7474] - HTTP port
36
+ * @param {string} [options.host='127.0.0.1'] - Bind address
37
+ * @param {string} [options.token] - Bearer token for auth (null = no auth)
38
+ * @param {object} [options.daemonSupervisor] - DaemonSupervisor instance
39
+ * @param {object} [options.opsHandlers] - Ops handlers API (for history)
40
+ */
41
+ constructor(options = {}) {
42
+ super();
43
+ this.port = options.port ?? 7474;
44
+ this.host = options.host ?? '127.0.0.1';
45
+ this.token = options.token || process.env.AIWG_WEB_TOKEN || null;
46
+ this.daemonSupervisor = options.daemonSupervisor || null;
47
+ this.opsHandlers = options.opsHandlers || null;
48
+ this.server = null;
49
+ this.sseClients = new Set(); // event stream clients
50
+ this.sseOutputClients = new Map(); // loopId -> Set<res>
51
+ this._startTime = Date.now();
52
+ }
53
+
54
+ async start() {
55
+ return new Promise((resolve, reject) => {
56
+ this.server = http.createServer((req, res) => this._handleRequest(req, res));
57
+
58
+ this.server.on('error', (err) => {
59
+ if (!this.server.listening) {
60
+ reject(err);
61
+ } else {
62
+ this.emit('error', err);
63
+ }
64
+ });
65
+
66
+ this.server.listen(this.port, this.host, () => {
67
+ // When port: 0 is requested, the OS assigns a free port — read back
68
+ // the actual bound port so callers can connect. Eliminates port-pick
69
+ // races in tests that previously rolled random ports.
70
+ const addr = this.server.address();
71
+ if (addr && typeof addr === 'object' && typeof addr.port === 'number') {
72
+ this.port = addr.port;
73
+ }
74
+ this.emit('listening', { port: this.port, host: this.host });
75
+ resolve();
76
+ });
77
+ });
78
+ }
79
+
80
+ async stop() {
81
+ // Close all SSE connections
82
+ for (const client of this.sseClients) {
83
+ client.end();
84
+ }
85
+ this.sseClients.clear();
86
+
87
+ for (const [, clients] of this.sseOutputClients) {
88
+ for (const client of clients) {
89
+ client.end();
90
+ }
91
+ }
92
+ this.sseOutputClients.clear();
93
+
94
+ return new Promise((resolve) => {
95
+ if (this.server) {
96
+ this.server.close(() => resolve());
97
+ } else {
98
+ resolve();
99
+ }
100
+ });
101
+ }
102
+
103
+ /**
104
+ * Push an event to all SSE /sse/events clients.
105
+ */
106
+ broadcastEvent(eventType, data) {
107
+ const payload = `event: ${eventType}\ndata: ${JSON.stringify(data)}\n\n`;
108
+ for (const client of this.sseClients) {
109
+ if (!client.destroyed) {
110
+ client.write(payload);
111
+ }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Push output data to SSE /sse/output/:loopId clients.
117
+ */
118
+ pushOutput(loopId, chunk) {
119
+ const clients = this.sseOutputClients.get(loopId);
120
+ if (!clients) return;
121
+ const payload = `data: ${JSON.stringify({ loopId, chunk })}\n\n`;
122
+ for (const client of clients) {
123
+ if (!client.destroyed) {
124
+ client.write(payload);
125
+ }
126
+ }
127
+ }
128
+
129
+ get url() {
130
+ return `http://${this.host}:${this.port}`;
131
+ }
132
+
133
+ // --- Request handling ---
134
+
135
+ async _handleRequest(req, res) {
136
+ const url = new URL(req.url, `http://${req.headers.host}`);
137
+ const pathname = url.pathname;
138
+
139
+ this._applyCorsHeaders(res);
140
+ if (req.method === 'OPTIONS') {
141
+ res.writeHead(204);
142
+ res.end();
143
+ return;
144
+ }
145
+
146
+ // Auth check for all paths except root and static (optional)
147
+ if (this.token && (pathname.startsWith('/api/') || pathname.startsWith('/sse/'))) {
148
+ if (!this._checkAuth(req, url)) {
149
+ this._sendJSON(res, 401, { error: 'Unauthorized' });
150
+ return;
151
+ }
152
+ }
153
+
154
+ try {
155
+ // API routes
156
+ if (pathname === '/api/status' && req.method === 'GET') {
157
+ return this._handleApiStatus(req, res);
158
+ }
159
+ if (pathname === '/api/loops' && req.method === 'GET') {
160
+ return this._handleApiLoops(req, res);
161
+ }
162
+ if (pathname === '/api/history' && req.method === 'GET') {
163
+ return this._handleApiHistory(req, res, url);
164
+ }
165
+ if (pathname === '/api/resources' && req.method === 'GET') {
166
+ return this._handleApiResources(req, res);
167
+ }
168
+ if (pathname === '/api/submit' && req.method === 'POST') {
169
+ return this._handleApiSubmit(req, res);
170
+ }
171
+ if (pathname.startsWith('/api/cancel/') && req.method === 'POST') {
172
+ const loopId = pathname.slice('/api/cancel/'.length);
173
+ return this._handleApiCancel(req, res, loopId);
174
+ }
175
+
176
+ // SSE routes
177
+ if (pathname === '/sse/events' && req.method === 'GET') {
178
+ return this._handleSSEEvents(req, res);
179
+ }
180
+ if (pathname.startsWith('/sse/output/') && req.method === 'GET') {
181
+ const loopId = pathname.slice('/sse/output/'.length);
182
+ return this._handleSSEOutput(req, res, loopId);
183
+ }
184
+
185
+ // Static files
186
+ if (pathname === '/' || pathname === '/index.html') {
187
+ return this._serveFile(res, 'index.html');
188
+ }
189
+ if (pathname.startsWith('/static/')) {
190
+ const filePath = pathname.slice('/static/'.length);
191
+ return this._serveFile(res, filePath);
192
+ }
193
+
194
+ // 404
195
+ this._sendJSON(res, 404, { error: 'Not found' });
196
+ } catch (err) {
197
+ this._sendJSON(res, 500, { error: err.message });
198
+ }
199
+ }
200
+
201
+ _checkAuth(req, url) {
202
+ if (!this.token) return true;
203
+
204
+ // Check Authorization header
205
+ const authHeader = req.headers.authorization;
206
+ if (authHeader && authHeader.startsWith('Bearer ')) {
207
+ return authHeader.slice(7) === this.token;
208
+ }
209
+
210
+ // Check query param
211
+ const tokenParam = url.searchParams.get('token');
212
+ if (tokenParam) {
213
+ return tokenParam === this.token;
214
+ }
215
+
216
+ return false;
217
+ }
218
+
219
+ // --- API Handlers ---
220
+
221
+ _handleApiStatus(_req, res) {
222
+ if (!this.daemonSupervisor) {
223
+ return this._sendJSON(res, 200, { status: 'starting', message: 'Supervisor not initialized' });
224
+ }
225
+ const status = this.daemonSupervisor.status();
226
+ this._sendJSON(res, 200, {
227
+ status: 'healthy',
228
+ uptime: Math.floor((Date.now() - this._startTime) / 1000),
229
+ concurrency: { used: status.concurrencyUsed, max: status.concurrencyMax },
230
+ queue: { depth: status.queueDepth, max: status.queueMax },
231
+ circuit: status.circuitState,
232
+ budget: { used: status.budgetUsed, limit: status.budgetLimit },
233
+ });
234
+ }
235
+
236
+ _handleApiLoops(_req, res) {
237
+ if (!this.daemonSupervisor) {
238
+ return this._sendJSON(res, 200, { running: [], queued: [] });
239
+ }
240
+ const status = this.daemonSupervisor.status();
241
+ this._sendJSON(res, 200, {
242
+ running: status.running,
243
+ queued: status.queued,
244
+ });
245
+ }
246
+
247
+ _handleApiHistory(_req, res, url) {
248
+ const limit = parseInt(url.searchParams.get('limit') || '20', 10);
249
+ if (this.opsHandlers) {
250
+ const history = this.opsHandlers.getHistory();
251
+ this._sendJSON(res, 200, history.slice(-limit).reverse());
252
+ } else {
253
+ this._sendJSON(res, 200, []);
254
+ }
255
+ }
256
+
257
+ _handleApiResources(_req, res) {
258
+ const totalMem = os.totalmem();
259
+ const freeMem = os.freemem();
260
+ const status = this.daemonSupervisor ? this.daemonSupervisor.status() : null;
261
+
262
+ this._sendJSON(res, 200, {
263
+ cpu: { cores: os.cpus().length, loadAvg: os.loadavg() },
264
+ memory: {
265
+ totalMb: Math.round(totalMem / 1024 / 1024),
266
+ freeMb: Math.round(freeMem / 1024 / 1024),
267
+ percentUsed: parseFloat(((1 - freeMem / totalMem) * 100).toFixed(1)),
268
+ },
269
+ queueDepth: status?.queueDepth ?? 0,
270
+ budgetRemaining: status
271
+ ? (status.budgetLimit > 0 ? status.budgetLimit - status.budgetUsed : 'unlimited')
272
+ : 'unknown',
273
+ });
274
+ }
275
+
276
+ async _handleApiSubmit(req, res) {
277
+ if (!this.daemonSupervisor) {
278
+ return this._sendJSON(res, 503, { error: 'Supervisor not initialized' });
279
+ }
280
+
281
+ const body = await this._readBody(req);
282
+ if (!body.prompt) {
283
+ return this._sendJSON(res, 400, { error: 'Missing required field: prompt' });
284
+ }
285
+
286
+ try {
287
+ const result = this.daemonSupervisor.submit({
288
+ loopId: body.loopId,
289
+ prompt: body.prompt,
290
+ priority: body.priority || 0,
291
+ estimatedCostUsd: body.estimatedCostUsd || 0,
292
+ });
293
+ this._sendJSON(res, 201, result);
294
+ } catch (err) {
295
+ this._sendJSON(res, 422, { error: err.message });
296
+ }
297
+ }
298
+
299
+ _handleApiCancel(_req, res, loopId) {
300
+ if (!this.daemonSupervisor) {
301
+ return this._sendJSON(res, 503, { error: 'Supervisor not initialized' });
302
+ }
303
+
304
+ const cancelled = this.daemonSupervisor.cancel(loopId);
305
+ this._sendJSON(res, 200, { cancelled, loopId });
306
+ }
307
+
308
+ // --- SSE Handlers ---
309
+
310
+ _handleSSEEvents(_req, res) {
311
+ res.writeHead(200, {
312
+ 'Content-Type': 'text/event-stream',
313
+ 'Cache-Control': 'no-cache',
314
+ 'Connection': 'keep-alive',
315
+ });
316
+ res.write(':connected\n\n');
317
+
318
+ this.sseClients.add(res);
319
+ res.on('close', () => this.sseClients.delete(res));
320
+ }
321
+
322
+ _handleSSEOutput(_req, res, loopId) {
323
+ res.writeHead(200, {
324
+ 'Content-Type': 'text/event-stream',
325
+ 'Cache-Control': 'no-cache',
326
+ 'Connection': 'keep-alive',
327
+ });
328
+ res.write(`:connected to ${loopId}\n\n`);
329
+
330
+ if (!this.sseOutputClients.has(loopId)) {
331
+ this.sseOutputClients.set(loopId, new Set());
332
+ }
333
+ this.sseOutputClients.get(loopId).add(res);
334
+
335
+ res.on('close', () => {
336
+ const clients = this.sseOutputClients.get(loopId);
337
+ if (clients) {
338
+ clients.delete(res);
339
+ if (clients.size === 0) {
340
+ this.sseOutputClients.delete(loopId);
341
+ }
342
+ }
343
+ });
344
+ }
345
+
346
+ // --- Utilities ---
347
+
348
+ _serveFile(res, filePath) {
349
+ // Prevent directory traversal
350
+ const normalized = path.normalize(filePath).replace(/^(\.\.(\/|\\|$))+/, '');
351
+ const fullPath = path.join(WEB_UI_DIR, normalized);
352
+
353
+ if (!fullPath.startsWith(WEB_UI_DIR)) {
354
+ this._sendJSON(res, 403, { error: 'Forbidden' });
355
+ return;
356
+ }
357
+
358
+ try {
359
+ const content = fs.readFileSync(fullPath);
360
+ const ext = path.extname(fullPath);
361
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
362
+ res.writeHead(200, { 'Content-Type': contentType });
363
+ res.end(content);
364
+ } catch (err) {
365
+ if (err.code === 'ENOENT') {
366
+ this._sendJSON(res, 404, { error: 'File not found' });
367
+ } else {
368
+ this._sendJSON(res, 500, { error: err.message });
369
+ }
370
+ }
371
+ }
372
+
373
+ _sendJSON(res, statusCode, data) {
374
+ if (res.headersSent) return;
375
+ res.writeHead(statusCode, { 'Content-Type': 'application/json' });
376
+ res.end(JSON.stringify(data));
377
+ }
378
+
379
+ _applyCorsHeaders(res) {
380
+ res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1');
381
+ res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
382
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
383
+ }
384
+
385
+ _readBody(req) {
386
+ return new Promise((resolve, reject) => {
387
+ let data = '';
388
+ req.on('data', (chunk) => { data += chunk; });
389
+ req.on('end', () => {
390
+ try {
391
+ resolve(data ? JSON.parse(data) : {});
392
+ } catch {
393
+ reject(new Error('Invalid JSON body'));
394
+ }
395
+ });
396
+ req.on('error', reject);
397
+ });
398
+ }
399
+ }