loop-task 2.1.4 → 2.1.7

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 (148) hide show
  1. package/dist/app/App.js +119 -0
  2. package/dist/{tui → app}/index.js +4 -5
  3. package/dist/app/providers/index.js +1 -0
  4. package/dist/cli/import-writer.js +1 -1
  5. package/dist/cli.js +9 -9
  6. package/dist/client/cli-format.js +7 -0
  7. package/dist/client/commands.js +2 -164
  8. package/dist/client/ipc.js +3 -3
  9. package/dist/client/project-commands.js +159 -0
  10. package/dist/core/{command-runner.js → command/command-runner.js} +3 -3
  11. package/dist/core/{foreground-loop.js → foreground/index.js} +4 -4
  12. package/dist/core/{log-rotator.js → logging/log-rotator.js} +1 -1
  13. package/dist/core/loop/chain-executor.js +67 -0
  14. package/dist/core/loop/delay-utils.js +65 -0
  15. package/dist/core/loop/loop-controller.js +191 -0
  16. package/dist/core/loop/loop-runner.js +132 -0
  17. package/dist/core/loop/run-executor.js +90 -0
  18. package/dist/core/loop/types.js +1 -0
  19. package/dist/daemon/daemon-log.js +1 -1
  20. package/dist/daemon/http/helpers.js +81 -0
  21. package/dist/daemon/http/openapi.js +92 -0
  22. package/dist/daemon/http/route-loops.js +218 -0
  23. package/dist/daemon/http/route-misc.js +36 -0
  24. package/dist/daemon/http/route-projects.js +55 -0
  25. package/dist/daemon/http/route-tasks.js +53 -0
  26. package/dist/daemon/http/routes.js +17 -0
  27. package/dist/daemon/http/server.js +64 -0
  28. package/dist/daemon/http/sse.js +36 -0
  29. package/dist/daemon/index.js +7 -9
  30. package/dist/{ipc/handlers → daemon/ipc}/logs-stream.js +1 -1
  31. package/dist/daemon/managers/loop-entry.js +24 -0
  32. package/dist/daemon/{manager.js → managers/loop-manager.js} +32 -152
  33. package/dist/daemon/managers/loop-options.js +16 -0
  34. package/dist/daemon/managers/loop-serialization.js +43 -0
  35. package/dist/daemon/{projects.js → managers/project-manager.js} +6 -4
  36. package/dist/daemon/{task-manager.js → managers/task-manager.js} +5 -3
  37. package/dist/daemon/server/handlers/index.js +86 -0
  38. package/dist/daemon/server/handlers/log-handlers.js +130 -0
  39. package/dist/daemon/server/handlers/loop-handlers.js +54 -0
  40. package/dist/daemon/server/handlers/project-handlers.js +37 -0
  41. package/dist/daemon/server/handlers/task-handlers.js +20 -0
  42. package/dist/daemon/server/index.js +113 -0
  43. package/dist/daemon/{spawner.js → spawner/index.js} +4 -4
  44. package/dist/daemon/{state.js → state/index.js} +4 -4
  45. package/dist/daemon/{file-watcher.js → watcher/index.js} +8 -6
  46. package/dist/duration.js +1 -1
  47. package/dist/{tui/state.js → entities/loops/filters.js} +0 -76
  48. package/dist/entities/loops/index.js +1 -0
  49. package/dist/entities/projects/filters.js +69 -0
  50. package/dist/entities/projects/index.js +1 -0
  51. package/dist/entities/tasks/filters.js +41 -0
  52. package/dist/entities/tasks/index.js +1 -0
  53. package/dist/{tui/components → features/chain-editor}/ChainEditor.js +7 -5
  54. package/dist/features/code-editor/CodeEditorModal.js +84 -0
  55. package/dist/{tui/components → features/code-editor}/CodeEditorPreview.js +3 -3
  56. package/dist/features/code-editor/useEditorKeyboard.js +147 -0
  57. package/dist/features/code-editor/useModalDimensions.js +9 -0
  58. package/dist/{tui → features/commands}/commands.js +2 -2
  59. package/dist/features/commands/useCommandHandlers.js +147 -0
  60. package/dist/features/commands/useContextualActions.js +75 -0
  61. package/dist/features/commands/useGlobalShortcuts.js +152 -0
  62. package/dist/features/forms/FormRouter.js +44 -0
  63. package/dist/{tui/components → features/overlays}/ContextHelpModal.js +3 -3
  64. package/dist/{tui/components → features/overlays}/ExportModal.js +3 -3
  65. package/dist/{tui/components → features/overlays}/HelpGuideModal.js +3 -3
  66. package/dist/{tui/components → features/overlays}/HelpModal.js +3 -3
  67. package/dist/features/overlays/OverlayStack.js +9 -0
  68. package/dist/{tui/components → features/overlays}/ProjectsModal.js +2 -2
  69. package/dist/{tui/components → features/overlays}/TaskPickerModal.js +2 -2
  70. package/dist/{tui/components → features/overlays}/WelcomeScreen.js +5 -3
  71. package/dist/features/overlays/useOverlayStack.js +51 -0
  72. package/dist/features/state/useAppState.js +150 -0
  73. package/dist/logger.js +0 -1
  74. package/dist/loop-config.js +9 -4
  75. package/dist/{config → shared/config}/constants.js +1 -1
  76. package/dist/shared/container/index.js +22 -0
  77. package/dist/{tui → shared}/hooks/useBreakpoint.js +1 -1
  78. package/dist/shared/hooks/useInject.js +6 -0
  79. package/dist/{tui → shared}/hooks/useLogStream.js +7 -5
  80. package/dist/{hooks → shared/hooks}/useLoopFormValidation.js +2 -2
  81. package/dist/{tui → shared}/hooks/useLoopPolling.js +6 -4
  82. package/dist/shared/{useUndoRedo.js → hooks/useUndoRedo.js} +2 -4
  83. package/dist/shared/providers/InversifyProvider.js +6 -0
  84. package/dist/shared/services/export-service.js +43 -0
  85. package/dist/shared/services/log-service.js +28 -0
  86. package/dist/shared/services/loop-service.js +78 -0
  87. package/dist/shared/services/project-service.js +39 -0
  88. package/dist/shared/services/task-service.js +41 -0
  89. package/dist/shared/services/types.js +7 -0
  90. package/dist/{tui/components → shared/ui}/Button.js +1 -1
  91. package/dist/{tui/components → shared/ui}/DebugPanel.js +1 -1
  92. package/dist/{tui/components → shared/ui}/FocusableButton.js +1 -1
  93. package/dist/{tui/components → shared/ui}/FocusableInput.js +1 -1
  94. package/dist/{tui/components → shared/ui}/FocusableList.js +1 -1
  95. package/dist/{tui/components → shared/ui}/Modal.js +1 -1
  96. package/dist/{tui/components → shared/ui}/SelectModal.js +2 -2
  97. package/dist/{tui/components → shared/ui}/Toast.js +1 -1
  98. package/dist/shared/ui/state.js +9 -0
  99. package/dist/{tui → shared}/utils/paste.js +2 -2
  100. package/dist/{tui → shared}/utils/validation.js +1 -1
  101. package/dist/widgets/command-input/CommandDropdown.js +69 -0
  102. package/dist/widgets/command-input/CommandInput.js +129 -0
  103. package/dist/widgets/command-input/HintBar.js +9 -0
  104. package/dist/widgets/command-input/InputModes.js +68 -0
  105. package/dist/{tui/components → widgets/commands-browser}/CommandsBrowserModal.js +3 -3
  106. package/dist/{tui/components → widgets/header}/Header.js +3 -3
  107. package/dist/{tui/components → widgets/header}/TabBar.js +1 -1
  108. package/dist/{tui/components → widgets/left-panel}/LeftPanel.js +3 -3
  109. package/dist/{tui/components → widgets/left-panel}/Navigator.js +3 -3
  110. package/dist/{tui/components → widgets/left-panel}/ProjectsPage.js +9 -34
  111. package/dist/widgets/left-panel/ProjectsPageParts.js +34 -0
  112. package/dist/{tui/components → widgets/left-panel}/TaskBrowser.js +4 -4
  113. package/dist/{tui/components → widgets/log-modal}/LogModal.js +8 -6
  114. package/dist/widgets/loop-form/CreateForm.js +75 -0
  115. package/dist/widgets/loop-form/TextField.js +9 -0
  116. package/dist/{tui/components → widgets/loop-form}/WizardForm.js +5 -10
  117. package/dist/widgets/loop-form/useCreateSteps.js +107 -0
  118. package/dist/widgets/loop-form/useHandleComplete.js +74 -0
  119. package/dist/{tui/components → widgets/project-form}/ProjectForm.js +9 -7
  120. package/dist/{tui/components → widgets/right-panel}/Inspector.js +4 -4
  121. package/dist/{tui/components → widgets/right-panel}/RightPanel.js +4 -4
  122. package/dist/{tui/components → widgets/right-panel}/RunHistory.js +52 -4
  123. package/dist/{tui/components → widgets/task-form}/TaskForm.js +11 -9
  124. package/package.json +2 -1
  125. package/dist/core/loop-controller.js +0 -511
  126. package/dist/daemon/http-server.js +0 -599
  127. package/dist/daemon/server.js +0 -374
  128. package/dist/tui/App.js +0 -680
  129. package/dist/tui/components/CodeEditorModal.js +0 -244
  130. package/dist/tui/components/CommandInput.js +0 -273
  131. package/dist/tui/components/CreateForm.js +0 -224
  132. package/dist/tui/daemon.js +0 -142
  133. package/dist/tui/format.js +0 -111
  134. /package/dist/{tui/router.js → app/router/index.js} +0 -0
  135. /package/dist/{tui → app}/types.js +0 -0
  136. /package/dist/core/{resolve-cwd.js → command/resolve-cwd.js} +0 -0
  137. /package/dist/core/{context-parser.js → context/context-parser.js} +0 -0
  138. /package/dist/core/{template.js → context/template.js} +0 -0
  139. /package/dist/core/{log-parser.js → logging/log-parser.js} +0 -0
  140. /package/dist/core/{scheduling.js → scheduling/index.js} +0 -0
  141. /package/dist/{ipc → daemon/ipc}/send.js +0 -0
  142. /package/dist/{config → shared/config}/paths.js +0 -0
  143. /package/dist/{i18n → shared/i18n}/en.json +0 -0
  144. /package/dist/{i18n → shared/i18n}/index.js +0 -0
  145. /package/dist/{board → shared/ui}/format.js +0 -0
  146. /package/dist/{tui → shared/ui}/hooks/useHoverState.js +0 -0
  147. /package/dist/{tui → shared/ui}/theme.js +0 -0
  148. /package/dist/{tui → shared}/utils/syntax.js +0 -0
@@ -1,599 +0,0 @@
1
- import http from "node:http";
2
- import fs from "node:fs";
3
- import { HTTP_API_PORT, HTTP_API_HOST, LOG_TAIL_DEFAULT } from "../config/constants.js";
4
- import { daemonLog } from "./daemon-log.js";
5
- import { tail } from "../shared/tail.js";
6
- import { buildLoopOptions } from "../loop-config.js";
7
- function sendJson(res, status, data) {
8
- const body = JSON.stringify(data);
9
- res.writeHead(status, {
10
- "Content-Type": "application/json",
11
- "Content-Length": Buffer.byteLength(body),
12
- });
13
- res.end(body);
14
- }
15
- function sendOk(res, data, status = 200) {
16
- sendJson(res, status, { ok: true, data: data ?? null });
17
- }
18
- function sendError(res, status, message) {
19
- sendJson(res, status, { ok: false, error: { message } });
20
- }
21
- function sendNotFound(res, id) {
22
- sendError(res, 404, `Not found: ${id}`);
23
- }
24
- function matchRoute(routes, method, pathSegments) {
25
- for (const route of routes) {
26
- if (route.method !== method)
27
- continue;
28
- if (route.segments.length !== pathSegments.length)
29
- continue;
30
- const params = {};
31
- let matched = true;
32
- for (let i = 0; i < route.segments.length; i++) {
33
- const routeSeg = route.segments[i];
34
- const pathSeg = pathSegments[i];
35
- if (routeSeg.startsWith(":")) {
36
- params[routeSeg.slice(1)] = decodeURIComponent(pathSeg);
37
- }
38
- else if (routeSeg !== pathSeg) {
39
- matched = false;
40
- break;
41
- }
42
- }
43
- if (matched) {
44
- return { params, handler: route.handler };
45
- }
46
- }
47
- return null;
48
- }
49
- function parsePath(url) {
50
- if (!url)
51
- return [];
52
- const pathname = url.split("?")[0] ?? "";
53
- return pathname.split("/").filter((s) => s.length > 0);
54
- }
55
- function parseQuery(url) {
56
- if (!url)
57
- return new URLSearchParams();
58
- const qs = url.split("?")[1] ?? "";
59
- return new URLSearchParams(qs);
60
- }
61
- async function readBody(req) {
62
- return new Promise((resolve, reject) => {
63
- let body = "";
64
- req.on("data", (chunk) => {
65
- body += chunk.toString();
66
- if (body.length > 1024 * 1024) {
67
- reject(new Error("Body too large"));
68
- req.destroy();
69
- }
70
- });
71
- req.on("end", () => {
72
- if (!body.trim()) {
73
- resolve({});
74
- return;
75
- }
76
- try {
77
- resolve(JSON.parse(body));
78
- }
79
- catch {
80
- reject(new Error("Invalid JSON body"));
81
- }
82
- });
83
- req.on("error", reject);
84
- });
85
- }
86
- export class HttpApiServer {
87
- server;
88
- manager;
89
- taskManager;
90
- projectManager;
91
- routes = [];
92
- sseClients = new Set();
93
- constructor(manager, taskManager, projectManager) {
94
- this.manager = manager;
95
- this.taskManager = taskManager;
96
- this.projectManager = projectManager;
97
- this.server = http.createServer((req, res) => this.handleRequest(req, res));
98
- this.registerRoutes();
99
- }
100
- async listen(port = HTTP_API_PORT, host = HTTP_API_HOST) {
101
- return new Promise((resolve, reject) => {
102
- this.server.on("error", (err) => {
103
- if (err.code === "EADDRINUSE") {
104
- daemonLog(`HTTP API server: port ${port} already in use, skipping HTTP transport`);
105
- resolve();
106
- }
107
- else {
108
- reject(err);
109
- }
110
- });
111
- this.server.listen(port, host, () => {
112
- daemonLog(`HTTP API server listening on ${host}:${port}`);
113
- resolve();
114
- });
115
- });
116
- }
117
- async close() {
118
- for (const client of this.sseClients) {
119
- client.destroy();
120
- }
121
- this.sseClients.clear();
122
- return new Promise((resolve) => {
123
- this.server.close(() => resolve());
124
- });
125
- }
126
- broadcastEvent(event, data) {
127
- const payload = `event: ${event}\ndata: ${JSON.stringify(data ?? {})}\n\n`;
128
- for (const client of this.sseClients) {
129
- try {
130
- client.write(payload);
131
- }
132
- catch {
133
- this.sseClients.delete(client);
134
- }
135
- }
136
- }
137
- registerRoutes() {
138
- const r = (method, path, handler) => {
139
- const segments = path.split("/").filter((s) => s.length > 0);
140
- this.routes.push({ method, segments, handler });
141
- };
142
- r("GET", "/api/loops", (_req, res) => {
143
- sendOk(res, this.manager.list());
144
- });
145
- r("GET", "/api/loops/:id", (_req, res, params) => {
146
- const meta = this.manager.status(params.id);
147
- if (!meta) {
148
- sendNotFound(res, params.id);
149
- return;
150
- }
151
- sendOk(res, meta);
152
- });
153
- r("POST", "/api/loops", async (req, res) => {
154
- try {
155
- const body = await readBody(req);
156
- const intervalHuman = body.intervalHuman ?? "5m";
157
- const { options } = buildLoopOptions(intervalHuman, {
158
- command: body.command,
159
- commandArgs: body.commandArgs,
160
- taskId: body.taskId,
161
- cwd: body.cwd,
162
- now: body.now,
163
- maxRuns: body.maxRuns,
164
- verbose: body.verbose,
165
- description: body.description,
166
- projectId: body.projectId,
167
- offset: body.offset,
168
- });
169
- const id = this.manager.start(options, intervalHuman);
170
- sendOk(res, { id }, 201);
171
- }
172
- catch (err) {
173
- sendError(res, 400, err instanceof Error ? err.message : String(err));
174
- }
175
- });
176
- r("PATCH", "/api/loops/:id", async (req, res, params) => {
177
- try {
178
- const body = await readBody(req);
179
- const intervalHuman = body.intervalHuman ?? "5m";
180
- const { options } = buildLoopOptions(intervalHuman, {
181
- command: body.command,
182
- commandArgs: body.commandArgs,
183
- taskId: body.taskId,
184
- cwd: body.cwd,
185
- now: body.now,
186
- maxRuns: body.maxRuns,
187
- verbose: body.verbose,
188
- description: body.description,
189
- projectId: body.projectId,
190
- offset: body.offset,
191
- });
192
- const ok = await this.manager.update(params.id, options, intervalHuman);
193
- if (!ok) {
194
- sendNotFound(res, params.id);
195
- return;
196
- }
197
- sendOk(res, { id: params.id });
198
- }
199
- catch (err) {
200
- sendError(res, 400, err instanceof Error ? err.message : String(err));
201
- }
202
- });
203
- r("DELETE", "/api/loops/:id", async (_req, res, params) => {
204
- const ok = await this.manager.delete(params.id);
205
- if (!ok) {
206
- sendNotFound(res, params.id);
207
- return;
208
- }
209
- sendOk(res);
210
- });
211
- r("POST", "/api/loops/:id/pause", (_req, res, params) => {
212
- if (!this.manager.pause(params.id)) {
213
- sendNotFound(res, params.id);
214
- return;
215
- }
216
- sendOk(res);
217
- });
218
- r("POST", "/api/loops/:id/resume", (_req, res, params) => {
219
- if (!this.manager.resume(params.id)) {
220
- sendNotFound(res, params.id);
221
- return;
222
- }
223
- sendOk(res);
224
- });
225
- r("POST", "/api/loops/:id/trigger", (_req, res, params) => {
226
- if (this.manager.isMaxRunsBlocked(params.id)) {
227
- sendError(res, 400, "Max runs reached");
228
- return;
229
- }
230
- if (this.manager.isRunning(params.id)) {
231
- sendError(res, 409, "Loop is already running");
232
- return;
233
- }
234
- if (!this.manager.trigger(params.id)) {
235
- sendNotFound(res, params.id);
236
- return;
237
- }
238
- sendOk(res);
239
- });
240
- r("POST", "/api/loops/:id/stop", (_req, res, params) => {
241
- if (!this.manager.stopLoop(params.id)) {
242
- sendNotFound(res, params.id);
243
- return;
244
- }
245
- sendOk(res);
246
- });
247
- r("POST", "/api/loops/stop-all", (_req, res) => {
248
- const count = this.manager.stopAllLoops();
249
- sendOk(res, { count });
250
- });
251
- r("GET", "/api/loops/:id/logs", (_req, res, params) => {
252
- const logPath = this.manager.getLogPath(params.id);
253
- if (!logPath) {
254
- sendNotFound(res, params.id);
255
- return;
256
- }
257
- const query = parseQuery(_req.url);
258
- const tailCount = parseInt(query.get("tail") ?? String(LOG_TAIL_DEFAULT), 10);
259
- if (!fs.existsSync(logPath)) {
260
- sendOk(res, "");
261
- return;
262
- }
263
- const content = fs.readFileSync(logPath, "utf-8");
264
- sendOk(res, tail(content, tailCount).join("\n"));
265
- });
266
- r("GET", "/api/loops/:id/logs/stream", (_req, res, params) => {
267
- const logPath = this.manager.getLogPath(params.id);
268
- if (!logPath) {
269
- sendNotFound(res, params.id);
270
- return;
271
- }
272
- res.writeHead(200, {
273
- "Content-Type": "text/event-stream",
274
- "Cache-Control": "no-cache",
275
- "Connection": "keep-alive",
276
- });
277
- const query = parseQuery(_req.url);
278
- const tailCount = parseInt(query.get("tail") ?? "0", 10);
279
- if (fs.existsSync(logPath)) {
280
- const content = fs.readFileSync(logPath, "utf-8");
281
- for (const line of tail(content, tailCount)) {
282
- if (line) {
283
- res.write(`data: ${line}\n\n`);
284
- }
285
- }
286
- }
287
- let fileSize = fs.existsSync(logPath) ? fs.statSync(logPath).size : 0;
288
- const watcher = fs.watch(logPath, (eventType) => {
289
- if (eventType === "rename" && !fs.existsSync(logPath)) {
290
- watcher.close();
291
- res.write("event: end\ndata: {}\n\n");
292
- res.end();
293
- return;
294
- }
295
- if (eventType === "change") {
296
- try {
297
- const stat = fs.statSync(logPath);
298
- if (stat.size > fileSize) {
299
- const fd = fs.openSync(logPath, "r");
300
- const buf = Buffer.alloc(stat.size - fileSize);
301
- fs.readSync(fd, buf, 0, buf.length, fileSize);
302
- fs.closeSync(fd);
303
- fileSize = stat.size;
304
- for (const line of buf.toString().split("\n")) {
305
- if (line) {
306
- res.write(`data: ${line}\n\n`);
307
- }
308
- }
309
- }
310
- }
311
- catch {
312
- watcher.close();
313
- res.end();
314
- }
315
- }
316
- });
317
- _req.on("close", () => {
318
- watcher.close();
319
- res.end();
320
- });
321
- });
322
- r("GET", "/api/loops/:id/runs/:num", (_req, res, params) => {
323
- const { id, num } = params;
324
- const logPath = this.manager.getLogPath(id);
325
- if (!logPath || !fs.existsSync(logPath)) {
326
- sendOk(res, "");
327
- return;
328
- }
329
- const meta = this.manager.status(id);
330
- if (!meta) {
331
- sendNotFound(res, id);
332
- return;
333
- }
334
- const runNumber = parseInt(num, 10);
335
- const records = meta.runHistory
336
- .filter((r) => r.runNumber === runNumber)
337
- .sort((a, b) => a.logOffset - b.logOffset);
338
- if (records.length === 0) {
339
- sendOk(res, "");
340
- return;
341
- }
342
- const buffer = fs.readFileSync(logPath);
343
- const allSorted = meta.runHistory.slice().sort((a, b) => a.logOffset - b.logOffset);
344
- const parts = records.map((record) => {
345
- const start = record.logOffset;
346
- const idx = allSorted.indexOf(record);
347
- const end = idx < allSorted.length - 1 ? allSorted[idx + 1].logOffset : buffer.length;
348
- return buffer.toString("utf-8", start, end);
349
- });
350
- sendOk(res, parts.join(""));
351
- });
352
- r("GET", "/api/tasks", (_req, res) => {
353
- sendOk(res, this.taskManager.list());
354
- });
355
- r("GET", "/api/tasks/:id", (_req, res, params) => {
356
- const task = this.taskManager.get(params.id);
357
- if (!task) {
358
- sendNotFound(res, params.id);
359
- return;
360
- }
361
- sendOk(res, task);
362
- });
363
- r("POST", "/api/tasks", async (req, res) => {
364
- try {
365
- const body = await readBody(req);
366
- if (!body.name?.trim()) {
367
- sendError(res, 400, "Task name is required");
368
- return;
369
- }
370
- if (!body.command?.trim()) {
371
- sendError(res, 400, "Task command is required");
372
- return;
373
- }
374
- const task = this.taskManager.create(body);
375
- sendOk(res, task, 201);
376
- }
377
- catch (err) {
378
- sendError(res, 400, err instanceof Error ? err.message : String(err));
379
- }
380
- });
381
- r("PATCH", "/api/tasks/:id", async (req, res, params) => {
382
- try {
383
- const body = await readBody(req);
384
- const updated = this.taskManager.update(params.id, body);
385
- if (!updated) {
386
- sendNotFound(res, params.id);
387
- return;
388
- }
389
- sendOk(res, updated);
390
- }
391
- catch (err) {
392
- sendError(res, 400, err instanceof Error ? err.message : String(err));
393
- }
394
- });
395
- r("DELETE", "/api/tasks/:id", (_req, res, params) => {
396
- if (!this.taskManager.delete(params.id)) {
397
- sendNotFound(res, params.id);
398
- return;
399
- }
400
- sendOk(res);
401
- });
402
- r("GET", "/api/projects", (_req, res) => {
403
- sendOk(res, this.projectManager.getAll());
404
- });
405
- r("POST", "/api/projects", async (req, res) => {
406
- try {
407
- const body = await readBody(req);
408
- if (!body.name?.trim()) {
409
- sendError(res, 400, "Project name is required");
410
- return;
411
- }
412
- const project = this.projectManager.create(body.name.trim(), body.color ?? "#ffffff");
413
- sendOk(res, project, 201);
414
- }
415
- catch (err) {
416
- sendError(res, 400, err instanceof Error ? err.message : String(err));
417
- }
418
- });
419
- r("PATCH", "/api/projects/:id", async (req, res, params) => {
420
- try {
421
- const body = await readBody(req);
422
- if (!body.name?.trim()) {
423
- sendError(res, 400, "Project name is required");
424
- return;
425
- }
426
- this.projectManager.update(params.id, body.name.trim(), body.color);
427
- sendOk(res);
428
- }
429
- catch (err) {
430
- const msg = err instanceof Error ? err.message : String(err);
431
- if (msg.includes("not found")) {
432
- sendNotFound(res, params.id);
433
- }
434
- else {
435
- sendError(res, 400, msg);
436
- }
437
- }
438
- });
439
- r("DELETE", "/api/projects/:id", (_req, res, params) => {
440
- try {
441
- this.projectManager.delete(params.id);
442
- sendOk(res);
443
- }
444
- catch (err) {
445
- const msg = err instanceof Error ? err.message : String(err);
446
- if (msg.includes("not found") || msg.includes("system")) {
447
- sendError(res, 400, msg);
448
- }
449
- else {
450
- sendError(res, 500, msg);
451
- }
452
- }
453
- });
454
- r("GET", "/api/openapi.json", (_req, res) => {
455
- const spec = this.buildOpenApiSpec();
456
- const body = JSON.stringify(spec, null, 2);
457
- res.writeHead(200, {
458
- "Content-Type": "application/json",
459
- "Content-Length": Buffer.byteLength(body),
460
- });
461
- res.end(body);
462
- });
463
- r("GET", "/api/docs", (_req, res) => {
464
- const html = this.buildSwaggerHtml();
465
- res.writeHead(200, {
466
- "Content-Type": "text/html",
467
- "Content-Length": Buffer.byteLength(html),
468
- });
469
- res.end(html);
470
- });
471
- r("GET", "/", (_req, res) => {
472
- const html = this.buildSwaggerHtml();
473
- res.writeHead(200, {
474
- "Content-Type": "text/html",
475
- "Content-Length": Buffer.byteLength(html),
476
- });
477
- res.end(html);
478
- });
479
- r("GET", "/api/events", (_req, res) => {
480
- res.writeHead(200, {
481
- "Content-Type": "text/event-stream",
482
- "Cache-Control": "no-cache",
483
- "Connection": "keep-alive",
484
- });
485
- res.write(": connected\n\n");
486
- this.sseClients.add(res);
487
- _req.on("close", () => {
488
- this.sseClients.delete(res);
489
- });
490
- });
491
- }
492
- buildOpenApiSpec() {
493
- return {
494
- openapi: "3.0.3",
495
- info: {
496
- title: "loop-task HTTP API",
497
- version: "1.0.0",
498
- description: "REST + SSE API for managing loops, tasks, projects, and logs. All endpoints are localhost-only (127.0.0.1).",
499
- },
500
- servers: [
501
- { url: `http://${HTTP_API_HOST}:${HTTP_API_PORT}`, description: "Local daemon" },
502
- ],
503
- paths: {
504
- "/api/loops": {
505
- get: { summary: "List all loops", tags: ["Loops"], responses: { "200": { description: "Array of loops", content: { "application/json": { schema: { type: "array" } } } } } },
506
- post: { summary: "Create a new loop", tags: ["Loops"], requestBody: { content: { "application/json": { schema: { type: "object", properties: { command: { type: "string" }, commandArgs: { type: "array", items: { type: "string" } }, intervalHuman: { type: "string", example: "5m" }, cwd: { type: "string" }, description: { type: "string" }, taskId: { type: "string" }, now: { type: "boolean" }, maxRuns: { type: "integer" }, verbose: { type: "boolean" }, projectId: { type: "string" }, offset: { type: "integer" } } } } } }, responses: { "201": { description: "Loop created", content: { "application/json": { schema: { type: "object", properties: { id: { type: "string" } } } } } }, "400": { description: "Validation error" } } },
507
- },
508
- "/api/loops/{id}": {
509
- get: { summary: "Get loop status", tags: ["Loops"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Loop details" }, "404": { description: "Not found" } } },
510
- patch: { summary: "Update a loop", tags: ["Loops"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], requestBody: { content: { "application/json": { schema: { type: "object" } } } }, responses: { "200": { description: "Updated" }, "400": { description: "Validation error" }, "404": { description: "Not found" } } },
511
- delete: { summary: "Delete a loop", tags: ["Loops"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Deleted" }, "404": { description: "Not found" } } },
512
- },
513
- "/api/loops/{id}/pause": { post: { summary: "Pause a loop", tags: ["Loops"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Paused" }, "404": { description: "Not found" } } } },
514
- "/api/loops/{id}/resume": { post: { summary: "Resume a loop", tags: ["Loops"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Resumed" }, "404": { description: "Not found" } } } },
515
- "/api/loops/{id}/trigger": { post: { summary: "Trigger a loop now", tags: ["Loops"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Triggered" }, "404": { description: "Not found" }, "400": { description: "Max runs reached" }, "409": { description: "Already running" } } } },
516
- "/api/loops/{id}/stop": { post: { summary: "Stop a loop", tags: ["Loops"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Stopped" }, "404": { description: "Not found" } } } },
517
- "/api/loops/stop-all": { post: { summary: "Stop all loops", tags: ["Loops"], responses: { "200": { description: "All stopped", content: { "application/json": { schema: { type: "object", properties: { count: { type: "integer" } } } } } } } } },
518
- "/api/loops/{id}/logs": { get: { summary: "Fetch loop logs", tags: ["Logs"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }, { name: "tail", in: "query", schema: { type: "integer", default: 50 } }], responses: { "200": { description: "Log content" }, "404": { description: "Not found" } } } },
519
- "/api/loops/{id}/logs/stream": { get: { summary: "Stream logs via SSE", tags: ["Logs"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }, { name: "tail", in: "query", schema: { type: "integer" } }], responses: { "200": { description: "SSE stream" }, "404": { description: "Not found" } } } },
520
- "/api/loops/{id}/runs/{num}": { get: { summary: "Get run-specific log", tags: ["Logs"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }, { name: "num", in: "path", required: true, schema: { type: "integer" } }], responses: { "200": { description: "Run log content" } } } },
521
- "/api/tasks": {
522
- get: { summary: "List all tasks", tags: ["Tasks"], responses: { "200": { description: "Array of tasks" } } },
523
- post: { summary: "Create a task", tags: ["Tasks"], requestBody: { content: { "application/json": { schema: { type: "object", properties: { id: { type: "string" }, name: { type: "string" }, command: { type: "string" }, commandArgs: { type: "array", items: { type: "string" } }, onSuccessTaskId: { type: "string" }, onFailureTaskId: { type: "string" } } } } } }, responses: { "201": { description: "Task created" }, "400": { description: "Validation error" } } },
524
- },
525
- "/api/tasks/{id}": {
526
- get: { summary: "Get a task", tags: ["Tasks"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Task details" }, "404": { description: "Not found" } } },
527
- patch: { summary: "Update a task", tags: ["Tasks"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], requestBody: { content: { "application/json": { schema: { type: "object" } } } }, responses: { "200": { description: "Updated" }, "404": { description: "Not found" } } },
528
- delete: { summary: "Delete a task", tags: ["Tasks"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Deleted" }, "404": { description: "Not found" } } },
529
- },
530
- "/api/projects": {
531
- get: { summary: "List all projects", tags: ["Projects"], responses: { "200": { description: "Array of projects" } } },
532
- post: { summary: "Create a project", tags: ["Projects"], requestBody: { content: { "application/json": { schema: { type: "object", properties: { name: { type: "string" }, color: { type: "string" } } } } } }, responses: { "201": { description: "Project created" }, "400": { description: "Validation error" } } },
533
- },
534
- "/api/projects/{id}": {
535
- patch: { summary: "Update a project", tags: ["Projects"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], requestBody: { content: { "application/json": { schema: { type: "object", properties: { name: { type: "string" }, color: { type: "string" } } } } } }, responses: { "200": { description: "Updated" }, "404": { description: "Not found" }, "400": { description: "Validation error" } } },
536
- delete: { summary: "Delete a project", tags: ["Projects"], parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "Deleted" }, "400": { description: "Cannot delete system project" } } },
537
- },
538
- "/api/events": { get: { summary: "Subscribe to daemon events via SSE", tags: ["Events"], responses: { "200": { description: "SSE event stream" } } } },
539
- "/api/openapi.json": { get: { summary: "OpenAPI 3.0 spec", tags: ["Docs"], responses: { "200": { description: "OpenAPI JSON spec" } } } },
540
- "/api/docs": { get: { summary: "Swagger UI", tags: ["Docs"], responses: { "200": { description: "HTML page" } } } },
541
- },
542
- };
543
- }
544
- buildSwaggerHtml() {
545
- const specUrl = "/api/openapi.json";
546
- return `<!DOCTYPE html>
547
- <html lang="en">
548
- <head>
549
- <meta charset="UTF-8">
550
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
551
- <title>loop-task API</title>
552
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css">
553
- <style>
554
- body { margin: 0; }
555
- .swagger-ui { max-width: 1200px; margin: 0 auto; }
556
- .header { background: #0d1117; color: #58a6ff; padding: 12px 24px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-size: 14px; }
557
- .header a { color: #58a6ff; text-decoration: none; }
558
- .header a:hover { text-decoration: underline; }
559
- </style>
560
- </head>
561
- <body>
562
- <div class="header">
563
- <strong>loop-task HTTP API</strong> &mdash;
564
- <a href="/api/openapi.json">OpenAPI JSON</a> &mdash;
565
- <a href="/api/docs">Swagger UI</a>
566
- </div>
567
- <div id="swagger-ui"></div>
568
- <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
569
- <script>
570
- window.onload = function() {
571
- window.ui = SwaggerUIBundle({
572
- url: "${specUrl}",
573
- dom_id: "#swagger-ui",
574
- deepLinking: true,
575
- presets: [SwaggerUIBundle.presets.apis],
576
- layout: "BaseLayout",
577
- });
578
- };
579
- </script>
580
- </body>
581
- </html>`;
582
- }
583
- async handleRequest(req, res) {
584
- try {
585
- const pathSegments = parsePath(req.url);
586
- const match = matchRoute(this.routes, req.method ?? "GET", pathSegments);
587
- if (!match) {
588
- sendError(res, 404, `Not found: ${req.method} ${req.url}`);
589
- return;
590
- }
591
- await match.handler(req, res, match.params);
592
- }
593
- catch (err) {
594
- if (!res.headersSent) {
595
- sendError(res, 500, err instanceof Error ? err.message : String(err));
596
- }
597
- }
598
- }
599
- }