kombinat 0.0.0-stage → 0.2.2
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.
- package/README.md +217 -2
- package/bin/kombinat.js +12 -0
- package/dist/cli.js +4876 -0
- package/dist/web-app/assets/index-BV7O2RdG.css +2 -0
- package/dist/web-app/assets/index-BvFjiquo.js +134 -0
- package/dist/web-app/index.html +25 -0
- package/package.json +54 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4876 @@
|
|
|
1
|
+
// src/cli.ts
|
|
2
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { isMatching as isMatching8, match as match14 } from "ts-pattern";
|
|
5
|
+
|
|
6
|
+
// ../domains/id/schemas.ts
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
var routineNameSchema = z.string().brand();
|
|
9
|
+
var runIdSchema = z.string().brand();
|
|
10
|
+
var calendarEntryIdSchema = z.string().brand();
|
|
11
|
+
var sessionIdSchema = z.string().brand();
|
|
12
|
+
|
|
13
|
+
// ../domains/run/schemas.ts
|
|
14
|
+
import { z as z3 } from "zod";
|
|
15
|
+
|
|
16
|
+
// ../domains/agent/schemas.ts
|
|
17
|
+
import { z as z2 } from "zod";
|
|
18
|
+
var agentNameSchema = z2.enum(["claude", "codex", "command"]);
|
|
19
|
+
|
|
20
|
+
// ../domains/run/schemas.ts
|
|
21
|
+
var runStatusSchema = z3.enum(["running", "succeeded", "failed", "timed_out", "aborted"]);
|
|
22
|
+
var runTriggerSchema = z3.enum(["schedule", "manual", "catch_up", "webhook"]);
|
|
23
|
+
var runRecordSchema = z3.object({
|
|
24
|
+
id: runIdSchema,
|
|
25
|
+
routine: routineNameSchema,
|
|
26
|
+
agent: agentNameSchema,
|
|
27
|
+
trigger: runTriggerSchema,
|
|
28
|
+
scheduledFor: z3.string().nullable(),
|
|
29
|
+
startedAt: z3.string(),
|
|
30
|
+
endedAt: z3.string().nullable(),
|
|
31
|
+
status: runStatusSchema,
|
|
32
|
+
pid: z3.number().nullable(),
|
|
33
|
+
exitCode: z3.number().nullable(),
|
|
34
|
+
sessionId: sessionIdSchema.nullable(),
|
|
35
|
+
resumeCommand: z3.string().nullable(),
|
|
36
|
+
model: z3.string().nullable(),
|
|
37
|
+
costUsd: z3.number().nullable(),
|
|
38
|
+
numTurns: z3.number().nullable(),
|
|
39
|
+
durationMs: z3.number().nullable(),
|
|
40
|
+
resultText: z3.string().nullable(),
|
|
41
|
+
error: z3.string().nullable(),
|
|
42
|
+
logFile: z3.string()
|
|
43
|
+
});
|
|
44
|
+
var runsCursorSchema = z3.string().brand();
|
|
45
|
+
var runsCursorKeySchema = z3.object({
|
|
46
|
+
startedAt: z3.string(),
|
|
47
|
+
routine: routineNameSchema,
|
|
48
|
+
id: runIdSchema
|
|
49
|
+
});
|
|
50
|
+
var runsPageSchema = z3.object({
|
|
51
|
+
runs: z3.array(runRecordSchema),
|
|
52
|
+
nextCursor: runsCursorSchema.nullable(),
|
|
53
|
+
total: z3.number()
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// ../tui/src/app.ts
|
|
57
|
+
import { isMatching as isMatching2, match as match4, P as P2 } from "ts-pattern";
|
|
58
|
+
|
|
59
|
+
// ../utils/date-time.ts
|
|
60
|
+
var absoluteFormatter = new Intl.DateTimeFormat("en-GB", {
|
|
61
|
+
weekday: "short",
|
|
62
|
+
day: "numeric",
|
|
63
|
+
month: "short",
|
|
64
|
+
year: "numeric",
|
|
65
|
+
hour: "2-digit",
|
|
66
|
+
minute: "2-digit",
|
|
67
|
+
second: "2-digit"
|
|
68
|
+
});
|
|
69
|
+
var shortFormatter = new Intl.DateTimeFormat("en-GB", {
|
|
70
|
+
day: "numeric",
|
|
71
|
+
month: "short",
|
|
72
|
+
hour: "2-digit",
|
|
73
|
+
minute: "2-digit",
|
|
74
|
+
second: "2-digit"
|
|
75
|
+
});
|
|
76
|
+
var timestampFormatter = new Intl.DateTimeFormat("en-GB", {
|
|
77
|
+
weekday: "short",
|
|
78
|
+
day: "numeric",
|
|
79
|
+
month: "short",
|
|
80
|
+
hour: "2-digit",
|
|
81
|
+
minute: "2-digit",
|
|
82
|
+
second: "2-digit"
|
|
83
|
+
});
|
|
84
|
+
var clockFormatter = new Intl.DateTimeFormat("en-GB", {
|
|
85
|
+
hour: "2-digit",
|
|
86
|
+
minute: "2-digit"
|
|
87
|
+
});
|
|
88
|
+
var monthFormatter = new Intl.DateTimeFormat("en-US", { month: "short" });
|
|
89
|
+
var weekdayFormatter = new Intl.DateTimeFormat("en-GB", { weekday: "short" });
|
|
90
|
+
var relativeFormatter = new Intl.RelativeTimeFormat("en", { numeric: "auto", style: "short" });
|
|
91
|
+
var SECOND = { unit: "second", seconds: 1 };
|
|
92
|
+
var relativeUnits = [
|
|
93
|
+
{ unit: "year", seconds: 365 * 24 * 3600 },
|
|
94
|
+
{ unit: "month", seconds: 30 * 24 * 3600 },
|
|
95
|
+
{ unit: "week", seconds: 7 * 24 * 3600 },
|
|
96
|
+
{ unit: "day", seconds: 24 * 3600 },
|
|
97
|
+
{ unit: "hour", seconds: 3600 },
|
|
98
|
+
{ unit: "minute", seconds: 60 },
|
|
99
|
+
SECOND
|
|
100
|
+
];
|
|
101
|
+
function formatTimestamp(iso) {
|
|
102
|
+
return timestampFormatter.format(new Date(iso));
|
|
103
|
+
}
|
|
104
|
+
function formatSpan(ms) {
|
|
105
|
+
const seconds = Math.floor(Math.abs(ms) / 1e3);
|
|
106
|
+
if (seconds < 60) return `${seconds}s`;
|
|
107
|
+
const minutes = Math.floor(seconds / 60);
|
|
108
|
+
if (minutes < 60) return `${minutes}m`;
|
|
109
|
+
const hours = Math.floor(minutes / 60);
|
|
110
|
+
if (hours < 10) return minutes % 60 ? `${hours}h ${minutes % 60}m` : `${hours}h`;
|
|
111
|
+
if (hours < 48) return `${hours}h`;
|
|
112
|
+
return `${Math.floor(hours / 24)}d`;
|
|
113
|
+
}
|
|
114
|
+
function formatRelativeCompact(iso, now = Date.now()) {
|
|
115
|
+
if (!iso) return "-";
|
|
116
|
+
const diff = new Date(iso).getTime() - now;
|
|
117
|
+
if (Math.abs(diff) < 1e4) return "now";
|
|
118
|
+
return diff > 0 ? `in ${formatSpan(diff)}` : `${formatSpan(diff)} ago`;
|
|
119
|
+
}
|
|
120
|
+
function formatDuration(ms) {
|
|
121
|
+
if (ms === null) return "-";
|
|
122
|
+
const totalSeconds = Math.round(ms / 1e3);
|
|
123
|
+
if (totalSeconds < 60) return `${totalSeconds}s`;
|
|
124
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
125
|
+
const seconds = totalSeconds % 60;
|
|
126
|
+
if (minutes < 60) return `${minutes}m ${seconds}s`;
|
|
127
|
+
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ../utils/error.ts
|
|
131
|
+
function getErrorMessage(error) {
|
|
132
|
+
return error instanceof Error ? error.message : String(error);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ../tui/src/terminal/text.ts
|
|
136
|
+
import { stripVTControlCharacters } from "node:util";
|
|
137
|
+
|
|
138
|
+
// ../tui/src/terminal/theme.ts
|
|
139
|
+
var PALETTE = {
|
|
140
|
+
page: "#09090a",
|
|
141
|
+
surface: "#111113",
|
|
142
|
+
raised: "#18181b",
|
|
143
|
+
overlay: "#222226",
|
|
144
|
+
fg: "#ececee",
|
|
145
|
+
prose: "#cfcfd3",
|
|
146
|
+
secondary: "#a3a3a9",
|
|
147
|
+
muted: "#8b8b92",
|
|
148
|
+
faint: "#47474d",
|
|
149
|
+
positive: "#4cc38a",
|
|
150
|
+
negative: "#f2555a",
|
|
151
|
+
warning: "#f0913f",
|
|
152
|
+
info: "#6b9cff",
|
|
153
|
+
accent: "#f07846"
|
|
154
|
+
};
|
|
155
|
+
var CUBE_STEPS = [0, 95, 135, 175, 215, 255];
|
|
156
|
+
function toRgb(hex) {
|
|
157
|
+
const value = Number.parseInt(hex.slice(1), 16);
|
|
158
|
+
return { r: value >> 16 & 255, g: value >> 8 & 255, b: value & 255 };
|
|
159
|
+
}
|
|
160
|
+
function distance(left, right) {
|
|
161
|
+
return (left.r - right.r) ** 2 + (left.g - right.g) ** 2 + (left.b - right.b) ** 2;
|
|
162
|
+
}
|
|
163
|
+
function nearestStep(channel) {
|
|
164
|
+
return CUBE_STEPS.reduce(
|
|
165
|
+
(best, step, index) => Math.abs(step - channel) < Math.abs((CUBE_STEPS[best] ?? 0) - channel) ? index : best,
|
|
166
|
+
0
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
function toAnsi256(rgb) {
|
|
170
|
+
const [r, g, b] = [nearestStep(rgb.r), nearestStep(rgb.g), nearestStep(rgb.b)];
|
|
171
|
+
const cube = { r: CUBE_STEPS[r] ?? 0, g: CUBE_STEPS[g] ?? 0, b: CUBE_STEPS[b] ?? 0 };
|
|
172
|
+
const greyLevel = Math.min(23, Math.max(0, Math.round(((rgb.r + rgb.g + rgb.b) / 3 - 8) / 10)));
|
|
173
|
+
const greyValue = 8 + greyLevel * 10;
|
|
174
|
+
const grey = { r: greyValue, g: greyValue, b: greyValue };
|
|
175
|
+
return distance(rgb, grey) < distance(rgb, cube) ? 232 + greyLevel : 16 + 36 * r + 6 * g + b;
|
|
176
|
+
}
|
|
177
|
+
var isTruecolor = /^(truecolor|24bit)$/i.test(process.env["COLORTERM"] ?? "");
|
|
178
|
+
function color(layer, name) {
|
|
179
|
+
const rgb = toRgb(PALETTE[name]);
|
|
180
|
+
return isTruecolor ? `${layer};2;${rgb.r};${rgb.g};${rgb.b}` : `${layer};5;${toAnsi256(rgb)}`;
|
|
181
|
+
}
|
|
182
|
+
var fg = (name) => color(38, name);
|
|
183
|
+
var bg = (name) => color(48, name);
|
|
184
|
+
var BASE = `${bg("page")};${fg("fg")}`;
|
|
185
|
+
|
|
186
|
+
// ../tui/src/terminal/text.ts
|
|
187
|
+
var S = {
|
|
188
|
+
bold: "1",
|
|
189
|
+
dim: fg("muted"),
|
|
190
|
+
italic: "3",
|
|
191
|
+
underline: "4",
|
|
192
|
+
inverse: "7",
|
|
193
|
+
red: fg("negative"),
|
|
194
|
+
green: fg("positive"),
|
|
195
|
+
yellow: fg("warning"),
|
|
196
|
+
blue: fg("info"),
|
|
197
|
+
magenta: fg("fg"),
|
|
198
|
+
cyan: fg("secondary"),
|
|
199
|
+
grey: fg("faint"),
|
|
200
|
+
accent: fg("accent"),
|
|
201
|
+
boldRed: `1;${fg("negative")}`,
|
|
202
|
+
boldGreen: `1;${fg("positive")}`,
|
|
203
|
+
boldYellow: `1;${fg("warning")}`,
|
|
204
|
+
boldBlue: `1;${fg("info")}`,
|
|
205
|
+
boldMagenta: `1;${fg("fg")}`,
|
|
206
|
+
boldCyan: `1;${fg("fg")}`,
|
|
207
|
+
heading: `1;${fg("secondary")}`,
|
|
208
|
+
selected: bg("overlay"),
|
|
209
|
+
hover: bg("raised"),
|
|
210
|
+
surface: bg("surface"),
|
|
211
|
+
popup: bg("overlay")
|
|
212
|
+
};
|
|
213
|
+
var ZERO_WIDTH = [
|
|
214
|
+
[768, 879],
|
|
215
|
+
[8203, 8207],
|
|
216
|
+
[8400, 8447],
|
|
217
|
+
[65024, 65039],
|
|
218
|
+
[65056, 65071],
|
|
219
|
+
[127995, 127999],
|
|
220
|
+
[917760, 917999]
|
|
221
|
+
];
|
|
222
|
+
var WIDE = [
|
|
223
|
+
[4352, 4447],
|
|
224
|
+
[8986, 8987],
|
|
225
|
+
[9001, 9002],
|
|
226
|
+
[9193, 9196],
|
|
227
|
+
[9200, 9200],
|
|
228
|
+
[9203, 9203],
|
|
229
|
+
[9725, 9726],
|
|
230
|
+
[9748, 9749],
|
|
231
|
+
[9800, 9811],
|
|
232
|
+
[9855, 9855],
|
|
233
|
+
[9875, 9875],
|
|
234
|
+
[9889, 9889],
|
|
235
|
+
[9898, 9899],
|
|
236
|
+
[9917, 9918],
|
|
237
|
+
[9924, 9925],
|
|
238
|
+
[9934, 9934],
|
|
239
|
+
[9940, 9940],
|
|
240
|
+
[9962, 9962],
|
|
241
|
+
[9970, 9971],
|
|
242
|
+
[9973, 9973],
|
|
243
|
+
[9978, 9978],
|
|
244
|
+
[9981, 9981],
|
|
245
|
+
[9989, 9989],
|
|
246
|
+
[9994, 9995],
|
|
247
|
+
[10024, 10024],
|
|
248
|
+
[10060, 10060],
|
|
249
|
+
[10062, 10062],
|
|
250
|
+
[10067, 10069],
|
|
251
|
+
[10071, 10071],
|
|
252
|
+
[10133, 10135],
|
|
253
|
+
[10160, 10160],
|
|
254
|
+
[10175, 10175],
|
|
255
|
+
[11035, 11036],
|
|
256
|
+
[11088, 11088],
|
|
257
|
+
[11093, 11093],
|
|
258
|
+
[11904, 12350],
|
|
259
|
+
[12353, 13311],
|
|
260
|
+
[13312, 19903],
|
|
261
|
+
[19968, 40959],
|
|
262
|
+
[40960, 42191],
|
|
263
|
+
[44032, 55203],
|
|
264
|
+
[63744, 64255],
|
|
265
|
+
[65072, 65103],
|
|
266
|
+
[65280, 65376],
|
|
267
|
+
[65504, 65510],
|
|
268
|
+
[126980, 126980],
|
|
269
|
+
[127183, 127183],
|
|
270
|
+
[127374, 127374],
|
|
271
|
+
[127377, 127386],
|
|
272
|
+
[127488, 127569],
|
|
273
|
+
[127744, 128591],
|
|
274
|
+
[128640, 128767],
|
|
275
|
+
[128992, 129003],
|
|
276
|
+
[129280, 129535],
|
|
277
|
+
[129648, 129791],
|
|
278
|
+
[131072, 262141]
|
|
279
|
+
];
|
|
280
|
+
function checkIsInRanges(code, ranges) {
|
|
281
|
+
for (const [from, to] of ranges) {
|
|
282
|
+
if (code < from) return false;
|
|
283
|
+
if (code <= to) return true;
|
|
284
|
+
}
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
function charWidth(char) {
|
|
288
|
+
const code = char.codePointAt(0) ?? 0;
|
|
289
|
+
if (code === 8205 || checkIsInRanges(code, ZERO_WIDTH)) return 0;
|
|
290
|
+
return checkIsInRanges(code, WIDE) ? 2 : 1;
|
|
291
|
+
}
|
|
292
|
+
function textWidth(text2) {
|
|
293
|
+
let width = 0;
|
|
294
|
+
for (const char of text2) width += charWidth(char);
|
|
295
|
+
return width;
|
|
296
|
+
}
|
|
297
|
+
function sanitize(text2) {
|
|
298
|
+
return stripVTControlCharacters(text2).replace(/\t/g, " ").replace(/(?!\n)[\p{Cc}\p{Cf}\p{Variation_Selector}]/gu, "");
|
|
299
|
+
}
|
|
300
|
+
function lineWidth(line) {
|
|
301
|
+
return line.reduce((sum, span) => sum + textWidth(span.text), 0);
|
|
302
|
+
}
|
|
303
|
+
function pushText(out, text2, source) {
|
|
304
|
+
if (!text2) return;
|
|
305
|
+
const last = out[out.length - 1];
|
|
306
|
+
if (last && last.style === source.style && last.link === source.link) {
|
|
307
|
+
last.text += text2;
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
const span = { text: text2 };
|
|
311
|
+
if (source.style !== void 0) span.style = source.style;
|
|
312
|
+
if (source.link !== void 0) span.link = source.link;
|
|
313
|
+
out.push(span);
|
|
314
|
+
}
|
|
315
|
+
function sliceLine(line, start, end) {
|
|
316
|
+
const out = [];
|
|
317
|
+
let col = 0;
|
|
318
|
+
for (const span of line) {
|
|
319
|
+
let text2 = "";
|
|
320
|
+
for (const char of span.text) {
|
|
321
|
+
const w = charWidth(char);
|
|
322
|
+
if (col >= start && col + w <= end) text2 += char;
|
|
323
|
+
else if (w === 2 && col < end && col + w > start) text2 += " ";
|
|
324
|
+
col += w;
|
|
325
|
+
if (col >= end) break;
|
|
326
|
+
}
|
|
327
|
+
pushText(out, text2, span);
|
|
328
|
+
if (col >= end) break;
|
|
329
|
+
}
|
|
330
|
+
return out;
|
|
331
|
+
}
|
|
332
|
+
function fitLine(line, width) {
|
|
333
|
+
const current = lineWidth(line);
|
|
334
|
+
if (current <= width)
|
|
335
|
+
return current === width ? line : [...line, { text: " ".repeat(width - current) }];
|
|
336
|
+
if (width <= 0) return [];
|
|
337
|
+
const out = [];
|
|
338
|
+
let col = 0;
|
|
339
|
+
let lastSpan = line[0] ?? { text: "" };
|
|
340
|
+
outer: for (const span of line) {
|
|
341
|
+
let text2 = "";
|
|
342
|
+
for (const char of span.text) {
|
|
343
|
+
const w = charWidth(char);
|
|
344
|
+
if (col + w > width - 1) {
|
|
345
|
+
pushText(out, text2, span);
|
|
346
|
+
lastSpan = span;
|
|
347
|
+
break outer;
|
|
348
|
+
}
|
|
349
|
+
text2 += char;
|
|
350
|
+
col += w;
|
|
351
|
+
}
|
|
352
|
+
pushText(out, text2, span);
|
|
353
|
+
lastSpan = span;
|
|
354
|
+
}
|
|
355
|
+
pushText(out, "\u2026", lastSpan);
|
|
356
|
+
col += 1;
|
|
357
|
+
return col < width ? [...out, { text: " ".repeat(width - col) }] : out;
|
|
358
|
+
}
|
|
359
|
+
function toLine(cells) {
|
|
360
|
+
const out = [];
|
|
361
|
+
for (const cell of cells) pushText(out, cell.char, cell.span);
|
|
362
|
+
return out;
|
|
363
|
+
}
|
|
364
|
+
function cellAfterColumns(cells, from, columns2) {
|
|
365
|
+
let index = from;
|
|
366
|
+
for (let col = 0; index < cells.length && col < columns2; index++) {
|
|
367
|
+
col += cells[index]?.width ?? 0;
|
|
368
|
+
}
|
|
369
|
+
return index;
|
|
370
|
+
}
|
|
371
|
+
function wrapLine(line, width, indent = 0) {
|
|
372
|
+
const hang = indent < width ? indent : 0;
|
|
373
|
+
const cells = line.flatMap(
|
|
374
|
+
(span) => Array.from(span.text, (char) => ({ char, width: charWidth(char), span }))
|
|
375
|
+
);
|
|
376
|
+
const lines = [];
|
|
377
|
+
let start = 0;
|
|
378
|
+
while (start < cells.length || lines.length === 0) {
|
|
379
|
+
const isFirst = lines.length === 0;
|
|
380
|
+
if (!isFirst) while (cells[start]?.char === " ") start++;
|
|
381
|
+
if (start >= cells.length && !isFirst) break;
|
|
382
|
+
const available = isFirst ? width : width - hang;
|
|
383
|
+
let end = start;
|
|
384
|
+
let used = 0;
|
|
385
|
+
for (let cell = cells[end]; cell !== void 0 && used + cell.width <= available; cell = cells[end]) {
|
|
386
|
+
used += cell.width;
|
|
387
|
+
end++;
|
|
388
|
+
}
|
|
389
|
+
if (end === start && end < cells.length) end++;
|
|
390
|
+
if (end < cells.length) {
|
|
391
|
+
const minBreak = Math.max(start + 1, isFirst ? cellAfterColumns(cells, start, hang) : 0);
|
|
392
|
+
for (let i = end; i >= minBreak; i--) {
|
|
393
|
+
if (cells[i]?.char !== " ") continue;
|
|
394
|
+
end = i;
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
let last = end;
|
|
399
|
+
while (last > start && cells[last - 1]?.char === " ") last--;
|
|
400
|
+
const body = toLine(cells.slice(start, last));
|
|
401
|
+
lines.push(isFirst || hang === 0 ? body : [{ text: " ".repeat(hang) }, ...body]);
|
|
402
|
+
start = end;
|
|
403
|
+
}
|
|
404
|
+
return lines;
|
|
405
|
+
}
|
|
406
|
+
function sgr(base, style) {
|
|
407
|
+
const params = [base, style].filter(Boolean).join(";");
|
|
408
|
+
return params ? `\x1B[0;${params}m` : "\x1B[0m";
|
|
409
|
+
}
|
|
410
|
+
function toAnsi(line, base) {
|
|
411
|
+
let out = "";
|
|
412
|
+
for (const span of line) {
|
|
413
|
+
const text2 = span.link ? `\x1B]8;;${span.link}\x07${span.text}\x1B]8;;\x07` : span.text;
|
|
414
|
+
out += sgr(base, span.style) + text2;
|
|
415
|
+
}
|
|
416
|
+
return `${out}\x1B[0m`;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// ../tui/src/views.ts
|
|
420
|
+
import { isMatching, match as match3, P } from "ts-pattern";
|
|
421
|
+
|
|
422
|
+
// ../domains/run/utils.ts
|
|
423
|
+
import { match } from "ts-pattern";
|
|
424
|
+
|
|
425
|
+
// ../domains/run/constants.ts
|
|
426
|
+
var RUNS_PAGE_SIZE = 50;
|
|
427
|
+
var RUNS_CURSOR_ERROR = "cursor must be one that /api/runs returned";
|
|
428
|
+
|
|
429
|
+
// ../domains/run/utils.ts
|
|
430
|
+
function createRunId(now = /* @__PURE__ */ new Date()) {
|
|
431
|
+
const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
|
|
432
|
+
const suffix = Math.random().toString(36).slice(2, 6);
|
|
433
|
+
return runIdSchema.parse(`${stamp}-${suffix}`);
|
|
434
|
+
}
|
|
435
|
+
function getRunDurationMs(run, now = Date.now()) {
|
|
436
|
+
const end = run.endedAt ? new Date(run.endedAt).getTime() : now;
|
|
437
|
+
return end - new Date(run.startedAt).getTime();
|
|
438
|
+
}
|
|
439
|
+
function getRunStatusLabel(status) {
|
|
440
|
+
return match(status).with("running", () => "Running").with("succeeded", () => "Succeeded").with("failed", () => "Failed").with("timed_out", () => "Timed out").with("aborted", () => "Aborted").exhaustive();
|
|
441
|
+
}
|
|
442
|
+
function getTriggerLabel(trigger) {
|
|
443
|
+
return match(trigger).with("schedule", () => "Scheduled").with("manual", () => "Manual").with("catch_up", () => "Catch-up").with("webhook", () => "Webhook").exhaustive();
|
|
444
|
+
}
|
|
445
|
+
function compareText(a, b) {
|
|
446
|
+
if (a === b) return 0;
|
|
447
|
+
return a < b ? -1 : 1;
|
|
448
|
+
}
|
|
449
|
+
function compareRunsByNewest(a, b) {
|
|
450
|
+
return compareText(b.startedAt, a.startedAt) || compareText(b.routine, a.routine) || compareText(b.id, a.id);
|
|
451
|
+
}
|
|
452
|
+
function encodeRunsCursor({ startedAt, routine, id }) {
|
|
453
|
+
return runsCursorSchema.parse(JSON.stringify({ startedAt, routine, id }));
|
|
454
|
+
}
|
|
455
|
+
function decodeRunsCursor(cursor) {
|
|
456
|
+
try {
|
|
457
|
+
const key = runsCursorKeySchema.safeParse(JSON.parse(cursor));
|
|
458
|
+
return key.success ? key.data : null;
|
|
459
|
+
} catch {
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
function parseRunsPageQuery(params) {
|
|
464
|
+
const routine = params.get("routine");
|
|
465
|
+
const cursor = params.get("cursor");
|
|
466
|
+
const cursorKey = cursor === null ? null : decodeRunsCursor(cursor);
|
|
467
|
+
if (cursor !== null && cursorKey === null) return null;
|
|
468
|
+
return { routine: routine === null ? null : routineNameSchema.parse(routine), cursor: cursorKey };
|
|
469
|
+
}
|
|
470
|
+
function paginateRuns(newestFirstRuns, cursor, pageSize = RUNS_PAGE_SIZE) {
|
|
471
|
+
const start = cursor === null ? 0 : newestFirstRuns.findIndex((run) => compareRunsByNewest(run, cursor) > 0);
|
|
472
|
+
const page = start === -1 ? [] : newestFirstRuns.slice(start, start + pageSize);
|
|
473
|
+
const last = page.at(-1);
|
|
474
|
+
const hasMore = start !== -1 && start + pageSize < newestFirstRuns.length;
|
|
475
|
+
return {
|
|
476
|
+
runs: page,
|
|
477
|
+
nextCursor: hasMore && last !== void 0 ? encodeRunsCursor(last) : null,
|
|
478
|
+
total: newestFirstRuns.length
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// ../domains/scheduler/utils.ts
|
|
483
|
+
import { match as match2 } from "ts-pattern";
|
|
484
|
+
function getSkipReasonLabel(reason) {
|
|
485
|
+
return match2(reason).with("already_running", () => "already running").with("concurrency_limit", () => "concurrency limit").with("disabled", () => "disabled").exhaustive();
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// ../domains/transcript/utils.ts
|
|
489
|
+
var PREVIEW_LENGTH = 160;
|
|
490
|
+
function toPreview(value) {
|
|
491
|
+
const firstLine = value.split("\n")[0] ?? "";
|
|
492
|
+
return firstLine.length > PREVIEW_LENGTH ? `${firstLine.slice(0, PREVIEW_LENGTH - 1)}\u2026` : firstLine;
|
|
493
|
+
}
|
|
494
|
+
function checkIsSubagent(item) {
|
|
495
|
+
return "isSubagent" in item && item.isSubagent;
|
|
496
|
+
}
|
|
497
|
+
function getTranscriptEmptyLabel(isRunning) {
|
|
498
|
+
return isRunning ? "Waiting for the first events\u2026" : "No transcript events.";
|
|
499
|
+
}
|
|
500
|
+
function getTranscriptResultLabel(isError) {
|
|
501
|
+
return isError ? "Finished with error" : "Finished";
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ../domains/webhook/utils.ts
|
|
505
|
+
function formatPayloadSize(bytes) {
|
|
506
|
+
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
|
|
507
|
+
}
|
|
508
|
+
function getQueuePositionLabel(index) {
|
|
509
|
+
return index === 0 ? "Next" : `#${index + 1}`;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// ../tui/src/terminal/markdown.ts
|
|
513
|
+
var HEADING_STYLES = [S.boldMagenta, S.boldBlue, S.boldCyan, S.bold, S.bold, S.bold];
|
|
514
|
+
var INLINE = /(\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\([^)\s]+\)|~~[^~]+~~)/g;
|
|
515
|
+
function renderInline(text2, baseStyle) {
|
|
516
|
+
const spans = [];
|
|
517
|
+
const withBase = (style) => baseStyle ? `${baseStyle};${style}` : style;
|
|
518
|
+
const pushPlain = (value) => value && spans.push(baseStyle ? { text: value, style: baseStyle } : { text: value });
|
|
519
|
+
let last = 0;
|
|
520
|
+
for (const match15 of text2.matchAll(INLINE)) {
|
|
521
|
+
pushPlain(text2.slice(last, match15.index));
|
|
522
|
+
const token = match15[0];
|
|
523
|
+
if (token.startsWith("`")) spans.push({ text: token.slice(1, -1), style: withBase(S.cyan) });
|
|
524
|
+
else if (token.startsWith("**") || token.startsWith("__"))
|
|
525
|
+
spans.push({ text: token.slice(2, -2), style: withBase(S.bold) });
|
|
526
|
+
else if (token.startsWith("~~")) spans.push({ text: token.slice(2, -2), style: withBase("9") });
|
|
527
|
+
else {
|
|
528
|
+
const [, label, href] = /^\[([^\]]+)\]\(([^)\s]+)\)$/.exec(token) ?? [];
|
|
529
|
+
if (label !== void 0 && href !== void 0) {
|
|
530
|
+
spans.push({ text: label, style: withBase(`${S.underline};${S.blue}`), link: href });
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
last = match15.index + token.length;
|
|
534
|
+
}
|
|
535
|
+
pushPlain(text2.slice(last));
|
|
536
|
+
return spans;
|
|
537
|
+
}
|
|
538
|
+
function prefixed(prefix, body, width) {
|
|
539
|
+
const indent = textWidth(prefix.text);
|
|
540
|
+
return wrapLine([prefix, ...body], width, indent);
|
|
541
|
+
}
|
|
542
|
+
function renderMarkdown(source, width) {
|
|
543
|
+
const lines = [];
|
|
544
|
+
let inCode = false;
|
|
545
|
+
let lastWasBlank = true;
|
|
546
|
+
for (const rawLine of sanitize(source.replace(/\r\n/g, "\n")).split("\n")) {
|
|
547
|
+
if (/^\s*(```|~~~)/.test(rawLine)) {
|
|
548
|
+
inCode = !inCode;
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
if (inCode) {
|
|
552
|
+
lines.push(
|
|
553
|
+
...wrapLine(
|
|
554
|
+
[
|
|
555
|
+
{ text: "\u2502 ", style: S.dim },
|
|
556
|
+
{ text: rawLine, style: S.cyan }
|
|
557
|
+
],
|
|
558
|
+
width,
|
|
559
|
+
2
|
|
560
|
+
)
|
|
561
|
+
);
|
|
562
|
+
lastWasBlank = false;
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
if (!rawLine.trim()) {
|
|
566
|
+
if (!lastWasBlank) lines.push([]);
|
|
567
|
+
lastWasBlank = true;
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
lastWasBlank = false;
|
|
571
|
+
const [, hashes, heading] = /^(#{1,6})\s+(.*)$/.exec(rawLine) ?? [];
|
|
572
|
+
if (hashes !== void 0 && heading !== void 0) {
|
|
573
|
+
lines.push(...wrapLine(renderInline(heading, HEADING_STYLES[hashes.length - 1]), width));
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(rawLine)) {
|
|
577
|
+
lines.push([{ text: "\u2500".repeat(Math.min(width, 40)), style: S.dim }]);
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
const [, quote] = /^\s*>\s?(.*)$/.exec(rawLine) ?? [];
|
|
581
|
+
if (quote !== void 0) {
|
|
582
|
+
lines.push(...prefixed({ text: "\u258E ", style: S.dim }, renderInline(quote, S.italic), width));
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
const [, bulletIndent, bullet] = /^(\s*)[-*+]\s+(.*)$/.exec(rawLine) ?? [];
|
|
586
|
+
if (bulletIndent !== void 0 && bullet !== void 0) {
|
|
587
|
+
lines.push(
|
|
588
|
+
...prefixed({ text: `${bulletIndent}\u2022 `, style: S.yellow }, renderInline(bullet), width)
|
|
589
|
+
);
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
const [, numberIndent, number, item] = /^(\s*)(\d+[.)])\s+(.*)$/.exec(rawLine) ?? [];
|
|
593
|
+
if (numberIndent !== void 0 && number !== void 0 && item !== void 0) {
|
|
594
|
+
lines.push(
|
|
595
|
+
...prefixed(
|
|
596
|
+
{ text: `${numberIndent}${number} `, style: S.yellow },
|
|
597
|
+
renderInline(item),
|
|
598
|
+
width
|
|
599
|
+
)
|
|
600
|
+
);
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
if (/^\s*\|/.test(rawLine)) {
|
|
604
|
+
lines.push(
|
|
605
|
+
...wrapLine(
|
|
606
|
+
rawLine.split(/(\|)/).filter(Boolean).map((part) => part === "|" ? { text: part, style: S.dim } : { text: part }),
|
|
607
|
+
width
|
|
608
|
+
)
|
|
609
|
+
);
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
lines.push(...wrapLine(renderInline(rawLine), width));
|
|
613
|
+
}
|
|
614
|
+
while (lines.at(-1)?.length === 0) lines.pop();
|
|
615
|
+
return lines;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// ../tui/src/views.ts
|
|
619
|
+
var SPINNER = "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F";
|
|
620
|
+
var MAX_BLOCK_LINES = 200;
|
|
621
|
+
var MAX_LINE_CHARS = 2e3;
|
|
622
|
+
function getStatusLook(status) {
|
|
623
|
+
return match3(status).with("running", () => ({ icon: "\u25CF", style: S.yellow })).with("succeeded", () => ({ icon: "\u2713", style: S.green })).with("failed", () => ({ icon: "\u2717", style: S.red })).with("timed_out", () => ({ icon: "\u2717", style: S.red })).with("aborted", () => ({ icon: "\u2298", style: S.dim })).exhaustive();
|
|
624
|
+
}
|
|
625
|
+
var text = (value, style) => style ? { text: value, style } : { text: value };
|
|
626
|
+
var blank = () => ({ line: [] });
|
|
627
|
+
var toContent = (lines) => lines.map((line) => ({ line }));
|
|
628
|
+
function spinner(now) {
|
|
629
|
+
return SPINNER.charAt(Math.floor(now / 100) % SPINNER.length);
|
|
630
|
+
}
|
|
631
|
+
function statusIcon(status, now) {
|
|
632
|
+
const look = getStatusLook(status);
|
|
633
|
+
return text(isMatching("running", status) ? spinner(now) : look.icon, look.style);
|
|
634
|
+
}
|
|
635
|
+
function statusBadge(status, now) {
|
|
636
|
+
const look = getStatusLook(status);
|
|
637
|
+
return [statusIcon(status, now), text(` ${getRunStatusLabel(status)}`, look.style)];
|
|
638
|
+
}
|
|
639
|
+
function fitCell(cell) {
|
|
640
|
+
const width = lineWidth(cell.line);
|
|
641
|
+
if (cell.align !== "right" || width >= cell.width) return fitLine(cell.line, cell.width);
|
|
642
|
+
return [text(" ".repeat(cell.width - width)), ...cell.line];
|
|
643
|
+
}
|
|
644
|
+
function columns(cells, gap = 2) {
|
|
645
|
+
return cells.flatMap(
|
|
646
|
+
(cell, index) => index === 0 ? fitCell(cell) : [text(" ".repeat(gap)), ...fitCell(cell)]
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
function withStyle(line, style) {
|
|
650
|
+
return line.map((span) => ({ ...span, style: span.style ? `${span.style};${style}` : style }));
|
|
651
|
+
}
|
|
652
|
+
function onBackground(line, background) {
|
|
653
|
+
return line.map((span) => ({
|
|
654
|
+
...span,
|
|
655
|
+
style: span.style ? `${background};${span.style}` : background
|
|
656
|
+
}));
|
|
657
|
+
}
|
|
658
|
+
function titleSpans(title, isFocused, icon) {
|
|
659
|
+
const [, key, name = title] = /^\[(\S+)\] (.*)$/.exec(title) ?? [];
|
|
660
|
+
return [
|
|
661
|
+
...icon ? [icon, text(" ")] : [],
|
|
662
|
+
...key ? [text(`${key} `, S.grey)] : [],
|
|
663
|
+
text(name, isFocused ? S.boldMagenta : S.heading)
|
|
664
|
+
];
|
|
665
|
+
}
|
|
666
|
+
function box({
|
|
667
|
+
title,
|
|
668
|
+
width,
|
|
669
|
+
height,
|
|
670
|
+
body,
|
|
671
|
+
isFocused,
|
|
672
|
+
footer,
|
|
673
|
+
highlightRow,
|
|
674
|
+
icon,
|
|
675
|
+
tone = "panel"
|
|
676
|
+
}) {
|
|
677
|
+
const isPopup = match3(tone).with("popup", () => true).with("panel", () => false).exhaustive();
|
|
678
|
+
const fill = isPopup ? S.popup : S.surface;
|
|
679
|
+
const inner = width - 4;
|
|
680
|
+
const bar = isFocused ? text("\u258C", S.accent) : text(" ");
|
|
681
|
+
const footerLine = footer ? [text(footer, isFocused ? S.cyan : S.grey)] : [];
|
|
682
|
+
const header = [
|
|
683
|
+
...fitLine(titleSpans(title, isFocused, icon), Math.max(0, inner - lineWidth(footerLine))),
|
|
684
|
+
...footerLine
|
|
685
|
+
];
|
|
686
|
+
const edge = text(" ");
|
|
687
|
+
const row = (content, background = fill) => [
|
|
688
|
+
...onBackground([bar], fill),
|
|
689
|
+
...onBackground([text(" "), ...fitLine(content, inner), text(" ")], background),
|
|
690
|
+
...isPopup ? onBackground([edge], fill) : [edge]
|
|
691
|
+
];
|
|
692
|
+
const rows = Array.from({ length: Math.max(0, height - 2) }, (_, index) => {
|
|
693
|
+
const content = body[index] ?? [];
|
|
694
|
+
if (index !== highlightRow) return row(content);
|
|
695
|
+
return row(content, `${fill};${isFocused ? S.selected : S.hover}`);
|
|
696
|
+
});
|
|
697
|
+
const last = isPopup ? row([]) : [text(" ".repeat(width))];
|
|
698
|
+
return [row(header), ...rows, last];
|
|
699
|
+
}
|
|
700
|
+
function overlayOnto(frame, popup, width) {
|
|
701
|
+
const popupWidth = lineWidth(popup[0] ?? []);
|
|
702
|
+
const top = Math.max(0, Math.floor((frame.length - popup.length) / 2));
|
|
703
|
+
const left = Math.max(0, Math.floor((width - popupWidth) / 2));
|
|
704
|
+
return frame.map((row, index) => {
|
|
705
|
+
const popupRow = popup[index - top];
|
|
706
|
+
if (!popupRow) return row;
|
|
707
|
+
return [...sliceLine(row, 0, left), ...popupRow, ...sliceLine(row, left + popupWidth, width)];
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
function statusLines(overview, error, loadedAt, now) {
|
|
711
|
+
if (error) {
|
|
712
|
+
return [
|
|
713
|
+
[text("\u2717 ", S.red), text("daemon not reachable", S.boldRed)],
|
|
714
|
+
[
|
|
715
|
+
text(
|
|
716
|
+
loadedAt ? `showing data from ${formatRelativeCompact(new Date(loadedAt).toISOString(), now)}` : "is it running? check with the status command",
|
|
717
|
+
S.dim
|
|
718
|
+
)
|
|
719
|
+
]
|
|
720
|
+
];
|
|
721
|
+
}
|
|
722
|
+
if (!overview) return [[text("connecting\u2026", S.dim)]];
|
|
723
|
+
const { status } = overview;
|
|
724
|
+
return [
|
|
725
|
+
[
|
|
726
|
+
text("\u25CF ", S.green),
|
|
727
|
+
text("daemon", S.bold),
|
|
728
|
+
text(` pid ${status.pid}`, S.dim),
|
|
729
|
+
text(" \xB7 ", S.dim),
|
|
730
|
+
text(`up ${formatSpan(now - new Date(status.startedAt).getTime())}`, S.dim)
|
|
731
|
+
],
|
|
732
|
+
[
|
|
733
|
+
text("tick "),
|
|
734
|
+
text(formatRelativeCompact(status.lastTickAt, now), S.cyan),
|
|
735
|
+
text(" \xB7 ", S.dim),
|
|
736
|
+
text(
|
|
737
|
+
`${status.running}/${status.maxConcurrentRuns} running`,
|
|
738
|
+
status.running > 0 ? S.boldYellow : void 0
|
|
739
|
+
),
|
|
740
|
+
text(" \xB7 ", S.dim),
|
|
741
|
+
text(status.timezone, S.magenta)
|
|
742
|
+
]
|
|
743
|
+
];
|
|
744
|
+
}
|
|
745
|
+
function formatCopyright(version, now) {
|
|
746
|
+
const copyright = `\xA9 ${new Date(now).getFullYear()}`;
|
|
747
|
+
return version === void 0 ? copyright : `v${version} \xB7 ${copyright}`;
|
|
748
|
+
}
|
|
749
|
+
function formatQueueLabel(count) {
|
|
750
|
+
return `${count} in queue`;
|
|
751
|
+
}
|
|
752
|
+
function getRoutineTabs(routine) {
|
|
753
|
+
return routine.webhook ? ["runs", "prompt", "skips", "queue"] : ["runs", "prompt", "skips"];
|
|
754
|
+
}
|
|
755
|
+
function routineRow(routine, width, now) {
|
|
756
|
+
const icon = routine.running ? text(spinner(now), S.yellow) : routine.lastRun ? statusIcon(routine.lastRun.status, now) : text("\xB7", S.dim);
|
|
757
|
+
const next = !routine.enabled ? "off" : routine.nextRunAt ? formatRelativeCompact(routine.nextRunAt, now) : "manual";
|
|
758
|
+
return [
|
|
759
|
+
icon,
|
|
760
|
+
text(" "),
|
|
761
|
+
...columns([
|
|
762
|
+
{
|
|
763
|
+
line: [
|
|
764
|
+
text(routine.name, routine.running ? S.boldYellow : routine.enabled ? void 0 : S.dim),
|
|
765
|
+
...routine.queuedWebhooks > 0 ? [text(` ${formatQueueLabel(routine.queuedWebhooks)}`, S.yellow)] : []
|
|
766
|
+
],
|
|
767
|
+
width: Math.max(4, width - 13)
|
|
768
|
+
},
|
|
769
|
+
{ line: [text(next, routine.nextRunAt ? S.cyan : S.dim)], width: 9, align: "right" }
|
|
770
|
+
])
|
|
771
|
+
];
|
|
772
|
+
}
|
|
773
|
+
function runRow(run, width, now) {
|
|
774
|
+
return [
|
|
775
|
+
statusIcon(run.status, now),
|
|
776
|
+
text(" "),
|
|
777
|
+
...columns(
|
|
778
|
+
[
|
|
779
|
+
{ line: [text(run.routine)], width: Math.max(4, width - 21) },
|
|
780
|
+
{
|
|
781
|
+
line: [text(formatRelativeCompact(run.startedAt, now), S.cyan)],
|
|
782
|
+
width: 10,
|
|
783
|
+
align: "right"
|
|
784
|
+
},
|
|
785
|
+
{
|
|
786
|
+
line: [text(formatDuration(getRunDurationMs(run, now)), S.magenta)],
|
|
787
|
+
width: 7,
|
|
788
|
+
align: "right"
|
|
789
|
+
}
|
|
790
|
+
],
|
|
791
|
+
1
|
|
792
|
+
)
|
|
793
|
+
];
|
|
794
|
+
}
|
|
795
|
+
function detailRows(pairs, width) {
|
|
796
|
+
const labelWidth = 10;
|
|
797
|
+
const isTwoColumn = width >= 96;
|
|
798
|
+
const half = Math.floor(width / 2);
|
|
799
|
+
const rows = [];
|
|
800
|
+
const label = (value) => text(value.padEnd(labelWidth), S.dim);
|
|
801
|
+
const queue = [...pairs];
|
|
802
|
+
for (let pair = queue.shift(); pair !== void 0; pair = queue.shift()) {
|
|
803
|
+
const next = queue[0];
|
|
804
|
+
if (isTwoColumn && pair.isWide !== true && next !== void 0 && next.isWide !== true) {
|
|
805
|
+
rows.push([
|
|
806
|
+
...fitLine([label(pair.label), ...pair.value], half),
|
|
807
|
+
...fitLine([label(next.label), ...next.value], width - half)
|
|
808
|
+
]);
|
|
809
|
+
queue.shift();
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
const [first = [], ...rest] = wrapLine(pair.value, width - labelWidth);
|
|
813
|
+
rows.push(
|
|
814
|
+
[label(pair.label), ...first],
|
|
815
|
+
...rest.map((line) => [text(" ".repeat(labelWidth)), ...line])
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
return rows;
|
|
819
|
+
}
|
|
820
|
+
function sectionTitle(title, aside) {
|
|
821
|
+
return [text(title.toUpperCase(), S.heading), ...aside ? [text(` ${aside}`, S.grey)] : []];
|
|
822
|
+
}
|
|
823
|
+
function timeValue(iso, now) {
|
|
824
|
+
if (!iso) return [text("-", S.dim)];
|
|
825
|
+
return [text(formatTimestamp(iso)), text(` \xB7 ${formatRelativeCompact(iso, now)}`, S.cyan)];
|
|
826
|
+
}
|
|
827
|
+
function getTabLabel(tab, detail, runs) {
|
|
828
|
+
const formatCount = (items) => items === void 0 ? "" : ` ${items.length}`;
|
|
829
|
+
return match3(tab).with("runs", () => runs === void 0 ? "Runs" : `Runs ${runs.total}`).with("prompt", () => "Prompt").with("skips", () => `Skipped${formatCount(detail?.skips)}`).with("queue", () => `Queue${formatCount(detail?.queue)}`).exhaustive();
|
|
830
|
+
}
|
|
831
|
+
function tabBar(tabs, active) {
|
|
832
|
+
return [
|
|
833
|
+
...tabs.flatMap((tab) => [
|
|
834
|
+
text(` ${tab.label} `, tab.id === active ? `${S.boldMagenta};${S.selected}` : S.dim),
|
|
835
|
+
text(" ")
|
|
836
|
+
]),
|
|
837
|
+
text(" [ ] switch", S.grey)
|
|
838
|
+
];
|
|
839
|
+
}
|
|
840
|
+
function runsTable(routine, { runs, total }, width, now) {
|
|
841
|
+
if (runs.length === 0) return [{ line: [text("No runs yet.", S.dim)] }];
|
|
842
|
+
const isWide = width >= 78;
|
|
843
|
+
const header = isWide ? [
|
|
844
|
+
{ line: [text("STATUS")], width: 12 },
|
|
845
|
+
{ line: [text("RUN")], width: 22 },
|
|
846
|
+
{ line: [text("TRIGGER")], width: 9 },
|
|
847
|
+
{ line: [text("STARTED")], width: 10, align: "right" },
|
|
848
|
+
{ line: [text("DURATION")], width: 8, align: "right" },
|
|
849
|
+
{ line: [text("TURNS")], width: 5, align: "right" }
|
|
850
|
+
] : [
|
|
851
|
+
{ line: [text(" ")], width: 1 },
|
|
852
|
+
{ line: [text("RUN")], width: Math.max(8, width - 24) },
|
|
853
|
+
{ line: [text("STARTED")], width: 10, align: "right" },
|
|
854
|
+
{ line: [text("TIME")], width: 7, align: "right" }
|
|
855
|
+
];
|
|
856
|
+
const headerLine = withStyle(columns(header), S.dim);
|
|
857
|
+
const rows = runs.map((run) => {
|
|
858
|
+
const started = [text(formatRelativeCompact(run.startedAt, now), S.cyan)];
|
|
859
|
+
const duration = [text(formatDuration(getRunDurationMs(run, now)), S.magenta)];
|
|
860
|
+
const cells = isWide ? [
|
|
861
|
+
{ line: statusBadge(run.status, now), width: 12 },
|
|
862
|
+
{ line: [text(run.id)], width: 22 },
|
|
863
|
+
{ line: [text(getTriggerLabel(run.trigger), S.dim)], width: 9 },
|
|
864
|
+
{ line: started, width: 10, align: "right" },
|
|
865
|
+
{ line: duration, width: 8, align: "right" },
|
|
866
|
+
{ line: [text(String(run.numTurns ?? "-"))], width: 5, align: "right" }
|
|
867
|
+
] : [
|
|
868
|
+
{ line: [statusIcon(run.status, now)], width: 1 },
|
|
869
|
+
{ line: [text(run.id)], width: Math.max(8, width - 24) },
|
|
870
|
+
{ line: started, width: 10, align: "right" },
|
|
871
|
+
{ line: duration, width: 7, align: "right" }
|
|
872
|
+
];
|
|
873
|
+
return { line: columns(cells), action: { kind: "open-run", routine, id: run.id } };
|
|
874
|
+
});
|
|
875
|
+
const more = total - runs.length;
|
|
876
|
+
return [
|
|
877
|
+
{ line: headerLine },
|
|
878
|
+
...rows,
|
|
879
|
+
...more > 0 ? [{ line: [text(`${more} more\u2026`, S.dim)] }] : []
|
|
880
|
+
];
|
|
881
|
+
}
|
|
882
|
+
function skipsTable(skips, now) {
|
|
883
|
+
if (skips.length === 0) return [{ line: [text("Nothing skipped.", S.dim)] }];
|
|
884
|
+
const header = withStyle(
|
|
885
|
+
columns([
|
|
886
|
+
{ line: [text("SKIPPED")], width: 10 },
|
|
887
|
+
{ line: [text("SCHEDULED FOR")], width: 22 },
|
|
888
|
+
{ line: [text("REASON")], width: 20 }
|
|
889
|
+
]),
|
|
890
|
+
S.dim
|
|
891
|
+
);
|
|
892
|
+
const rows = [...skips].reverse().map(
|
|
893
|
+
(skip) => columns([
|
|
894
|
+
{ line: [text(formatRelativeCompact(skip.at, now), S.cyan)], width: 10 },
|
|
895
|
+
{ line: [text(formatTimestamp(skip.scheduledFor))], width: 22 },
|
|
896
|
+
{ line: [text(getSkipReasonLabel(skip.reason), S.yellow)], width: 20 }
|
|
897
|
+
])
|
|
898
|
+
);
|
|
899
|
+
return toContent([header, ...rows]);
|
|
900
|
+
}
|
|
901
|
+
var QUEUE_BODY_LINES = 3;
|
|
902
|
+
function wrapQueueBody(preview, width) {
|
|
903
|
+
const body = sanitize(preview.replace(/\s+/g, " ").trim());
|
|
904
|
+
if (body === "") return [[text("empty body", S.dim)]];
|
|
905
|
+
const lines = wrapLine([text(body)], width);
|
|
906
|
+
if (lines.length <= QUEUE_BODY_LINES) return lines;
|
|
907
|
+
const kept = lines.slice(0, QUEUE_BODY_LINES - 1);
|
|
908
|
+
const last = lines[QUEUE_BODY_LINES - 1] ?? [];
|
|
909
|
+
return [...kept, [...sliceLine(last, 0, width - 1), text("\u2026")]];
|
|
910
|
+
}
|
|
911
|
+
function buildQueueTable(queue, width, now) {
|
|
912
|
+
if (queue.length === 0) return [{ line: [text("Nothing in the queue.", S.dim)] }];
|
|
913
|
+
const bodyWidth = Math.max(8, width - 30);
|
|
914
|
+
const bodyIndent = text(" ".repeat(width - bodyWidth));
|
|
915
|
+
const header = withStyle(
|
|
916
|
+
columns([
|
|
917
|
+
{ line: [text("#")], width: 6 },
|
|
918
|
+
{ line: [text("QUEUED")], width: 10 },
|
|
919
|
+
{ line: [text("SIZE")], width: 8, align: "right" },
|
|
920
|
+
{ line: [text("BODY")], width: bodyWidth }
|
|
921
|
+
]),
|
|
922
|
+
S.dim
|
|
923
|
+
);
|
|
924
|
+
const rows = queue.flatMap((webhook, index) => {
|
|
925
|
+
const [first = [], ...rest] = wrapQueueBody(webhook.preview, bodyWidth);
|
|
926
|
+
const position = text(getQueuePositionLabel(index), index === 0 ? S.boldYellow : void 0);
|
|
927
|
+
return [
|
|
928
|
+
columns([
|
|
929
|
+
{ line: [position], width: 6 },
|
|
930
|
+
{ line: [text(formatRelativeCompact(webhook.queuedAt, now), S.cyan)], width: 10 },
|
|
931
|
+
{ line: [text(formatPayloadSize(webhook.bytes), S.magenta)], width: 8, align: "right" },
|
|
932
|
+
{ line: first, width: bodyWidth }
|
|
933
|
+
]),
|
|
934
|
+
...rest.map((line) => [bodyIndent, ...line])
|
|
935
|
+
];
|
|
936
|
+
});
|
|
937
|
+
return toContent([header, ...rows]);
|
|
938
|
+
}
|
|
939
|
+
function routinePage({
|
|
940
|
+
summary,
|
|
941
|
+
detail,
|
|
942
|
+
runs,
|
|
943
|
+
tab,
|
|
944
|
+
width,
|
|
945
|
+
now,
|
|
946
|
+
error
|
|
947
|
+
}) {
|
|
948
|
+
const routine = detail ?? summary;
|
|
949
|
+
const dot = text(" \xB7 ", S.dim);
|
|
950
|
+
const chips = [
|
|
951
|
+
text(routine.scheduleHuman, S.boldYellow),
|
|
952
|
+
...routine.schedule ? [dot, text(routine.schedule, S.yellow)] : [],
|
|
953
|
+
dot,
|
|
954
|
+
text(routine.agent, S.boldCyan),
|
|
955
|
+
...[
|
|
956
|
+
routine.model === null ? null : text(routine.model, S.blue),
|
|
957
|
+
routine.effort === null ? null : text(`effort ${routine.effort}`),
|
|
958
|
+
routine.permissionMode === null ? null : text(`permission ${routine.permissionMode}`)
|
|
959
|
+
].flatMap((chip) => chip === null ? [] : [dot, chip]),
|
|
960
|
+
dot,
|
|
961
|
+
routine.enabled ? text("\u25CF enabled", S.green) : text("\u25CB disabled", S.dim)
|
|
962
|
+
];
|
|
963
|
+
const lastRun = routine.lastRun;
|
|
964
|
+
const pairs = [
|
|
965
|
+
{ label: "cwd", value: [text(routine.cwd)], isWide: true },
|
|
966
|
+
...routine.command === null ? [] : [{ label: "command", value: [text(routine.command, S.cyan)], isWide: true }],
|
|
967
|
+
{ label: "file", value: [text(routine.file)], isWide: true },
|
|
968
|
+
{ label: "next run", value: timeValue(routine.nextRunAt, now), isWide: true },
|
|
969
|
+
{
|
|
970
|
+
label: "last run",
|
|
971
|
+
value: lastRun ? [
|
|
972
|
+
...statusBadge(lastRun.status, now),
|
|
973
|
+
text(` \xB7 ${formatRelativeCompact(lastRun.startedAt, now)}`, S.cyan)
|
|
974
|
+
] : [text("never", S.dim)],
|
|
975
|
+
isWide: true
|
|
976
|
+
},
|
|
977
|
+
...routine.lastSkip ? [
|
|
978
|
+
{
|
|
979
|
+
label: "last skip",
|
|
980
|
+
value: [
|
|
981
|
+
text(formatRelativeCompact(routine.lastSkip.at, now), S.cyan),
|
|
982
|
+
text(` \xB7 ${getSkipReasonLabel(routine.lastSkip.reason)}`, S.yellow)
|
|
983
|
+
],
|
|
984
|
+
isWide: true
|
|
985
|
+
}
|
|
986
|
+
] : [],
|
|
987
|
+
{ label: "timeout", value: [text(`${routine.timeoutMinutes} min`)] },
|
|
988
|
+
{
|
|
989
|
+
label: "budget",
|
|
990
|
+
value: [text(routine.maxBudgetUsd === null ? "none" : `$${routine.maxBudgetUsd.toFixed(2)}`)]
|
|
991
|
+
}
|
|
992
|
+
];
|
|
993
|
+
const header = toContent([
|
|
994
|
+
[
|
|
995
|
+
text(routine.name, S.boldMagenta),
|
|
996
|
+
...routine.running ? [text(` ${spinner(now)} running`, S.boldYellow)] : [],
|
|
997
|
+
...routine.queuedWebhooks > 0 ? [text(` \xB7 ${formatQueueLabel(routine.queuedWebhooks)}`, S.yellow)] : []
|
|
998
|
+
],
|
|
999
|
+
...wrapLine([text(sanitize(routine.description))], width),
|
|
1000
|
+
[],
|
|
1001
|
+
...wrapLine(chips, width),
|
|
1002
|
+
[],
|
|
1003
|
+
...detailRows(pairs, width),
|
|
1004
|
+
[],
|
|
1005
|
+
tabBar(
|
|
1006
|
+
getRoutineTabs(routine).map((id) => ({ id, label: getTabLabel(id, detail, runs) })),
|
|
1007
|
+
tab
|
|
1008
|
+
),
|
|
1009
|
+
[text("\u2500".repeat(width), S.grey)]
|
|
1010
|
+
]);
|
|
1011
|
+
if (!detail) {
|
|
1012
|
+
return {
|
|
1013
|
+
mode: "scroll",
|
|
1014
|
+
lines: [...header, { line: [text(error ?? "loading\u2026", error ? S.red : S.dim)] }]
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
return match3(tab).with("runs", () => ({
|
|
1018
|
+
mode: "select",
|
|
1019
|
+
lines: [
|
|
1020
|
+
...header,
|
|
1021
|
+
...runs === void 0 ? [{ line: [text("loading\u2026", S.dim)] }] : runsTable(routine.name, runs, width, now)
|
|
1022
|
+
]
|
|
1023
|
+
})).with("prompt", () => ({
|
|
1024
|
+
mode: "scroll",
|
|
1025
|
+
lines: [...header, ...toContent(renderMarkdown(detail.prompt, width))]
|
|
1026
|
+
})).with("skips", () => ({
|
|
1027
|
+
mode: "scroll",
|
|
1028
|
+
lines: [...header, ...skipsTable(detail.skips, now)]
|
|
1029
|
+
})).with("queue", () => ({
|
|
1030
|
+
mode: "scroll",
|
|
1031
|
+
lines: [...header, ...buildQueueTable(detail.queue, width, now)]
|
|
1032
|
+
})).exhaustive();
|
|
1033
|
+
}
|
|
1034
|
+
function runHeaderLines(run, cwd, width, now) {
|
|
1035
|
+
const pairs = [
|
|
1036
|
+
{ label: "status", value: statusBadge(run.status, now) },
|
|
1037
|
+
{ label: "trigger", value: [text(getTriggerLabel(run.trigger))] },
|
|
1038
|
+
...run.scheduledFor ? [{ label: "scheduled", value: timeValue(run.scheduledFor, now), isWide: true }] : [],
|
|
1039
|
+
{ label: "started", value: timeValue(run.startedAt, now) },
|
|
1040
|
+
{ label: "ended", value: timeValue(run.endedAt, now) },
|
|
1041
|
+
{ label: "duration", value: [text(formatDuration(getRunDurationMs(run, now)), S.magenta)] },
|
|
1042
|
+
{ label: "turns", value: [text(String(run.numTurns ?? "-"))] },
|
|
1043
|
+
{ label: "agent", value: [text(run.agent, S.cyan)] },
|
|
1044
|
+
{ label: "model", value: [text(run.model ?? "-", S.blue)] },
|
|
1045
|
+
{ label: "exit code", value: [text(String(run.exitCode ?? "-"))] },
|
|
1046
|
+
{ label: "session", value: [text(run.sessionId ?? "-")], isWide: true },
|
|
1047
|
+
...run.resumeCommand === null ? [] : [
|
|
1048
|
+
{
|
|
1049
|
+
label: "resume",
|
|
1050
|
+
value: [text(`${cwd === null ? "" : `cd ${cwd} && `}${run.resumeCommand}`, S.cyan)],
|
|
1051
|
+
isWide: true
|
|
1052
|
+
}
|
|
1053
|
+
],
|
|
1054
|
+
{ label: "log", value: [text(run.logFile, S.dim)], isWide: true }
|
|
1055
|
+
];
|
|
1056
|
+
const lines = [
|
|
1057
|
+
[text(run.id, S.boldMagenta), text(` ${run.routine}`, S.cyan)],
|
|
1058
|
+
[],
|
|
1059
|
+
...detailRows(pairs, width)
|
|
1060
|
+
];
|
|
1061
|
+
if (run.error) {
|
|
1062
|
+
lines.push(
|
|
1063
|
+
[],
|
|
1064
|
+
...sanitize(run.error).split("\n").flatMap((errorLine) => wrapLine([text("\u258C ", S.red), text(errorLine, S.red)], width, 2))
|
|
1065
|
+
);
|
|
1066
|
+
}
|
|
1067
|
+
if (run.resultText)
|
|
1068
|
+
lines.push([], sectionTitle("Result"), ...renderMarkdown(run.resultText, width));
|
|
1069
|
+
return toContent(lines);
|
|
1070
|
+
}
|
|
1071
|
+
function formatInput(input) {
|
|
1072
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
1073
|
+
return JSON.stringify(input ?? null, null, 2).split("\n");
|
|
1074
|
+
return Object.entries(input).flatMap(([key, value]) => {
|
|
1075
|
+
if (typeof value === "string" && value.includes("\n"))
|
|
1076
|
+
return [`${key}:`, ...value.split("\n").map((line) => ` ${line}`)];
|
|
1077
|
+
return [`${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`];
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
function blockLines(label, source, style, width) {
|
|
1081
|
+
const gutter = text(" \u2502 ", S.grey);
|
|
1082
|
+
const body = [];
|
|
1083
|
+
let isCut = false;
|
|
1084
|
+
for (const raw of source) {
|
|
1085
|
+
if (body.length >= MAX_BLOCK_LINES) {
|
|
1086
|
+
isCut = true;
|
|
1087
|
+
break;
|
|
1088
|
+
}
|
|
1089
|
+
isCut ||= raw.length > MAX_LINE_CHARS;
|
|
1090
|
+
body.push(
|
|
1091
|
+
...wrapLine([text(sanitize(raw.slice(0, MAX_LINE_CHARS)), style)], Math.max(10, width - 4))
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
isCut ||= body.length > MAX_BLOCK_LINES;
|
|
1095
|
+
const lines = [
|
|
1096
|
+
[gutter, text(label, S.bold)],
|
|
1097
|
+
...body.slice(0, MAX_BLOCK_LINES).map((line) => [gutter, ...line])
|
|
1098
|
+
];
|
|
1099
|
+
if (isCut) lines.push([gutter, text("\u2026 cut here, the full output is in the log file", S.dim)]);
|
|
1100
|
+
return lines;
|
|
1101
|
+
}
|
|
1102
|
+
function toolLines(tool, toggle, isExpanded, width, isRunning) {
|
|
1103
|
+
const pending = tool.result === null && isRunning ? text(" \u2026 running", S.yellow) : null;
|
|
1104
|
+
const suffix = tool.result?.isError === true ? text(" \u2717 error", S.red) : pending;
|
|
1105
|
+
const headerWidth = width - (suffix ? textWidth(suffix.text) : 0);
|
|
1106
|
+
const header = [
|
|
1107
|
+
...fitLine(
|
|
1108
|
+
[
|
|
1109
|
+
toggle,
|
|
1110
|
+
text(tool.name, S.boldCyan),
|
|
1111
|
+
text(" "),
|
|
1112
|
+
text(sanitize(tool.preview).replace(/\s+/g, " "), S.dim)
|
|
1113
|
+
],
|
|
1114
|
+
headerWidth
|
|
1115
|
+
),
|
|
1116
|
+
...suffix ? [suffix] : []
|
|
1117
|
+
];
|
|
1118
|
+
if (!isExpanded) return [header];
|
|
1119
|
+
const result = tool.result ? blockLines(
|
|
1120
|
+
tool.result.isError ? "Error" : "Result",
|
|
1121
|
+
(tool.result.content || "(empty)").split("\n"),
|
|
1122
|
+
tool.result.isError ? S.red : void 0,
|
|
1123
|
+
width
|
|
1124
|
+
) : blockLines("Result", [isRunning ? "waiting for the result\u2026" : "no result"], S.dim, width);
|
|
1125
|
+
return [header, ...blockLines("Input", formatInput(tool.input), S.cyan, width), ...result];
|
|
1126
|
+
}
|
|
1127
|
+
function itemLines(item, isExpanded, width, isRunning) {
|
|
1128
|
+
const toggle = text(isExpanded ? "\u25BE " : "\u25B8 ", S.dim);
|
|
1129
|
+
return match3(item).with({ kind: "hook" }, (hook) => {
|
|
1130
|
+
const exit = text(`exit ${hook.exitCode ?? "?"}`, hook.exitCode === 0 ? S.green : S.red);
|
|
1131
|
+
const header = fitLine(
|
|
1132
|
+
[
|
|
1133
|
+
hook.output ? toggle : text(" "),
|
|
1134
|
+
text("before hook", S.bold),
|
|
1135
|
+
text(" "),
|
|
1136
|
+
text(hook.command, S.cyan),
|
|
1137
|
+
text(" "),
|
|
1138
|
+
exit
|
|
1139
|
+
],
|
|
1140
|
+
width
|
|
1141
|
+
);
|
|
1142
|
+
return isExpanded && hook.output ? [header, ...blockLines("Output", hook.output.split("\n"), void 0, width)] : [header];
|
|
1143
|
+
}).with(
|
|
1144
|
+
{ kind: "init" },
|
|
1145
|
+
(init) => wrapLine(
|
|
1146
|
+
[
|
|
1147
|
+
text("\u25CF ", S.green),
|
|
1148
|
+
text("Session started", S.bold),
|
|
1149
|
+
...init.model === null ? [] : [text(` ${init.model}`, S.blue)],
|
|
1150
|
+
...init.cwd === null ? [] : [text(` ${init.cwd}`, S.dim)],
|
|
1151
|
+
...init.toolCount === null ? [] : [text(` ${init.toolCount} tools`, S.dim)],
|
|
1152
|
+
...init.permissionMode === null ? [] : [text(` permission ${init.permissionMode}`, S.dim)]
|
|
1153
|
+
],
|
|
1154
|
+
width,
|
|
1155
|
+
2
|
|
1156
|
+
)
|
|
1157
|
+
).with({ kind: "text" }, ({ text: source }) => renderMarkdown(source, width)).with({ kind: "tool" }, (tool) => toolLines(tool, toggle, isExpanded, width, isRunning)).with({ kind: "result" }, (result) => {
|
|
1158
|
+
const look = result.isError ? { icon: "\u2717", style: S.boldRed } : { icon: "\u2713", style: S.boldGreen };
|
|
1159
|
+
return [
|
|
1160
|
+
[
|
|
1161
|
+
text(`${look.icon} ${getTranscriptResultLabel(result.isError)}`, look.style),
|
|
1162
|
+
text(` ${result.numTurns ?? "-"} turns`),
|
|
1163
|
+
text(` ${formatDuration(result.durationMs)}`, S.magenta)
|
|
1164
|
+
]
|
|
1165
|
+
];
|
|
1166
|
+
}).exhaustive();
|
|
1167
|
+
}
|
|
1168
|
+
function checkIsExpandable(item) {
|
|
1169
|
+
return match3(item).with({ kind: "tool" }, () => true).with({ kind: "hook" }, (hook) => hook.output !== "").otherwise(() => false);
|
|
1170
|
+
}
|
|
1171
|
+
function transcriptLines(items, eventCount, expanded, width, isRunning) {
|
|
1172
|
+
const lines = [
|
|
1173
|
+
blank(),
|
|
1174
|
+
{ line: sectionTitle("Transcript", `${eventCount} events`) }
|
|
1175
|
+
];
|
|
1176
|
+
if (items.length === 0)
|
|
1177
|
+
return [
|
|
1178
|
+
...lines,
|
|
1179
|
+
{
|
|
1180
|
+
line: [text(getTranscriptEmptyLabel(isRunning), S.dim)]
|
|
1181
|
+
}
|
|
1182
|
+
];
|
|
1183
|
+
let previousKind = null;
|
|
1184
|
+
for (const item of items) {
|
|
1185
|
+
const isSubagent = checkIsSubagent(item);
|
|
1186
|
+
const needsGap = isMatching({ kind: P.union("text", "result") }, item) || isMatching("text", previousKind);
|
|
1187
|
+
if (needsGap && (lines.at(-1)?.line.length ?? 0) > 0) lines.push(blank());
|
|
1188
|
+
const innerWidth = isSubagent ? width - 2 : width;
|
|
1189
|
+
const action = { kind: "toggle", key: item.key };
|
|
1190
|
+
itemLines(item, expanded.has(item.key), innerWidth, isRunning).forEach((line, index) => {
|
|
1191
|
+
lines.push({
|
|
1192
|
+
line: isSubagent ? [text("\u250A ", S.grey), ...line] : line,
|
|
1193
|
+
itemKey: item.key,
|
|
1194
|
+
isItemStart: index === 0,
|
|
1195
|
+
...checkIsExpandable(item) ? { action } : {}
|
|
1196
|
+
});
|
|
1197
|
+
});
|
|
1198
|
+
previousKind = item.kind;
|
|
1199
|
+
}
|
|
1200
|
+
return lines;
|
|
1201
|
+
}
|
|
1202
|
+
var HELP = [
|
|
1203
|
+
["\u2191 \u2193 j k", "move"],
|
|
1204
|
+
["enter l \u2192", "open, expand a tool call"],
|
|
1205
|
+
["esc h \u2190", "back"],
|
|
1206
|
+
["tab shift-tab", "next / previous panel"],
|
|
1207
|
+
["1 2 0", "routines / runs / detail"],
|
|
1208
|
+
["g G", "top / bottom (G follows a running run)"],
|
|
1209
|
+
["ctrl-d ctrl-u", "half page down / up"],
|
|
1210
|
+
["pgdn pgup", "page down / up"],
|
|
1211
|
+
["[ ]", "routine tabs: runs, prompt, skipped"],
|
|
1212
|
+
["{ }", "previous / next transcript item"],
|
|
1213
|
+
["e", "expand or collapse every tool call"],
|
|
1214
|
+
["r", "run the selected routine now"],
|
|
1215
|
+
["R ctrl-r", "refresh now"],
|
|
1216
|
+
["?", "toggle this help"],
|
|
1217
|
+
["q ctrl-c", "quit"]
|
|
1218
|
+
];
|
|
1219
|
+
function helpPopup(width, height) {
|
|
1220
|
+
const popupWidth = Math.min(64, width - 4);
|
|
1221
|
+
const keys = HELP.map(([keys2, label]) => [
|
|
1222
|
+
text(` ${keys2.padEnd(18)}`, S.boldCyan),
|
|
1223
|
+
text(label)
|
|
1224
|
+
]);
|
|
1225
|
+
const body = keys.length + 5 <= height ? [[], ...keys, [], [text(" any key closes", S.dim)]] : keys;
|
|
1226
|
+
return box({
|
|
1227
|
+
title: "Keys",
|
|
1228
|
+
width: popupWidth,
|
|
1229
|
+
height: body.length + 2,
|
|
1230
|
+
body,
|
|
1231
|
+
isFocused: true,
|
|
1232
|
+
footer: "esc",
|
|
1233
|
+
tone: "popup"
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
function confirmPopup(routine, width) {
|
|
1237
|
+
const popupWidth = Math.min(Math.max(44, textWidth(routine) + 20), width - 4);
|
|
1238
|
+
const body = [
|
|
1239
|
+
[],
|
|
1240
|
+
[text(" Start "), text(routine, S.boldMagenta), text(" now?")],
|
|
1241
|
+
[text(" The daemon runs it in the background.", S.dim)],
|
|
1242
|
+
[],
|
|
1243
|
+
[
|
|
1244
|
+
text(" y", S.boldGreen),
|
|
1245
|
+
text(" start "),
|
|
1246
|
+
text("any other key", S.boldRed),
|
|
1247
|
+
text(" cancel")
|
|
1248
|
+
]
|
|
1249
|
+
];
|
|
1250
|
+
return box({
|
|
1251
|
+
title: "Run now",
|
|
1252
|
+
width: popupWidth,
|
|
1253
|
+
height: body.length + 2,
|
|
1254
|
+
body,
|
|
1255
|
+
isFocused: true,
|
|
1256
|
+
tone: "popup"
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
function hintsBar(hints, right, width) {
|
|
1260
|
+
const left = hints.flatMap(([key, label]) => [
|
|
1261
|
+
text(` ${key}`, S.boldCyan),
|
|
1262
|
+
text(` ${label} `, S.dim)
|
|
1263
|
+
]);
|
|
1264
|
+
const rightWidth = Math.min(lineWidth(right), Math.floor(width / 2));
|
|
1265
|
+
return [...fitLine(left, width - rightWidth - 1), text(" "), ...fitLine(right, rightWidth)];
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// ../tui/src/app.ts
|
|
1269
|
+
var FOCUS_ORDER = ["routines", "runs", "detail"];
|
|
1270
|
+
var MIN_WIDTH = 60;
|
|
1271
|
+
var MIN_HEIGHT = 18;
|
|
1272
|
+
var MESSAGE_MS = 6e3;
|
|
1273
|
+
var RUN_CACHE_SIZE = 4;
|
|
1274
|
+
var LOAD_MORE_ROWS = 10;
|
|
1275
|
+
var runKey = (routine, id) => `${routine}/${id}`;
|
|
1276
|
+
var pageKey = (page) => match4(page).with({ kind: "routine" }, ({ name }) => `routine:${name}`).with({ kind: "run" }, (run) => `run:${runKey(run.routine, run.id)}`).exhaustive();
|
|
1277
|
+
var pageTitle = (page) => match4(page).with({ kind: "routine" }, ({ name }) => `[0] ${name}`).with({ kind: "run" }, (run) => `[0] ${run.routine} \u203A ${run.id}`).exhaustive();
|
|
1278
|
+
var OPEN_KEYS = /* @__PURE__ */ new Set(["enter", "space", "l", "right"]);
|
|
1279
|
+
var BACK_KEYS = /* @__PURE__ */ new Set(["escape", "h", "left", "backspace"]);
|
|
1280
|
+
var clamp = (value, min, max) => Math.max(min, Math.min(max, value));
|
|
1281
|
+
var actionLines = (content) => content.lines.flatMap((line, index) => line.action ? [index] : []);
|
|
1282
|
+
var getSelectTargets = (content) => isMatching2({ mode: "select" }, content) ? actionLines(content) : null;
|
|
1283
|
+
var messageContent = (text2, isError = false) => ({
|
|
1284
|
+
mode: "scroll",
|
|
1285
|
+
lines: [{ line: [{ text: text2, style: isError ? S.red : S.dim }] }]
|
|
1286
|
+
});
|
|
1287
|
+
function getAnchor(content, line, cursor) {
|
|
1288
|
+
const current = content.lines[line];
|
|
1289
|
+
if (isMatching2({ mode: "select" }, content)) {
|
|
1290
|
+
return match4(current?.action).with({ kind: "open-run" }, ({ routine, id }) => ({
|
|
1291
|
+
cursor,
|
|
1292
|
+
key: runKey(routine, id),
|
|
1293
|
+
offset: 0
|
|
1294
|
+
})).otherwise(() => null);
|
|
1295
|
+
}
|
|
1296
|
+
if (!current?.itemKey) return null;
|
|
1297
|
+
let start = line;
|
|
1298
|
+
while (start > 0 && content.lines[start]?.isItemStart !== true && content.lines[start - 1]?.itemKey === current.itemKey) {
|
|
1299
|
+
start--;
|
|
1300
|
+
}
|
|
1301
|
+
return { cursor, key: current.itemKey, offset: line - start };
|
|
1302
|
+
}
|
|
1303
|
+
function getStep(key, height) {
|
|
1304
|
+
const half = Math.max(1, Math.floor(height / 2));
|
|
1305
|
+
const page = Math.max(1, height - 1);
|
|
1306
|
+
return match4(key).with(P2.union("j", "down"), () => 1).with(P2.union("k", "up"), () => -1).with("C-d", () => half).with("C-u", () => -half).with(P2.union("pagedown", "C-f"), () => page).with(P2.union("pageup", "C-b"), () => -page).with(P2.union("g", "home"), () => -Infinity).with(P2.union("G", "end"), () => Infinity).otherwise(() => null);
|
|
1307
|
+
}
|
|
1308
|
+
function tooSmall(width, height) {
|
|
1309
|
+
const message = [
|
|
1310
|
+
{
|
|
1311
|
+
text: `terminal too small: need ${MIN_WIDTH}x${MIN_HEIGHT}, have ${width}x${height}`,
|
|
1312
|
+
style: S.yellow
|
|
1313
|
+
}
|
|
1314
|
+
];
|
|
1315
|
+
return Array.from(
|
|
1316
|
+
{ length: height },
|
|
1317
|
+
(_, row) => fitLine(row === Math.floor(height / 2) ? message : [], width)
|
|
1318
|
+
);
|
|
1319
|
+
}
|
|
1320
|
+
var TuiApp = class {
|
|
1321
|
+
client;
|
|
1322
|
+
now;
|
|
1323
|
+
onChange;
|
|
1324
|
+
pageLoadDelayMs;
|
|
1325
|
+
focus = "routines";
|
|
1326
|
+
listFocus = "routines";
|
|
1327
|
+
cursors = { routines: 0, runs: 0 };
|
|
1328
|
+
selectedKeys = { routines: null, runs: null };
|
|
1329
|
+
listScroll = { routines: 0, runs: 0 };
|
|
1330
|
+
listHeights = { routines: 1, runs: 1 };
|
|
1331
|
+
stack = [];
|
|
1332
|
+
overlay = null;
|
|
1333
|
+
message = null;
|
|
1334
|
+
overview = null;
|
|
1335
|
+
overviewError = null;
|
|
1336
|
+
loadedAt = null;
|
|
1337
|
+
routineDetails = /* @__PURE__ */ new Map();
|
|
1338
|
+
routineRuns = /* @__PURE__ */ new Map();
|
|
1339
|
+
// Serialized, so a refresh and the next page never overwrite each other.
|
|
1340
|
+
runsLoads = /* @__PURE__ */ new Map();
|
|
1341
|
+
loadingMoreRuns = /* @__PURE__ */ new Set();
|
|
1342
|
+
runData = /* @__PURE__ */ new Map();
|
|
1343
|
+
pageErrors = /* @__PURE__ */ new Map();
|
|
1344
|
+
refreshing = null;
|
|
1345
|
+
pageLoadTimer = null;
|
|
1346
|
+
viewport = null;
|
|
1347
|
+
constructor({ client, now = Date.now, onChange = () => {
|
|
1348
|
+
}, pageLoadDelayMs = 120 }) {
|
|
1349
|
+
this.client = client;
|
|
1350
|
+
this.now = now;
|
|
1351
|
+
this.onChange = onChange;
|
|
1352
|
+
this.pageLoadDelayMs = pageLoadDelayMs;
|
|
1353
|
+
}
|
|
1354
|
+
get routines() {
|
|
1355
|
+
return this.overview?.routines ?? [];
|
|
1356
|
+
}
|
|
1357
|
+
get runs() {
|
|
1358
|
+
return this.overview?.runs ?? [];
|
|
1359
|
+
}
|
|
1360
|
+
get page() {
|
|
1361
|
+
return this.stack[this.stack.length - 1];
|
|
1362
|
+
}
|
|
1363
|
+
checkHasActiveRuns() {
|
|
1364
|
+
return (this.overview?.status.running ?? 0) > 0 || this.routines.some((routine) => routine.running);
|
|
1365
|
+
}
|
|
1366
|
+
dispose() {
|
|
1367
|
+
if (this.pageLoadTimer) clearTimeout(this.pageLoadTimer);
|
|
1368
|
+
}
|
|
1369
|
+
refresh() {
|
|
1370
|
+
this.refreshing ??= this.loadOverview().finally(() => {
|
|
1371
|
+
this.refreshing = null;
|
|
1372
|
+
});
|
|
1373
|
+
return this.refreshing;
|
|
1374
|
+
}
|
|
1375
|
+
async loadOverview() {
|
|
1376
|
+
try {
|
|
1377
|
+
this.overview = await this.client.getOverview();
|
|
1378
|
+
this.overviewError = null;
|
|
1379
|
+
this.loadedAt = this.now();
|
|
1380
|
+
} catch (err) {
|
|
1381
|
+
this.overviewError = getErrorMessage(err);
|
|
1382
|
+
}
|
|
1383
|
+
this.syncSelection();
|
|
1384
|
+
this.onChange();
|
|
1385
|
+
await this.loadVisiblePage();
|
|
1386
|
+
}
|
|
1387
|
+
async loadVisiblePage() {
|
|
1388
|
+
const page = this.page;
|
|
1389
|
+
if (!page) return;
|
|
1390
|
+
const key = pageKey(page);
|
|
1391
|
+
try {
|
|
1392
|
+
await match4(page).with({ kind: "routine" }, async ({ name }) => {
|
|
1393
|
+
const [detail] = await Promise.all([
|
|
1394
|
+
this.client.getRoutine(name),
|
|
1395
|
+
this.queueRunsLoad(name, () => this.reloadRuns(name))
|
|
1396
|
+
]);
|
|
1397
|
+
this.routineDetails.set(name, detail);
|
|
1398
|
+
}).with({ kind: "run" }, async (run) => this.loadRun(run)).exhaustive();
|
|
1399
|
+
this.pageErrors.delete(key);
|
|
1400
|
+
} catch (err) {
|
|
1401
|
+
this.pageErrors.set(key, getErrorMessage(err));
|
|
1402
|
+
}
|
|
1403
|
+
this.onChange();
|
|
1404
|
+
}
|
|
1405
|
+
queueRunsLoad(name, load) {
|
|
1406
|
+
const next = (this.runsLoads.get(name) ?? Promise.resolve()).then(load);
|
|
1407
|
+
this.runsLoads.set(
|
|
1408
|
+
name,
|
|
1409
|
+
next.catch(() => {
|
|
1410
|
+
})
|
|
1411
|
+
);
|
|
1412
|
+
return next;
|
|
1413
|
+
}
|
|
1414
|
+
async reloadRuns(name) {
|
|
1415
|
+
const loadedCount = this.routineRuns.get(name)?.runs.length ?? 0;
|
|
1416
|
+
let page = await this.client.getRuns(name, null);
|
|
1417
|
+
const runs = [...page.runs];
|
|
1418
|
+
while (page.nextCursor !== null && runs.length < loadedCount) {
|
|
1419
|
+
page = await this.client.getRuns(name, page.nextCursor);
|
|
1420
|
+
runs.push(...page.runs);
|
|
1421
|
+
}
|
|
1422
|
+
this.routineRuns.set(name, { ...page, runs });
|
|
1423
|
+
}
|
|
1424
|
+
loadMoreRuns(name) {
|
|
1425
|
+
if (this.loadingMoreRuns.has(name)) return;
|
|
1426
|
+
this.loadingMoreRuns.add(name);
|
|
1427
|
+
this.queueRunsLoad(name, async () => {
|
|
1428
|
+
const loaded = this.routineRuns.get(name);
|
|
1429
|
+
if (loaded === void 0 || loaded.nextCursor === null) return;
|
|
1430
|
+
const page = await this.client.getRuns(name, loaded.nextCursor);
|
|
1431
|
+
this.routineRuns.set(name, { ...page, runs: [...loaded.runs, ...page.runs] });
|
|
1432
|
+
}).catch((err) => {
|
|
1433
|
+
this.flash(getErrorMessage(err), "error");
|
|
1434
|
+
}).finally(() => {
|
|
1435
|
+
this.loadingMoreRuns.delete(name);
|
|
1436
|
+
this.onChange();
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
async loadRun(page) {
|
|
1440
|
+
const key = runKey(page.routine, page.id);
|
|
1441
|
+
const cached = this.runData.get(key);
|
|
1442
|
+
if (cached && !isMatching2({ status: "running" }, cached.run)) return;
|
|
1443
|
+
this.storeRun(key, await this.client.getRun(page.routine, page.id), cached);
|
|
1444
|
+
}
|
|
1445
|
+
storeRun(key, { run, transcript }, previous) {
|
|
1446
|
+
this.runData.delete(key);
|
|
1447
|
+
this.runData.set(key, {
|
|
1448
|
+
run,
|
|
1449
|
+
eventCount: transcript.eventCount,
|
|
1450
|
+
items: transcript.items,
|
|
1451
|
+
expanded: previous?.expanded ?? /* @__PURE__ */ new Set(),
|
|
1452
|
+
expandedVersion: previous?.expandedVersion ?? 0,
|
|
1453
|
+
transcript: previous?.transcript ?? null
|
|
1454
|
+
});
|
|
1455
|
+
for (const oldKey of this.runData.keys()) {
|
|
1456
|
+
if (this.runData.size <= RUN_CACHE_SIZE) break;
|
|
1457
|
+
this.runData.delete(oldKey);
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
requestPageLoad() {
|
|
1461
|
+
if (this.pageLoadDelayMs === null) return;
|
|
1462
|
+
if (this.pageLoadTimer) clearTimeout(this.pageLoadTimer);
|
|
1463
|
+
this.pageLoadTimer = setTimeout(() => {
|
|
1464
|
+
this.pageLoadTimer = null;
|
|
1465
|
+
void this.loadVisiblePage();
|
|
1466
|
+
}, this.pageLoadDelayMs);
|
|
1467
|
+
}
|
|
1468
|
+
listKeys(list) {
|
|
1469
|
+
return match4(list).with("routines", () => this.routines.map((routine) => routine.name)).with("runs", () => this.runs.map((run) => runKey(run.routine, run.id))).exhaustive();
|
|
1470
|
+
}
|
|
1471
|
+
// Keeps the cursor on the same routine or run when the lists change under it.
|
|
1472
|
+
syncSelection() {
|
|
1473
|
+
for (const list of ["routines", "runs"]) {
|
|
1474
|
+
const keys = this.listKeys(list);
|
|
1475
|
+
const selected = this.selectedKeys[list];
|
|
1476
|
+
const found = selected === null ? -1 : keys.indexOf(selected);
|
|
1477
|
+
this.cursors[list] = found === -1 ? clamp(this.cursors[list], 0, Math.max(0, keys.length - 1)) : found;
|
|
1478
|
+
this.selectedKeys[list] = keys[this.cursors[list]] ?? null;
|
|
1479
|
+
}
|
|
1480
|
+
const base = this.basePage();
|
|
1481
|
+
if (!base) this.stack = [];
|
|
1482
|
+
else if (!this.stack[0] || pageKey(this.stack[0]) !== pageKey(base)) this.stack = [base];
|
|
1483
|
+
}
|
|
1484
|
+
basePage() {
|
|
1485
|
+
return match4(this.listFocus).with("routines", () => {
|
|
1486
|
+
const routine = this.routines[this.cursors.routines];
|
|
1487
|
+
return routine ? { kind: "routine", name: routine.name, tab: "runs", cursor: 0, scroll: 0, anchor: null } : null;
|
|
1488
|
+
}).with("runs", () => {
|
|
1489
|
+
const run = this.runs[this.cursors.runs];
|
|
1490
|
+
return run ? {
|
|
1491
|
+
kind: "run",
|
|
1492
|
+
routine: run.routine,
|
|
1493
|
+
id: run.id,
|
|
1494
|
+
cursor: 0,
|
|
1495
|
+
scroll: 0,
|
|
1496
|
+
anchor: null,
|
|
1497
|
+
follow: false
|
|
1498
|
+
} : null;
|
|
1499
|
+
}).exhaustive();
|
|
1500
|
+
}
|
|
1501
|
+
resetStack() {
|
|
1502
|
+
const base = this.basePage();
|
|
1503
|
+
this.stack = base ? [base] : [];
|
|
1504
|
+
this.requestPageLoad();
|
|
1505
|
+
}
|
|
1506
|
+
focusList(list) {
|
|
1507
|
+
this.focus = list;
|
|
1508
|
+
if (this.listFocus === list && this.stack.length <= 1) return;
|
|
1509
|
+
this.listFocus = list;
|
|
1510
|
+
this.resetStack();
|
|
1511
|
+
}
|
|
1512
|
+
focusDetail() {
|
|
1513
|
+
if (this.page) this.focus = "detail";
|
|
1514
|
+
}
|
|
1515
|
+
cycleFocus(direction) {
|
|
1516
|
+
let index = FOCUS_ORDER.indexOf(this.focus);
|
|
1517
|
+
for (let i = 0; i < FOCUS_ORDER.length; i++) {
|
|
1518
|
+
index = (index + direction + FOCUS_ORDER.length) % FOCUS_ORDER.length;
|
|
1519
|
+
const moved = match4(FOCUS_ORDER[index] ?? "routines").with(P2.union("routines", "runs"), (list) => {
|
|
1520
|
+
this.focusList(list);
|
|
1521
|
+
return true;
|
|
1522
|
+
}).with("detail", () => {
|
|
1523
|
+
this.focusDetail();
|
|
1524
|
+
return this.page !== void 0;
|
|
1525
|
+
}).exhaustive();
|
|
1526
|
+
if (moved) return;
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
back() {
|
|
1530
|
+
if (this.stack.length > 1) this.stack.pop();
|
|
1531
|
+
else this.focus = this.listFocus;
|
|
1532
|
+
}
|
|
1533
|
+
// A popup only takes keys pressed after it is on screen, so a pasted "ry" can never start a run.
|
|
1534
|
+
handleKeys(keys, width, height) {
|
|
1535
|
+
for (const key of keys) {
|
|
1536
|
+
const hadOverlay = this.overlay !== null;
|
|
1537
|
+
if (this.handleKey(key) === "quit") return "quit";
|
|
1538
|
+
this.render(width, height);
|
|
1539
|
+
if (!hadOverlay && this.overlay) return void 0;
|
|
1540
|
+
}
|
|
1541
|
+
return void 0;
|
|
1542
|
+
}
|
|
1543
|
+
handleKey(key) {
|
|
1544
|
+
if (key === "C-c") return "quit";
|
|
1545
|
+
if (this.overlay) {
|
|
1546
|
+
this.handleOverlayKey(this.overlay, key);
|
|
1547
|
+
return void 0;
|
|
1548
|
+
}
|
|
1549
|
+
if (key === "q") return "quit";
|
|
1550
|
+
match4(key).with("?", () => {
|
|
1551
|
+
this.overlay = { kind: "help" };
|
|
1552
|
+
}).with("tab", () => this.cycleFocus(1)).with("S-tab", () => this.cycleFocus(-1)).with("1", () => this.focusList("routines")).with("2", () => this.focusList("runs")).with("0", () => this.focusDetail()).with("r", () => this.askToRun()).with(P2.union("R", "C-r"), () => void this.refresh()).otherwise(
|
|
1553
|
+
() => match4(this.focus).with("detail", () => this.handleDetailKey(key)).with(P2.union("routines", "runs"), (list) => this.handleListKey(list, key)).exhaustive()
|
|
1554
|
+
);
|
|
1555
|
+
return void 0;
|
|
1556
|
+
}
|
|
1557
|
+
handleOverlayKey(overlay, key) {
|
|
1558
|
+
this.overlay = null;
|
|
1559
|
+
if (key === "y" && isMatching2({ kind: "confirm-run" }, overlay))
|
|
1560
|
+
void this.startRun(overlay.routine);
|
|
1561
|
+
}
|
|
1562
|
+
handleListKey(list, key) {
|
|
1563
|
+
if (OPEN_KEYS.has(key)) {
|
|
1564
|
+
this.focusDetail();
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
const step = getStep(key, this.listHeights[list]);
|
|
1568
|
+
if (step === null) return;
|
|
1569
|
+
const keys = this.listKeys(list);
|
|
1570
|
+
const next = clamp(this.cursors[list] + step, 0, Math.max(0, keys.length - 1));
|
|
1571
|
+
if (next === this.cursors[list]) return;
|
|
1572
|
+
this.cursors[list] = next;
|
|
1573
|
+
this.selectedKeys[list] = keys[next] ?? null;
|
|
1574
|
+
this.resetStack();
|
|
1575
|
+
}
|
|
1576
|
+
handleDetailKey(key) {
|
|
1577
|
+
const page = this.page;
|
|
1578
|
+
if (!page) return;
|
|
1579
|
+
if (BACK_KEYS.has(key)) {
|
|
1580
|
+
this.back();
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
if (!this.viewport) return;
|
|
1584
|
+
const { content, height } = this.viewport;
|
|
1585
|
+
if (OPEN_KEYS.has(key)) {
|
|
1586
|
+
this.activate(page, content);
|
|
1587
|
+
return;
|
|
1588
|
+
}
|
|
1589
|
+
if (this.handlePageKey(page, content, key)) return;
|
|
1590
|
+
const step = getStep(key, height);
|
|
1591
|
+
if (step !== null) this.moveCursor(page, content, step, height);
|
|
1592
|
+
}
|
|
1593
|
+
handlePageKey(page, content, key) {
|
|
1594
|
+
return match4([page, key, content.mode]).with([{ kind: "routine" }, "]", P2._], ([routinePage2]) => {
|
|
1595
|
+
this.switchTab(routinePage2, 1);
|
|
1596
|
+
return true;
|
|
1597
|
+
}).with([{ kind: "routine" }, "[", P2._], ([routinePage2]) => {
|
|
1598
|
+
this.switchTab(routinePage2, -1);
|
|
1599
|
+
return true;
|
|
1600
|
+
}).with([{ kind: "run" }, "e", P2._], ([runPage]) => {
|
|
1601
|
+
this.toggleAll(runPage);
|
|
1602
|
+
return true;
|
|
1603
|
+
}).with([P2._, "}", "line"], () => {
|
|
1604
|
+
this.jumpItem(page, content, 1);
|
|
1605
|
+
return true;
|
|
1606
|
+
}).with([P2._, "{", "line"], () => {
|
|
1607
|
+
this.jumpItem(page, content, -1);
|
|
1608
|
+
return true;
|
|
1609
|
+
}).otherwise(() => false);
|
|
1610
|
+
}
|
|
1611
|
+
moveCursor(page, content, step, height) {
|
|
1612
|
+
if (isMatching2({ mode: "scroll" }, content)) {
|
|
1613
|
+
page.scroll = clamp(page.scroll + step, 0, Math.max(0, content.lines.length - height));
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
const last = (getSelectTargets(content) ?? content.lines).length - 1;
|
|
1617
|
+
page.cursor = clamp(page.cursor + step, 0, Math.max(0, last));
|
|
1618
|
+
if (isMatching2({ kind: "run" }, page)) page.follow = step > 0 && page.cursor === last;
|
|
1619
|
+
if (isMatching2({ kind: "routine", tab: "runs" }, page) && page.cursor >= last - LOAD_MORE_ROWS) {
|
|
1620
|
+
this.loadMoreRuns(page.name);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
switchTab(page, direction) {
|
|
1624
|
+
const routine = this.routines.find((candidate) => candidate.name === page.name);
|
|
1625
|
+
const tabs = routine === void 0 ? ["runs"] : getRoutineTabs(routine);
|
|
1626
|
+
page.tab = tabs[(tabs.indexOf(page.tab) + direction + tabs.length) % tabs.length] ?? "runs";
|
|
1627
|
+
page.cursor = 0;
|
|
1628
|
+
page.scroll = 0;
|
|
1629
|
+
page.anchor = null;
|
|
1630
|
+
}
|
|
1631
|
+
activate(page, content) {
|
|
1632
|
+
if (isMatching2({ mode: "select" }, content)) {
|
|
1633
|
+
this.openRun(content.lines[actionLines(content)[page.cursor] ?? -1]?.action);
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
const action = content.lines[page.cursor]?.action;
|
|
1637
|
+
if (!isMatching2({ kind: "run" }, page) || !isMatching2({ kind: "toggle" }, action)) return;
|
|
1638
|
+
const data = this.runData.get(runKey(page.routine, page.id));
|
|
1639
|
+
if (!data) return;
|
|
1640
|
+
const isExpanding = !data.expanded.has(action.key);
|
|
1641
|
+
if (isExpanding) data.expanded.add(action.key);
|
|
1642
|
+
else data.expanded.delete(action.key);
|
|
1643
|
+
data.expandedVersion++;
|
|
1644
|
+
const updated = this.moveCursorToItem(page, action.key);
|
|
1645
|
+
if (isExpanding && updated && this.viewport)
|
|
1646
|
+
this.revealItem(page, updated, action.key, this.viewport.height);
|
|
1647
|
+
}
|
|
1648
|
+
openRun(action) {
|
|
1649
|
+
if (!isMatching2({ kind: "open-run" }, action)) return;
|
|
1650
|
+
this.stack.push({
|
|
1651
|
+
kind: "run",
|
|
1652
|
+
routine: action.routine,
|
|
1653
|
+
id: action.id,
|
|
1654
|
+
cursor: 0,
|
|
1655
|
+
scroll: 0,
|
|
1656
|
+
anchor: null,
|
|
1657
|
+
follow: false
|
|
1658
|
+
});
|
|
1659
|
+
this.requestPageLoad();
|
|
1660
|
+
}
|
|
1661
|
+
revealItem(page, content, itemKey, height) {
|
|
1662
|
+
let end = page.cursor;
|
|
1663
|
+
while (content.lines[end + 1]?.itemKey === itemKey && content.lines[end + 1]?.isItemStart !== true) {
|
|
1664
|
+
end++;
|
|
1665
|
+
}
|
|
1666
|
+
page.scroll = Math.max(page.scroll, Math.min(page.cursor, end - height + 1));
|
|
1667
|
+
}
|
|
1668
|
+
toggleAll(page) {
|
|
1669
|
+
const data = this.runData.get(runKey(page.routine, page.id));
|
|
1670
|
+
if (!data) return;
|
|
1671
|
+
const keys = data.items.filter(checkIsExpandable).map((item) => item.key);
|
|
1672
|
+
const shouldExpand = keys.some((key) => !data.expanded.has(key));
|
|
1673
|
+
data.expanded = new Set(shouldExpand ? keys : []);
|
|
1674
|
+
data.expandedVersion++;
|
|
1675
|
+
this.moveCursorToItem(page, this.viewport?.content.lines[page.cursor]?.itemKey);
|
|
1676
|
+
}
|
|
1677
|
+
moveCursorToItem(page, itemKey) {
|
|
1678
|
+
if (!this.viewport || !itemKey) return null;
|
|
1679
|
+
const content = this.buildPageContent(page, this.viewport.width, this.now());
|
|
1680
|
+
const index = content.lines.findIndex((line) => line.isItemStart && line.itemKey === itemKey);
|
|
1681
|
+
if (index !== -1) page.cursor = index;
|
|
1682
|
+
page.follow = false;
|
|
1683
|
+
page.anchor = null;
|
|
1684
|
+
return content;
|
|
1685
|
+
}
|
|
1686
|
+
jumpItem(page, content, direction) {
|
|
1687
|
+
for (let i = page.cursor + direction; i >= 0 && i < content.lines.length; i += direction) {
|
|
1688
|
+
if (content.lines[i]?.isItemStart !== true) continue;
|
|
1689
|
+
page.cursor = i;
|
|
1690
|
+
if (isMatching2({ kind: "run" }, page)) page.follow = false;
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
contextRoutine() {
|
|
1695
|
+
return match4(this.focus).with("routines", () => this.routines[this.cursors.routines]?.name ?? null).with("runs", () => this.runs[this.cursors.runs]?.routine ?? null).with(
|
|
1696
|
+
"detail",
|
|
1697
|
+
() => match4(this.page).with({ kind: "routine" }, ({ name }) => name).with({ kind: "run" }, ({ routine }) => routine).otherwise(() => null)
|
|
1698
|
+
).exhaustive();
|
|
1699
|
+
}
|
|
1700
|
+
askToRun() {
|
|
1701
|
+
const name = this.contextRoutine();
|
|
1702
|
+
if (!name) return;
|
|
1703
|
+
if (this.routines.find((routine) => routine.name === name)?.running) {
|
|
1704
|
+
this.flash(`${name} is already running`, "error");
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
this.overlay = { kind: "confirm-run", routine: name };
|
|
1708
|
+
}
|
|
1709
|
+
async startRun(name) {
|
|
1710
|
+
try {
|
|
1711
|
+
await this.client.startRun(name);
|
|
1712
|
+
this.flash(`started ${name}`, "ok");
|
|
1713
|
+
} catch (err) {
|
|
1714
|
+
this.flash(getErrorMessage(err), "error");
|
|
1715
|
+
}
|
|
1716
|
+
await this.refreshing;
|
|
1717
|
+
await this.refresh();
|
|
1718
|
+
}
|
|
1719
|
+
flash(text2, tone) {
|
|
1720
|
+
this.message = { text: text2, tone, at: this.now() };
|
|
1721
|
+
this.onChange();
|
|
1722
|
+
}
|
|
1723
|
+
render(width, height) {
|
|
1724
|
+
if (width < MIN_WIDTH || height < MIN_HEIGHT) return tooSmall(width, height);
|
|
1725
|
+
const now = this.now();
|
|
1726
|
+
const leftWidth = clamp(Math.round(width * 0.36), 34, 56);
|
|
1727
|
+
const bodyHeight = height - 1;
|
|
1728
|
+
const statusHeight = 4;
|
|
1729
|
+
const listsHeight = bodyHeight - statusHeight;
|
|
1730
|
+
const routinesHeight = clamp(this.routines.length + 2, 4, Math.floor(listsHeight * 0.6));
|
|
1731
|
+
const left = [
|
|
1732
|
+
...box({
|
|
1733
|
+
title: "Kombinat",
|
|
1734
|
+
icon: { text: "\u259F", style: S.accent },
|
|
1735
|
+
width: leftWidth,
|
|
1736
|
+
height: statusHeight,
|
|
1737
|
+
body: statusLines(this.overview, this.overviewError, this.loadedAt, now),
|
|
1738
|
+
isFocused: false,
|
|
1739
|
+
footer: formatCopyright(this.overview?.status.version, now)
|
|
1740
|
+
}),
|
|
1741
|
+
...this.renderList(
|
|
1742
|
+
"routines",
|
|
1743
|
+
"[1] Routines",
|
|
1744
|
+
this.routines.map((routine) => routineRow(routine, leftWidth - 4, now)),
|
|
1745
|
+
leftWidth,
|
|
1746
|
+
routinesHeight
|
|
1747
|
+
),
|
|
1748
|
+
...this.renderList(
|
|
1749
|
+
"runs",
|
|
1750
|
+
"[2] Recent runs",
|
|
1751
|
+
this.runs.map((run) => runRow(run, leftWidth - 4, now)),
|
|
1752
|
+
leftWidth,
|
|
1753
|
+
listsHeight - routinesHeight
|
|
1754
|
+
)
|
|
1755
|
+
];
|
|
1756
|
+
const right = this.renderDetail(width - leftWidth, bodyHeight, now);
|
|
1757
|
+
const frame = left.map((line, index) => [...line, ...right[index] ?? []]);
|
|
1758
|
+
frame.push(hintsBar(this.hints(), this.statusRight(now), width));
|
|
1759
|
+
if (!this.overlay) return frame;
|
|
1760
|
+
const popup = match4(this.overlay).with({ kind: "help" }, () => helpPopup(width, height)).with({ kind: "confirm-run" }, ({ routine }) => confirmPopup(routine, width)).exhaustive();
|
|
1761
|
+
return overlayOnto(frame, popup, width);
|
|
1762
|
+
}
|
|
1763
|
+
renderList(list, title, rows, width, height) {
|
|
1764
|
+
const visible = Math.max(1, height - 2);
|
|
1765
|
+
this.listHeights[list] = visible;
|
|
1766
|
+
const cursor = this.cursors[list];
|
|
1767
|
+
const scroll = clamp(this.listScroll[list], Math.max(0, cursor - visible + 1), cursor);
|
|
1768
|
+
this.listScroll[list] = scroll;
|
|
1769
|
+
if (rows.length === 0) {
|
|
1770
|
+
const empty = this.overview ? "nothing here yet" : this.overviewError ? "" : "loading\u2026";
|
|
1771
|
+
return box({
|
|
1772
|
+
title,
|
|
1773
|
+
width,
|
|
1774
|
+
height,
|
|
1775
|
+
body: [[{ text: empty, style: S.dim }]],
|
|
1776
|
+
isFocused: this.focus === list
|
|
1777
|
+
});
|
|
1778
|
+
}
|
|
1779
|
+
return box({
|
|
1780
|
+
title,
|
|
1781
|
+
width,
|
|
1782
|
+
height,
|
|
1783
|
+
body: rows.slice(scroll, scroll + visible),
|
|
1784
|
+
isFocused: this.focus === list,
|
|
1785
|
+
footer: `${cursor + 1} of ${rows.length}`,
|
|
1786
|
+
highlightRow: cursor - scroll
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
1789
|
+
renderDetail(width, height, now) {
|
|
1790
|
+
const page = this.page;
|
|
1791
|
+
const isFocused = isMatching2("detail", this.focus);
|
|
1792
|
+
if (!page) {
|
|
1793
|
+
this.viewport = null;
|
|
1794
|
+
return box({ title: "[0] Detail", width, height, body: [], isFocused });
|
|
1795
|
+
}
|
|
1796
|
+
const contentWidth = width - 4;
|
|
1797
|
+
const visible = height - 2;
|
|
1798
|
+
const content = this.buildPageContent(page, contentWidth, now);
|
|
1799
|
+
this.clampPage(page, content, visible, isFocused);
|
|
1800
|
+
this.viewport = { content, height: visible, width: contentWidth };
|
|
1801
|
+
const cursorLine = isFocused ? match4(content.mode).with("scroll", () => null).with("select", () => actionLines(content)[page.cursor] ?? null).with("line", () => page.cursor).exhaustive() : null;
|
|
1802
|
+
const body = content.lines.slice(page.scroll, page.scroll + visible).map(({ line }) => line);
|
|
1803
|
+
const isFollowing = isMatching2({ kind: "run", follow: true }, page) && isMatching2({ status: "running" }, this.runData.get(runKey(page.routine, page.id))?.run);
|
|
1804
|
+
const percent = content.lines.length > visible ? `${Math.round(100 * Math.min(content.lines.length, page.scroll + visible) / content.lines.length)}%` : "";
|
|
1805
|
+
const footer = [isFollowing ? "following" : "", percent].filter(Boolean).join(" \xB7 ");
|
|
1806
|
+
return box({
|
|
1807
|
+
title: pageTitle(page),
|
|
1808
|
+
width,
|
|
1809
|
+
height,
|
|
1810
|
+
body,
|
|
1811
|
+
isFocused,
|
|
1812
|
+
footer: footer || void 0,
|
|
1813
|
+
highlightRow: cursorLine === null ? null : cursorLine - page.scroll
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
buildPageContent(page, width, now) {
|
|
1817
|
+
const error = this.pageErrors.get(pageKey(page));
|
|
1818
|
+
return match4(page).with({ kind: "routine" }, (routine) => this.buildRoutineContent(routine, error, width, now)).with({ kind: "run" }, (run) => this.buildRunContent(run, error, width, now)).exhaustive();
|
|
1819
|
+
}
|
|
1820
|
+
buildRoutineContent(page, error, width, now) {
|
|
1821
|
+
const summary = this.routines.find((routine) => routine.name === page.name) ?? this.routineDetails.get(page.name);
|
|
1822
|
+
if (!summary) return messageContent(error ?? `Unknown routine ${page.name}`, true);
|
|
1823
|
+
return routinePage({
|
|
1824
|
+
summary,
|
|
1825
|
+
detail: this.routineDetails.get(page.name),
|
|
1826
|
+
runs: this.routineRuns.get(page.name),
|
|
1827
|
+
tab: page.tab,
|
|
1828
|
+
width,
|
|
1829
|
+
now,
|
|
1830
|
+
error
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
buildRunContent(page, error, width, now) {
|
|
1834
|
+
const data = this.runData.get(runKey(page.routine, page.id));
|
|
1835
|
+
if (!data) return messageContent(error ?? "loading\u2026", Boolean(error));
|
|
1836
|
+
const isRunning = isMatching2({ status: "running" }, data.run);
|
|
1837
|
+
const cacheKey = `${width}|${data.eventCount}|${data.expandedVersion}|${String(isRunning)}`;
|
|
1838
|
+
if (data.transcript?.key !== cacheKey) {
|
|
1839
|
+
data.transcript = {
|
|
1840
|
+
key: cacheKey,
|
|
1841
|
+
lines: transcriptLines(data.items, data.eventCount, data.expanded, width, isRunning)
|
|
1842
|
+
};
|
|
1843
|
+
}
|
|
1844
|
+
const cwd = data.items.flatMap(
|
|
1845
|
+
(item) => match4(item).with({ kind: "init" }, (init) => [init.cwd]).otherwise(() => [])
|
|
1846
|
+
)[0];
|
|
1847
|
+
return {
|
|
1848
|
+
mode: "line",
|
|
1849
|
+
lines: [...runHeaderLines(data.run, cwd ?? null, width, now), ...data.transcript.lines]
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
clampPage(page, content, height, isFocused) {
|
|
1853
|
+
const maxScroll = Math.max(0, content.lines.length - height);
|
|
1854
|
+
if (isMatching2({ mode: "scroll" }, content)) {
|
|
1855
|
+
page.scroll = clamp(page.scroll, 0, maxScroll);
|
|
1856
|
+
return;
|
|
1857
|
+
}
|
|
1858
|
+
const targets = getSelectTargets(content);
|
|
1859
|
+
const last = (targets ?? content.lines).length - 1;
|
|
1860
|
+
if (isMatching2({ kind: "run", follow: true }, page)) page.cursor = last;
|
|
1861
|
+
else if (isFocused) this.restoreAnchor(page, content, targets);
|
|
1862
|
+
page.cursor = clamp(page.cursor, 0, Math.max(0, last));
|
|
1863
|
+
const line = targets ? targets[page.cursor] : page.cursor;
|
|
1864
|
+
if (line === void 0) {
|
|
1865
|
+
page.scroll = clamp(page.scroll, 0, maxScroll);
|
|
1866
|
+
page.anchor = null;
|
|
1867
|
+
return;
|
|
1868
|
+
}
|
|
1869
|
+
if (page.cursor === 0) page.scroll = 0;
|
|
1870
|
+
page.scroll = clamp(page.scroll, Math.max(0, line - height + 1), Math.min(line, maxScroll));
|
|
1871
|
+
page.anchor = isFocused ? getAnchor(content, line, page.cursor) : null;
|
|
1872
|
+
}
|
|
1873
|
+
// Only when the cursor did not move since the last render, otherwise the key that moved it wins.
|
|
1874
|
+
restoreAnchor(page, content, targets) {
|
|
1875
|
+
const anchor = page.anchor;
|
|
1876
|
+
if (!anchor || anchor.cursor !== page.cursor) return;
|
|
1877
|
+
if (targets) {
|
|
1878
|
+
const index = targets.findIndex((line) => getAnchor(content, line, 0)?.key === anchor.key);
|
|
1879
|
+
if (index !== -1) page.cursor = index;
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
const start = content.lines.findIndex((line) => line.isItemStart && line.itemKey === anchor.key);
|
|
1883
|
+
if (start === -1) return;
|
|
1884
|
+
const shift = start + anchor.offset - page.cursor;
|
|
1885
|
+
page.cursor += shift;
|
|
1886
|
+
page.scroll += shift;
|
|
1887
|
+
}
|
|
1888
|
+
hints() {
|
|
1889
|
+
const tail = [
|
|
1890
|
+
["?", "help"],
|
|
1891
|
+
["q", "quit"]
|
|
1892
|
+
];
|
|
1893
|
+
return match4({ focus: this.focus, page: this.page }).with({ focus: P2.union("routines", "runs") }, ({ focus }) => [
|
|
1894
|
+
["\u2191\u2193", "move"],
|
|
1895
|
+
["enter", "open"],
|
|
1896
|
+
[
|
|
1897
|
+
"r",
|
|
1898
|
+
match4(focus).with("runs", () => "run again").with("routines", () => "run now").exhaustive()
|
|
1899
|
+
],
|
|
1900
|
+
["tab", "panels"],
|
|
1901
|
+
["R", "refresh"],
|
|
1902
|
+
...tail
|
|
1903
|
+
]).with({ page: { kind: "run" } }, () => [
|
|
1904
|
+
["\u2191\u2193", "move"],
|
|
1905
|
+
["enter", "expand"],
|
|
1906
|
+
["e", "expand all"],
|
|
1907
|
+
["{ }", "items"],
|
|
1908
|
+
["G", "follow"],
|
|
1909
|
+
["esc", "back"],
|
|
1910
|
+
["r", "run now"],
|
|
1911
|
+
...tail
|
|
1912
|
+
]).with({ page: { kind: "routine", tab: "runs" } }, () => [
|
|
1913
|
+
["\u2191\u2193", "move"],
|
|
1914
|
+
["enter", "open run"],
|
|
1915
|
+
["[ ]", "tabs"],
|
|
1916
|
+
["esc", "back"],
|
|
1917
|
+
["r", "run now"],
|
|
1918
|
+
...tail
|
|
1919
|
+
]).otherwise(() => [
|
|
1920
|
+
["\u2191\u2193", "scroll"],
|
|
1921
|
+
["[ ]", "tabs"],
|
|
1922
|
+
["esc", "back"],
|
|
1923
|
+
["r", "run now"],
|
|
1924
|
+
...tail
|
|
1925
|
+
]);
|
|
1926
|
+
}
|
|
1927
|
+
statusRight(now) {
|
|
1928
|
+
if (this.message && now - this.message.at < MESSAGE_MS)
|
|
1929
|
+
return [
|
|
1930
|
+
{
|
|
1931
|
+
text: this.message.text,
|
|
1932
|
+
style: match4(this.message.tone).with("ok", () => S.boldGreen).with("error", () => S.boldRed).exhaustive()
|
|
1933
|
+
}
|
|
1934
|
+
];
|
|
1935
|
+
if (this.overviewError) return [{ text: this.overviewError, style: S.red }];
|
|
1936
|
+
if (this.loadedAt === null) return [];
|
|
1937
|
+
return [
|
|
1938
|
+
{
|
|
1939
|
+
text: `updated ${formatRelativeCompact(new Date(this.loadedAt).toISOString(), now)}`,
|
|
1940
|
+
style: S.dim
|
|
1941
|
+
}
|
|
1942
|
+
];
|
|
1943
|
+
}
|
|
1944
|
+
};
|
|
1945
|
+
|
|
1946
|
+
// ../domains/daemon/schemas.ts
|
|
1947
|
+
import { z as z4 } from "zod";
|
|
1948
|
+
var daemonStatusSchema = z4.object({
|
|
1949
|
+
// Older daemons do not send it, and tui --url may talk to one.
|
|
1950
|
+
version: z4.string().optional(),
|
|
1951
|
+
pid: z4.number(),
|
|
1952
|
+
startedAt: z4.string(),
|
|
1953
|
+
lastTickAt: z4.string().nullable(),
|
|
1954
|
+
routinesDir: z4.string(),
|
|
1955
|
+
stateDir: z4.string(),
|
|
1956
|
+
claudeBin: z4.string(),
|
|
1957
|
+
codexBin: z4.string(),
|
|
1958
|
+
maxConcurrentRuns: z4.number(),
|
|
1959
|
+
running: z4.number(),
|
|
1960
|
+
timezone: z4.string(),
|
|
1961
|
+
now: z4.string()
|
|
1962
|
+
});
|
|
1963
|
+
|
|
1964
|
+
// ../domains/daemon/requests.ts
|
|
1965
|
+
async function getDaemonStatus(http2) {
|
|
1966
|
+
return http2.request("/api/status", daemonStatusSchema);
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
// ../domains/routine/requests.ts
|
|
1970
|
+
import { z as z8 } from "zod";
|
|
1971
|
+
|
|
1972
|
+
// ../domains/routine/schemas.ts
|
|
1973
|
+
import { z as z7 } from "zod";
|
|
1974
|
+
|
|
1975
|
+
// ../domains/scheduler/schemas.ts
|
|
1976
|
+
import { z as z5 } from "zod";
|
|
1977
|
+
var skipReasonSchema = z5.enum(["already_running", "concurrency_limit", "disabled"]);
|
|
1978
|
+
var skipSchema = z5.object({
|
|
1979
|
+
at: z5.string(),
|
|
1980
|
+
scheduledFor: z5.string(),
|
|
1981
|
+
reason: skipReasonSchema
|
|
1982
|
+
});
|
|
1983
|
+
var schedulerStateSchema = z5.object({
|
|
1984
|
+
startedAt: z5.string(),
|
|
1985
|
+
lastTickAt: z5.string(),
|
|
1986
|
+
routines: z5.record(
|
|
1987
|
+
routineNameSchema,
|
|
1988
|
+
z5.object({ lastScheduledFor: z5.string().nullable(), skips: z5.array(skipSchema) })
|
|
1989
|
+
)
|
|
1990
|
+
});
|
|
1991
|
+
|
|
1992
|
+
// ../domains/webhook/schemas.ts
|
|
1993
|
+
import { z as z6 } from "zod";
|
|
1994
|
+
var queuedWebhookSchema = z6.object({
|
|
1995
|
+
runId: runIdSchema,
|
|
1996
|
+
queuedAt: z6.string(),
|
|
1997
|
+
bytes: z6.number(),
|
|
1998
|
+
preview: z6.string()
|
|
1999
|
+
});
|
|
2000
|
+
|
|
2001
|
+
// ../domains/routine/schemas.ts
|
|
2002
|
+
var routineSummarySchema = z7.object({
|
|
2003
|
+
name: routineNameSchema,
|
|
2004
|
+
description: z7.string(),
|
|
2005
|
+
schedule: z7.string().nullable(),
|
|
2006
|
+
scheduleHuman: z7.string(),
|
|
2007
|
+
nextRunAt: z7.string().nullable(),
|
|
2008
|
+
enabled: z7.boolean(),
|
|
2009
|
+
webhook: z7.boolean(),
|
|
2010
|
+
webhookGate: z7.string().nullable(),
|
|
2011
|
+
queuedWebhooks: z7.number(),
|
|
2012
|
+
agent: agentNameSchema,
|
|
2013
|
+
model: z7.string().nullable(),
|
|
2014
|
+
effort: z7.string().nullable(),
|
|
2015
|
+
permissionMode: z7.string().nullable(),
|
|
2016
|
+
command: z7.string().nullable(),
|
|
2017
|
+
cwd: z7.string(),
|
|
2018
|
+
timeoutMinutes: z7.number(),
|
|
2019
|
+
maxBudgetUsd: z7.number().nullable(),
|
|
2020
|
+
file: z7.string(),
|
|
2021
|
+
running: z7.boolean(),
|
|
2022
|
+
lastRun: runRecordSchema.nullable(),
|
|
2023
|
+
lastSkip: skipSchema.nullable()
|
|
2024
|
+
});
|
|
2025
|
+
var routineDetailSchema = routineSummarySchema.extend({
|
|
2026
|
+
prompt: z7.string(),
|
|
2027
|
+
skips: z7.array(skipSchema),
|
|
2028
|
+
queue: z7.array(queuedWebhookSchema)
|
|
2029
|
+
});
|
|
2030
|
+
var startedRunSchema = z7.object({ ok: z7.literal(true) });
|
|
2031
|
+
|
|
2032
|
+
// ../domains/routine/requests.ts
|
|
2033
|
+
async function getRoutines(http2) {
|
|
2034
|
+
return http2.request("/api/routines", z8.array(routineSummarySchema));
|
|
2035
|
+
}
|
|
2036
|
+
async function getRoutine(http2, name) {
|
|
2037
|
+
return http2.request(`/api/routines/${encodeURIComponent(name)}`, routineDetailSchema);
|
|
2038
|
+
}
|
|
2039
|
+
async function startRoutineRun(http2, name) {
|
|
2040
|
+
await http2.request(`/api/routines/${encodeURIComponent(name)}/run`, startedRunSchema, {
|
|
2041
|
+
method: "POST"
|
|
2042
|
+
});
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
// ../domains/transcript/schemas.ts
|
|
2046
|
+
import { z as z9 } from "zod";
|
|
2047
|
+
var toolResultSchema = z9.object({ content: z9.string(), isError: z9.boolean() });
|
|
2048
|
+
var hookItemSchema = z9.object({
|
|
2049
|
+
kind: z9.literal("hook"),
|
|
2050
|
+
key: z9.string(),
|
|
2051
|
+
command: z9.string(),
|
|
2052
|
+
exitCode: z9.number().nullable(),
|
|
2053
|
+
output: z9.string()
|
|
2054
|
+
});
|
|
2055
|
+
var initItemSchema = z9.object({
|
|
2056
|
+
kind: z9.literal("init"),
|
|
2057
|
+
key: z9.string(),
|
|
2058
|
+
model: z9.string().nullable(),
|
|
2059
|
+
cwd: z9.string().nullable(),
|
|
2060
|
+
toolCount: z9.number().nullable(),
|
|
2061
|
+
permissionMode: z9.string().nullable()
|
|
2062
|
+
});
|
|
2063
|
+
var textItemSchema = z9.object({
|
|
2064
|
+
kind: z9.literal("text"),
|
|
2065
|
+
key: z9.string(),
|
|
2066
|
+
text: z9.string(),
|
|
2067
|
+
isSubagent: z9.boolean()
|
|
2068
|
+
});
|
|
2069
|
+
var toolItemSchema = z9.object({
|
|
2070
|
+
kind: z9.literal("tool"),
|
|
2071
|
+
key: z9.string(),
|
|
2072
|
+
id: z9.string(),
|
|
2073
|
+
name: z9.string(),
|
|
2074
|
+
input: z9.unknown().optional(),
|
|
2075
|
+
preview: z9.string(),
|
|
2076
|
+
result: toolResultSchema.nullable(),
|
|
2077
|
+
isSubagent: z9.boolean()
|
|
2078
|
+
});
|
|
2079
|
+
var resultItemSchema = z9.object({
|
|
2080
|
+
kind: z9.literal("result"),
|
|
2081
|
+
key: z9.string(),
|
|
2082
|
+
text: z9.string(),
|
|
2083
|
+
isError: z9.boolean(),
|
|
2084
|
+
costUsd: z9.number().nullable(),
|
|
2085
|
+
numTurns: z9.number().nullable(),
|
|
2086
|
+
durationMs: z9.number().nullable()
|
|
2087
|
+
});
|
|
2088
|
+
var transcriptItemSchema = z9.discriminatedUnion("kind", [
|
|
2089
|
+
hookItemSchema,
|
|
2090
|
+
initItemSchema,
|
|
2091
|
+
textItemSchema,
|
|
2092
|
+
toolItemSchema,
|
|
2093
|
+
resultItemSchema
|
|
2094
|
+
]);
|
|
2095
|
+
var transcriptSchema = z9.object({
|
|
2096
|
+
eventCount: z9.number(),
|
|
2097
|
+
items: z9.array(transcriptItemSchema)
|
|
2098
|
+
});
|
|
2099
|
+
|
|
2100
|
+
// ../domains/run/requests.ts
|
|
2101
|
+
function getRunApiPath(routine, id) {
|
|
2102
|
+
return `/api/runs/${encodeURIComponent(routine)}/${encodeURIComponent(id)}`;
|
|
2103
|
+
}
|
|
2104
|
+
async function getRunsPage(http2, routine, cursor) {
|
|
2105
|
+
const params = new URLSearchParams();
|
|
2106
|
+
if (routine !== null) params.set("routine", routine);
|
|
2107
|
+
if (cursor !== null) params.set("cursor", cursor);
|
|
2108
|
+
return http2.request(`/api/runs?${params.toString()}`, runsPageSchema);
|
|
2109
|
+
}
|
|
2110
|
+
async function getRun(http2, routine, id) {
|
|
2111
|
+
return http2.request(getRunApiPath(routine, id), runRecordSchema);
|
|
2112
|
+
}
|
|
2113
|
+
async function getRunTranscript(http2, routine, id) {
|
|
2114
|
+
return http2.request(`${getRunApiPath(routine, id)}/transcript`, transcriptSchema);
|
|
2115
|
+
}
|
|
2116
|
+
async function getRunWithTranscript(http2, routine, id) {
|
|
2117
|
+
const [run, transcript] = await Promise.all([
|
|
2118
|
+
getRun(http2, routine, id),
|
|
2119
|
+
getRunTranscript(http2, routine, id)
|
|
2120
|
+
]);
|
|
2121
|
+
return { run, transcript };
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
// ../utils/http.ts
|
|
2125
|
+
import { z as z10 } from "zod";
|
|
2126
|
+
var errorBodySchema = z10.object({ error: z10.string() });
|
|
2127
|
+
async function readResponse(response, schema) {
|
|
2128
|
+
const body = await response.json().catch(() => null);
|
|
2129
|
+
if (!response.ok) {
|
|
2130
|
+
const error = errorBodySchema.safeParse(body);
|
|
2131
|
+
throw new Error(error.success ? error.data.error : `${response.status} ${response.statusText}`);
|
|
2132
|
+
}
|
|
2133
|
+
return schema.parse(body);
|
|
2134
|
+
}
|
|
2135
|
+
function createHttpClient({
|
|
2136
|
+
baseUrl = "",
|
|
2137
|
+
timeoutMs,
|
|
2138
|
+
networkErrorMessage
|
|
2139
|
+
} = {}) {
|
|
2140
|
+
async function send(path14, init) {
|
|
2141
|
+
const url = `${baseUrl}${path14}`;
|
|
2142
|
+
const options = timeoutMs === void 0 ? init : { ...init, signal: AbortSignal.timeout(timeoutMs) };
|
|
2143
|
+
if (networkErrorMessage === void 0) return fetch(url, options);
|
|
2144
|
+
try {
|
|
2145
|
+
return await fetch(url, options);
|
|
2146
|
+
} catch {
|
|
2147
|
+
throw new Error(networkErrorMessage);
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
return {
|
|
2151
|
+
async request(path14, schema, init) {
|
|
2152
|
+
return readResponse(await send(path14, init), schema);
|
|
2153
|
+
}
|
|
2154
|
+
};
|
|
2155
|
+
}
|
|
2156
|
+
var sameOriginApi = createHttpClient();
|
|
2157
|
+
|
|
2158
|
+
// ../tui/src/daemon-client.ts
|
|
2159
|
+
function createDaemonClient(baseUrl) {
|
|
2160
|
+
const http2 = createHttpClient({
|
|
2161
|
+
baseUrl,
|
|
2162
|
+
timeoutMs: 3e4,
|
|
2163
|
+
networkErrorMessage: `daemon not reachable at ${baseUrl}`
|
|
2164
|
+
});
|
|
2165
|
+
return {
|
|
2166
|
+
async getOverview() {
|
|
2167
|
+
const [status, routines, { runs }] = await Promise.all([
|
|
2168
|
+
getDaemonStatus(http2),
|
|
2169
|
+
getRoutines(http2),
|
|
2170
|
+
getRunsPage(http2, null, null)
|
|
2171
|
+
]);
|
|
2172
|
+
return { status, routines, runs };
|
|
2173
|
+
},
|
|
2174
|
+
getRoutine: async (name) => getRoutine(http2, name),
|
|
2175
|
+
getRuns: async (routine, cursor) => getRunsPage(http2, routine, cursor),
|
|
2176
|
+
getRun: async (routine, id) => getRunWithTranscript(http2, routine, id),
|
|
2177
|
+
async startRun(name) {
|
|
2178
|
+
await startRoutineRun(http2, name);
|
|
2179
|
+
}
|
|
2180
|
+
};
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
// ../tui/src/terminal/keys.ts
|
|
2184
|
+
var CSI_KEYS = {
|
|
2185
|
+
A: "up",
|
|
2186
|
+
B: "down",
|
|
2187
|
+
C: "right",
|
|
2188
|
+
D: "left",
|
|
2189
|
+
H: "home",
|
|
2190
|
+
F: "end",
|
|
2191
|
+
Z: "S-tab",
|
|
2192
|
+
"1~": "home",
|
|
2193
|
+
"4~": "end",
|
|
2194
|
+
"5~": "pageup",
|
|
2195
|
+
"6~": "pagedown",
|
|
2196
|
+
"7~": "home",
|
|
2197
|
+
"8~": "end",
|
|
2198
|
+
"200~": "paste-start",
|
|
2199
|
+
"201~": "paste-end"
|
|
2200
|
+
};
|
|
2201
|
+
var CONTROL_KEYS = {
|
|
2202
|
+
"\r": "enter",
|
|
2203
|
+
"\n": "enter",
|
|
2204
|
+
" ": "tab",
|
|
2205
|
+
"\x7F": "backspace",
|
|
2206
|
+
"\b": "backspace",
|
|
2207
|
+
" ": "space"
|
|
2208
|
+
};
|
|
2209
|
+
function parseKeys(chunk) {
|
|
2210
|
+
const keys = [];
|
|
2211
|
+
let i = 0;
|
|
2212
|
+
while (i < chunk.length) {
|
|
2213
|
+
const char = chunk.charAt(i);
|
|
2214
|
+
if (char === "\x1B") {
|
|
2215
|
+
const sequence = /^\x1b(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(chunk.slice(i));
|
|
2216
|
+
if (sequence) {
|
|
2217
|
+
const [whole, params = "", final, ss3] = sequence;
|
|
2218
|
+
const code = ss3 ?? (final === "~" ? `${params}~` : params ? "" : final ?? "");
|
|
2219
|
+
const name = CSI_KEYS[code];
|
|
2220
|
+
if (name) keys.push(name);
|
|
2221
|
+
i += whole.length;
|
|
2222
|
+
continue;
|
|
2223
|
+
}
|
|
2224
|
+
keys.push("escape");
|
|
2225
|
+
i += 1;
|
|
2226
|
+
continue;
|
|
2227
|
+
}
|
|
2228
|
+
const control = CONTROL_KEYS[char];
|
|
2229
|
+
if (control !== void 0) {
|
|
2230
|
+
keys.push(control);
|
|
2231
|
+
} else if (char < " ") {
|
|
2232
|
+
keys.push(`C-${String.fromCharCode(char.charCodeAt(0) + 96)}`);
|
|
2233
|
+
} else {
|
|
2234
|
+
keys.push(char);
|
|
2235
|
+
}
|
|
2236
|
+
i += 1;
|
|
2237
|
+
}
|
|
2238
|
+
return keys;
|
|
2239
|
+
}
|
|
2240
|
+
function createKeyReader() {
|
|
2241
|
+
let isPasting = false;
|
|
2242
|
+
let pending = "";
|
|
2243
|
+
return (chunk) => {
|
|
2244
|
+
const input = pending + chunk;
|
|
2245
|
+
const cutOff = /\x1b(\[[0-9;]*|O)$/.exec(input);
|
|
2246
|
+
pending = cutOff ? cutOff[0] : "";
|
|
2247
|
+
return parseKeys(cutOff ? input.slice(0, cutOff.index) : input).filter((key) => {
|
|
2248
|
+
if (key === "paste-start") isPasting = true;
|
|
2249
|
+
else if (key === "paste-end") isPasting = false;
|
|
2250
|
+
else return !isPasting;
|
|
2251
|
+
return false;
|
|
2252
|
+
});
|
|
2253
|
+
};
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
// ../tui/src/terminal/terminal.ts
|
|
2257
|
+
var PAGE = `\x1B[0;${BASE}m`;
|
|
2258
|
+
var ENTER = `\x1B[?1049h\x1B[?25l\x1B[?7l\x1B[?2004h${PAGE}\x1B[2J`;
|
|
2259
|
+
var LEAVE = "\x1B[0m\x1B[?2004l\x1B[?7h\x1B[?25h\x1B[?1049l";
|
|
2260
|
+
var BEGIN_FRAME = "\x1B[?2026h";
|
|
2261
|
+
var END_FRAME = "\x1B[?2026l";
|
|
2262
|
+
var Terminal = class {
|
|
2263
|
+
previous = [];
|
|
2264
|
+
isActive = false;
|
|
2265
|
+
get width() {
|
|
2266
|
+
return process.stdout.columns;
|
|
2267
|
+
}
|
|
2268
|
+
get height() {
|
|
2269
|
+
return process.stdout.rows;
|
|
2270
|
+
}
|
|
2271
|
+
start(onKeys, onResize) {
|
|
2272
|
+
this.isActive = true;
|
|
2273
|
+
process.stdout.write(ENTER);
|
|
2274
|
+
process.stdin.setRawMode(true);
|
|
2275
|
+
process.stdin.setEncoding("utf8");
|
|
2276
|
+
const readKeys = createKeyReader();
|
|
2277
|
+
process.stdin.on("data", (chunk) => {
|
|
2278
|
+
const keys = readKeys(chunk);
|
|
2279
|
+
if (keys.length > 0) onKeys(keys);
|
|
2280
|
+
});
|
|
2281
|
+
process.stdin.resume();
|
|
2282
|
+
process.stdout.on("resize", () => {
|
|
2283
|
+
this.previous = [];
|
|
2284
|
+
process.stdout.write(`${PAGE}\x1B[2J`);
|
|
2285
|
+
onResize();
|
|
2286
|
+
});
|
|
2287
|
+
}
|
|
2288
|
+
draw(frame) {
|
|
2289
|
+
if (!this.isActive) return;
|
|
2290
|
+
const rows = frame.map((line) => toAnsi(line, BASE));
|
|
2291
|
+
let output = "";
|
|
2292
|
+
rows.forEach((row, index) => {
|
|
2293
|
+
if (row !== this.previous[index]) output += `\x1B[${index + 1};1H${PAGE}\x1B[2K${row}`;
|
|
2294
|
+
});
|
|
2295
|
+
this.previous = rows;
|
|
2296
|
+
if (output) process.stdout.write(BEGIN_FRAME + output + END_FRAME);
|
|
2297
|
+
}
|
|
2298
|
+
stop() {
|
|
2299
|
+
if (!this.isActive) return;
|
|
2300
|
+
this.isActive = false;
|
|
2301
|
+
process.stdout.write(LEAVE);
|
|
2302
|
+
process.stdin.setRawMode(false);
|
|
2303
|
+
process.stdin.pause();
|
|
2304
|
+
}
|
|
2305
|
+
};
|
|
2306
|
+
|
|
2307
|
+
// ../tui/src/index.ts
|
|
2308
|
+
var POLL_ACTIVE_MS = 3e3;
|
|
2309
|
+
var POLL_IDLE_MS = 1e4;
|
|
2310
|
+
var FRAME_ACTIVE_MS = 150;
|
|
2311
|
+
var FRAME_IDLE_MS = 1e3;
|
|
2312
|
+
function runTui(baseUrl, stopSignal) {
|
|
2313
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
2314
|
+
throw new Error("tui needs an interactive terminal");
|
|
2315
|
+
const terminal = new Terminal();
|
|
2316
|
+
const draw = () => terminal.draw(app.render(terminal.width, terminal.height));
|
|
2317
|
+
const app = new TuiApp({ client: createDaemonClient(baseUrl), onChange: draw });
|
|
2318
|
+
let pollTimer;
|
|
2319
|
+
let frameTimer;
|
|
2320
|
+
return new Promise((resolve) => {
|
|
2321
|
+
const quit = () => {
|
|
2322
|
+
clearTimeout(pollTimer);
|
|
2323
|
+
clearTimeout(frameTimer);
|
|
2324
|
+
app.dispose();
|
|
2325
|
+
terminal.stop();
|
|
2326
|
+
resolve();
|
|
2327
|
+
};
|
|
2328
|
+
const crash = (err) => {
|
|
2329
|
+
terminal.stop();
|
|
2330
|
+
console.error(err);
|
|
2331
|
+
process.exit(1);
|
|
2332
|
+
};
|
|
2333
|
+
process.on("uncaughtException", crash);
|
|
2334
|
+
process.on("unhandledRejection", crash);
|
|
2335
|
+
for (const signal of ["SIGTERM", "SIGHUP", "SIGINT", "SIGQUIT"])
|
|
2336
|
+
process.on(signal, quit);
|
|
2337
|
+
stopSignal?.addEventListener("abort", quit);
|
|
2338
|
+
const poll = async () => {
|
|
2339
|
+
await app.refresh();
|
|
2340
|
+
pollTimer = setTimeout(
|
|
2341
|
+
() => void poll(),
|
|
2342
|
+
app.checkHasActiveRuns() ? POLL_ACTIVE_MS : POLL_IDLE_MS
|
|
2343
|
+
);
|
|
2344
|
+
};
|
|
2345
|
+
const repaint = () => {
|
|
2346
|
+
draw();
|
|
2347
|
+
frameTimer = setTimeout(repaint, app.checkHasActiveRuns() ? FRAME_ACTIVE_MS : FRAME_IDLE_MS);
|
|
2348
|
+
};
|
|
2349
|
+
terminal.start((keys) => {
|
|
2350
|
+
if (app.handleKeys(keys, terminal.width, terminal.height) === "quit") {
|
|
2351
|
+
quit();
|
|
2352
|
+
return;
|
|
2353
|
+
}
|
|
2354
|
+
draw();
|
|
2355
|
+
}, draw);
|
|
2356
|
+
void poll();
|
|
2357
|
+
repaint();
|
|
2358
|
+
});
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
// ../utils/cron.ts
|
|
2362
|
+
function splitCron(expression) {
|
|
2363
|
+
const [minute, hour, dayOfMonth, month, dayOfWeek, ...rest] = expression.trim().split(/\s+/);
|
|
2364
|
+
if (minute === void 0 || hour === void 0 || dayOfMonth === void 0 || month === void 0 || dayOfWeek === void 0 || rest.length > 0) {
|
|
2365
|
+
throw new Error(`Cron expression must have 5 fields, got "${expression}"`);
|
|
2366
|
+
}
|
|
2367
|
+
return [minute, hour, dayOfMonth, month, dayOfWeek];
|
|
2368
|
+
}
|
|
2369
|
+
function parseBounds(range, hasStep, min, max) {
|
|
2370
|
+
if (range === "*") return [min, max];
|
|
2371
|
+
if (range.includes("-")) {
|
|
2372
|
+
const [from = Number.NaN, to = Number.NaN] = range.split("-").map(Number);
|
|
2373
|
+
return [from, to];
|
|
2374
|
+
}
|
|
2375
|
+
const start = Number(range);
|
|
2376
|
+
return [start, hasStep ? max : start];
|
|
2377
|
+
}
|
|
2378
|
+
function parseField(field, min, max) {
|
|
2379
|
+
const values = /* @__PURE__ */ new Set();
|
|
2380
|
+
for (const part of field.split(",")) {
|
|
2381
|
+
const [range = "", stepPart] = part.split("/");
|
|
2382
|
+
const step = stepPart === void 0 ? 1 : Number(stepPart);
|
|
2383
|
+
if (!Number.isInteger(step) || step < 1) throw new Error(`Invalid cron step "${part}"`);
|
|
2384
|
+
const [start, end] = parseBounds(range, stepPart !== void 0, min, max);
|
|
2385
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < min || end > max || start > end) {
|
|
2386
|
+
throw new Error(`Invalid cron field "${field}" (allowed ${min}-${max})`);
|
|
2387
|
+
}
|
|
2388
|
+
for (let value = start; value <= end; value += step) values.add(value);
|
|
2389
|
+
}
|
|
2390
|
+
return values;
|
|
2391
|
+
}
|
|
2392
|
+
function parseCron(expression) {
|
|
2393
|
+
const [minute, hour, dayOfMonth, month, dayOfWeek] = splitCron(expression);
|
|
2394
|
+
return {
|
|
2395
|
+
minute: parseField(minute, 0, 59),
|
|
2396
|
+
hour: parseField(hour, 0, 23),
|
|
2397
|
+
dayOfMonth: parseField(dayOfMonth, 1, 31),
|
|
2398
|
+
month: parseField(month, 1, 12),
|
|
2399
|
+
dayOfWeek: new Set([...parseField(dayOfWeek, 0, 7)].map((day) => day === 7 ? 0 : day)),
|
|
2400
|
+
dayOfMonthRestricted: dayOfMonth !== "*",
|
|
2401
|
+
dayOfWeekRestricted: dayOfWeek !== "*"
|
|
2402
|
+
};
|
|
2403
|
+
}
|
|
2404
|
+
function checkMatchesFields(c, date) {
|
|
2405
|
+
if (!c.minute.has(date.getMinutes()) || !c.hour.has(date.getHours()) || !c.month.has(date.getMonth() + 1))
|
|
2406
|
+
return false;
|
|
2407
|
+
const domMatch = c.dayOfMonth.has(date.getDate());
|
|
2408
|
+
const dowMatch = c.dayOfWeek.has(date.getDay());
|
|
2409
|
+
if (c.dayOfMonthRestricted && c.dayOfWeekRestricted) return domMatch || dowMatch;
|
|
2410
|
+
if (c.dayOfMonthRestricted) return domMatch;
|
|
2411
|
+
if (c.dayOfWeekRestricted) return dowMatch;
|
|
2412
|
+
return true;
|
|
2413
|
+
}
|
|
2414
|
+
function nextCronRun(expression, after) {
|
|
2415
|
+
const fields = parseCron(expression);
|
|
2416
|
+
const cursor = new Date(after);
|
|
2417
|
+
cursor.setSeconds(0, 0);
|
|
2418
|
+
cursor.setMinutes(cursor.getMinutes() + 1);
|
|
2419
|
+
const limit = 366 * 24 * 60;
|
|
2420
|
+
for (let i = 0; i < limit; i++) {
|
|
2421
|
+
if (checkMatchesFields(fields, cursor)) return cursor;
|
|
2422
|
+
cursor.setMinutes(cursor.getMinutes() + 1);
|
|
2423
|
+
}
|
|
2424
|
+
return void 0;
|
|
2425
|
+
}
|
|
2426
|
+
function cronRunsBetween(expression, afterExclusive, untilInclusive) {
|
|
2427
|
+
const fields = parseCron(expression);
|
|
2428
|
+
const runs = [];
|
|
2429
|
+
const cursor = new Date(afterExclusive);
|
|
2430
|
+
cursor.setSeconds(0, 0);
|
|
2431
|
+
cursor.setMinutes(cursor.getMinutes() + 1);
|
|
2432
|
+
while (cursor <= untilInclusive) {
|
|
2433
|
+
if (checkMatchesFields(fields, cursor)) runs.push(new Date(cursor));
|
|
2434
|
+
cursor.setMinutes(cursor.getMinutes() + 1);
|
|
2435
|
+
}
|
|
2436
|
+
return runs;
|
|
2437
|
+
}
|
|
2438
|
+
function getHourRuns(hours) {
|
|
2439
|
+
const runs = [];
|
|
2440
|
+
for (const hour of [...hours].sort((a, b) => a - b)) {
|
|
2441
|
+
const last2 = runs.at(-1);
|
|
2442
|
+
if (last2?.to === hour - 1) last2.to = hour;
|
|
2443
|
+
else runs.push({ from: hour, to: hour });
|
|
2444
|
+
}
|
|
2445
|
+
const first = runs[0];
|
|
2446
|
+
const last = runs.at(-1);
|
|
2447
|
+
if (runs.length > 1 && first?.from === 0 && last?.to === 23) {
|
|
2448
|
+
runs.shift();
|
|
2449
|
+
last.to = first.to;
|
|
2450
|
+
}
|
|
2451
|
+
return runs;
|
|
2452
|
+
}
|
|
2453
|
+
var DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
|
2454
|
+
var pad = (n) => String(n).padStart(2, "0");
|
|
2455
|
+
function describeCron(expression) {
|
|
2456
|
+
const [minute, hour, dom, month, dow] = splitCron(expression);
|
|
2457
|
+
const c = parseCron(expression);
|
|
2458
|
+
const singleMinute = c.minute.size === 1 ? [...c.minute][0] : void 0;
|
|
2459
|
+
const singleHour = c.hour.size === 1 ? [...c.hour][0] : void 0;
|
|
2460
|
+
const time = singleMinute !== void 0 && singleHour !== void 0 ? `${pad(singleHour)}:${pad(singleMinute)}` : void 0;
|
|
2461
|
+
const dayNames = [...c.dayOfWeek].sort((a, b) => a - b).map((day) => DAY_NAMES[day] ?? String(day));
|
|
2462
|
+
const isWeekdays = dow === "1-5";
|
|
2463
|
+
if (dom === "*" && month === "*") {
|
|
2464
|
+
if (time && dow === "*") return `Daily at ${time}`;
|
|
2465
|
+
if (time && isWeekdays) return `Weekdays at ${time}`;
|
|
2466
|
+
if (time && dayNames.length === 1) return `Weekly on ${dayNames[0]} at ${time}`;
|
|
2467
|
+
if (time) return `${dayNames.join(", ")} at ${time}`;
|
|
2468
|
+
if (singleMinute !== void 0 && hour === "*" && dow === "*")
|
|
2469
|
+
return `Hourly at :${pad(singleMinute)}`;
|
|
2470
|
+
if (singleMinute !== void 0 && hour.includes("/") && dow === "*") {
|
|
2471
|
+
const [first, last] = [Math.min(...c.hour), Math.max(...c.hour)].map(
|
|
2472
|
+
(h) => `${pad(h)}:${pad(singleMinute)}`
|
|
2473
|
+
);
|
|
2474
|
+
const span = hour.startsWith("*") ? `from ${first}` : `${first}-${last}`;
|
|
2475
|
+
return `Every ${hour.split("/")[1]} hours at :${pad(singleMinute)}, ${span}`;
|
|
2476
|
+
}
|
|
2477
|
+
if (singleMinute !== void 0 && hour.includes("-") && dow === "*") {
|
|
2478
|
+
const spans = getHourRuns(c.hour).map(
|
|
2479
|
+
({ from, to }) => from === to ? `${pad(from)}:${pad(singleMinute)}` : `${pad(from)}:00-${pad(to)}:59`
|
|
2480
|
+
);
|
|
2481
|
+
const last = spans.pop() ?? "";
|
|
2482
|
+
const span = spans.length > 0 ? `${spans.join(", ")} and ${last}` : last;
|
|
2483
|
+
return `Hourly at :${pad(singleMinute)}, ${span}`;
|
|
2484
|
+
}
|
|
2485
|
+
if (singleMinute !== void 0 && dow === "*" && c.hour.size <= 4) {
|
|
2486
|
+
const times = [...c.hour].sort((a, b) => a - b).map((h) => `${pad(h)}:${pad(singleMinute)}`);
|
|
2487
|
+
return `Daily at ${times.slice(0, -1).join(", ")} and ${times.at(-1) ?? ""}`;
|
|
2488
|
+
}
|
|
2489
|
+
if (singleMinute !== void 0 && dow === "*") {
|
|
2490
|
+
return `At :${pad(singleMinute)} on hours ${[...c.hour].sort((a, b) => a - b).join(", ")}`;
|
|
2491
|
+
}
|
|
2492
|
+
if (minute.startsWith("*/") && hour === "*" && dow === "*")
|
|
2493
|
+
return `Every ${minute.slice(2)} minutes`;
|
|
2494
|
+
}
|
|
2495
|
+
return `cron ${expression}`;
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
// src/config.ts
|
|
2499
|
+
import fs2 from "node:fs";
|
|
2500
|
+
import os from "node:os";
|
|
2501
|
+
import path from "node:path";
|
|
2502
|
+
import { z as z11 } from "zod";
|
|
2503
|
+
|
|
2504
|
+
// src/utils/json.ts
|
|
2505
|
+
import fs from "node:fs";
|
|
2506
|
+
function parseJson(text2) {
|
|
2507
|
+
try {
|
|
2508
|
+
const value = JSON.parse(text2);
|
|
2509
|
+
return value;
|
|
2510
|
+
} catch {
|
|
2511
|
+
return void 0;
|
|
2512
|
+
}
|
|
2513
|
+
}
|
|
2514
|
+
function checkIsRecord(value) {
|
|
2515
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2516
|
+
}
|
|
2517
|
+
function readJsonFile(file, schema) {
|
|
2518
|
+
if (!fs.existsSync(file)) return null;
|
|
2519
|
+
const parsed = schema.safeParse(parseJson(fs.readFileSync(file, "utf8")));
|
|
2520
|
+
return parsed.success ? parsed.data : null;
|
|
2521
|
+
}
|
|
2522
|
+
function writeJsonFile(file, value) {
|
|
2523
|
+
fs.writeFileSync(`${file}.tmp`, JSON.stringify(value, null, 2));
|
|
2524
|
+
fs.renameSync(`${file}.tmp`, file);
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
// src/config.ts
|
|
2528
|
+
var PACKAGE_NAME = "kombinat";
|
|
2529
|
+
var DEFAULT_PORT = 7433;
|
|
2530
|
+
var packageJsonSchema = z11.object({ version: z11.string() });
|
|
2531
|
+
function findProjectRoot(from) {
|
|
2532
|
+
for (let dir = from; ; dir = path.dirname(dir)) {
|
|
2533
|
+
if (fs2.existsSync(path.join(dir, "package.json"))) return dir;
|
|
2534
|
+
if (path.dirname(dir) === dir) return from;
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
function findPackageLink(from) {
|
|
2538
|
+
for (let dir = from; ; dir = path.dirname(dir)) {
|
|
2539
|
+
const candidate = path.join(dir, "node_modules", PACKAGE_NAME);
|
|
2540
|
+
if (fs2.existsSync(candidate)) return candidate;
|
|
2541
|
+
if (path.dirname(dir) === dir) return null;
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
var projectRoot = findProjectRoot(process.cwd());
|
|
2545
|
+
var ownRoot = path.resolve(import.meta.dirname, "..");
|
|
2546
|
+
var packageLink = findPackageLink(projectRoot);
|
|
2547
|
+
var installedRoot = packageLink !== null && fs2.realpathSync(packageLink) === fs2.realpathSync(ownRoot) ? packageLink : null;
|
|
2548
|
+
var packageRoot = installedRoot ?? ownRoot;
|
|
2549
|
+
var fromSource = fs2.existsSync(path.join(packageRoot, "src", "cli.ts"));
|
|
2550
|
+
var env = (name) => process.env[name];
|
|
2551
|
+
var config = {
|
|
2552
|
+
projectRoot,
|
|
2553
|
+
packageRoot,
|
|
2554
|
+
workspaceRoot: fromSource ? path.resolve(fs2.realpathSync(packageRoot), "..", "..") : null,
|
|
2555
|
+
cliBin: path.join(packageRoot, "bin", "kombinat.js"),
|
|
2556
|
+
version: readJsonFile(path.join(packageRoot, "package.json"), packageJsonSchema)?.version,
|
|
2557
|
+
fromSource,
|
|
2558
|
+
installedInProject: installedRoot !== null,
|
|
2559
|
+
projectHasCopy: packageLink !== null,
|
|
2560
|
+
routinesDir: env("KOMBINAT_ROUTINES_DIR") ?? path.join(projectRoot, "routines"),
|
|
2561
|
+
stateDir: env("KOMBINAT_STATE_DIR") ?? path.join(os.homedir(), ".kombinat"),
|
|
2562
|
+
webAppDist: path.join(packageRoot, "dist", "web-app"),
|
|
2563
|
+
port: Number(env("KOMBINAT_PORT") ?? DEFAULT_PORT),
|
|
2564
|
+
claudeBin: env("CLAUDE_BIN") ?? path.join(os.homedir(), ".local", "bin", "claude"),
|
|
2565
|
+
codexBin: env("CODEX_BIN") ?? "codex",
|
|
2566
|
+
tickSeconds: Number(env("KOMBINAT_TICK_SECONDS") ?? 30),
|
|
2567
|
+
maxConcurrentRuns: Number(env("KOMBINAT_MAX_CONCURRENT") ?? 3),
|
|
2568
|
+
catchUpWindowDays: 7,
|
|
2569
|
+
pullMinutes: Number(env("KOMBINAT_PULL_MINUTES") ?? 5),
|
|
2570
|
+
pullBranch: env("KOMBINAT_PULL_BRANCH") ?? "main",
|
|
2571
|
+
managed: env("KOMBINAT_MANAGED") === "1",
|
|
2572
|
+
launchdLabel: "com.kombinat.daemon"
|
|
2573
|
+
};
|
|
2574
|
+
var getCliArgs = (...args) => [config.cliBin, ...args];
|
|
2575
|
+
|
|
2576
|
+
// src/domains/routine/storage.ts
|
|
2577
|
+
import fs3 from "node:fs";
|
|
2578
|
+
import path3 from "node:path";
|
|
2579
|
+
|
|
2580
|
+
// src/domains/routine/utils.ts
|
|
2581
|
+
import os2 from "node:os";
|
|
2582
|
+
import path2 from "node:path";
|
|
2583
|
+
|
|
2584
|
+
// src/domains/agent/registry.ts
|
|
2585
|
+
import { match as match7 } from "ts-pattern";
|
|
2586
|
+
|
|
2587
|
+
// src/domains/agent/claude.ts
|
|
2588
|
+
import { match as match5 } from "ts-pattern";
|
|
2589
|
+
import { z as z12 } from "zod";
|
|
2590
|
+
|
|
2591
|
+
// src/domains/agent/settings.ts
|
|
2592
|
+
function pickOne(value, allowed, field, agent) {
|
|
2593
|
+
if (value === null) return null;
|
|
2594
|
+
const found = allowed.find((candidate) => candidate === value);
|
|
2595
|
+
if (found === void 0) {
|
|
2596
|
+
throw new Error(`${field} must be one of ${allowed.join(", ")} for agent ${agent}`);
|
|
2597
|
+
}
|
|
2598
|
+
return found;
|
|
2599
|
+
}
|
|
2600
|
+
function rejectUnsupported(raw, fields, agent) {
|
|
2601
|
+
const used = fields.filter((field) => raw[field] !== null);
|
|
2602
|
+
if (used.length > 0) throw new Error(`agent ${agent} does not support ${used.join(", ")}`);
|
|
2603
|
+
}
|
|
2604
|
+
function withoutEnv(names) {
|
|
2605
|
+
return Object.fromEntries(Object.entries(process.env).filter(([name]) => !names.includes(name)));
|
|
2606
|
+
}
|
|
2607
|
+
function getUnattendedNote({ routine, runId, trigger }) {
|
|
2608
|
+
return [
|
|
2609
|
+
`This session was started unattended by the kombinat scheduler for routine "${routine.name}" (run ${runId}, trigger ${trigger}).`,
|
|
2610
|
+
"Nobody is watching and nobody can answer questions, so make sensible calls, record them, and finish on your own."
|
|
2611
|
+
].join(" ");
|
|
2612
|
+
}
|
|
2613
|
+
|
|
2614
|
+
// src/domains/agent/claude.ts
|
|
2615
|
+
var DEFAULT_MODEL = "claude-opus-5-5";
|
|
2616
|
+
var DEFAULT_EFFORT = "high";
|
|
2617
|
+
var DEFAULT_PERMISSION_MODE = "auto";
|
|
2618
|
+
var EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
2619
|
+
var PERMISSION_MODES = [
|
|
2620
|
+
"auto",
|
|
2621
|
+
"acceptEdits",
|
|
2622
|
+
"dontAsk",
|
|
2623
|
+
"bypassPermissions",
|
|
2624
|
+
"plan",
|
|
2625
|
+
"manual"
|
|
2626
|
+
];
|
|
2627
|
+
var DROPPED_ENV = [
|
|
2628
|
+
"ANTHROPIC_API_KEY",
|
|
2629
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
2630
|
+
"CLAUDECODE",
|
|
2631
|
+
"CLAUDE_CODE_ENTRYPOINT"
|
|
2632
|
+
];
|
|
2633
|
+
var PREVIEW_FIELDS = {
|
|
2634
|
+
Bash: "command",
|
|
2635
|
+
Read: "file_path",
|
|
2636
|
+
Edit: "file_path",
|
|
2637
|
+
MultiEdit: "file_path",
|
|
2638
|
+
Write: "file_path",
|
|
2639
|
+
NotebookEdit: "notebook_path",
|
|
2640
|
+
Grep: "pattern",
|
|
2641
|
+
Glob: "pattern",
|
|
2642
|
+
WebFetch: "url",
|
|
2643
|
+
WebSearch: "query",
|
|
2644
|
+
Task: "description",
|
|
2645
|
+
Agent: "description",
|
|
2646
|
+
Skill: "skill",
|
|
2647
|
+
ToolSearch: "query"
|
|
2648
|
+
};
|
|
2649
|
+
var contentBlockSchema = z12.object({
|
|
2650
|
+
type: z12.string().optional(),
|
|
2651
|
+
text: z12.string().optional(),
|
|
2652
|
+
id: z12.string().optional(),
|
|
2653
|
+
name: z12.string().optional(),
|
|
2654
|
+
input: z12.unknown().optional(),
|
|
2655
|
+
tool_use_id: z12.string().optional(),
|
|
2656
|
+
content: z12.unknown().optional(),
|
|
2657
|
+
is_error: z12.boolean().optional()
|
|
2658
|
+
});
|
|
2659
|
+
var textPartSchema = z12.object({ type: z12.literal("text"), text: z12.string() });
|
|
2660
|
+
var claudeEventSchema = z12.object({
|
|
2661
|
+
type: z12.string().optional(),
|
|
2662
|
+
subtype: z12.string().optional(),
|
|
2663
|
+
session_id: sessionIdSchema.optional(),
|
|
2664
|
+
parent_tool_use_id: z12.string().nullable().optional(),
|
|
2665
|
+
message: z12.object({ content: z12.unknown().optional() }).optional(),
|
|
2666
|
+
model: z12.string().optional(),
|
|
2667
|
+
cwd: z12.string().optional(),
|
|
2668
|
+
tools: z12.array(z12.unknown()).optional(),
|
|
2669
|
+
permissionMode: z12.string().optional(),
|
|
2670
|
+
result: z12.string().optional(),
|
|
2671
|
+
is_error: z12.boolean().optional(),
|
|
2672
|
+
total_cost_usd: z12.number().optional(),
|
|
2673
|
+
num_turns: z12.number().optional(),
|
|
2674
|
+
duration_ms: z12.number().optional()
|
|
2675
|
+
});
|
|
2676
|
+
function toClaudeEvents(events) {
|
|
2677
|
+
return events.flatMap((event) => {
|
|
2678
|
+
const parsed = claudeEventSchema.safeParse(event);
|
|
2679
|
+
return parsed.success ? [parsed.data] : [];
|
|
2680
|
+
});
|
|
2681
|
+
}
|
|
2682
|
+
function getContentBlocks(event) {
|
|
2683
|
+
const content = event.message?.content;
|
|
2684
|
+
if (!Array.isArray(content)) return [];
|
|
2685
|
+
return content.flatMap((block) => {
|
|
2686
|
+
const parsed = contentBlockSchema.safeParse(block);
|
|
2687
|
+
return parsed.success ? [parsed.data] : [];
|
|
2688
|
+
});
|
|
2689
|
+
}
|
|
2690
|
+
function getInputPreview(name, input) {
|
|
2691
|
+
const field = PREVIEW_FIELDS[name];
|
|
2692
|
+
const value = field !== void 0 && checkIsRecord(input) ? input[field] : void 0;
|
|
2693
|
+
return toPreview(typeof value === "string" ? value : JSON.stringify(input ?? {}));
|
|
2694
|
+
}
|
|
2695
|
+
function stringifyResultContent(content) {
|
|
2696
|
+
if (typeof content === "string") return content;
|
|
2697
|
+
if (!Array.isArray(content)) return JSON.stringify(content, null, 2);
|
|
2698
|
+
return content.map((part) => {
|
|
2699
|
+
const textPart = textPartSchema.safeParse(part);
|
|
2700
|
+
return textPart.success ? textPart.data.text : JSON.stringify(part);
|
|
2701
|
+
}).join("\n");
|
|
2702
|
+
}
|
|
2703
|
+
function collectToolResults(events) {
|
|
2704
|
+
const results = /* @__PURE__ */ new Map();
|
|
2705
|
+
for (const event of events) {
|
|
2706
|
+
if (event.type !== "user") continue;
|
|
2707
|
+
for (const block of getContentBlocks(event)) {
|
|
2708
|
+
if (block.type !== "tool_result" || block.tool_use_id === void 0) continue;
|
|
2709
|
+
results.set(block.tool_use_id, {
|
|
2710
|
+
content: stringifyResultContent(block.content),
|
|
2711
|
+
isError: block.is_error === true
|
|
2712
|
+
});
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
return results;
|
|
2716
|
+
}
|
|
2717
|
+
function toBlockItems(block, key, isSubagent, results) {
|
|
2718
|
+
return match5(block).with(
|
|
2719
|
+
{ type: "text" },
|
|
2720
|
+
({ text: text2 }) => text2?.trim() ? [{ kind: "text", key, text: text2, isSubagent }] : []
|
|
2721
|
+
).with({ type: "tool_use" }, (tool) => {
|
|
2722
|
+
const name = tool.name ?? "tool";
|
|
2723
|
+
return [
|
|
2724
|
+
{
|
|
2725
|
+
kind: "tool",
|
|
2726
|
+
key,
|
|
2727
|
+
id: tool.id ?? key,
|
|
2728
|
+
name,
|
|
2729
|
+
input: tool.input,
|
|
2730
|
+
preview: getInputPreview(name, tool.input),
|
|
2731
|
+
result: tool.id === void 0 ? null : results.get(tool.id) ?? null,
|
|
2732
|
+
isSubagent
|
|
2733
|
+
}
|
|
2734
|
+
];
|
|
2735
|
+
}).otherwise(() => []);
|
|
2736
|
+
}
|
|
2737
|
+
function toItems(event, index, results) {
|
|
2738
|
+
return match5(event).with({ type: "system", subtype: "init" }, (init) => [
|
|
2739
|
+
{
|
|
2740
|
+
kind: "init",
|
|
2741
|
+
key: `init-${index}`,
|
|
2742
|
+
model: init.model ?? null,
|
|
2743
|
+
cwd: init.cwd ?? null,
|
|
2744
|
+
toolCount: init.tools?.length ?? null,
|
|
2745
|
+
permissionMode: init.permissionMode ?? null
|
|
2746
|
+
}
|
|
2747
|
+
]).with(
|
|
2748
|
+
{ type: "assistant" },
|
|
2749
|
+
(assistant) => getContentBlocks(assistant).flatMap(
|
|
2750
|
+
(block, blockIndex) => toBlockItems(
|
|
2751
|
+
block,
|
|
2752
|
+
`${index}-${blockIndex}`,
|
|
2753
|
+
Boolean(assistant.parent_tool_use_id),
|
|
2754
|
+
results
|
|
2755
|
+
)
|
|
2756
|
+
)
|
|
2757
|
+
).with({ type: "result" }, (result) => [
|
|
2758
|
+
{
|
|
2759
|
+
kind: "result",
|
|
2760
|
+
key: `result-${index}`,
|
|
2761
|
+
text: result.result ?? "",
|
|
2762
|
+
isError: result.is_error === true,
|
|
2763
|
+
costUsd: result.total_cost_usd ?? null,
|
|
2764
|
+
numTurns: result.num_turns ?? null,
|
|
2765
|
+
durationMs: result.duration_ms ?? null
|
|
2766
|
+
}
|
|
2767
|
+
]).otherwise(() => []);
|
|
2768
|
+
}
|
|
2769
|
+
function readResult(event) {
|
|
2770
|
+
const update = {
|
|
2771
|
+
resultText: event.result ?? null,
|
|
2772
|
+
costUsd: event.total_cost_usd ?? null,
|
|
2773
|
+
numTurns: event.num_turns ?? null,
|
|
2774
|
+
durationMs: event.duration_ms ?? null
|
|
2775
|
+
};
|
|
2776
|
+
if (event.is_error === true) update.error = event.result ?? "Claude reported an error result";
|
|
2777
|
+
return update;
|
|
2778
|
+
}
|
|
2779
|
+
var claudeAgent = {
|
|
2780
|
+
name: "claude",
|
|
2781
|
+
output: "jsonl",
|
|
2782
|
+
binaryEnv: "CLAUDE_BIN",
|
|
2783
|
+
resolveSettings(raw) {
|
|
2784
|
+
rejectUnsupported(raw, ["command"], "claude");
|
|
2785
|
+
return {
|
|
2786
|
+
...raw,
|
|
2787
|
+
model: raw.model ?? DEFAULT_MODEL,
|
|
2788
|
+
effort: pickOne(raw.effort, EFFORTS, "effort", "claude") ?? DEFAULT_EFFORT,
|
|
2789
|
+
permissionMode: pickOne(raw.permissionMode, PERMISSION_MODES, "permissionMode", "claude") ?? DEFAULT_PERMISSION_MODE
|
|
2790
|
+
};
|
|
2791
|
+
},
|
|
2792
|
+
buildInvocation(context) {
|
|
2793
|
+
const { routine } = context;
|
|
2794
|
+
const args = [
|
|
2795
|
+
"-p",
|
|
2796
|
+
"--output-format",
|
|
2797
|
+
"stream-json",
|
|
2798
|
+
"--verbose",
|
|
2799
|
+
"--permission-mode",
|
|
2800
|
+
routine.permissionMode ?? DEFAULT_PERMISSION_MODE,
|
|
2801
|
+
"--permission-prompts",
|
|
2802
|
+
"none",
|
|
2803
|
+
"--model",
|
|
2804
|
+
routine.model ?? DEFAULT_MODEL,
|
|
2805
|
+
"--effort",
|
|
2806
|
+
routine.effort ?? DEFAULT_EFFORT,
|
|
2807
|
+
"--name",
|
|
2808
|
+
`routine/${routine.name}/${context.runId}`,
|
|
2809
|
+
"--append-system-prompt",
|
|
2810
|
+
getUnattendedNote(context)
|
|
2811
|
+
];
|
|
2812
|
+
if (routine.maxBudgetUsd !== null) {
|
|
2813
|
+
args.push("--max-budget-usd", String(routine.maxBudgetUsd));
|
|
2814
|
+
}
|
|
2815
|
+
return { command: config.claudeBin, args, env: withoutEnv(DROPPED_ENV), input: routine.prompt };
|
|
2816
|
+
},
|
|
2817
|
+
readEvent(event) {
|
|
2818
|
+
const parsed = claudeEventSchema.safeParse(event);
|
|
2819
|
+
if (!parsed.success) return {};
|
|
2820
|
+
return match5(parsed.data).with({ type: "system", subtype: "init" }, (init) => {
|
|
2821
|
+
const update = {};
|
|
2822
|
+
if (init.session_id !== void 0) update.sessionId = init.session_id;
|
|
2823
|
+
if (init.model !== void 0) update.model = init.model;
|
|
2824
|
+
return update;
|
|
2825
|
+
}).with({ type: "result" }, readResult).otherwise(() => ({}));
|
|
2826
|
+
},
|
|
2827
|
+
buildTranscript(events) {
|
|
2828
|
+
const claudeEvents = toClaudeEvents(events);
|
|
2829
|
+
const results = collectToolResults(claudeEvents);
|
|
2830
|
+
return claudeEvents.flatMap((event, index) => toItems(event, index, results));
|
|
2831
|
+
},
|
|
2832
|
+
getResumeCommand: (sessionId) => `claude --resume ${sessionId}`
|
|
2833
|
+
};
|
|
2834
|
+
|
|
2835
|
+
// src/domains/agent/codex.ts
|
|
2836
|
+
import { match as match6, P as P3 } from "ts-pattern";
|
|
2837
|
+
import { z as z13 } from "zod";
|
|
2838
|
+
var DEFAULT_SANDBOX = "workspace-write";
|
|
2839
|
+
var EFFORTS2 = ["minimal", "low", "medium", "high", "xhigh"];
|
|
2840
|
+
var SANDBOX_MODES = ["read-only", "workspace-write", "danger-full-access"];
|
|
2841
|
+
var DROPPED_ENV2 = ["OPENAI_API_KEY", "CODEX_API_KEY"];
|
|
2842
|
+
var codexErrorSchema = z13.object({ message: z13.string().optional() });
|
|
2843
|
+
var codexItemSchema = z13.object({
|
|
2844
|
+
id: z13.string().optional(),
|
|
2845
|
+
type: z13.string().optional(),
|
|
2846
|
+
text: z13.string().optional(),
|
|
2847
|
+
command: z13.string().optional(),
|
|
2848
|
+
aggregated_output: z13.string().optional(),
|
|
2849
|
+
exit_code: z13.number().nullable().optional(),
|
|
2850
|
+
status: z13.string().optional(),
|
|
2851
|
+
changes: z13.array(z13.object({ path: z13.string().optional(), kind: z13.string().optional() })).optional(),
|
|
2852
|
+
server: z13.string().optional(),
|
|
2853
|
+
tool: z13.string().optional(),
|
|
2854
|
+
arguments: z13.unknown().optional(),
|
|
2855
|
+
result: z13.unknown().optional(),
|
|
2856
|
+
error: codexErrorSchema.nullable().optional(),
|
|
2857
|
+
query: z13.string().optional(),
|
|
2858
|
+
items: z13.array(z13.object({ text: z13.string().optional(), completed: z13.boolean().optional() })).optional(),
|
|
2859
|
+
message: z13.string().optional()
|
|
2860
|
+
});
|
|
2861
|
+
var codexEventSchema = z13.object({
|
|
2862
|
+
type: z13.string().optional(),
|
|
2863
|
+
thread_id: sessionIdSchema.optional(),
|
|
2864
|
+
item: codexItemSchema.optional(),
|
|
2865
|
+
error: codexErrorSchema.optional(),
|
|
2866
|
+
message: z13.string().optional()
|
|
2867
|
+
});
|
|
2868
|
+
var mcpResultSchema = z13.object({ content: z13.array(z13.unknown()) });
|
|
2869
|
+
var textPartSchema2 = z13.object({ text: z13.string() });
|
|
2870
|
+
function toCodexEvents(events) {
|
|
2871
|
+
return events.flatMap((event) => {
|
|
2872
|
+
const parsed = codexEventSchema.safeParse(event);
|
|
2873
|
+
return parsed.success ? [parsed.data] : [];
|
|
2874
|
+
});
|
|
2875
|
+
}
|
|
2876
|
+
function stringifyMcpResult(result) {
|
|
2877
|
+
const parsed = mcpResultSchema.safeParse(result);
|
|
2878
|
+
if (!parsed.success) return JSON.stringify(result ?? null, null, 2);
|
|
2879
|
+
return parsed.data.content.map((part) => {
|
|
2880
|
+
const textPart = textPartSchema2.safeParse(part);
|
|
2881
|
+
return textPart.success ? textPart.data.text : JSON.stringify(part);
|
|
2882
|
+
}).join("\n");
|
|
2883
|
+
}
|
|
2884
|
+
function getCommandResult(item) {
|
|
2885
|
+
if (item.status === "in_progress") return null;
|
|
2886
|
+
const isError = item.status === "failed" || item.status === "declined" || item.exit_code !== void 0 && item.exit_code !== null && item.exit_code !== 0;
|
|
2887
|
+
return { content: item.aggregated_output ?? "", isError };
|
|
2888
|
+
}
|
|
2889
|
+
function getMcpResult(item) {
|
|
2890
|
+
if (item.status === "in_progress") return null;
|
|
2891
|
+
if (item.error?.message !== void 0) return { content: item.error.message, isError: true };
|
|
2892
|
+
return { content: stringifyMcpResult(item.result), isError: item.status === "failed" };
|
|
2893
|
+
}
|
|
2894
|
+
function getStatusResult(item) {
|
|
2895
|
+
return match6(item.status).with("in_progress", () => null).with("failed", () => ({ content: "failed", isError: true })).otherwise((status) => ({ content: status ?? "", isError: false }));
|
|
2896
|
+
}
|
|
2897
|
+
function toTool(key, name, input, preview, result) {
|
|
2898
|
+
return { kind: "tool", key, id: key, name, input, preview, result, isSubagent: false };
|
|
2899
|
+
}
|
|
2900
|
+
function toTodoMarkdown(entries) {
|
|
2901
|
+
return entries.map((entry) => `- [${entry.completed === true ? "x" : " "}] ${entry.text ?? ""}`).join("\n");
|
|
2902
|
+
}
|
|
2903
|
+
function toItem(item, index) {
|
|
2904
|
+
const key = `item-${item.id ?? index}`;
|
|
2905
|
+
return match6(item).with(
|
|
2906
|
+
{ type: "agent_message" },
|
|
2907
|
+
({ text: text2 }) => text2?.trim() ? { kind: "text", key, text: text2, isSubagent: false } : null
|
|
2908
|
+
).with(
|
|
2909
|
+
{ type: "command_execution" },
|
|
2910
|
+
(command) => toTool(
|
|
2911
|
+
key,
|
|
2912
|
+
"Shell",
|
|
2913
|
+
{ command: command.command },
|
|
2914
|
+
toPreview(command.command ?? ""),
|
|
2915
|
+
getCommandResult(command)
|
|
2916
|
+
)
|
|
2917
|
+
).with({ type: "file_change" }, (change) => {
|
|
2918
|
+
const changes = change.changes ?? [];
|
|
2919
|
+
const preview = changes.map((file) => `${file.kind ?? "update"} ${file.path ?? ""}`).join(", ");
|
|
2920
|
+
return toTool(key, "Edit", { changes }, toPreview(preview), getStatusResult(change));
|
|
2921
|
+
}).with(
|
|
2922
|
+
{ type: "mcp_tool_call" },
|
|
2923
|
+
(call) => toTool(
|
|
2924
|
+
key,
|
|
2925
|
+
`${call.server ?? "mcp"}.${call.tool ?? "tool"}`,
|
|
2926
|
+
call.arguments,
|
|
2927
|
+
toPreview(JSON.stringify(call.arguments ?? {})),
|
|
2928
|
+
getMcpResult(call)
|
|
2929
|
+
)
|
|
2930
|
+
).with(
|
|
2931
|
+
{ type: "web_search" },
|
|
2932
|
+
(search) => toTool(
|
|
2933
|
+
key,
|
|
2934
|
+
"WebSearch",
|
|
2935
|
+
{ query: search.query },
|
|
2936
|
+
toPreview(search.query ?? ""),
|
|
2937
|
+
getStatusResult(search)
|
|
2938
|
+
)
|
|
2939
|
+
).with({ type: "todo_list" }, ({ items }) => ({
|
|
2940
|
+
kind: "text",
|
|
2941
|
+
key,
|
|
2942
|
+
text: toTodoMarkdown(items ?? []),
|
|
2943
|
+
isSubagent: false
|
|
2944
|
+
})).with({ type: "error" }, ({ message }) => ({
|
|
2945
|
+
kind: "text",
|
|
2946
|
+
key,
|
|
2947
|
+
text: `**Error:** ${message ?? "unknown error"}`,
|
|
2948
|
+
isSubagent: false
|
|
2949
|
+
})).otherwise(() => null);
|
|
2950
|
+
}
|
|
2951
|
+
function toResult(index, numTurns, error) {
|
|
2952
|
+
return {
|
|
2953
|
+
kind: "result",
|
|
2954
|
+
key: `result-${index}`,
|
|
2955
|
+
text: error ?? "",
|
|
2956
|
+
isError: error !== null,
|
|
2957
|
+
costUsd: null,
|
|
2958
|
+
numTurns,
|
|
2959
|
+
durationMs: null
|
|
2960
|
+
};
|
|
2961
|
+
}
|
|
2962
|
+
var codexAgent = {
|
|
2963
|
+
name: "codex",
|
|
2964
|
+
output: "jsonl",
|
|
2965
|
+
binaryEnv: "CODEX_BIN",
|
|
2966
|
+
resolveSettings(raw) {
|
|
2967
|
+
rejectUnsupported(raw, ["command", "maxBudgetUsd"], "codex");
|
|
2968
|
+
return {
|
|
2969
|
+
...raw,
|
|
2970
|
+
effort: pickOne(raw.effort, EFFORTS2, "effort", "codex"),
|
|
2971
|
+
permissionMode: pickOne(raw.permissionMode, SANDBOX_MODES, "permissionMode", "codex") ?? DEFAULT_SANDBOX
|
|
2972
|
+
};
|
|
2973
|
+
},
|
|
2974
|
+
buildInvocation(context) {
|
|
2975
|
+
const { routine } = context;
|
|
2976
|
+
const args = [
|
|
2977
|
+
"exec",
|
|
2978
|
+
"--json",
|
|
2979
|
+
"--skip-git-repo-check",
|
|
2980
|
+
"--sandbox",
|
|
2981
|
+
routine.permissionMode ?? DEFAULT_SANDBOX
|
|
2982
|
+
];
|
|
2983
|
+
if (routine.model !== null) args.push("--model", routine.model);
|
|
2984
|
+
if (routine.effort !== null) {
|
|
2985
|
+
args.push("--config", `model_reasoning_effort="${routine.effort}"`);
|
|
2986
|
+
}
|
|
2987
|
+
args.push("-");
|
|
2988
|
+
return {
|
|
2989
|
+
command: config.codexBin,
|
|
2990
|
+
args,
|
|
2991
|
+
env: withoutEnv(DROPPED_ENV2),
|
|
2992
|
+
input: `${getUnattendedNote(context)}
|
|
2993
|
+
|
|
2994
|
+
${routine.prompt}`
|
|
2995
|
+
};
|
|
2996
|
+
},
|
|
2997
|
+
readEvent(event, record) {
|
|
2998
|
+
const parsed = codexEventSchema.safeParse(event);
|
|
2999
|
+
if (!parsed.success) return {};
|
|
3000
|
+
return match6(parsed.data).with({ type: "thread.started", thread_id: P3.string }, ({ thread_id }) => ({
|
|
3001
|
+
sessionId: thread_id
|
|
3002
|
+
})).with(
|
|
3003
|
+
{ type: "item.completed", item: { type: "agent_message", text: P3.string } },
|
|
3004
|
+
({ item }) => ({ resultText: item.text })
|
|
3005
|
+
).with({ type: "turn.completed" }, () => ({ numTurns: (record.numTurns ?? 0) + 1 })).with({ type: "turn.failed" }, ({ error }) => ({
|
|
3006
|
+
error: error?.message ?? "Codex reported a failed turn"
|
|
3007
|
+
})).otherwise(() => ({}));
|
|
3008
|
+
},
|
|
3009
|
+
buildTranscript(events) {
|
|
3010
|
+
const items = [];
|
|
3011
|
+
const positions = /* @__PURE__ */ new Map();
|
|
3012
|
+
let turns = 0;
|
|
3013
|
+
const upsert = (item) => {
|
|
3014
|
+
if (item === null) return;
|
|
3015
|
+
const position = positions.get(item.key);
|
|
3016
|
+
if (position === void 0) {
|
|
3017
|
+
positions.set(item.key, items.length);
|
|
3018
|
+
items.push(item);
|
|
3019
|
+
} else {
|
|
3020
|
+
items[position] = item;
|
|
3021
|
+
}
|
|
3022
|
+
};
|
|
3023
|
+
toCodexEvents(events).forEach((event, index) => {
|
|
3024
|
+
if (event.type === "turn.completed") turns += 1;
|
|
3025
|
+
upsert(
|
|
3026
|
+
match6(event).with({ type: "thread.started" }, () => ({
|
|
3027
|
+
kind: "init",
|
|
3028
|
+
key: `init-${index}`,
|
|
3029
|
+
model: null,
|
|
3030
|
+
cwd: null,
|
|
3031
|
+
toolCount: null,
|
|
3032
|
+
permissionMode: null
|
|
3033
|
+
})).with(
|
|
3034
|
+
{ type: P3.union("item.started", "item.updated", "item.completed") },
|
|
3035
|
+
({ item }) => item === void 0 ? null : toItem(item, index)
|
|
3036
|
+
).with({ type: "turn.completed" }, () => toResult(index, turns, null)).with(
|
|
3037
|
+
{ type: "turn.failed" },
|
|
3038
|
+
({ error }) => toResult(index, turns, error?.message ?? "turn failed")
|
|
3039
|
+
).with({ type: "error" }, ({ message }) => ({
|
|
3040
|
+
kind: "text",
|
|
3041
|
+
key: `error-${index}`,
|
|
3042
|
+
text: `**Error:** ${message ?? "unknown error"}`,
|
|
3043
|
+
isSubagent: false
|
|
3044
|
+
})).otherwise(() => null)
|
|
3045
|
+
);
|
|
3046
|
+
});
|
|
3047
|
+
return items;
|
|
3048
|
+
},
|
|
3049
|
+
getResumeCommand: (sessionId) => `codex resume ${sessionId}`
|
|
3050
|
+
};
|
|
3051
|
+
|
|
3052
|
+
// src/domains/agent/schemas.ts
|
|
3053
|
+
import { z as z14 } from "zod";
|
|
3054
|
+
var outputEventSchema = z14.object({ type: z14.literal("output"), text: z14.string() });
|
|
3055
|
+
|
|
3056
|
+
// src/domains/agent/command.ts
|
|
3057
|
+
var MAX_RESULT_CHARS = 2e4;
|
|
3058
|
+
var commandAgent = {
|
|
3059
|
+
name: "command",
|
|
3060
|
+
output: "text",
|
|
3061
|
+
binaryEnv: null,
|
|
3062
|
+
resolveSettings(raw) {
|
|
3063
|
+
rejectUnsupported(raw, ["model", "effort", "permissionMode", "maxBudgetUsd"], "command");
|
|
3064
|
+
if (raw.command === null) throw new Error("agent command needs a command");
|
|
3065
|
+
return raw;
|
|
3066
|
+
},
|
|
3067
|
+
buildInvocation({ routine, runId, trigger }) {
|
|
3068
|
+
return {
|
|
3069
|
+
command: "/bin/sh",
|
|
3070
|
+
args: ["-c", routine.command ?? ""],
|
|
3071
|
+
env: {
|
|
3072
|
+
...process.env,
|
|
3073
|
+
KOMBINAT_ROUTINE: routine.name,
|
|
3074
|
+
KOMBINAT_RUN_ID: runId,
|
|
3075
|
+
KOMBINAT_TRIGGER: trigger
|
|
3076
|
+
},
|
|
3077
|
+
input: `${routine.prompt}
|
|
3078
|
+
`
|
|
3079
|
+
};
|
|
3080
|
+
},
|
|
3081
|
+
readEvent(event, record) {
|
|
3082
|
+
const output = outputEventSchema.safeParse(event);
|
|
3083
|
+
if (!output.success) return {};
|
|
3084
|
+
const { text: text2 } = output.data;
|
|
3085
|
+
const resultText = record.resultText === null ? text2 : `${record.resultText}
|
|
3086
|
+
${text2}`;
|
|
3087
|
+
return { resultText: resultText.slice(-MAX_RESULT_CHARS) };
|
|
3088
|
+
},
|
|
3089
|
+
buildTranscript(events) {
|
|
3090
|
+
const text2 = events.flatMap((event) => {
|
|
3091
|
+
const output = outputEventSchema.safeParse(event);
|
|
3092
|
+
return output.success ? [output.data.text] : [];
|
|
3093
|
+
}).join("\n");
|
|
3094
|
+
return text2.trim() ? [{ kind: "text", key: "output", text: text2, isSubagent: false }] : [];
|
|
3095
|
+
},
|
|
3096
|
+
getResumeCommand: () => null
|
|
3097
|
+
};
|
|
3098
|
+
|
|
3099
|
+
// src/domains/agent/registry.ts
|
|
3100
|
+
function getAgent(name) {
|
|
3101
|
+
return match7(name).with("claude", () => claudeAgent).with("codex", () => codexAgent).with("command", () => commandAgent).exhaustive();
|
|
3102
|
+
}
|
|
3103
|
+
function parseAgentName(value) {
|
|
3104
|
+
const parsed = agentNameSchema.safeParse(value);
|
|
3105
|
+
if (!parsed.success) {
|
|
3106
|
+
throw new Error(`agent must be one of ${agentNameSchema.options.join(", ")}`);
|
|
3107
|
+
}
|
|
3108
|
+
return parsed.data;
|
|
3109
|
+
}
|
|
3110
|
+
|
|
3111
|
+
// src/domains/routine/utils.ts
|
|
3112
|
+
var DEFAULT_TIMEOUT_MINUTES = 55;
|
|
3113
|
+
function parseScalar(raw) {
|
|
3114
|
+
const value = raw.trim();
|
|
3115
|
+
if (/^".*"$/.test(value) || /^'.*'$/.test(value)) return value.slice(1, -1);
|
|
3116
|
+
if (value === "true") return true;
|
|
3117
|
+
if (value === "false") return false;
|
|
3118
|
+
if (value === "null" || value === "~") return "";
|
|
3119
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) return Number(value);
|
|
3120
|
+
return value;
|
|
3121
|
+
}
|
|
3122
|
+
function parseFrontmatter(source) {
|
|
3123
|
+
const found = /^---\r?\n(?<head>[\s\S]*?)\r?\n---\r?\n?(?<body>[\s\S]*)$/.exec(source);
|
|
3124
|
+
if (!found?.groups) throw new Error("Routine file must start with a YAML frontmatter block");
|
|
3125
|
+
const data = {};
|
|
3126
|
+
for (const line of (found.groups["head"] ?? "").split(/\r?\n/)) {
|
|
3127
|
+
if (!line.trim() || line.trim().startsWith("#")) continue;
|
|
3128
|
+
const separator = line.indexOf(":");
|
|
3129
|
+
if (separator === -1) throw new Error(`Invalid frontmatter line: "${line}"`);
|
|
3130
|
+
data[line.slice(0, separator).trim()] = parseScalar(line.slice(separator + 1));
|
|
3131
|
+
}
|
|
3132
|
+
return { data, body: (found.groups["body"] ?? "").trim() };
|
|
3133
|
+
}
|
|
3134
|
+
function readString(data, key) {
|
|
3135
|
+
const value = data[key];
|
|
3136
|
+
return value === void 0 || value === "" ? null : String(value);
|
|
3137
|
+
}
|
|
3138
|
+
function readNumber(data, key) {
|
|
3139
|
+
const value = readString(data, key);
|
|
3140
|
+
if (value === null) return null;
|
|
3141
|
+
const number = Number(value);
|
|
3142
|
+
if (Number.isNaN(number)) throw new Error(`${key} must be a number`);
|
|
3143
|
+
return number;
|
|
3144
|
+
}
|
|
3145
|
+
function readBoolean(data, key) {
|
|
3146
|
+
const value = data[key];
|
|
3147
|
+
if (value === void 0 || value === "") return null;
|
|
3148
|
+
if (typeof value !== "boolean") throw new Error(`${key} must be true or false`);
|
|
3149
|
+
return value;
|
|
3150
|
+
}
|
|
3151
|
+
function readSchedule(data) {
|
|
3152
|
+
const schedule = readString(data, "schedule");
|
|
3153
|
+
return schedule === "manual" ? null : schedule;
|
|
3154
|
+
}
|
|
3155
|
+
function withFile(file, read) {
|
|
3156
|
+
try {
|
|
3157
|
+
return read();
|
|
3158
|
+
} catch (error) {
|
|
3159
|
+
throw new Error(`${file}: ${getErrorMessage(error)}`, { cause: error });
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
function readAgentSettings(data, agent) {
|
|
3163
|
+
return getAgent(agent).resolveSettings({
|
|
3164
|
+
model: readString(data, "model"),
|
|
3165
|
+
effort: readString(data, "effort"),
|
|
3166
|
+
permissionMode: readString(data, "permissionMode"),
|
|
3167
|
+
command: readString(data, "command"),
|
|
3168
|
+
maxBudgetUsd: readNumber(data, "maxBudgetUsd")
|
|
3169
|
+
});
|
|
3170
|
+
}
|
|
3171
|
+
function buildRoutine(file, source) {
|
|
3172
|
+
const { data, body } = parseFrontmatter(source);
|
|
3173
|
+
const fileName = path2.basename(file, ".md");
|
|
3174
|
+
const name = readString(data, "name") ?? fileName;
|
|
3175
|
+
if (name !== fileName) {
|
|
3176
|
+
throw new Error(`${file}: frontmatter name "${name}" must match the file name "${fileName}"`);
|
|
3177
|
+
}
|
|
3178
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {
|
|
3179
|
+
throw new Error(`${file}: name must be lowercase kebab-case`);
|
|
3180
|
+
}
|
|
3181
|
+
const schedule = readSchedule(data);
|
|
3182
|
+
if (schedule !== null) parseCron(schedule);
|
|
3183
|
+
const cwd = readString(data, "cwd");
|
|
3184
|
+
if (cwd === null) throw new Error(`${file}: cwd is required`);
|
|
3185
|
+
if (!body) throw new Error(`${file}: prompt body is empty`);
|
|
3186
|
+
const agent = withFile(file, () => parseAgentName(readString(data, "agent") ?? "claude"));
|
|
3187
|
+
const webhook = withFile(file, () => readBoolean(data, "webhook")) ?? false;
|
|
3188
|
+
const webhookGate = readString(data, "webhookGate");
|
|
3189
|
+
if (webhookGate !== null && !webhook) throw new Error(`${file}: webhookGate needs webhook: true`);
|
|
3190
|
+
return {
|
|
3191
|
+
name: routineNameSchema.parse(name),
|
|
3192
|
+
description: readString(data, "description") ?? "",
|
|
3193
|
+
schedule,
|
|
3194
|
+
cwd: cwd.replace(/^~(?=\/|$)/, os2.homedir()),
|
|
3195
|
+
agent,
|
|
3196
|
+
...withFile(file, () => readAgentSettings(data, agent)),
|
|
3197
|
+
enabled: data["enabled"] === void 0 ? true : Boolean(data["enabled"]),
|
|
3198
|
+
webhook,
|
|
3199
|
+
webhookGate,
|
|
3200
|
+
timeoutMinutes: withFile(file, () => readNumber(data, "timeoutMinutes")) ?? DEFAULT_TIMEOUT_MINUTES,
|
|
3201
|
+
before: readString(data, "before"),
|
|
3202
|
+
prompt: body,
|
|
3203
|
+
file
|
|
3204
|
+
};
|
|
3205
|
+
}
|
|
3206
|
+
function describeSchedule(routine) {
|
|
3207
|
+
return routine.schedule === null ? "Manual" : describeCron(routine.schedule);
|
|
3208
|
+
}
|
|
3209
|
+
function getNextRun(routine, now = /* @__PURE__ */ new Date()) {
|
|
3210
|
+
if (!routine.schedule || !routine.enabled) return null;
|
|
3211
|
+
return nextCronRun(routine.schedule, now)?.toISOString() ?? null;
|
|
3212
|
+
}
|
|
3213
|
+
|
|
3214
|
+
// src/domains/routine/storage.ts
|
|
3215
|
+
function loadRoutines(dir = config.routinesDir) {
|
|
3216
|
+
if (!fs3.existsSync(dir)) return [];
|
|
3217
|
+
return fs3.readdirSync(dir).filter((entry) => entry.endsWith(".md")).sort().map((entry) => {
|
|
3218
|
+
const file = path3.join(dir, entry);
|
|
3219
|
+
return buildRoutine(file, fs3.readFileSync(file, "utf8"));
|
|
3220
|
+
});
|
|
3221
|
+
}
|
|
3222
|
+
function getRoutine2(name, dir = config.routinesDir) {
|
|
3223
|
+
const routine = loadRoutines(dir).find((candidate) => candidate.name === name);
|
|
3224
|
+
if (!routine) throw new Error(`Unknown routine "${name}" (looked in ${dir})`);
|
|
3225
|
+
return routine;
|
|
3226
|
+
}
|
|
3227
|
+
|
|
3228
|
+
// src/domains/run/runner.ts
|
|
3229
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
3230
|
+
import fs6 from "node:fs";
|
|
3231
|
+
import path7 from "node:path";
|
|
3232
|
+
import readline from "node:readline";
|
|
3233
|
+
import { isMatching as isMatching4, match as match8 } from "ts-pattern";
|
|
3234
|
+
|
|
3235
|
+
// src/domains/run/hook-env.ts
|
|
3236
|
+
import path4 from "node:path";
|
|
3237
|
+
function withHookEnv(env2) {
|
|
3238
|
+
return {
|
|
3239
|
+
...env2,
|
|
3240
|
+
KOMBINAT_REPO: config.projectRoot,
|
|
3241
|
+
PATH: `${path4.join(config.projectRoot, "scripts")}:${env2["PATH"] ?? ""}`
|
|
3242
|
+
};
|
|
3243
|
+
}
|
|
3244
|
+
|
|
3245
|
+
// src/domains/run/payload.ts
|
|
3246
|
+
import fs5 from "node:fs";
|
|
3247
|
+
import path6 from "node:path";
|
|
3248
|
+
|
|
3249
|
+
// src/domains/run/storage.ts
|
|
3250
|
+
import fs4 from "node:fs";
|
|
3251
|
+
import path5 from "node:path";
|
|
3252
|
+
import { isMatching as isMatching3 } from "ts-pattern";
|
|
3253
|
+
function getRunsDir(routine) {
|
|
3254
|
+
return path5.join(config.stateDir, "runs", routine);
|
|
3255
|
+
}
|
|
3256
|
+
function ensureStateDirs() {
|
|
3257
|
+
fs4.mkdirSync(path5.join(config.stateDir, "runs"), { recursive: true });
|
|
3258
|
+
}
|
|
3259
|
+
function writeRunRecord(record) {
|
|
3260
|
+
const dir = getRunsDir(record.routine);
|
|
3261
|
+
fs4.mkdirSync(dir, { recursive: true });
|
|
3262
|
+
writeJsonFile(path5.join(dir, `${record.id}.json`), record);
|
|
3263
|
+
}
|
|
3264
|
+
function readRunRecord(routine, id) {
|
|
3265
|
+
return readJsonFile(path5.join(getRunsDir(routine), `${id}.json`), runRecordSchema);
|
|
3266
|
+
}
|
|
3267
|
+
function checkIsProcessAlive(pid) {
|
|
3268
|
+
if (!pid) return false;
|
|
3269
|
+
try {
|
|
3270
|
+
process.kill(pid, 0);
|
|
3271
|
+
return true;
|
|
3272
|
+
} catch {
|
|
3273
|
+
return false;
|
|
3274
|
+
}
|
|
3275
|
+
}
|
|
3276
|
+
function reconcileRecord(record) {
|
|
3277
|
+
if (!isMatching3({ status: "running" }, record) || checkIsProcessAlive(record.pid)) return record;
|
|
3278
|
+
const reconciled = {
|
|
3279
|
+
...record,
|
|
3280
|
+
status: "aborted",
|
|
3281
|
+
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3282
|
+
error: "Runner process disappeared"
|
|
3283
|
+
};
|
|
3284
|
+
writeRunRecord(reconciled);
|
|
3285
|
+
return reconciled;
|
|
3286
|
+
}
|
|
3287
|
+
function readRuns(routine) {
|
|
3288
|
+
const dir = getRunsDir(routine);
|
|
3289
|
+
if (!fs4.existsSync(dir)) return [];
|
|
3290
|
+
return fs4.readdirSync(dir).filter((entry) => entry.endsWith(".json")).flatMap((entry) => {
|
|
3291
|
+
const record = readJsonFile(path5.join(dir, entry), runRecordSchema);
|
|
3292
|
+
return record === null ? [] : [reconcileRecord(record)];
|
|
3293
|
+
});
|
|
3294
|
+
}
|
|
3295
|
+
function listRuns(routine) {
|
|
3296
|
+
return readRuns(routine).sort(compareRunsByNewest);
|
|
3297
|
+
}
|
|
3298
|
+
function listAllRuns() {
|
|
3299
|
+
const root = path5.join(config.stateDir, "runs");
|
|
3300
|
+
if (!fs4.existsSync(root)) return [];
|
|
3301
|
+
return fs4.readdirSync(root).flatMap((routine) => readRuns(routineNameSchema.parse(routine))).sort(compareRunsByNewest);
|
|
3302
|
+
}
|
|
3303
|
+
function getRunningRuns() {
|
|
3304
|
+
return listAllRuns().filter(isMatching3({ status: "running" }));
|
|
3305
|
+
}
|
|
3306
|
+
|
|
3307
|
+
// src/domains/run/payload.ts
|
|
3308
|
+
function getPayloadFile(routine, runId) {
|
|
3309
|
+
return path6.join(getRunsDir(routine), `${runId}.payload`);
|
|
3310
|
+
}
|
|
3311
|
+
function writePayload(routine, runId, payload) {
|
|
3312
|
+
fs5.mkdirSync(getRunsDir(routine), { recursive: true });
|
|
3313
|
+
fs5.writeFileSync(getPayloadFile(routine, runId), payload);
|
|
3314
|
+
}
|
|
3315
|
+
function takePayload(routine, runId) {
|
|
3316
|
+
const file = getPayloadFile(routine, runId);
|
|
3317
|
+
if (!fs5.existsSync(file)) return null;
|
|
3318
|
+
const payload = fs5.readFileSync(file, "utf8");
|
|
3319
|
+
fs5.rmSync(file);
|
|
3320
|
+
return payload;
|
|
3321
|
+
}
|
|
3322
|
+
function appendPayload(prompt, payload) {
|
|
3323
|
+
const longestRun = (payload.match(/`+/g) ?? []).reduce(
|
|
3324
|
+
(max, run) => Math.max(max, run.length),
|
|
3325
|
+
0
|
|
3326
|
+
);
|
|
3327
|
+
const fence = "`".repeat(Math.max(3, longestRun + 1));
|
|
3328
|
+
const body = payload.endsWith("\n") ? payload : `${payload}
|
|
3329
|
+
`;
|
|
3330
|
+
return `${prompt}
|
|
3331
|
+
|
|
3332
|
+
This run was started by a webhook. Its request body:
|
|
3333
|
+
|
|
3334
|
+
${fence}
|
|
3335
|
+
${body}${fence}
|
|
3336
|
+
`;
|
|
3337
|
+
}
|
|
3338
|
+
|
|
3339
|
+
// src/domains/run/runner.ts
|
|
3340
|
+
var BEFORE_HOOK_TIMEOUT_MS = 3 * 6e4;
|
|
3341
|
+
var PENDING_START_MS = BEFORE_HOOK_TIMEOUT_MS + 6e4;
|
|
3342
|
+
var KILL_GRACE_MS = 6e4;
|
|
3343
|
+
var STDERR_CHUNKS = 200;
|
|
3344
|
+
function checkIsBinaryFound(command) {
|
|
3345
|
+
if (command.includes("/")) return fs6.existsSync(command);
|
|
3346
|
+
return (process.env["PATH"] ?? "").split(":").some((dir) => dir !== "" && fs6.existsSync(path7.join(dir, command)));
|
|
3347
|
+
}
|
|
3348
|
+
function finishRecord(record, patch) {
|
|
3349
|
+
const finished = { ...record, ...patch, endedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
3350
|
+
writeRunRecord(finished);
|
|
3351
|
+
return finished;
|
|
3352
|
+
}
|
|
3353
|
+
function runBeforeHook({ command, cwd, env: env2, logFile }) {
|
|
3354
|
+
const result = spawnSync("/bin/sh", ["-c", command], {
|
|
3355
|
+
cwd,
|
|
3356
|
+
env: withHookEnv(env2),
|
|
3357
|
+
timeout: BEFORE_HOOK_TIMEOUT_MS,
|
|
3358
|
+
encoding: "utf8"
|
|
3359
|
+
});
|
|
3360
|
+
const output = `${result.stdout}${result.stderr}`.trim();
|
|
3361
|
+
const event = { type: "before_hook", command, exitCode: result.status, output };
|
|
3362
|
+
fs6.appendFileSync(logFile, `${JSON.stringify(event)}
|
|
3363
|
+
`);
|
|
3364
|
+
if (result.error) return `before hook failed to start: ${result.error.message}`;
|
|
3365
|
+
if (result.status !== 0) {
|
|
3366
|
+
return `before hook exited with ${result.status}: ${output.slice(-1500)}`;
|
|
3367
|
+
}
|
|
3368
|
+
return null;
|
|
3369
|
+
}
|
|
3370
|
+
function killAfter(child, minutes) {
|
|
3371
|
+
let fired = false;
|
|
3372
|
+
const timer = setTimeout(() => {
|
|
3373
|
+
fired = true;
|
|
3374
|
+
child.kill("SIGINT");
|
|
3375
|
+
setTimeout(() => child.kill("SIGTERM"), KILL_GRACE_MS).unref();
|
|
3376
|
+
}, minutes * 6e4);
|
|
3377
|
+
return { clear: () => clearTimeout(timer), checkHasFired: () => fired };
|
|
3378
|
+
}
|
|
3379
|
+
function toEvent(agent, line) {
|
|
3380
|
+
return match8(agent.output).with("jsonl", () => parseJson(line)).with("text", () => ({ type: "output", text: line })).exhaustive();
|
|
3381
|
+
}
|
|
3382
|
+
function toLogLine(agent, line, event) {
|
|
3383
|
+
return match8(agent.output).with("jsonl", () => line).with("text", () => JSON.stringify(event)).exhaustive();
|
|
3384
|
+
}
|
|
3385
|
+
async function runRoutine(routine, options) {
|
|
3386
|
+
const agent = getAgent(routine.agent);
|
|
3387
|
+
const id = options.runId ?? createRunId();
|
|
3388
|
+
const runsDir = getRunsDir(routine.name);
|
|
3389
|
+
const logFile = path7.join(runsDir, `${id}.jsonl`);
|
|
3390
|
+
fs6.mkdirSync(runsDir, { recursive: true });
|
|
3391
|
+
const record = {
|
|
3392
|
+
id,
|
|
3393
|
+
routine: routine.name,
|
|
3394
|
+
agent: routine.agent,
|
|
3395
|
+
trigger: options.trigger,
|
|
3396
|
+
scheduledFor: options.scheduledFor ?? null,
|
|
3397
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3398
|
+
endedAt: null,
|
|
3399
|
+
status: "running",
|
|
3400
|
+
pid: null,
|
|
3401
|
+
exitCode: null,
|
|
3402
|
+
sessionId: null,
|
|
3403
|
+
resumeCommand: null,
|
|
3404
|
+
model: routine.model,
|
|
3405
|
+
costUsd: null,
|
|
3406
|
+
numTurns: null,
|
|
3407
|
+
durationMs: null,
|
|
3408
|
+
resultText: null,
|
|
3409
|
+
error: null,
|
|
3410
|
+
logFile
|
|
3411
|
+
};
|
|
3412
|
+
const payload = takePayload(routine.name, id);
|
|
3413
|
+
const task = payload === null ? routine : { ...routine, prompt: appendPayload(routine.prompt, payload) };
|
|
3414
|
+
const invocation = agent.buildInvocation({ routine: task, runId: id, trigger: options.trigger });
|
|
3415
|
+
if (!fs6.existsSync(routine.cwd)) {
|
|
3416
|
+
return finishRecord(record, { status: "failed", error: `cwd does not exist: ${routine.cwd}` });
|
|
3417
|
+
}
|
|
3418
|
+
if (!checkIsBinaryFound(invocation.command)) {
|
|
3419
|
+
const hint = agent.binaryEnv === null ? "" : ` (set ${agent.binaryEnv})`;
|
|
3420
|
+
return finishRecord(record, {
|
|
3421
|
+
status: "failed",
|
|
3422
|
+
error: `${agent.name} binary not found at ${invocation.command}${hint}`
|
|
3423
|
+
});
|
|
3424
|
+
}
|
|
3425
|
+
if (routine.before !== null) {
|
|
3426
|
+
const beforeError = runBeforeHook({
|
|
3427
|
+
command: routine.before,
|
|
3428
|
+
cwd: routine.cwd,
|
|
3429
|
+
env: invocation.env,
|
|
3430
|
+
logFile
|
|
3431
|
+
});
|
|
3432
|
+
if (beforeError !== null) return finishRecord(record, { status: "failed", error: beforeError });
|
|
3433
|
+
}
|
|
3434
|
+
const child = spawn(invocation.command, invocation.args, {
|
|
3435
|
+
cwd: routine.cwd,
|
|
3436
|
+
env: invocation.env,
|
|
3437
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
3438
|
+
});
|
|
3439
|
+
record.pid = child.pid ?? null;
|
|
3440
|
+
writeRunRecord(record);
|
|
3441
|
+
const log2 = fs6.createWriteStream(logFile, { flags: "a" });
|
|
3442
|
+
const stderrChunks = [];
|
|
3443
|
+
child.stderr.on("data", (chunk) => {
|
|
3444
|
+
stderrChunks.push(String(chunk));
|
|
3445
|
+
if (stderrChunks.length > STDERR_CHUNKS) stderrChunks.shift();
|
|
3446
|
+
});
|
|
3447
|
+
readline.createInterface({ input: child.stdout }).on("line", (line) => {
|
|
3448
|
+
const event = toEvent(agent, line);
|
|
3449
|
+
log2.write(`${toLogLine(agent, line, event)}
|
|
3450
|
+
`);
|
|
3451
|
+
if (event === void 0) return;
|
|
3452
|
+
const update = agent.readEvent(event, record);
|
|
3453
|
+
Object.assign(record, update);
|
|
3454
|
+
if (update.sessionId !== void 0 && update.sessionId !== null) {
|
|
3455
|
+
record.resumeCommand = agent.getResumeCommand(update.sessionId);
|
|
3456
|
+
writeRunRecord(record);
|
|
3457
|
+
}
|
|
3458
|
+
});
|
|
3459
|
+
const killTimer = killAfter(child, routine.timeoutMinutes);
|
|
3460
|
+
child.stdin.on("error", () => void 0);
|
|
3461
|
+
child.stdin.end(invocation.input);
|
|
3462
|
+
const exitCode = await new Promise((resolve) => {
|
|
3463
|
+
child.on("close", (code) => resolve(code));
|
|
3464
|
+
child.on("error", (error) => {
|
|
3465
|
+
record.error = error.message;
|
|
3466
|
+
resolve(-1);
|
|
3467
|
+
});
|
|
3468
|
+
});
|
|
3469
|
+
killTimer.clear();
|
|
3470
|
+
log2.end();
|
|
3471
|
+
if (killTimer.checkHasFired()) {
|
|
3472
|
+
return finishRecord(record, {
|
|
3473
|
+
status: "timed_out",
|
|
3474
|
+
exitCode,
|
|
3475
|
+
error: `Killed after ${routine.timeoutMinutes} minutes`
|
|
3476
|
+
});
|
|
3477
|
+
}
|
|
3478
|
+
if (exitCode !== 0) {
|
|
3479
|
+
const stderr = stderrChunks.join("").trim().slice(-2e3);
|
|
3480
|
+
return finishRecord(record, {
|
|
3481
|
+
status: "failed",
|
|
3482
|
+
exitCode,
|
|
3483
|
+
error: record.error ?? (stderr || `exit code ${exitCode}`)
|
|
3484
|
+
});
|
|
3485
|
+
}
|
|
3486
|
+
return finishRecord(record, { status: record.error === null ? "succeeded" : "failed", exitCode });
|
|
3487
|
+
}
|
|
3488
|
+
var pendingStarts = /* @__PURE__ */ new Map();
|
|
3489
|
+
function checkIsStarting(routineName, now = Date.now()) {
|
|
3490
|
+
const pending = pendingStarts.get(routineName);
|
|
3491
|
+
if (pending === void 0) return false;
|
|
3492
|
+
const isWaiting = now - pending.startedAt < PENDING_START_MS && readRunRecord(routineName, pending.runId) === null;
|
|
3493
|
+
if (!isWaiting) pendingStarts.delete(routineName);
|
|
3494
|
+
return isWaiting;
|
|
3495
|
+
}
|
|
3496
|
+
function checkIsRunning(routineName) {
|
|
3497
|
+
return checkIsStarting(routineName) || listRuns(routineName).some(isMatching4({ status: "running" }));
|
|
3498
|
+
}
|
|
3499
|
+
function startDetachedRun(routineName, options) {
|
|
3500
|
+
const runId = options.runId ?? createRunId();
|
|
3501
|
+
const args = getCliArgs("run", routineName, "--trigger", options.trigger, "--run-id", runId);
|
|
3502
|
+
if (options.scheduledFor) args.push("--scheduled-for", options.scheduledFor);
|
|
3503
|
+
pendingStarts.set(routineName, { runId, startedAt: Date.now() });
|
|
3504
|
+
spawn(process.execPath, args, {
|
|
3505
|
+
cwd: config.projectRoot,
|
|
3506
|
+
env: process.env,
|
|
3507
|
+
detached: true,
|
|
3508
|
+
stdio: "ignore"
|
|
3509
|
+
}).unref();
|
|
3510
|
+
}
|
|
3511
|
+
|
|
3512
|
+
// src/domains/scheduler/storage.ts
|
|
3513
|
+
import path8 from "node:path";
|
|
3514
|
+
var schedulerFile = () => path8.join(config.stateDir, "scheduler.json");
|
|
3515
|
+
function readSchedulerState() {
|
|
3516
|
+
return readJsonFile(schedulerFile(), schedulerStateSchema);
|
|
3517
|
+
}
|
|
3518
|
+
function writeSchedulerState(state) {
|
|
3519
|
+
ensureStateDirs();
|
|
3520
|
+
writeJsonFile(schedulerFile(), state);
|
|
3521
|
+
}
|
|
3522
|
+
function getSkips(routine) {
|
|
3523
|
+
return readSchedulerState()?.routines[routine]?.skips ?? [];
|
|
3524
|
+
}
|
|
3525
|
+
|
|
3526
|
+
// src/domains/webhook/queue.ts
|
|
3527
|
+
import fs7 from "node:fs";
|
|
3528
|
+
import path9 from "node:path";
|
|
3529
|
+
var WEBHOOK_QUEUE_LIMIT = 100;
|
|
3530
|
+
var PREVIEW_CHARS = 2e3;
|
|
3531
|
+
var lastQueuedAt = 0;
|
|
3532
|
+
function getQueueDir(routine) {
|
|
3533
|
+
return path9.join(config.stateDir, "queue", routine);
|
|
3534
|
+
}
|
|
3535
|
+
function listQueueFiles(routine) {
|
|
3536
|
+
const dir = getQueueDir(routine);
|
|
3537
|
+
if (!fs7.existsSync(dir)) return [];
|
|
3538
|
+
return fs7.readdirSync(dir).filter((entry) => entry.endsWith(".payload")).sort();
|
|
3539
|
+
}
|
|
3540
|
+
function countQueuedWebhooks(routine) {
|
|
3541
|
+
return listQueueFiles(routine).length;
|
|
3542
|
+
}
|
|
3543
|
+
function enqueueWebhook(routine, runId, payload) {
|
|
3544
|
+
if (countQueuedWebhooks(routine) >= WEBHOOK_QUEUE_LIMIT) return false;
|
|
3545
|
+
const dir = getQueueDir(routine);
|
|
3546
|
+
fs7.mkdirSync(dir, { recursive: true });
|
|
3547
|
+
lastQueuedAt = Math.max(Date.now(), lastQueuedAt + 1);
|
|
3548
|
+
const queuedAt = String(lastQueuedAt).padStart(15, "0");
|
|
3549
|
+
fs7.writeFileSync(path9.join(dir, `${queuedAt}-${runId}.payload`), payload);
|
|
3550
|
+
return true;
|
|
3551
|
+
}
|
|
3552
|
+
function getRunId(entry) {
|
|
3553
|
+
return runIdSchema.parse(entry.slice(entry.indexOf("-") + 1, -".payload".length));
|
|
3554
|
+
}
|
|
3555
|
+
function takeQueuedWebhook(routine) {
|
|
3556
|
+
const [oldest] = listQueueFiles(routine);
|
|
3557
|
+
if (oldest === void 0) return null;
|
|
3558
|
+
const file = path9.join(getQueueDir(routine), oldest);
|
|
3559
|
+
const payload = fs7.readFileSync(file, "utf8");
|
|
3560
|
+
fs7.rmSync(file);
|
|
3561
|
+
return { runId: getRunId(oldest), payload };
|
|
3562
|
+
}
|
|
3563
|
+
function listQueuedWebhooks(routine) {
|
|
3564
|
+
return listQueueFiles(routine).map((entry) => {
|
|
3565
|
+
const file = path9.join(getQueueDir(routine), entry);
|
|
3566
|
+
return {
|
|
3567
|
+
runId: getRunId(entry),
|
|
3568
|
+
queuedAt: new Date(Number(entry.slice(0, entry.indexOf("-")))).toISOString(),
|
|
3569
|
+
bytes: fs7.statSync(file).size,
|
|
3570
|
+
preview: fs7.readFileSync(file, "utf8").slice(0, PREVIEW_CHARS)
|
|
3571
|
+
};
|
|
3572
|
+
});
|
|
3573
|
+
}
|
|
3574
|
+
function listQueuedRoutines() {
|
|
3575
|
+
const root = path9.join(config.stateDir, "queue");
|
|
3576
|
+
if (!fs7.existsSync(root)) return [];
|
|
3577
|
+
return fs7.readdirSync(root).map((entry) => routineNameSchema.parse(entry)).filter((routine) => countQueuedWebhooks(routine) > 0);
|
|
3578
|
+
}
|
|
3579
|
+
|
|
3580
|
+
// src/domains/scheduler/tick.ts
|
|
3581
|
+
function loadState(now) {
|
|
3582
|
+
return readSchedulerState() ?? {
|
|
3583
|
+
startedAt: now.toISOString(),
|
|
3584
|
+
lastTickAt: now.toISOString(),
|
|
3585
|
+
routines: {}
|
|
3586
|
+
};
|
|
3587
|
+
}
|
|
3588
|
+
function recordSkip(state, routine, scheduledFor, reason, now) {
|
|
3589
|
+
const entry = state.routines[routine.name] ?? { lastScheduledFor: null, skips: [] };
|
|
3590
|
+
entry.skips = [
|
|
3591
|
+
...entry.skips.slice(-49),
|
|
3592
|
+
{ at: now.toISOString(), scheduledFor: scheduledFor.toISOString(), reason }
|
|
3593
|
+
];
|
|
3594
|
+
entry.lastScheduledFor = scheduledFor.toISOString();
|
|
3595
|
+
state.routines[routine.name] = entry;
|
|
3596
|
+
}
|
|
3597
|
+
function markScheduled(state, routine, scheduledFor) {
|
|
3598
|
+
const entry = state.routines[routine.name] ?? { lastScheduledFor: null, skips: [] };
|
|
3599
|
+
entry.lastScheduledFor = scheduledFor.toISOString();
|
|
3600
|
+
state.routines[routine.name] = entry;
|
|
3601
|
+
}
|
|
3602
|
+
function tick(now = /* @__PURE__ */ new Date()) {
|
|
3603
|
+
const state = loadState(now);
|
|
3604
|
+
const started = [];
|
|
3605
|
+
const skipped = [];
|
|
3606
|
+
const floor = new Date(now.getTime() - config.catchUpWindowDays * 864e5);
|
|
3607
|
+
const lastTick = new Date(state.lastTickAt);
|
|
3608
|
+
const routines = loadRoutines();
|
|
3609
|
+
const runningNames = /* @__PURE__ */ new Set([
|
|
3610
|
+
...getRunningRuns().map((r) => r.routine),
|
|
3611
|
+
...routines.map((r) => r.name).filter((name) => checkIsStarting(name))
|
|
3612
|
+
]);
|
|
3613
|
+
let runningCount = runningNames.size;
|
|
3614
|
+
for (const routine of routines) {
|
|
3615
|
+
if (!routine.schedule) continue;
|
|
3616
|
+
const entry = state.routines[routine.name];
|
|
3617
|
+
const lastScheduled = entry?.lastScheduledFor ? new Date(entry.lastScheduledFor) : null;
|
|
3618
|
+
const after = new Date(
|
|
3619
|
+
Math.max(floor.getTime(), lastTick.getTime(), lastScheduled?.getTime() ?? 0)
|
|
3620
|
+
);
|
|
3621
|
+
const due = cronRunsBetween(routine.schedule, after, now);
|
|
3622
|
+
const scheduledFor = due.at(-1);
|
|
3623
|
+
if (scheduledFor === void 0) continue;
|
|
3624
|
+
const isCatchUp = due.length > 1 || now.getTime() - scheduledFor.getTime() > 2 * config.tickSeconds * 1e3 + 6e4;
|
|
3625
|
+
if (!routine.enabled) {
|
|
3626
|
+
recordSkip(state, routine, scheduledFor, "disabled", now);
|
|
3627
|
+
continue;
|
|
3628
|
+
}
|
|
3629
|
+
if (runningNames.has(routine.name)) {
|
|
3630
|
+
recordSkip(state, routine, scheduledFor, "already_running", now);
|
|
3631
|
+
skipped.push(`${routine.name} (already running)`);
|
|
3632
|
+
continue;
|
|
3633
|
+
}
|
|
3634
|
+
if (runningCount >= config.maxConcurrentRuns) {
|
|
3635
|
+
skipped.push(`${routine.name} (concurrency limit, will retry)`);
|
|
3636
|
+
continue;
|
|
3637
|
+
}
|
|
3638
|
+
startDetachedRun(routine.name, {
|
|
3639
|
+
trigger: isCatchUp ? "catch_up" : "schedule",
|
|
3640
|
+
scheduledFor: scheduledFor.toISOString()
|
|
3641
|
+
});
|
|
3642
|
+
markScheduled(state, routine, scheduledFor);
|
|
3643
|
+
runningCount += 1;
|
|
3644
|
+
runningNames.add(routine.name);
|
|
3645
|
+
started.push(routine.name);
|
|
3646
|
+
}
|
|
3647
|
+
for (const name of listQueuedRoutines()) {
|
|
3648
|
+
const routine = routines.find((candidate) => candidate.name === name);
|
|
3649
|
+
if (routine === void 0 || !routine.enabled || !routine.webhook) continue;
|
|
3650
|
+
if (runningNames.has(name) || runningCount >= config.maxConcurrentRuns) continue;
|
|
3651
|
+
const queued = takeQueuedWebhook(name);
|
|
3652
|
+
if (queued === null) continue;
|
|
3653
|
+
if (queued.payload !== "") writePayload(name, queued.runId, queued.payload);
|
|
3654
|
+
startDetachedRun(name, { trigger: "webhook", runId: queued.runId });
|
|
3655
|
+
runningCount += 1;
|
|
3656
|
+
runningNames.add(name);
|
|
3657
|
+
started.push(name);
|
|
3658
|
+
}
|
|
3659
|
+
state.lastTickAt = now.toISOString();
|
|
3660
|
+
writeSchedulerState(state);
|
|
3661
|
+
return { started, skipped };
|
|
3662
|
+
}
|
|
3663
|
+
function startSchedulerLoop(log2) {
|
|
3664
|
+
const run = () => {
|
|
3665
|
+
try {
|
|
3666
|
+
const { started, skipped } = tick();
|
|
3667
|
+
for (const name of started) log2(`started ${name}`);
|
|
3668
|
+
for (const name of skipped) log2(`skipped ${name}`);
|
|
3669
|
+
} catch (err) {
|
|
3670
|
+
log2(`tick failed: ${getErrorMessage(err)}`);
|
|
3671
|
+
}
|
|
3672
|
+
};
|
|
3673
|
+
run();
|
|
3674
|
+
const timer = setInterval(run, config.tickSeconds * 1e3);
|
|
3675
|
+
return () => clearInterval(timer);
|
|
3676
|
+
}
|
|
3677
|
+
|
|
3678
|
+
// src/features/connect/connect.ts
|
|
3679
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
3680
|
+
import net from "node:net";
|
|
3681
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
3682
|
+
import { match as match9 } from "ts-pattern";
|
|
3683
|
+
var PROBE_INTERVAL_MS = 300;
|
|
3684
|
+
function buildSshArgs(destination, localPort, remotePort) {
|
|
3685
|
+
return [
|
|
3686
|
+
"-N",
|
|
3687
|
+
"-o",
|
|
3688
|
+
"ExitOnForwardFailure=yes",
|
|
3689
|
+
// A shared connection would keep the tunnel in another ssh process.
|
|
3690
|
+
"-o",
|
|
3691
|
+
"ControlMaster=no",
|
|
3692
|
+
"-o",
|
|
3693
|
+
"ControlPath=none",
|
|
3694
|
+
"-o",
|
|
3695
|
+
"ServerAliveInterval=15",
|
|
3696
|
+
"-L",
|
|
3697
|
+
`127.0.0.1:${localPort}:127.0.0.1:${remotePort}`,
|
|
3698
|
+
"--",
|
|
3699
|
+
destination
|
|
3700
|
+
];
|
|
3701
|
+
}
|
|
3702
|
+
function getFreePort() {
|
|
3703
|
+
return new Promise((resolve, reject) => {
|
|
3704
|
+
const server = net.createServer();
|
|
3705
|
+
server.on("error", reject);
|
|
3706
|
+
server.listen(0, "127.0.0.1", () => {
|
|
3707
|
+
const address = server.address();
|
|
3708
|
+
const port = typeof address === "object" && address !== null ? address.port : 0;
|
|
3709
|
+
server.close(() => {
|
|
3710
|
+
resolve(port);
|
|
3711
|
+
});
|
|
3712
|
+
});
|
|
3713
|
+
});
|
|
3714
|
+
}
|
|
3715
|
+
function isListening(port) {
|
|
3716
|
+
return new Promise((resolve) => {
|
|
3717
|
+
const socket = net.connect(port, "127.0.0.1");
|
|
3718
|
+
socket.once("connect", () => {
|
|
3719
|
+
socket.destroy();
|
|
3720
|
+
resolve(true);
|
|
3721
|
+
});
|
|
3722
|
+
socket.once("error", () => {
|
|
3723
|
+
resolve(false);
|
|
3724
|
+
});
|
|
3725
|
+
});
|
|
3726
|
+
}
|
|
3727
|
+
function openTunnel(destination, localPort, remotePort) {
|
|
3728
|
+
const ssh = spawn2("ssh", buildSshArgs(destination, localPort, remotePort), {
|
|
3729
|
+
stdio: ["ignore", "ignore", "pipe"]
|
|
3730
|
+
});
|
|
3731
|
+
let isOpen = true;
|
|
3732
|
+
let isQuiet = false;
|
|
3733
|
+
let lastMessage = "";
|
|
3734
|
+
ssh.stderr.on("data", (chunk) => {
|
|
3735
|
+
if (isQuiet) lastMessage = String(chunk).trim().split("\n").at(-1) ?? "";
|
|
3736
|
+
else process.stderr.write(chunk);
|
|
3737
|
+
});
|
|
3738
|
+
const closed = new Promise((resolve) => {
|
|
3739
|
+
ssh.on("error", (error) => {
|
|
3740
|
+
isOpen = false;
|
|
3741
|
+
console.error(`ssh failed to start: ${error.message}`);
|
|
3742
|
+
resolve(1);
|
|
3743
|
+
});
|
|
3744
|
+
ssh.on("exit", (code) => {
|
|
3745
|
+
isOpen = false;
|
|
3746
|
+
resolve(code ?? 1);
|
|
3747
|
+
});
|
|
3748
|
+
});
|
|
3749
|
+
process.on("exit", () => ssh.kill());
|
|
3750
|
+
return {
|
|
3751
|
+
closed,
|
|
3752
|
+
checkIsOpen: () => isOpen,
|
|
3753
|
+
setQuiet: (quiet) => {
|
|
3754
|
+
isQuiet = quiet;
|
|
3755
|
+
lastMessage = "";
|
|
3756
|
+
},
|
|
3757
|
+
getLastMessage: () => lastMessage,
|
|
3758
|
+
close: () => ssh.kill()
|
|
3759
|
+
};
|
|
3760
|
+
}
|
|
3761
|
+
async function waitUntilListening(tunnel, port) {
|
|
3762
|
+
while (tunnel.checkIsOpen()) {
|
|
3763
|
+
if (await isListening(port)) return true;
|
|
3764
|
+
await sleep(PROBE_INTERVAL_MS);
|
|
3765
|
+
}
|
|
3766
|
+
return false;
|
|
3767
|
+
}
|
|
3768
|
+
function openInBrowser(url) {
|
|
3769
|
+
const opener = match9(process.platform).with("darwin", () => "open").with("win32", () => "explorer.exe").otherwise(() => "xdg-open");
|
|
3770
|
+
spawn2(opener, [url], { stdio: "ignore", detached: true }).on("error", () => void 0).unref();
|
|
3771
|
+
}
|
|
3772
|
+
async function reportLostConnection(tunnel, destination) {
|
|
3773
|
+
const exitCode = await tunnel.closed;
|
|
3774
|
+
const message = tunnel.getLastMessage();
|
|
3775
|
+
if (message) console.error(message);
|
|
3776
|
+
console.error(`connection to ${destination} closed`);
|
|
3777
|
+
return exitCode === 0 ? 1 : exitCode;
|
|
3778
|
+
}
|
|
3779
|
+
async function connect({ destination, remotePort, tui }) {
|
|
3780
|
+
const localPort = await getFreePort();
|
|
3781
|
+
const url = `http://127.0.0.1:${localPort}`;
|
|
3782
|
+
const tunnel = openTunnel(destination, localPort, remotePort);
|
|
3783
|
+
if (!await waitUntilListening(tunnel, localPort)) return tunnel.closed;
|
|
3784
|
+
tunnel.setQuiet(true);
|
|
3785
|
+
const failure = await createDaemonClient(url).getOverview().then(
|
|
3786
|
+
() => null,
|
|
3787
|
+
(error) => error
|
|
3788
|
+
);
|
|
3789
|
+
if (failure !== null) {
|
|
3790
|
+
tunnel.close();
|
|
3791
|
+
const reason = tunnel.getLastMessage() || getErrorMessage(failure);
|
|
3792
|
+
throw new Error(
|
|
3793
|
+
`no kombinat daemon answers on port ${remotePort} of ${destination}: ${reason}`,
|
|
3794
|
+
{
|
|
3795
|
+
cause: failure
|
|
3796
|
+
}
|
|
3797
|
+
);
|
|
3798
|
+
}
|
|
3799
|
+
if (tui) {
|
|
3800
|
+
const lost = new AbortController();
|
|
3801
|
+
void tunnel.closed.then(() => {
|
|
3802
|
+
lost.abort();
|
|
3803
|
+
});
|
|
3804
|
+
await runTui(url, lost.signal);
|
|
3805
|
+
if (!tunnel.checkIsOpen()) return reportLostConnection(tunnel, destination);
|
|
3806
|
+
tunnel.close();
|
|
3807
|
+
return 0;
|
|
3808
|
+
}
|
|
3809
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
|
3810
|
+
process.on(signal, () => process.exit(0));
|
|
3811
|
+
}
|
|
3812
|
+
tunnel.setQuiet(false);
|
|
3813
|
+
console.log(`connected to ${destination}, dashboard at ${url}, Ctrl-C to disconnect`);
|
|
3814
|
+
openInBrowser(url);
|
|
3815
|
+
return reportLostConnection(tunnel, destination);
|
|
3816
|
+
}
|
|
3817
|
+
|
|
3818
|
+
// src/features/launchd/install.ts
|
|
3819
|
+
import { execFileSync } from "node:child_process";
|
|
3820
|
+
import fs8 from "node:fs";
|
|
3821
|
+
import os3 from "node:os";
|
|
3822
|
+
import path10 from "node:path";
|
|
3823
|
+
var plistPath = () => path10.join(os3.homedir(), "Library", "LaunchAgents", `${config.launchdLabel}.plist`);
|
|
3824
|
+
var domain = () => `gui/${os3.userInfo().uid}`;
|
|
3825
|
+
var PASSED_ENV = [/^KOMBINAT_/, /^CLAUDE_BIN$/, /^CODEX_BIN$/];
|
|
3826
|
+
function escapeXml(value) {
|
|
3827
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
3828
|
+
}
|
|
3829
|
+
function unescapeXml(value) {
|
|
3830
|
+
return value.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
3831
|
+
}
|
|
3832
|
+
function buildDaemonPath(current = process.env["PATH"] ?? "") {
|
|
3833
|
+
const base = [
|
|
3834
|
+
path10.dirname(process.execPath),
|
|
3835
|
+
path10.join(os3.homedir(), ".local", "bin"),
|
|
3836
|
+
"/opt/homebrew/bin",
|
|
3837
|
+
"/usr/local/bin",
|
|
3838
|
+
"/usr/bin",
|
|
3839
|
+
"/bin",
|
|
3840
|
+
"/usr/sbin",
|
|
3841
|
+
"/sbin"
|
|
3842
|
+
];
|
|
3843
|
+
const inherited = current.split(":").filter((entry) => entry && !entry.includes("/.claude/plugins/") && !entry.includes("cryptexd"));
|
|
3844
|
+
return [.../* @__PURE__ */ new Set([...base, ...inherited])].join(":");
|
|
3845
|
+
}
|
|
3846
|
+
function renderPlist() {
|
|
3847
|
+
const passed = Object.entries(process.env).filter(
|
|
3848
|
+
(entry) => PASSED_ENV.some((pattern) => pattern.test(entry[0])) && entry[1] !== void 0
|
|
3849
|
+
);
|
|
3850
|
+
const env2 = {
|
|
3851
|
+
PATH: buildDaemonPath(),
|
|
3852
|
+
HOME: os3.homedir(),
|
|
3853
|
+
LANG: process.env["LANG"] ?? "en_US.UTF-8",
|
|
3854
|
+
...Object.fromEntries(passed),
|
|
3855
|
+
KOMBINAT_MANAGED: "1"
|
|
3856
|
+
};
|
|
3857
|
+
const envXml = Object.entries(env2).map(
|
|
3858
|
+
([key, value]) => ` <key>${escapeXml(key)}</key>
|
|
3859
|
+
<string>${escapeXml(value)}</string>`
|
|
3860
|
+
).join("\n");
|
|
3861
|
+
const programArguments = [process.execPath, ...getCliArgs("serve")].map((arg) => ` <string>${escapeXml(arg)}</string>`).join("\n");
|
|
3862
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
3863
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3864
|
+
<plist version="1.0">
|
|
3865
|
+
<dict>
|
|
3866
|
+
<key>Label</key>
|
|
3867
|
+
<string>${config.launchdLabel}</string>
|
|
3868
|
+
<key>ProgramArguments</key>
|
|
3869
|
+
<array>
|
|
3870
|
+
${programArguments}
|
|
3871
|
+
</array>
|
|
3872
|
+
<key>WorkingDirectory</key>
|
|
3873
|
+
<string>${escapeXml(config.projectRoot)}</string>
|
|
3874
|
+
<key>EnvironmentVariables</key>
|
|
3875
|
+
<dict>
|
|
3876
|
+
${envXml}
|
|
3877
|
+
</dict>
|
|
3878
|
+
<key>RunAtLoad</key>
|
|
3879
|
+
<true/>
|
|
3880
|
+
<key>KeepAlive</key>
|
|
3881
|
+
<true/>
|
|
3882
|
+
<key>AbandonProcessGroup</key>
|
|
3883
|
+
<true/>
|
|
3884
|
+
<key>ThrottleInterval</key>
|
|
3885
|
+
<integer>10</integer>
|
|
3886
|
+
<key>StandardOutPath</key>
|
|
3887
|
+
<string>${escapeXml(path10.join(config.stateDir, "daemon.log"))}</string>
|
|
3888
|
+
<key>StandardErrorPath</key>
|
|
3889
|
+
<string>${escapeXml(path10.join(config.stateDir, "daemon.err"))}</string>
|
|
3890
|
+
</dict>
|
|
3891
|
+
</plist>
|
|
3892
|
+
`;
|
|
3893
|
+
}
|
|
3894
|
+
function runLaunchctl(args, ignoreFailure = false) {
|
|
3895
|
+
try {
|
|
3896
|
+
execFileSync("launchctl", args, { stdio: "pipe" });
|
|
3897
|
+
} catch (err) {
|
|
3898
|
+
if (!ignoreFailure) throw err;
|
|
3899
|
+
}
|
|
3900
|
+
}
|
|
3901
|
+
function sleep2(ms) {
|
|
3902
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
3903
|
+
}
|
|
3904
|
+
function waitUntilUnloaded(timeoutMs = 1e4) {
|
|
3905
|
+
const deadline = Date.now() + timeoutMs;
|
|
3906
|
+
while (checkIsLaunchdLoaded() && Date.now() < deadline) sleep2(250);
|
|
3907
|
+
}
|
|
3908
|
+
function bootstrapWithRetry(attempts = 5) {
|
|
3909
|
+
for (let i = 1; i <= attempts; i++) {
|
|
3910
|
+
try {
|
|
3911
|
+
execFileSync("launchctl", ["bootstrap", domain(), plistPath()], { stdio: "pipe" });
|
|
3912
|
+
return;
|
|
3913
|
+
} catch (err) {
|
|
3914
|
+
if (i === attempts) throw err;
|
|
3915
|
+
sleep2(1e3);
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
}
|
|
3919
|
+
function checkIsLaunchdLoaded() {
|
|
3920
|
+
try {
|
|
3921
|
+
execFileSync("launchctl", ["print", `${domain()}/${config.launchdLabel}`], { stdio: "pipe" });
|
|
3922
|
+
return true;
|
|
3923
|
+
} catch {
|
|
3924
|
+
return false;
|
|
3925
|
+
}
|
|
3926
|
+
}
|
|
3927
|
+
function stopLaunchd() {
|
|
3928
|
+
runLaunchctl(["bootout", `${domain()}/${config.launchdLabel}`], true);
|
|
3929
|
+
waitUntilUnloaded();
|
|
3930
|
+
}
|
|
3931
|
+
function startLaunchd() {
|
|
3932
|
+
if (!fs8.existsSync(plistPath())) throw new Error(`${plistPath()} is missing, run install first`);
|
|
3933
|
+
bootstrapWithRetry();
|
|
3934
|
+
}
|
|
3935
|
+
function install() {
|
|
3936
|
+
if (!config.fromSource && !config.installedInProject) {
|
|
3937
|
+
throw new Error(
|
|
3938
|
+
config.projectHasCopy ? `this project has its own ${PACKAGE_NAME}, install with it: pnpm kombinat install or npx kombinat install` : `add ${PACKAGE_NAME} to this project first: pnpm add ${PACKAGE_NAME} or npm install ${PACKAGE_NAME}`
|
|
3939
|
+
);
|
|
3940
|
+
}
|
|
3941
|
+
if (!fs8.existsSync(config.routinesDir)) {
|
|
3942
|
+
throw new Error(
|
|
3943
|
+
`${config.routinesDir} is missing, run install from the folder that holds routines/`
|
|
3944
|
+
);
|
|
3945
|
+
}
|
|
3946
|
+
fs8.mkdirSync(config.stateDir, { recursive: true });
|
|
3947
|
+
fs8.mkdirSync(path10.dirname(plistPath()), { recursive: true });
|
|
3948
|
+
fs8.writeFileSync(plistPath(), renderPlist());
|
|
3949
|
+
stopLaunchd();
|
|
3950
|
+
startLaunchd();
|
|
3951
|
+
return plistPath();
|
|
3952
|
+
}
|
|
3953
|
+
function getDaemonFolder() {
|
|
3954
|
+
if (!fs8.existsSync(plistPath())) return null;
|
|
3955
|
+
const found = /<key>WorkingDirectory<\/key>\s*<string>(?<folder>[^<]*)<\/string>/.exec(
|
|
3956
|
+
fs8.readFileSync(plistPath(), "utf8")
|
|
3957
|
+
);
|
|
3958
|
+
const folder = found?.groups?.["folder"];
|
|
3959
|
+
return folder === void 0 ? null : unescapeXml(folder);
|
|
3960
|
+
}
|
|
3961
|
+
function uninstall() {
|
|
3962
|
+
stopLaunchd();
|
|
3963
|
+
if (fs8.existsSync(plistPath())) fs8.unlinkSync(plistPath());
|
|
3964
|
+
return plistPath();
|
|
3965
|
+
}
|
|
3966
|
+
function getLaunchdStatus() {
|
|
3967
|
+
try {
|
|
3968
|
+
return execFileSync("launchctl", ["print", `${domain()}/${config.launchdLabel}`], {
|
|
3969
|
+
stdio: "pipe"
|
|
3970
|
+
}).toString();
|
|
3971
|
+
} catch {
|
|
3972
|
+
return "not loaded";
|
|
3973
|
+
}
|
|
3974
|
+
}
|
|
3975
|
+
|
|
3976
|
+
// src/features/readme/readme.ts
|
|
3977
|
+
import fs9 from "node:fs";
|
|
3978
|
+
import path11 from "node:path";
|
|
3979
|
+
var START = "<!-- routines:start -->";
|
|
3980
|
+
var END = "<!-- routines:end -->";
|
|
3981
|
+
function renderRoutinesTable() {
|
|
3982
|
+
const rows = loadRoutines().sort(
|
|
3983
|
+
(a, b) => Number(Boolean(b.schedule)) - Number(Boolean(a.schedule)) || a.name.localeCompare(b.name)
|
|
3984
|
+
).map((r) => `| [${r.name}](routines/${r.name}.md) | ${describeWhen(r)} | ${r.description} |`);
|
|
3985
|
+
return ["| Routine | When | What it does |", "| - | - | - |", ...rows].join("\n");
|
|
3986
|
+
}
|
|
3987
|
+
function describeWhen(routine) {
|
|
3988
|
+
if (!routine.webhook) return describeSchedule(routine);
|
|
3989
|
+
return routine.schedule === null ? "On webhook" : `${describeSchedule(routine)} and on webhook`;
|
|
3990
|
+
}
|
|
3991
|
+
function updateReadme(file = path11.join(config.projectRoot, "README.md")) {
|
|
3992
|
+
const source = fs9.readFileSync(file, "utf8");
|
|
3993
|
+
const start = source.indexOf(START);
|
|
3994
|
+
const end = source.indexOf(END);
|
|
3995
|
+
if (start === -1 || end === -1) throw new Error(`README.md needs ${START} and ${END} markers`);
|
|
3996
|
+
const next = `${source.slice(0, start + START.length)}
|
|
3997
|
+
${renderRoutinesTable()}
|
|
3998
|
+
${source.slice(end)}`;
|
|
3999
|
+
if (next === source) return false;
|
|
4000
|
+
fs9.writeFileSync(file, next);
|
|
4001
|
+
return true;
|
|
4002
|
+
}
|
|
4003
|
+
|
|
4004
|
+
// src/features/self-update/reload.ts
|
|
4005
|
+
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
4006
|
+
import fs10 from "node:fs";
|
|
4007
|
+
import path12 from "node:path";
|
|
4008
|
+
import { isMatching as isMatching5 } from "ts-pattern";
|
|
4009
|
+
import { z as z15 } from "zod";
|
|
4010
|
+
var processErrorSchema = z15.object({ stderr: z15.string(), stdout: z15.string().optional() });
|
|
4011
|
+
function getProcessOutput(error) {
|
|
4012
|
+
const parsed = processErrorSchema.safeParse(error);
|
|
4013
|
+
const output = parsed.success ? parsed.data.stderr || parsed.data.stdout : void 0;
|
|
4014
|
+
return output || getErrorMessage(error);
|
|
4015
|
+
}
|
|
4016
|
+
var SKIPPED_FOLDERS = ["node_modules", "dist"];
|
|
4017
|
+
function checkIsSkipped(file) {
|
|
4018
|
+
return file.endsWith(".md") || file.split(path12.sep).some((segment) => SKIPPED_FOLDERS.includes(segment));
|
|
4019
|
+
}
|
|
4020
|
+
function getNewestMtime(root) {
|
|
4021
|
+
if (!fs10.existsSync(root)) return 0;
|
|
4022
|
+
const stat = fs10.statSync(root);
|
|
4023
|
+
if (stat.isFile()) return stat.mtimeMs;
|
|
4024
|
+
return fs10.readdirSync(root).filter((entry) => !checkIsSkipped(entry)).reduce(
|
|
4025
|
+
(newest, entry) => Math.max(newest, getNewestMtime(path12.join(root, entry))),
|
|
4026
|
+
stat.mtimeMs
|
|
4027
|
+
);
|
|
4028
|
+
}
|
|
4029
|
+
var SHARED_PACKAGES = ["domains", "utils"];
|
|
4030
|
+
var RESTART_SOURCES = ["tui/src", ...SHARED_PACKAGES];
|
|
4031
|
+
var REBUILD_SOURCES = ["web-app/src", "design-system", ...SHARED_PACKAGES];
|
|
4032
|
+
var webAppSources = (workspaceRoot) => [...REBUILD_SOURCES, "web-app/index.html", "web-app/vite.config.ts"].map(
|
|
4033
|
+
(source) => path12.join(workspaceRoot, "packages", source)
|
|
4034
|
+
);
|
|
4035
|
+
function checkIsWebAppStale(workspaceRoot = config.workspaceRoot) {
|
|
4036
|
+
if (workspaceRoot === null) return false;
|
|
4037
|
+
const built = path12.join(workspaceRoot, "packages", "cli", "dist", "web-app", "index.html");
|
|
4038
|
+
if (!fs10.existsSync(built)) return true;
|
|
4039
|
+
const builtAt = fs10.statSync(built).mtimeMs;
|
|
4040
|
+
return webAppSources(workspaceRoot).some((source) => getNewestMtime(source) > builtAt);
|
|
4041
|
+
}
|
|
4042
|
+
var PACKAGE_MANAGERS = [
|
|
4043
|
+
{
|
|
4044
|
+
command: "pnpm",
|
|
4045
|
+
install: ["-s", "install", "--frozen-lockfile"],
|
|
4046
|
+
lockfile: "pnpm-lock.yaml",
|
|
4047
|
+
marker: ".modules.yaml"
|
|
4048
|
+
},
|
|
4049
|
+
// Not npm ci: when it fails, node_modules is left empty, kombinat included.
|
|
4050
|
+
{
|
|
4051
|
+
command: "npm",
|
|
4052
|
+
install: ["install", "--no-audit", "--no-fund", "--loglevel=error"],
|
|
4053
|
+
lockfile: "package-lock.json",
|
|
4054
|
+
marker: ".package-lock.json"
|
|
4055
|
+
},
|
|
4056
|
+
// Yarn 2+ reads --frozen-lockfile as --immutable.
|
|
4057
|
+
{
|
|
4058
|
+
command: "yarn",
|
|
4059
|
+
install: ["install", "--frozen-lockfile"],
|
|
4060
|
+
lockfile: "yarn.lock",
|
|
4061
|
+
marker: ".yarn-integrity"
|
|
4062
|
+
}
|
|
4063
|
+
];
|
|
4064
|
+
var INSTALL_MARKER = ".kombinat-install";
|
|
4065
|
+
function getLockfileDirs(projectRoot2) {
|
|
4066
|
+
const dirs = [];
|
|
4067
|
+
for (let dir = projectRoot2; ; dir = path12.dirname(dir)) {
|
|
4068
|
+
dirs.push(dir);
|
|
4069
|
+
if (fs10.existsSync(path12.join(dir, ".git"))) return dirs;
|
|
4070
|
+
if (path12.dirname(dir) === dir) return [projectRoot2];
|
|
4071
|
+
}
|
|
4072
|
+
}
|
|
4073
|
+
function findDependencies(projectRoot2 = config.projectRoot) {
|
|
4074
|
+
for (const root of getLockfileDirs(projectRoot2)) {
|
|
4075
|
+
const manager = PACKAGE_MANAGERS.find(
|
|
4076
|
+
(candidate) => fs10.existsSync(path12.join(root, candidate.lockfile))
|
|
4077
|
+
);
|
|
4078
|
+
if (manager !== void 0) return { manager, root };
|
|
4079
|
+
}
|
|
4080
|
+
return null;
|
|
4081
|
+
}
|
|
4082
|
+
function getMtime(file) {
|
|
4083
|
+
return fs10.existsSync(file) ? fs10.statSync(file).mtimeMs : 0;
|
|
4084
|
+
}
|
|
4085
|
+
function checkIsStale({ manager, root }) {
|
|
4086
|
+
const installedAt = Math.max(
|
|
4087
|
+
...[manager.marker, INSTALL_MARKER].map(
|
|
4088
|
+
(marker) => getMtime(path12.join(root, "node_modules", marker))
|
|
4089
|
+
)
|
|
4090
|
+
);
|
|
4091
|
+
return ["package.json", manager.lockfile].some(
|
|
4092
|
+
(file) => getMtime(path12.join(root, file)) > installedAt
|
|
4093
|
+
);
|
|
4094
|
+
}
|
|
4095
|
+
function checkAreDepsStale(projectRoot2 = config.projectRoot) {
|
|
4096
|
+
const dependencies = findDependencies(projectRoot2);
|
|
4097
|
+
return dependencies !== null && checkIsStale(dependencies);
|
|
4098
|
+
}
|
|
4099
|
+
function runTool(command, args, cwd, log2) {
|
|
4100
|
+
try {
|
|
4101
|
+
const output = execFileSync2(command, args, {
|
|
4102
|
+
cwd,
|
|
4103
|
+
// Yarn 1 trips a Node deprecation warning on every run.
|
|
4104
|
+
env: { ...process.env, NODE_NO_WARNINGS: "1" },
|
|
4105
|
+
encoding: "utf8",
|
|
4106
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
4107
|
+
timeout: 5 * 6e4
|
|
4108
|
+
});
|
|
4109
|
+
log2(`${command} ${args.join(" ")}: ${output.trim().split("\n").at(-1) || "ok"}`);
|
|
4110
|
+
return true;
|
|
4111
|
+
} catch (err) {
|
|
4112
|
+
const lines = getProcessOutput(err).split("\n").filter((line) => line.trim() && !/^\s+at /.test(line));
|
|
4113
|
+
log2(`${command} ${args.join(" ")} failed: ${lines.slice(-5).join(" | ")}`);
|
|
4114
|
+
return false;
|
|
4115
|
+
}
|
|
4116
|
+
}
|
|
4117
|
+
var buildWebApp = (workspaceRoot, log2) => runTool("pnpm", ["-s", "--filter", "web-app", "run", "build"], workspaceRoot, log2);
|
|
4118
|
+
function installDepsIfStale(log2, projectRoot2 = config.projectRoot) {
|
|
4119
|
+
const dependencies = findDependencies(projectRoot2);
|
|
4120
|
+
if (dependencies === null || !checkIsStale(dependencies)) return false;
|
|
4121
|
+
const { manager, root } = dependencies;
|
|
4122
|
+
log2(`dependencies changed, running ${manager.command} ${manager.install.join(" ")}`);
|
|
4123
|
+
const isInstalled = runTool(manager.command, manager.install, root, log2);
|
|
4124
|
+
const modules = path12.join(root, "node_modules");
|
|
4125
|
+
if (isInstalled && fs10.existsSync(modules)) {
|
|
4126
|
+
fs10.writeFileSync(path12.join(modules, INSTALL_MARKER), "");
|
|
4127
|
+
}
|
|
4128
|
+
return isInstalled;
|
|
4129
|
+
}
|
|
4130
|
+
function installDepsBeforeRestart(log2, projectRoot2 = config.projectRoot) {
|
|
4131
|
+
return !checkAreDepsStale(projectRoot2) || installDepsIfStale(log2, projectRoot2);
|
|
4132
|
+
}
|
|
4133
|
+
function buildWebAppIfStale(log2) {
|
|
4134
|
+
const { workspaceRoot } = config;
|
|
4135
|
+
if (workspaceRoot === null || !checkIsWebAppStale(workspaceRoot)) return false;
|
|
4136
|
+
log2("ui sources newer than dist/web-app, building");
|
|
4137
|
+
return buildWebApp(workspaceRoot, log2);
|
|
4138
|
+
}
|
|
4139
|
+
function watchDebounced(target, delayMs, onChange) {
|
|
4140
|
+
if (!fs10.existsSync(target)) return null;
|
|
4141
|
+
let timer = null;
|
|
4142
|
+
let lastFile = "";
|
|
4143
|
+
const watcher = fs10.watch(target, { recursive: true }, (_event, file) => {
|
|
4144
|
+
if (file !== null && checkIsSkipped(file)) return;
|
|
4145
|
+
lastFile = file ?? "";
|
|
4146
|
+
if (timer) clearTimeout(timer);
|
|
4147
|
+
timer = setTimeout(() => onChange(lastFile), delayMs);
|
|
4148
|
+
});
|
|
4149
|
+
watcher.unref();
|
|
4150
|
+
return watcher;
|
|
4151
|
+
}
|
|
4152
|
+
function runGit(args) {
|
|
4153
|
+
return execFileSync2(
|
|
4154
|
+
"git",
|
|
4155
|
+
["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", ...args],
|
|
4156
|
+
{
|
|
4157
|
+
cwd: config.projectRoot,
|
|
4158
|
+
encoding: "utf8",
|
|
4159
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
4160
|
+
timeout: 9e4
|
|
4161
|
+
}
|
|
4162
|
+
).trim();
|
|
4163
|
+
}
|
|
4164
|
+
function pullLatest() {
|
|
4165
|
+
try {
|
|
4166
|
+
const branch = runGit(["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
4167
|
+
if (branch !== config.pullBranch)
|
|
4168
|
+
return { status: "skipped", detail: `on branch ${branch}, not ${config.pullBranch}` };
|
|
4169
|
+
const dirty = runGit(["status", "--porcelain", "--untracked-files=no"]);
|
|
4170
|
+
if (dirty)
|
|
4171
|
+
return {
|
|
4172
|
+
status: "skipped",
|
|
4173
|
+
detail: `working tree has local changes (${dirty.split("\n").length} files)`
|
|
4174
|
+
};
|
|
4175
|
+
const before = runGit(["rev-parse", "HEAD"]);
|
|
4176
|
+
runGit(["pull", "--ff-only", "--quiet", "origin", config.pullBranch]);
|
|
4177
|
+
const after = runGit(["rev-parse", "HEAD"]);
|
|
4178
|
+
if (before === after) return { status: "up_to_date", detail: after.slice(0, 10) };
|
|
4179
|
+
const summary = runGit(["log", "--oneline", `${before}..${after}`]);
|
|
4180
|
+
return { status: "updated", detail: summary.split("\n").reverse().join(" | ") };
|
|
4181
|
+
} catch (err) {
|
|
4182
|
+
const stderr = getProcessOutput(err).trim();
|
|
4183
|
+
return { status: "failed", detail: stderr.split("\n").slice(-3).join(" | ") };
|
|
4184
|
+
}
|
|
4185
|
+
}
|
|
4186
|
+
function startAutoPull(log2) {
|
|
4187
|
+
if (config.pullMinutes <= 0) return () => {
|
|
4188
|
+
};
|
|
4189
|
+
let lastMessage = "";
|
|
4190
|
+
const run = () => {
|
|
4191
|
+
const result = pullLatest();
|
|
4192
|
+
const message = isMatching5({ status: "up_to_date" }, result) ? "" : `git pull ${result.status}: ${result.detail}`;
|
|
4193
|
+
if (message && message !== lastMessage) log2(message);
|
|
4194
|
+
lastMessage = message;
|
|
4195
|
+
};
|
|
4196
|
+
const timer = setInterval(run, config.pullMinutes * 6e4);
|
|
4197
|
+
timer.unref();
|
|
4198
|
+
return () => clearInterval(timer);
|
|
4199
|
+
}
|
|
4200
|
+
function startReloadWatchers(log2, restart) {
|
|
4201
|
+
const dependencies = findDependencies();
|
|
4202
|
+
const installAndRestart = (reason) => {
|
|
4203
|
+
if (!installDepsBeforeRestart(log2)) {
|
|
4204
|
+
log2(`${reason}, but the dependency install failed, keeping this version running`);
|
|
4205
|
+
return;
|
|
4206
|
+
}
|
|
4207
|
+
if (!fs10.existsSync(config.cliBin)) {
|
|
4208
|
+
log2(`${config.cliBin} is missing after the install, keeping this version running`);
|
|
4209
|
+
return;
|
|
4210
|
+
}
|
|
4211
|
+
restart(reason);
|
|
4212
|
+
};
|
|
4213
|
+
const { workspaceRoot } = config;
|
|
4214
|
+
const sourceWatchers = workspaceRoot === null ? [] : [
|
|
4215
|
+
watchDebounced(
|
|
4216
|
+
path12.join(config.packageRoot, "src"),
|
|
4217
|
+
1500,
|
|
4218
|
+
(file) => installAndRestart(`src/${file} changed`)
|
|
4219
|
+
),
|
|
4220
|
+
...RESTART_SOURCES.map(
|
|
4221
|
+
(source) => watchDebounced(
|
|
4222
|
+
path12.join(workspaceRoot, "packages", source),
|
|
4223
|
+
1500,
|
|
4224
|
+
(file) => installAndRestart(`packages/${source}/${file} changed`)
|
|
4225
|
+
)
|
|
4226
|
+
),
|
|
4227
|
+
...REBUILD_SOURCES.map(
|
|
4228
|
+
(source) => watchDebounced(path12.join(workspaceRoot, "packages", source), 1500, (file) => {
|
|
4229
|
+
log2(`packages/${source}/${file} changed, rebuilding ui`);
|
|
4230
|
+
buildWebApp(workspaceRoot, log2);
|
|
4231
|
+
})
|
|
4232
|
+
)
|
|
4233
|
+
];
|
|
4234
|
+
const lockfile = dependencies === null ? null : path12.join(dependencies.root, dependencies.manager.lockfile);
|
|
4235
|
+
const watchers = [
|
|
4236
|
+
...sourceWatchers,
|
|
4237
|
+
lockfile === null ? null : watchDebounced(lockfile, 1500, () => installAndRestart("dependencies changed"))
|
|
4238
|
+
];
|
|
4239
|
+
return () => watchers.forEach((w) => w?.close());
|
|
4240
|
+
}
|
|
4241
|
+
|
|
4242
|
+
// src/server.ts
|
|
4243
|
+
import fs12 from "node:fs";
|
|
4244
|
+
import http from "node:http";
|
|
4245
|
+
import path13 from "node:path";
|
|
4246
|
+
import { isMatching as isMatching7, match as match13, P as P4 } from "ts-pattern";
|
|
4247
|
+
|
|
4248
|
+
// ../domains/calendar/utils.ts
|
|
4249
|
+
import { isMatching as isMatching6, match as match10 } from "ts-pattern";
|
|
4250
|
+
var DEFAULT_PLANNED_MINUTES = 20;
|
|
4251
|
+
var MIN_BLOCK_MINUTES = 10;
|
|
4252
|
+
function median(values) {
|
|
4253
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
4254
|
+
const mid = Math.floor(sorted.length / 2);
|
|
4255
|
+
const upper = sorted[mid];
|
|
4256
|
+
if (upper === void 0) return null;
|
|
4257
|
+
const lower = sorted.length % 2 === 0 ? sorted[mid - 1] ?? upper : upper;
|
|
4258
|
+
return (lower + upper) / 2;
|
|
4259
|
+
}
|
|
4260
|
+
function estimatePlannedMinutes(routine, runs) {
|
|
4261
|
+
const finished = runs.flatMap(
|
|
4262
|
+
(run) => run.routine === routine.name && run.endedAt !== null && !isMatching6({ status: "aborted" }, run) ? [(new Date(run.endedAt).getTime() - new Date(run.startedAt).getTime()) / 6e4] : []
|
|
4263
|
+
).slice(0, 5);
|
|
4264
|
+
const typical = median(finished);
|
|
4265
|
+
if (typical === null)
|
|
4266
|
+
return { minutes: Math.min(DEFAULT_PLANNED_MINUTES, routine.timeoutMinutes), estimated: false };
|
|
4267
|
+
return {
|
|
4268
|
+
minutes: Math.max(MIN_BLOCK_MINUTES, Math.min(Math.ceil(typical), routine.timeoutMinutes)),
|
|
4269
|
+
estimated: true
|
|
4270
|
+
};
|
|
4271
|
+
}
|
|
4272
|
+
function toRunEntry(run, now) {
|
|
4273
|
+
const start = new Date(run.startedAt);
|
|
4274
|
+
const rawEnd = run.endedAt ? new Date(run.endedAt) : now;
|
|
4275
|
+
const end = new Date(Math.max(rawEnd.getTime(), start.getTime() + MIN_BLOCK_MINUTES * 6e4));
|
|
4276
|
+
return {
|
|
4277
|
+
id: calendarEntryIdSchema.parse(`run:${run.routine}:${run.id}`),
|
|
4278
|
+
routine: run.routine,
|
|
4279
|
+
start: start.toISOString(),
|
|
4280
|
+
end: end.toISOString(),
|
|
4281
|
+
kind: "run",
|
|
4282
|
+
status: run.status,
|
|
4283
|
+
runId: run.id,
|
|
4284
|
+
trigger: run.trigger,
|
|
4285
|
+
estimated: false,
|
|
4286
|
+
overlaps: []
|
|
4287
|
+
};
|
|
4288
|
+
}
|
|
4289
|
+
function markOverlaps(entries) {
|
|
4290
|
+
const sorted = [...entries].sort((a, b) => a.start.localeCompare(b.start));
|
|
4291
|
+
sorted.forEach((entry, index) => {
|
|
4292
|
+
for (const other of sorted.slice(index + 1)) {
|
|
4293
|
+
if (other.start >= entry.end) break;
|
|
4294
|
+
if (entry.routine === other.routine) continue;
|
|
4295
|
+
entry.overlaps.push(other.id);
|
|
4296
|
+
other.overlaps.push(entry.id);
|
|
4297
|
+
}
|
|
4298
|
+
});
|
|
4299
|
+
return sorted;
|
|
4300
|
+
}
|
|
4301
|
+
function buildCalendar(routines, runs, from, to, now = /* @__PURE__ */ new Date()) {
|
|
4302
|
+
const runEntries = runs.filter((r) => new Date(r.startedAt) < to && new Date(r.endedAt ?? now) > from).map((r) => toRunEntry(r, now));
|
|
4303
|
+
const plannedFrom = new Date(Math.max(from.getTime(), now.getTime()));
|
|
4304
|
+
const plannedEntries = routines.flatMap((routine) => {
|
|
4305
|
+
if (!routine.enabled || routine.schedule === null || plannedFrom >= to) return [];
|
|
4306
|
+
const { minutes, estimated } = estimatePlannedMinutes(routine, runs);
|
|
4307
|
+
return cronRunsBetween(routine.schedule, plannedFrom, to).map((start) => ({
|
|
4308
|
+
id: calendarEntryIdSchema.parse(`planned:${routine.name}:${start.toISOString()}`),
|
|
4309
|
+
routine: routine.name,
|
|
4310
|
+
start: start.toISOString(),
|
|
4311
|
+
end: new Date(start.getTime() + minutes * 6e4).toISOString(),
|
|
4312
|
+
kind: "planned",
|
|
4313
|
+
status: null,
|
|
4314
|
+
runId: null,
|
|
4315
|
+
trigger: null,
|
|
4316
|
+
estimated,
|
|
4317
|
+
overlaps: []
|
|
4318
|
+
}));
|
|
4319
|
+
});
|
|
4320
|
+
return markOverlaps([...runEntries, ...plannedEntries]);
|
|
4321
|
+
}
|
|
4322
|
+
|
|
4323
|
+
// src/domains/run/event-log.ts
|
|
4324
|
+
import fs11 from "node:fs";
|
|
4325
|
+
import { z as z16 } from "zod";
|
|
4326
|
+
var beforeHookEventSchema = z16.object({
|
|
4327
|
+
type: z16.literal("before_hook"),
|
|
4328
|
+
command: z16.string(),
|
|
4329
|
+
exitCode: z16.number().nullable(),
|
|
4330
|
+
output: z16.string()
|
|
4331
|
+
});
|
|
4332
|
+
function toHookItem(event, index) {
|
|
4333
|
+
return {
|
|
4334
|
+
kind: "hook",
|
|
4335
|
+
key: `hook-${index}`,
|
|
4336
|
+
command: event.command,
|
|
4337
|
+
exitCode: event.exitCode,
|
|
4338
|
+
output: event.output
|
|
4339
|
+
};
|
|
4340
|
+
}
|
|
4341
|
+
function readRunEvents(record) {
|
|
4342
|
+
if (!fs11.existsSync(record.logFile)) return [];
|
|
4343
|
+
return fs11.readFileSync(record.logFile, "utf8").split("\n").filter(Boolean).map(parseJson).filter((event) => event !== void 0);
|
|
4344
|
+
}
|
|
4345
|
+
function buildRunTranscript(agent, events) {
|
|
4346
|
+
const hooks = [];
|
|
4347
|
+
const agentEvents = [];
|
|
4348
|
+
for (const event of events) {
|
|
4349
|
+
const hook = beforeHookEventSchema.safeParse(event);
|
|
4350
|
+
if (hook.success) hooks.push(toHookItem(hook.data, hooks.length));
|
|
4351
|
+
else agentEvents.push(event);
|
|
4352
|
+
}
|
|
4353
|
+
return {
|
|
4354
|
+
eventCount: events.length,
|
|
4355
|
+
items: [...hooks, ...getAgent(agent).buildTranscript(agentEvents)]
|
|
4356
|
+
};
|
|
4357
|
+
}
|
|
4358
|
+
|
|
4359
|
+
// src/domains/webhook/gate.ts
|
|
4360
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
4361
|
+
import { match as match11 } from "ts-pattern";
|
|
4362
|
+
var WEBHOOK_GATE_TIMEOUT_MS = 3e3;
|
|
4363
|
+
var WEBHOOK_GATE_IGNORE_EXIT_CODE = 78;
|
|
4364
|
+
function toDecision(exitCode, stdout, stderr, body) {
|
|
4365
|
+
return match11(exitCode).with(0, () => ({
|
|
4366
|
+
outcome: "run",
|
|
4367
|
+
payload: stdout.trim() === "" ? body : stdout
|
|
4368
|
+
})).with(WEBHOOK_GATE_IGNORE_EXIT_CODE, () => ({
|
|
4369
|
+
outcome: "ignore",
|
|
4370
|
+
response: parseJson(stdout) ?? null
|
|
4371
|
+
})).otherwise(() => ({
|
|
4372
|
+
outcome: "reject",
|
|
4373
|
+
reason: `exited with ${exitCode ?? "a signal"}: ${stderr.trim().slice(-500)}`
|
|
4374
|
+
}));
|
|
4375
|
+
}
|
|
4376
|
+
function decideWebhook(routine, request, timeoutMs = WEBHOOK_GATE_TIMEOUT_MS) {
|
|
4377
|
+
const body = request.body.toString("utf8");
|
|
4378
|
+
const gate = routine.webhookGate;
|
|
4379
|
+
if (gate === null) return Promise.resolve({ outcome: "run", payload: body });
|
|
4380
|
+
return new Promise((resolve) => {
|
|
4381
|
+
const child = spawn3("/bin/sh", ["-c", gate], {
|
|
4382
|
+
cwd: config.projectRoot,
|
|
4383
|
+
env: withHookEnv({
|
|
4384
|
+
...process.env,
|
|
4385
|
+
KOMBINAT_ROUTINE: routine.name,
|
|
4386
|
+
KOMBINAT_WEBHOOK_HEADERS: JSON.stringify(request.headers)
|
|
4387
|
+
}),
|
|
4388
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
4389
|
+
});
|
|
4390
|
+
const stdout = [];
|
|
4391
|
+
const stderr = [];
|
|
4392
|
+
child.stdout.on("data", (chunk) => stdout.push(chunk));
|
|
4393
|
+
child.stderr.on("data", (chunk) => stderr.push(chunk));
|
|
4394
|
+
let isTimedOut = false;
|
|
4395
|
+
const timer = setTimeout(() => {
|
|
4396
|
+
isTimedOut = true;
|
|
4397
|
+
child.kill("SIGKILL");
|
|
4398
|
+
}, timeoutMs);
|
|
4399
|
+
child.on("error", (error) => {
|
|
4400
|
+
clearTimeout(timer);
|
|
4401
|
+
resolve({ outcome: "reject", reason: `failed to start: ${error.message}` });
|
|
4402
|
+
});
|
|
4403
|
+
child.on("close", (exitCode) => {
|
|
4404
|
+
clearTimeout(timer);
|
|
4405
|
+
if (isTimedOut) {
|
|
4406
|
+
resolve({ outcome: "timeout" });
|
|
4407
|
+
return;
|
|
4408
|
+
}
|
|
4409
|
+
resolve(
|
|
4410
|
+
toDecision(
|
|
4411
|
+
exitCode,
|
|
4412
|
+
Buffer.concat(stdout).toString("utf8"),
|
|
4413
|
+
Buffer.concat(stderr).toString("utf8"),
|
|
4414
|
+
body
|
|
4415
|
+
)
|
|
4416
|
+
);
|
|
4417
|
+
});
|
|
4418
|
+
child.stdin.on("error", () => void 0);
|
|
4419
|
+
child.stdin.end(request.body);
|
|
4420
|
+
});
|
|
4421
|
+
}
|
|
4422
|
+
|
|
4423
|
+
// src/domains/webhook/receive.ts
|
|
4424
|
+
import { match as match12 } from "ts-pattern";
|
|
4425
|
+
function startOrQueueRun(routine, payload) {
|
|
4426
|
+
if (!routine.enabled) return { outcome: "disabled" };
|
|
4427
|
+
const runId = createRunId();
|
|
4428
|
+
if (checkIsRunning(routine.name) || countQueuedWebhooks(routine.name) > 0) {
|
|
4429
|
+
return enqueueWebhook(routine.name, runId, payload) ? { outcome: "queued", runId } : { outcome: "queue_full" };
|
|
4430
|
+
}
|
|
4431
|
+
if (payload !== "") writePayload(routine.name, runId, payload);
|
|
4432
|
+
startDetachedRun(routine.name, { trigger: "webhook", runId });
|
|
4433
|
+
return { outcome: "started", runId };
|
|
4434
|
+
}
|
|
4435
|
+
async function receiveWebhook(routine, request) {
|
|
4436
|
+
if (!routine.webhook) return { outcome: "no_webhook" };
|
|
4437
|
+
const decision = await decideWebhook(routine, request);
|
|
4438
|
+
return match12(decision).with({ outcome: "run" }, ({ payload }) => startOrQueueRun(routine, payload)).with({ outcome: "ignore" }, ({ response }) => ({
|
|
4439
|
+
outcome: "ignored",
|
|
4440
|
+
response
|
|
4441
|
+
})).with({ outcome: "reject" }, ({ reason }) => ({ outcome: "rejected", reason })).with({ outcome: "timeout" }, () => ({ outcome: "timed_out" })).exhaustive();
|
|
4442
|
+
}
|
|
4443
|
+
|
|
4444
|
+
// src/server.ts
|
|
4445
|
+
var MIME = {
|
|
4446
|
+
".html": "text/html; charset=utf-8",
|
|
4447
|
+
".js": "text/javascript; charset=utf-8",
|
|
4448
|
+
".css": "text/css; charset=utf-8",
|
|
4449
|
+
".svg": "image/svg+xml",
|
|
4450
|
+
".png": "image/png",
|
|
4451
|
+
".ico": "image/x-icon",
|
|
4452
|
+
".json": "application/json; charset=utf-8",
|
|
4453
|
+
".woff2": "font/woff2"
|
|
4454
|
+
};
|
|
4455
|
+
var MAX_CALENDAR_DAYS = 32;
|
|
4456
|
+
var MAX_BODY_KB = 256;
|
|
4457
|
+
var ok = (body) => ({ status: 200, body });
|
|
4458
|
+
var fail = (status, error) => ({ status, body: { error } });
|
|
4459
|
+
function toRoutineSummary(routine, runs) {
|
|
4460
|
+
return {
|
|
4461
|
+
name: routine.name,
|
|
4462
|
+
description: routine.description,
|
|
4463
|
+
schedule: routine.schedule,
|
|
4464
|
+
scheduleHuman: describeSchedule(routine),
|
|
4465
|
+
nextRunAt: getNextRun(routine),
|
|
4466
|
+
enabled: routine.enabled,
|
|
4467
|
+
webhook: routine.webhook,
|
|
4468
|
+
webhookGate: routine.webhookGate,
|
|
4469
|
+
queuedWebhooks: countQueuedWebhooks(routine.name),
|
|
4470
|
+
agent: routine.agent,
|
|
4471
|
+
model: routine.model,
|
|
4472
|
+
effort: routine.effort,
|
|
4473
|
+
permissionMode: routine.permissionMode,
|
|
4474
|
+
command: routine.command,
|
|
4475
|
+
cwd: routine.cwd,
|
|
4476
|
+
timeoutMinutes: routine.timeoutMinutes,
|
|
4477
|
+
maxBudgetUsd: routine.maxBudgetUsd,
|
|
4478
|
+
file: path13.relative(config.projectRoot, routine.file),
|
|
4479
|
+
running: checkIsStarting(routine.name) || runs.some(isMatching7({ status: "running" })),
|
|
4480
|
+
lastRun: runs[0] ?? null,
|
|
4481
|
+
lastSkip: getSkips(routine.name).at(-1) ?? null
|
|
4482
|
+
};
|
|
4483
|
+
}
|
|
4484
|
+
function getStatus(startedAt) {
|
|
4485
|
+
return {
|
|
4486
|
+
version: config.version,
|
|
4487
|
+
pid: process.pid,
|
|
4488
|
+
startedAt: startedAt.toISOString(),
|
|
4489
|
+
lastTickAt: readSchedulerState()?.lastTickAt ?? null,
|
|
4490
|
+
routinesDir: config.routinesDir,
|
|
4491
|
+
stateDir: config.stateDir,
|
|
4492
|
+
claudeBin: config.claudeBin,
|
|
4493
|
+
codexBin: config.codexBin,
|
|
4494
|
+
maxConcurrentRuns: config.maxConcurrentRuns,
|
|
4495
|
+
running: listAllRuns().filter(isMatching7({ status: "running" })).length + loadRoutines().filter((routine) => checkIsStarting(routine.name)).length,
|
|
4496
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
4497
|
+
now: (/* @__PURE__ */ new Date()).toISOString()
|
|
4498
|
+
};
|
|
4499
|
+
}
|
|
4500
|
+
function withRoutine(name, respond) {
|
|
4501
|
+
const routine = loadRoutines().find((candidate) => candidate.name === name);
|
|
4502
|
+
return routine === void 0 ? fail(404, `Unknown routine ${name}`) : respond(routine);
|
|
4503
|
+
}
|
|
4504
|
+
function withRun(routine, id, respond) {
|
|
4505
|
+
const record = readRunRecord(routine, id);
|
|
4506
|
+
return record === null ? fail(404, "Run not found") : respond(record);
|
|
4507
|
+
}
|
|
4508
|
+
function getRoutineDetail(routine) {
|
|
4509
|
+
const detail = {
|
|
4510
|
+
...toRoutineSummary(routine, listRuns(routine.name)),
|
|
4511
|
+
prompt: routine.prompt,
|
|
4512
|
+
skips: getSkips(routine.name),
|
|
4513
|
+
queue: listQueuedWebhooks(routine.name)
|
|
4514
|
+
};
|
|
4515
|
+
return ok(detail);
|
|
4516
|
+
}
|
|
4517
|
+
function startRun(routine) {
|
|
4518
|
+
if (checkIsRunning(routine.name)) return fail(409, `${routine.name} is already running`);
|
|
4519
|
+
startDetachedRun(routine.name, { trigger: "manual" });
|
|
4520
|
+
return { status: 202, body: { ok: true } };
|
|
4521
|
+
}
|
|
4522
|
+
async function handleWebhook(routine, context) {
|
|
4523
|
+
const { name } = routine;
|
|
4524
|
+
const outcome = await receiveWebhook(routine, context.request);
|
|
4525
|
+
return match13(outcome).with(
|
|
4526
|
+
{ outcome: "no_webhook" },
|
|
4527
|
+
() => fail(404, `${name} has no webhook, add webhook: true to its frontmatter`)
|
|
4528
|
+
).with({ outcome: P4.union("started", "queued") }, ({ runId }) => ok({ ok: true, runId })).with({ outcome: "ignored" }, ({ response }) => ok(response ?? { ok: true, runId: null })).with({ outcome: "rejected" }, ({ reason }) => {
|
|
4529
|
+
context.log(`webhookGate of ${name} ${reason}`);
|
|
4530
|
+
return fail(401, "webhookGate rejected the request");
|
|
4531
|
+
}).with({ outcome: "timed_out" }, () => {
|
|
4532
|
+
context.log(`webhookGate of ${name} timed out`);
|
|
4533
|
+
return fail(504, `webhookGate took longer than ${WEBHOOK_GATE_TIMEOUT_MS / 1e3} s`);
|
|
4534
|
+
}).with({ outcome: "disabled" }, () => fail(409, `${name} is disabled`)).with(
|
|
4535
|
+
{ outcome: "queue_full" },
|
|
4536
|
+
() => fail(429, `${name} already has ${WEBHOOK_QUEUE_LIMIT} webhooks waiting`)
|
|
4537
|
+
).exhaustive();
|
|
4538
|
+
}
|
|
4539
|
+
function getCalendar(url) {
|
|
4540
|
+
const from = new Date(url.searchParams.get("from") ?? "");
|
|
4541
|
+
const to = new Date(url.searchParams.get("to") ?? "");
|
|
4542
|
+
const isValid = !Number.isNaN(from.getTime()) && !Number.isNaN(to.getTime()) && to > from && to.getTime() - from.getTime() <= MAX_CALENDAR_DAYS * 864e5;
|
|
4543
|
+
if (!isValid) {
|
|
4544
|
+
return fail(400, `from and to must be ISO dates spanning at most ${MAX_CALENDAR_DAYS} days`);
|
|
4545
|
+
}
|
|
4546
|
+
return ok(buildCalendar(loadRoutines(), listAllRuns(), from, to));
|
|
4547
|
+
}
|
|
4548
|
+
function getRunsPage2(url) {
|
|
4549
|
+
const query = parseRunsPageQuery(url.searchParams);
|
|
4550
|
+
if (query === null) return fail(400, RUNS_CURSOR_ERROR);
|
|
4551
|
+
if (query.routine === null) return ok(paginateRuns(listAllRuns(), query.cursor));
|
|
4552
|
+
return withRoutine(
|
|
4553
|
+
query.routine,
|
|
4554
|
+
(routine) => ok(paginateRuns(listRuns(routine.name), query.cursor))
|
|
4555
|
+
);
|
|
4556
|
+
}
|
|
4557
|
+
function routeApi(request, context) {
|
|
4558
|
+
const { url, startedAt } = context;
|
|
4559
|
+
return match13(request).with(["GET", ["status"]], () => ok(getStatus(startedAt))).with(
|
|
4560
|
+
["GET", ["routines"]],
|
|
4561
|
+
() => ok(loadRoutines().map((routine) => toRoutineSummary(routine, listRuns(routine.name))))
|
|
4562
|
+
).with(
|
|
4563
|
+
["GET", ["routines", P4.string]],
|
|
4564
|
+
([, [, name]]) => withRoutine(routineNameSchema.parse(name), getRoutineDetail)
|
|
4565
|
+
).with(
|
|
4566
|
+
["POST", ["routines", P4.string, "run"]],
|
|
4567
|
+
([, [, name]]) => withRoutine(routineNameSchema.parse(name), startRun)
|
|
4568
|
+
).with(
|
|
4569
|
+
["POST", ["routines", P4.string, "webhook"]],
|
|
4570
|
+
([, [, name]]) => withRoutine(routineNameSchema.parse(name), (routine) => handleWebhook(routine, context))
|
|
4571
|
+
).with(["GET", ["calendar"]], () => getCalendar(url)).with(["GET", ["runs"]], () => getRunsPage2(url)).with(
|
|
4572
|
+
["GET", ["runs", P4.string, P4.string]],
|
|
4573
|
+
([, [, routine, id]]) => withRun(routineNameSchema.parse(routine), runIdSchema.parse(id), ok)
|
|
4574
|
+
).with(
|
|
4575
|
+
["GET", ["runs", P4.string, P4.string, "transcript"]],
|
|
4576
|
+
([, [, routine, id]]) => withRun(
|
|
4577
|
+
routineNameSchema.parse(routine),
|
|
4578
|
+
runIdSchema.parse(id),
|
|
4579
|
+
(record) => ok(buildRunTranscript(record.agent, readRunEvents(record)))
|
|
4580
|
+
)
|
|
4581
|
+
).otherwise(() => fail(404, "Not found"));
|
|
4582
|
+
}
|
|
4583
|
+
function sendJson(res, { status, body }) {
|
|
4584
|
+
res.writeHead(status, {
|
|
4585
|
+
"content-type": "application/json; charset=utf-8",
|
|
4586
|
+
"cache-control": "no-store"
|
|
4587
|
+
});
|
|
4588
|
+
res.end(JSON.stringify(body));
|
|
4589
|
+
}
|
|
4590
|
+
function serveStatic(res, url) {
|
|
4591
|
+
if (!fs12.existsSync(config.webAppDist)) {
|
|
4592
|
+
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
|
|
4593
|
+
res.end("kombinat API is up. Build the UI with `pnpm build` to get the dashboard here.\n");
|
|
4594
|
+
return;
|
|
4595
|
+
}
|
|
4596
|
+
const requested = path13.normalize(decodeURIComponent(url.pathname));
|
|
4597
|
+
const candidate = path13.join(config.webAppDist, requested);
|
|
4598
|
+
const isFile = candidate.startsWith(config.webAppDist) && fs12.existsSync(candidate) && fs12.statSync(candidate).isFile();
|
|
4599
|
+
const file = isFile ? candidate : path13.join(config.webAppDist, "index.html");
|
|
4600
|
+
res.writeHead(200, { "content-type": MIME[path13.extname(file)] ?? "application/octet-stream" });
|
|
4601
|
+
fs12.createReadStream(file).pipe(res);
|
|
4602
|
+
}
|
|
4603
|
+
function checkIsCrossSite(headers) {
|
|
4604
|
+
const site = headers["sec-fetch-site"];
|
|
4605
|
+
if (site !== void 0) return site !== "same-origin" && site !== "none";
|
|
4606
|
+
return headers.origin !== void 0 && URL.parse(headers.origin)?.host !== headers.host;
|
|
4607
|
+
}
|
|
4608
|
+
function readBody(req) {
|
|
4609
|
+
return new Promise((resolve, reject) => {
|
|
4610
|
+
const chunks = [];
|
|
4611
|
+
let size = 0;
|
|
4612
|
+
req.on("data", (chunk) => {
|
|
4613
|
+
size += chunk.length;
|
|
4614
|
+
if (size <= MAX_BODY_KB * 1024) chunks.push(chunk);
|
|
4615
|
+
});
|
|
4616
|
+
req.on("end", () => {
|
|
4617
|
+
resolve(size > MAX_BODY_KB * 1024 ? null : Buffer.concat(chunks));
|
|
4618
|
+
});
|
|
4619
|
+
req.on("error", reject);
|
|
4620
|
+
});
|
|
4621
|
+
}
|
|
4622
|
+
async function handleApi(req, segments, context) {
|
|
4623
|
+
const method = req.method ?? "GET";
|
|
4624
|
+
const { headers } = req;
|
|
4625
|
+
if (method === "GET") {
|
|
4626
|
+
return routeApi([method, segments], {
|
|
4627
|
+
...context,
|
|
4628
|
+
request: { body: Buffer.alloc(0), headers }
|
|
4629
|
+
});
|
|
4630
|
+
}
|
|
4631
|
+
if (checkIsCrossSite(headers)) {
|
|
4632
|
+
return fail(403, "Requests from other sites cannot change anything");
|
|
4633
|
+
}
|
|
4634
|
+
const body = await readBody(req);
|
|
4635
|
+
if (body === null) return fail(413, `The request body is larger than ${MAX_BODY_KB} KB`);
|
|
4636
|
+
return routeApi([method, segments], { ...context, request: { body, headers } });
|
|
4637
|
+
}
|
|
4638
|
+
function startServer(log2) {
|
|
4639
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
4640
|
+
const server = http.createServer((req, res) => {
|
|
4641
|
+
const url = new URL(req.url ?? "/", `http://localhost:${config.port}`);
|
|
4642
|
+
const [root, ...segments] = url.pathname.split("/").filter(Boolean);
|
|
4643
|
+
const respond = async () => {
|
|
4644
|
+
if (root !== "api") serveStatic(res, url);
|
|
4645
|
+
else sendJson(res, await handleApi(req, segments, { url, startedAt, log: log2 }));
|
|
4646
|
+
};
|
|
4647
|
+
respond().catch((error) => {
|
|
4648
|
+
const message = getErrorMessage(error);
|
|
4649
|
+
log2(`request failed ${url.pathname}: ${message}`);
|
|
4650
|
+
sendJson(res, fail(500, message));
|
|
4651
|
+
});
|
|
4652
|
+
});
|
|
4653
|
+
server.listen(config.port, "127.0.0.1", () => {
|
|
4654
|
+
log2(`ui at http://localhost:${config.port}`);
|
|
4655
|
+
});
|
|
4656
|
+
return server;
|
|
4657
|
+
}
|
|
4658
|
+
|
|
4659
|
+
// src/cli.ts
|
|
4660
|
+
var USAGE = `kombinat, run from the folder that holds routines/ (connect and tui --url work anywhere)
|
|
4661
|
+
|
|
4662
|
+
tui [--url <url>] keyboard dashboard in the terminal (works over ssh), talks to the
|
|
4663
|
+
running daemon, or to the one at --url
|
|
4664
|
+
connect <destination> dashboard of a daemon on another machine through an ssh tunnel, in the
|
|
4665
|
+
browser or with --tui in the terminal; --port is the daemon port
|
|
4666
|
+
there (default ${DEFAULT_PORT}), for example connect admin@mac-mini --tui
|
|
4667
|
+
list show routines from ./routines with next run and last status
|
|
4668
|
+
validate parse every routine file and report errors
|
|
4669
|
+
readme regenerate the routines table in README.md
|
|
4670
|
+
run <name> run one routine now in the foreground (what the scheduler spawns)
|
|
4671
|
+
serve run scheduler + web UI (what launchd runs); pulls the main branch
|
|
4672
|
+
every 5 min, installs deps and restarts when the lockfile changes;
|
|
4673
|
+
in a checkout of kombinat also builds the UI and restarts when
|
|
4674
|
+
packages/ change
|
|
4675
|
+
pull git pull once, the way serve does it (ff-only, clean tree)
|
|
4676
|
+
dev take over from launchd: scheduler + API from this checkout with no
|
|
4677
|
+
auto-restart, plus the Vite dev server; Ctrl-C hands back to launchd
|
|
4678
|
+
install write the LaunchAgent plist and start the daemon
|
|
4679
|
+
uninstall stop the daemon and remove the plist
|
|
4680
|
+
status daemon and scheduler state
|
|
4681
|
+
`;
|
|
4682
|
+
function log(line) {
|
|
4683
|
+
console.log(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}`);
|
|
4684
|
+
}
|
|
4685
|
+
function formatTime(iso) {
|
|
4686
|
+
return iso ? new Date(iso).toLocaleString() : "-";
|
|
4687
|
+
}
|
|
4688
|
+
function parseTrigger(value) {
|
|
4689
|
+
const parsed = runTriggerSchema.safeParse(value);
|
|
4690
|
+
if (!parsed.success) {
|
|
4691
|
+
throw new Error(`--trigger must be one of ${runTriggerSchema.options.join(", ")}`);
|
|
4692
|
+
}
|
|
4693
|
+
return parsed.data;
|
|
4694
|
+
}
|
|
4695
|
+
function parseRunId(value) {
|
|
4696
|
+
if (!/^[\w-]+$/.test(value)) throw new Error("--run-id must be letters, digits, _ and -");
|
|
4697
|
+
return runIdSchema.parse(value);
|
|
4698
|
+
}
|
|
4699
|
+
function parseUrl(value) {
|
|
4700
|
+
const url = URL.parse(value);
|
|
4701
|
+
if (url === null || !["http:", "https:"].includes(url.protocol)) {
|
|
4702
|
+
throw new Error("--url must be an http(s) URL, for example https://mac-mini.example.ts.net");
|
|
4703
|
+
}
|
|
4704
|
+
return value.replace(/\/+$/, "");
|
|
4705
|
+
}
|
|
4706
|
+
function parsePort(value) {
|
|
4707
|
+
const port = Number(value);
|
|
4708
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
4709
|
+
throw new Error("--port must be a port number");
|
|
4710
|
+
}
|
|
4711
|
+
return port;
|
|
4712
|
+
}
|
|
4713
|
+
function checkFlag(isSet, flag, command, owner) {
|
|
4714
|
+
if (isSet && command !== owner) throw new Error(`--${flag} only works with ${owner}`);
|
|
4715
|
+
}
|
|
4716
|
+
function startScheduler(options) {
|
|
4717
|
+
return options.scheduler ? startSchedulerLoop(log) : () => void 0;
|
|
4718
|
+
}
|
|
4719
|
+
async function showTui(options) {
|
|
4720
|
+
await runTui(options.url ?? `http://127.0.0.1:${config.port}`);
|
|
4721
|
+
process.exit(0);
|
|
4722
|
+
}
|
|
4723
|
+
async function connectTo(destination, options) {
|
|
4724
|
+
if (destination === void 0) {
|
|
4725
|
+
throw new Error("connect needs an ssh destination, for example admin@mac-mini");
|
|
4726
|
+
}
|
|
4727
|
+
process.exit(await connect({ destination, remotePort: options.remotePort, tui: options.tui }));
|
|
4728
|
+
}
|
|
4729
|
+
function listRoutines() {
|
|
4730
|
+
for (const routine of loadRoutines()) {
|
|
4731
|
+
const last = listRuns(routine.name)[0];
|
|
4732
|
+
const when = routine.schedule === null ? "manual" : describeCron(routine.schedule);
|
|
4733
|
+
console.log(
|
|
4734
|
+
[
|
|
4735
|
+
`${routine.enabled ? "\u25CF" : "\u25CB"} ${routine.name.padEnd(28)}`,
|
|
4736
|
+
routine.agent.padEnd(8),
|
|
4737
|
+
when.padEnd(32),
|
|
4738
|
+
`next ${formatTime(getNextRun(routine)).padEnd(22)}`,
|
|
4739
|
+
`last ${last ? `${last.status} ${formatTime(last.startedAt)}` : "-"}`
|
|
4740
|
+
].join(" ")
|
|
4741
|
+
);
|
|
4742
|
+
}
|
|
4743
|
+
}
|
|
4744
|
+
async function runOne(name, options) {
|
|
4745
|
+
if (name === void 0) throw new Error("run needs a routine name");
|
|
4746
|
+
ensureStateDirs();
|
|
4747
|
+
const record = await runRoutine(getRoutine2(routineNameSchema.parse(name)), {
|
|
4748
|
+
trigger: options.trigger,
|
|
4749
|
+
scheduledFor: options.scheduledFor,
|
|
4750
|
+
runId: options.runId
|
|
4751
|
+
});
|
|
4752
|
+
console.log(JSON.stringify(record, null, 2));
|
|
4753
|
+
process.exitCode = isMatching8({ status: "succeeded" }, record) ? 0 : 1;
|
|
4754
|
+
}
|
|
4755
|
+
function serve(options) {
|
|
4756
|
+
ensureStateDirs();
|
|
4757
|
+
const managed = config.managed ? ", managed by launchd" : "";
|
|
4758
|
+
log(
|
|
4759
|
+
`kombinat serve pid ${process.pid}, routines ${config.routinesDir}, state ${config.stateDir}${managed}`
|
|
4760
|
+
);
|
|
4761
|
+
installDepsIfStale(log);
|
|
4762
|
+
buildWebAppIfStale(log);
|
|
4763
|
+
const stopScheduler = startScheduler(options);
|
|
4764
|
+
const server = startServer(log);
|
|
4765
|
+
const shutdown = () => {
|
|
4766
|
+
stopScheduler();
|
|
4767
|
+
server.close();
|
|
4768
|
+
process.exit(0);
|
|
4769
|
+
};
|
|
4770
|
+
process.on("SIGTERM", shutdown);
|
|
4771
|
+
process.on("SIGINT", shutdown);
|
|
4772
|
+
if (!options.watch) return;
|
|
4773
|
+
if (config.managed) startAutoPull(log);
|
|
4774
|
+
startReloadWatchers(log, (reason) => {
|
|
4775
|
+
if (!config.managed) {
|
|
4776
|
+
log(`${reason}, restart serve to pick it up`);
|
|
4777
|
+
return;
|
|
4778
|
+
}
|
|
4779
|
+
log(`${reason}, exiting so launchd restarts with the new code`);
|
|
4780
|
+
shutdown();
|
|
4781
|
+
});
|
|
4782
|
+
}
|
|
4783
|
+
function pull() {
|
|
4784
|
+
const result = pullLatest();
|
|
4785
|
+
console.log(`${result.status}: ${result.detail}`);
|
|
4786
|
+
process.exitCode = isMatching8({ status: "failed" }, result) ? 1 : 0;
|
|
4787
|
+
}
|
|
4788
|
+
function dev(options) {
|
|
4789
|
+
const { workspaceRoot } = config;
|
|
4790
|
+
if (workspaceRoot === null)
|
|
4791
|
+
throw new Error("dev only works in a checkout of the kombinat repository");
|
|
4792
|
+
ensureStateDirs();
|
|
4793
|
+
const hadLaunchd = checkIsLaunchdLoaded();
|
|
4794
|
+
if (hadLaunchd) {
|
|
4795
|
+
stopLaunchd();
|
|
4796
|
+
log("stopped the launchd daemon, this process takes over until Ctrl-C");
|
|
4797
|
+
}
|
|
4798
|
+
const daemonFolder = hadLaunchd ? getDaemonFolder() : null;
|
|
4799
|
+
const isOtherFolder = daemonFolder !== null && daemonFolder !== config.projectRoot;
|
|
4800
|
+
if (isOtherFolder) log(`the daemon runs ${daemonFolder}, so the scheduler stays off here`);
|
|
4801
|
+
const stopScheduler = startScheduler({
|
|
4802
|
+
...options,
|
|
4803
|
+
scheduler: options.scheduler && !isOtherFolder
|
|
4804
|
+
});
|
|
4805
|
+
const server = startServer(log);
|
|
4806
|
+
const vite = spawn4("pnpm", ["-s", "--filter", "web-app", "run", "dev"], {
|
|
4807
|
+
cwd: workspaceRoot,
|
|
4808
|
+
stdio: "inherit"
|
|
4809
|
+
});
|
|
4810
|
+
let closing = false;
|
|
4811
|
+
const handBack = () => {
|
|
4812
|
+
if (closing) return;
|
|
4813
|
+
closing = true;
|
|
4814
|
+
vite.kill("SIGTERM");
|
|
4815
|
+
stopScheduler();
|
|
4816
|
+
server.close();
|
|
4817
|
+
if (hadLaunchd) {
|
|
4818
|
+
startLaunchd();
|
|
4819
|
+
log("launchd daemon started again");
|
|
4820
|
+
}
|
|
4821
|
+
process.exit(0);
|
|
4822
|
+
};
|
|
4823
|
+
process.on("SIGINT", handBack);
|
|
4824
|
+
process.on("SIGTERM", handBack);
|
|
4825
|
+
vite.on("exit", handBack);
|
|
4826
|
+
}
|
|
4827
|
+
function showStatus() {
|
|
4828
|
+
const launchd = getLaunchdStatus().split("\n").filter((line) => /state|pid|last exit|runs/.test(line)).join("\n");
|
|
4829
|
+
console.log(launchd || "not loaded");
|
|
4830
|
+
console.log(JSON.stringify(readSchedulerState(), null, 2));
|
|
4831
|
+
}
|
|
4832
|
+
function showUsage(command) {
|
|
4833
|
+
console.log(USAGE);
|
|
4834
|
+
process.exitCode = command === void 0 ? 0 : 1;
|
|
4835
|
+
}
|
|
4836
|
+
async function main() {
|
|
4837
|
+
const { positionals, values } = parseArgs({
|
|
4838
|
+
allowPositionals: true,
|
|
4839
|
+
options: {
|
|
4840
|
+
trigger: { type: "string", default: "manual" },
|
|
4841
|
+
"scheduled-for": { type: "string" },
|
|
4842
|
+
"run-id": { type: "string" },
|
|
4843
|
+
"no-watch": { type: "boolean", default: false },
|
|
4844
|
+
"no-scheduler": { type: "boolean", default: false },
|
|
4845
|
+
url: { type: "string" },
|
|
4846
|
+
port: { type: "string" },
|
|
4847
|
+
tui: { type: "boolean", default: false }
|
|
4848
|
+
}
|
|
4849
|
+
});
|
|
4850
|
+
const [command, name] = positionals;
|
|
4851
|
+
checkFlag(values.url !== void 0, "url", command, "tui");
|
|
4852
|
+
checkFlag(values.port !== void 0, "port", command, "connect");
|
|
4853
|
+
checkFlag(values.tui, "tui", command, "connect");
|
|
4854
|
+
const options = {
|
|
4855
|
+
trigger: parseTrigger(values.trigger),
|
|
4856
|
+
scheduledFor: values["scheduled-for"] ?? null,
|
|
4857
|
+
runId: values["run-id"] === void 0 ? null : parseRunId(values["run-id"]),
|
|
4858
|
+
watch: !values["no-watch"],
|
|
4859
|
+
scheduler: !values["no-scheduler"],
|
|
4860
|
+
url: values.url === void 0 ? null : parseUrl(values.url),
|
|
4861
|
+
remotePort: parsePort(values.port ?? String(DEFAULT_PORT)),
|
|
4862
|
+
tui: values.tui
|
|
4863
|
+
};
|
|
4864
|
+
await match14(command).with("tui", () => showTui(options)).with("connect", () => connectTo(name, options)).with("list", listRoutines).with("validate", () => console.log(`${loadRoutines().length} routine(s) ok`)).with(
|
|
4865
|
+
"readme",
|
|
4866
|
+
() => console.log(updateReadme() ? "README.md updated" : "README.md already up to date")
|
|
4867
|
+
).with("run", () => runOne(name, options)).with("serve", () => serve(options)).with("pull", pull).with("dev", () => dev(options)).with(
|
|
4868
|
+
"install",
|
|
4869
|
+
() => console.log(`installed ${install()}
|
|
4870
|
+
ui: http://localhost:${config.port}`)
|
|
4871
|
+
).with("uninstall", () => console.log(`removed ${uninstall()}`)).with("status", showStatus).otherwise(showUsage);
|
|
4872
|
+
}
|
|
4873
|
+
main().catch((error) => {
|
|
4874
|
+
console.error(error instanceof Error ? error.message : error);
|
|
4875
|
+
process.exit(1);
|
|
4876
|
+
});
|