@kvali/cli 0.6.8 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -5
- package/dist/claude-plugin/.claude-plugin/marketplace.json +1 -1
- package/dist/claude-plugin/.claude-plugin/plugin.json +2 -2
- package/dist/claude-plugin/README.md +6 -3
- package/dist/claude-plugin/hooks/model.ts +240 -12
- package/dist/claude-plugin/hooks/register.tsx +196 -12
- package/dist/kvali.mjs +3228 -223
- package/package.json +7 -2
package/dist/kvali.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
+
import { writeFile } from "node:fs/promises";
|
|
4
5
|
import os3 from "node:os";
|
|
5
|
-
import
|
|
6
|
+
import path19 from "node:path";
|
|
6
7
|
import process2 from "node:process";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
8
9
|
|
|
@@ -72,6 +73,29 @@ function fmtDuration(ms) {
|
|
|
72
73
|
if (h < 24) return `${h}h ${String(m % 60).padStart(2, "0")}m`;
|
|
73
74
|
return `${Math.floor(h / 24)}d ${h % 24}h`;
|
|
74
75
|
}
|
|
76
|
+
function planEta(s, now) {
|
|
77
|
+
const typical = s.current?.typicalMs;
|
|
78
|
+
if (!typical || typical <= 0) return void 0;
|
|
79
|
+
const p2 = progressOf(s.tasks);
|
|
80
|
+
const left = p2.total - p2.done;
|
|
81
|
+
if (p2.total === 0 || left <= 0) return void 0;
|
|
82
|
+
const spent = s.current ? Math.max(0, now - s.current.startedAt) : 0;
|
|
83
|
+
return Math.max(0, typical - spent) + (left - 1) * typical;
|
|
84
|
+
}
|
|
85
|
+
function fmtClock(ms) {
|
|
86
|
+
return new Date(ms).toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" });
|
|
87
|
+
}
|
|
88
|
+
function fmtAbout(ms) {
|
|
89
|
+
const m = Math.max(1, Math.round(ms / 6e4));
|
|
90
|
+
return m < 60 ? `~${m}m` : `~${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
|
|
91
|
+
}
|
|
92
|
+
function fmtEta(ms) {
|
|
93
|
+
if (ms < 6e4) return "under a minute left";
|
|
94
|
+
const m = Math.round(ms / 6e4);
|
|
95
|
+
if (m < 60) return `~${m}m left`;
|
|
96
|
+
const h = Math.floor(m / 60);
|
|
97
|
+
return m % 60 ? `~${h}h ${m % 60}m left` : `~${h}h left`;
|
|
98
|
+
}
|
|
75
99
|
function fmtAgo(at, now) {
|
|
76
100
|
const s = Math.round((now - at) / 1e3);
|
|
77
101
|
if (s < 10) return "just now";
|
|
@@ -152,6 +176,209 @@ function dayKeyLocal(ms) {
|
|
|
152
176
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
153
177
|
}
|
|
154
178
|
|
|
179
|
+
// ../core/src/limits.ts
|
|
180
|
+
var KEEP_MS = 6 * 36e5;
|
|
181
|
+
var PACE_MS = 60 * 6e4;
|
|
182
|
+
var MIN_SPAN_MS = 5 * 6e4;
|
|
183
|
+
var RESET_JITTER_MS = 5 * 6e4;
|
|
184
|
+
var SAMPLE_EVERY_MS = 5 * 6e4;
|
|
185
|
+
function runsOutAt(samples, latest, now) {
|
|
186
|
+
if (latest.usedPercent >= 100) return latest.at;
|
|
187
|
+
if (now - latest.at > PACE_MS) return void 0;
|
|
188
|
+
const recent = samples.filter((s) => s.at >= latest.at - PACE_MS && s.at <= latest.at);
|
|
189
|
+
const first = recent[0];
|
|
190
|
+
if (!first || latest.at - first.at < MIN_SPAN_MS) return void 0;
|
|
191
|
+
const rate = (latest.usedPercent - first.pct) / (latest.at - first.at);
|
|
192
|
+
if (!(rate > 0)) return void 0;
|
|
193
|
+
const out = latest.at + (100 - latest.usedPercent) / rate;
|
|
194
|
+
if (latest.resetsAt !== void 0 && out >= latest.resetsAt) return void 0;
|
|
195
|
+
return Math.round(out);
|
|
196
|
+
}
|
|
197
|
+
var LimitBook = class {
|
|
198
|
+
books = /* @__PURE__ */ new Map();
|
|
199
|
+
/** Adds a reading taken at `at`. Older readings than the window's latest are ignored. */
|
|
200
|
+
add(reading, at) {
|
|
201
|
+
if (!Number.isFinite(reading.usedPercent) || !Number.isFinite(at)) return;
|
|
202
|
+
const pct = Math.max(0, reading.usedPercent);
|
|
203
|
+
let book = this.books.get(reading.label);
|
|
204
|
+
if (book) {
|
|
205
|
+
const sameWindow = book.latest.resetsAt === void 0 || reading.resetsAt === void 0 || Math.abs(book.latest.resetsAt - reading.resetsAt) <= RESET_JITTER_MS;
|
|
206
|
+
if (!sameWindow) {
|
|
207
|
+
if (at <= book.latest.at) return;
|
|
208
|
+
book = void 0;
|
|
209
|
+
} else if (at < book.latest.at) {
|
|
210
|
+
if (at >= book.latest.at - KEEP_MS && !book.samples.some((s) => s.at === at)) {
|
|
211
|
+
book.samples.push({ at, pct });
|
|
212
|
+
book.samples.sort((a, b) => a.at - b.at);
|
|
213
|
+
}
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (!book) {
|
|
218
|
+
book = { latest: { ...reading, usedPercent: pct, at }, samples: [] };
|
|
219
|
+
this.books.set(reading.label, book);
|
|
220
|
+
}
|
|
221
|
+
const last = book.samples[book.samples.length - 1];
|
|
222
|
+
if (!last || last.pct !== pct || at - last.at >= SAMPLE_EVERY_MS) book.samples.push({ at, pct });
|
|
223
|
+
book.latest = { ...reading, usedPercent: pct, at };
|
|
224
|
+
const cutoff = at - KEEP_MS;
|
|
225
|
+
while (book.samples.length > 1 && book.samples[0].at < cutoff) book.samples.shift();
|
|
226
|
+
}
|
|
227
|
+
get size() {
|
|
228
|
+
return this.books.size;
|
|
229
|
+
}
|
|
230
|
+
/** The latest reading of each window, with when it runs out at the recent pace. Windows that have reset are dropped. */
|
|
231
|
+
windows(now) {
|
|
232
|
+
const out = [];
|
|
233
|
+
for (const [label, b] of this.books) {
|
|
234
|
+
const l = b.latest;
|
|
235
|
+
if (l.resetsAt !== void 0 && l.resetsAt <= now) {
|
|
236
|
+
this.books.delete(label);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
out.push({
|
|
240
|
+
label: l.label,
|
|
241
|
+
usedPercent: l.usedPercent,
|
|
242
|
+
resetsAt: l.resetsAt,
|
|
243
|
+
windowMinutes: l.windowMinutes,
|
|
244
|
+
at: l.at,
|
|
245
|
+
runsOutAt: runsOutAt(b.samples, l, now)
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
return out.sort((a, b) => (a.windowMinutes ?? Infinity) - (b.windowMinutes ?? Infinity));
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
function claudeWindowLabel(kind) {
|
|
252
|
+
if (kind === "five_hour") return { label: "5h", windowMinutes: 300 };
|
|
253
|
+
const week2 = /^seven_day(?:_(\w+))?$/.exec(kind);
|
|
254
|
+
if (week2) return { label: week2[1] ? `Weekly ${week2[1][0].toUpperCase()}${week2[1].slice(1)}` : "Weekly", windowMinutes: 10080 };
|
|
255
|
+
if (kind === "spend_limit") return { label: "Spend" };
|
|
256
|
+
return { label: kind.replace(/_/g, " ") };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ../core/src/week.ts
|
|
260
|
+
var WEEK_DAYS = 7;
|
|
261
|
+
function localDay(ms) {
|
|
262
|
+
const d = new Date(ms);
|
|
263
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
264
|
+
}
|
|
265
|
+
function weekDays(now) {
|
|
266
|
+
const d = new Date(now);
|
|
267
|
+
const out = [];
|
|
268
|
+
for (let i = WEEK_DAYS - 1; i >= 0; i--) out.push(localDay(new Date(d.getFullYear(), d.getMonth(), d.getDate() - i, 12).getTime()));
|
|
269
|
+
return out;
|
|
270
|
+
}
|
|
271
|
+
function weekStats(sessions, now) {
|
|
272
|
+
const days = weekDays(now).map((day) => ({ day, activeMs: 0, tokens: 0, tasksDone: 0 }));
|
|
273
|
+
const byDay = new Map(days.map((d) => [d.day, d]));
|
|
274
|
+
const since = (/* @__PURE__ */ new Date(`${days[0].day}T00:00:00`)).getTime();
|
|
275
|
+
const projects = /* @__PURE__ */ new Set();
|
|
276
|
+
const agentWork = /* @__PURE__ */ new Map();
|
|
277
|
+
let sessionsCount = 0;
|
|
278
|
+
let costUsd = 0;
|
|
279
|
+
let priced = false;
|
|
280
|
+
for (const s of sessions) {
|
|
281
|
+
let touched = false;
|
|
282
|
+
let work = 0;
|
|
283
|
+
for (const [day, u] of Object.entries(s.daily ?? {})) {
|
|
284
|
+
const d = byDay.get(day);
|
|
285
|
+
if (!d) continue;
|
|
286
|
+
touched = true;
|
|
287
|
+
d.activeMs += u.activeMs ?? 0;
|
|
288
|
+
d.tokens += u.tokens;
|
|
289
|
+
d.tasksDone += u.tasksDone ?? 0;
|
|
290
|
+
costUsd += u.costUsd;
|
|
291
|
+
work += (u.activeMs ?? 0) + 1;
|
|
292
|
+
}
|
|
293
|
+
if (!touched && !s.daily && s.updatedAt >= since) touched = true;
|
|
294
|
+
if (!touched) continue;
|
|
295
|
+
sessionsCount += 1;
|
|
296
|
+
if (s.projectPath) projects.add(s.projectPath);
|
|
297
|
+
agentWork.set(s.agentLabel, (agentWork.get(s.agentLabel) ?? 0) + work);
|
|
298
|
+
if (s.costUsd !== void 0) priced = true;
|
|
299
|
+
}
|
|
300
|
+
const sum = (k) => days.reduce((n, d) => n + d[k], 0);
|
|
301
|
+
const busiest = [...days].sort((a, b) => b.activeMs - a.activeMs)[0];
|
|
302
|
+
return {
|
|
303
|
+
days,
|
|
304
|
+
sessions: sessionsCount,
|
|
305
|
+
projects: projects.size,
|
|
306
|
+
agents: [...agentWork].sort((a, b) => b[1] - a[1]).map(([label]) => label),
|
|
307
|
+
activeMs: sum("activeMs"),
|
|
308
|
+
tasksDone: sum("tasksDone"),
|
|
309
|
+
tokens: sum("tokens"),
|
|
310
|
+
costUsd,
|
|
311
|
+
priced,
|
|
312
|
+
busiest: busiest && busiest.activeMs > 0 ? busiest : void 0
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function fmtWork(ms) {
|
|
316
|
+
const min = Math.round(ms / 6e4);
|
|
317
|
+
if (min < 60) return `${min} min`;
|
|
318
|
+
const h = ms / 36e5;
|
|
319
|
+
return h < 10 ? `${(Math.round(h * 10) / 10).toString()} h` : `${Math.round(h)} h`;
|
|
320
|
+
}
|
|
321
|
+
function weekdayShort(day) {
|
|
322
|
+
return ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(/* @__PURE__ */ new Date(`${day}T12:00:00`)).getDay()];
|
|
323
|
+
}
|
|
324
|
+
function weekRange(w) {
|
|
325
|
+
const f = (day) => (/* @__PURE__ */ new Date(`${day}T12:00:00`)).toLocaleDateString("en-US", { month: "short", day: "numeric" });
|
|
326
|
+
return `${f(w.days[0].day)} \u2013 ${f(w.days[w.days.length - 1].day)}`;
|
|
327
|
+
}
|
|
328
|
+
var KVALI_URL = "https://github.com/webGrandpa/kvali";
|
|
329
|
+
function weekShareText(w, opts = {}) {
|
|
330
|
+
const facts = [
|
|
331
|
+
w.activeMs >= 6e4 ? `${fmtWork(w.activeMs)} of agent work` : void 0,
|
|
332
|
+
w.tasksDone ? `${w.tasksDone} task${w.tasksDone === 1 ? "" : "s"} done` : void 0,
|
|
333
|
+
w.tokens ? `${fmtTokens(w.tokens)} tokens` : void 0,
|
|
334
|
+
opts.cost && w.priced && w.costUsd > 0 ? `${fmtUsd(w.costUsd)} at API prices` : void 0
|
|
335
|
+
].filter(Boolean);
|
|
336
|
+
const who = w.agents.length ? ` with ${w.agents.length === 1 ? w.agents[0] : `${w.agents.slice(0, -1).join(", ")} and ${w.agents[w.agents.length - 1]}`}` : "";
|
|
337
|
+
return `My AI coding agents this week${who}: ${facts.join(", ") || "getting started"}.
|
|
338
|
+
|
|
339
|
+
Tracked with Kvali, an open-source progress bar for AI agents: ${KVALI_URL}`;
|
|
340
|
+
}
|
|
341
|
+
var esc = (t) => t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
342
|
+
function weekSvg(w, opts = {}) {
|
|
343
|
+
const W = 1200;
|
|
344
|
+
const H = 630;
|
|
345
|
+
const font = `font-family="Inter, 'Segoe UI', -apple-system, Helvetica, Arial, sans-serif"`;
|
|
346
|
+
const max = Math.max(1, ...w.days.map((d) => d.activeMs));
|
|
347
|
+
const bars = w.days.map((d, i) => {
|
|
348
|
+
const h = Math.round(d.activeMs / max * 150);
|
|
349
|
+
const x = 760 + i * 58;
|
|
350
|
+
return `<rect x="${x}" y="${470 - h}" width="38" height="${Math.max(4, h)}" rx="8" fill="url(#pulse)" opacity="${d.activeMs ? 1 : 0.25}"/>
|
|
351
|
+
<text x="${x + 19}" y="500" text-anchor="middle" font-size="18" fill="#8b93a7" ${font}>${weekdayShort(d.day)}</text>`;
|
|
352
|
+
}).join("\n");
|
|
353
|
+
const stats = [
|
|
354
|
+
[String(w.tasksDone), "tasks done"],
|
|
355
|
+
[fmtTokens(w.tokens), "tokens"],
|
|
356
|
+
...opts.cost && w.priced && w.costUsd > 0 ? [[fmtUsd(w.costUsd), "API value"]] : [],
|
|
357
|
+
[String(w.agents.length), w.agents.length === 1 ? "agent" : "agents"]
|
|
358
|
+
].map(([v, l], i) => {
|
|
359
|
+
const x = 80 + i * 165;
|
|
360
|
+
return `<text x="${x}" y="470" font-size="44" font-weight="700" fill="#f0f3f8" ${font}>${esc(v)}</text><text x="${x}" y="502" font-size="20" fill="#8b93a7" ${font}>${esc(l)}</text>`;
|
|
361
|
+
}).join("\n");
|
|
362
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
|
|
363
|
+
<defs>
|
|
364
|
+
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#1d2129"/><stop offset="1" stop-color="#0e1014"/></linearGradient>
|
|
365
|
+
<linearGradient id="pulse" x1="0" y1="1" x2="0" y2="0"><stop offset="0" stop-color="#5aa2ff"/><stop offset="1" stop-color="#b58cf0"/></linearGradient>
|
|
366
|
+
<linearGradient id="line" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#e8875b"/><stop offset="0.35" stop-color="#b58cf0"/><stop offset="0.7" stop-color="#5aa2ff"/><stop offset="1" stop-color="#6fd18a"/></linearGradient>
|
|
367
|
+
</defs>
|
|
368
|
+
<rect width="${W}" height="${H}" fill="url(#bg)"/>
|
|
369
|
+
<g transform="translate(80 64) scale(0.5)"><rect width="128" height="128" rx="28" fill="#262a33"/><path d="M18 54h17l10-22 15 42 12-30 8 10h30" fill="none" stroke="url(#line)" stroke-width="8" stroke-linecap="round" stroke-linejoin="round"/></g>
|
|
370
|
+
<text x="160" y="108" font-size="34" font-weight="700" fill="#f0f3f8" ${font}>Kvali</text>
|
|
371
|
+
<text x="80" y="200" font-size="28" fill="#8b93a7" ${font}>My AI agents this week \xB7 ${esc(weekRange(w))}</text>
|
|
372
|
+
<text x="80" y="330" font-size="128" font-weight="800" fill="#f0f3f8" ${font}>${esc(fmtWork(w.activeMs))}</text>
|
|
373
|
+
<text x="80" y="380" font-size="30" fill="#c7cede" ${font}>of agent work${w.agents.length ? ` \xB7 ${esc(w.agents.join(" \xB7 "))}` : ""}</text>
|
|
374
|
+
${stats}
|
|
375
|
+
${bars}
|
|
376
|
+
<rect x="80" y="560" width="1040" height="2" fill="url(#line)" opacity="0.6"/>
|
|
377
|
+
<text x="80" y="600" font-size="22" fill="#8b93a7" ${font}>See what your AI agents are doing \xB7 github.com/webGrandpa/kvali</text>
|
|
378
|
+
</svg>
|
|
379
|
+
`;
|
|
380
|
+
}
|
|
381
|
+
|
|
155
382
|
// ../core/src/pricing.ts
|
|
156
383
|
var p = (input, cacheWrite5m, cacheWrite1h, cacheRead, output) => ({
|
|
157
384
|
input,
|
|
@@ -196,7 +423,7 @@ function anthropicModelKey(model) {
|
|
|
196
423
|
let m = model.toLowerCase();
|
|
197
424
|
const at = m.indexOf("claude");
|
|
198
425
|
if (at === -1) return void 0;
|
|
199
|
-
m = m.slice(at).replace(/\[[^\]]*\]/g, "").replace(/@.*$/, "");
|
|
426
|
+
m = m.slice(at).replace(/\[[^\]]*\]/g, "").replace(/@.*$/, "").replace(/(\d)\.(\d)/g, "$1-$2");
|
|
200
427
|
let r = /^claude-(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2}))?(?=-|$|:)/.exec(m);
|
|
201
428
|
if (r) return `${r[1]}-${r[2]}${r[3] ? `-${r[3]}` : ""}`;
|
|
202
429
|
r = /^claude-(\d+)(?:-(\d{1,2}))?-(opus|sonnet|haiku)/.exec(m);
|
|
@@ -254,8 +481,8 @@ var JsonlTail = class {
|
|
|
254
481
|
mtimeMs = -1;
|
|
255
482
|
ino;
|
|
256
483
|
path;
|
|
257
|
-
constructor(
|
|
258
|
-
this.path =
|
|
484
|
+
constructor(path20) {
|
|
485
|
+
this.path = path20;
|
|
259
486
|
}
|
|
260
487
|
/** Byte offset of the first unconsumed byte. */
|
|
261
488
|
get position() {
|
|
@@ -366,7 +593,7 @@ function staleness(updatedAt, ctx) {
|
|
|
366
593
|
|
|
367
594
|
// ../core/src/engine.ts
|
|
368
595
|
import os from "node:os";
|
|
369
|
-
import
|
|
596
|
+
import path11 from "node:path";
|
|
370
597
|
|
|
371
598
|
// ../core/src/adapters/antigravity.ts
|
|
372
599
|
import path2 from "node:path";
|
|
@@ -551,6 +778,11 @@ var TaskTimer = class {
|
|
|
551
778
|
steps = 0;
|
|
552
779
|
fileStarted = /* @__PURE__ */ new Map();
|
|
553
780
|
fileDurations = [];
|
|
781
|
+
onDone;
|
|
782
|
+
/** `onDone` hears each step the plan finishes, with when (for the day's count). */
|
|
783
|
+
constructor(onDone) {
|
|
784
|
+
this.onDone = onDone;
|
|
785
|
+
}
|
|
554
786
|
/** Feed the full task list whenever it changes, with the time of the change. */
|
|
555
787
|
observe(tasks, at) {
|
|
556
788
|
for (const t of tasks) {
|
|
@@ -562,6 +794,7 @@ var TaskTimer = class {
|
|
|
562
794
|
const s = this.started.get(key2);
|
|
563
795
|
if (s !== void 0 && at >= s) this.durations.push(at - s);
|
|
564
796
|
}
|
|
797
|
+
if (t.status === "completed" && prev !== void 0) this.onDone?.(at);
|
|
565
798
|
this.status.set(key2, t.status);
|
|
566
799
|
}
|
|
567
800
|
const cur = tasks.find((t) => t.status === "in_progress");
|
|
@@ -611,6 +844,16 @@ function parseTime(value) {
|
|
|
611
844
|
}
|
|
612
845
|
return void 0;
|
|
613
846
|
}
|
|
847
|
+
var WORK_GAP_MS = 15 * 6e4;
|
|
848
|
+
function addWork(daily, from, to) {
|
|
849
|
+
if (from === void 0 || !(to > from) || to - from > WORK_GAP_MS) return;
|
|
850
|
+
const b = daily[dayKey(to)] ??= { tokens: 0, costUsd: 0 };
|
|
851
|
+
b.activeMs = (b.activeMs ?? 0) + (to - from);
|
|
852
|
+
}
|
|
853
|
+
function addTaskDone(daily, at) {
|
|
854
|
+
const b = daily[dayKey(at)] ??= { tokens: 0, costUsd: 0 };
|
|
855
|
+
b.tasksDone = (b.tasksDone ?? 0) + 1;
|
|
856
|
+
}
|
|
614
857
|
function dayKey(ms) {
|
|
615
858
|
const d = new Date(ms);
|
|
616
859
|
const m = String(d.getMonth() + 1).padStart(2, "0");
|
|
@@ -731,6 +974,7 @@ var AntigravityAdapter = class {
|
|
|
731
974
|
return out;
|
|
732
975
|
}
|
|
733
976
|
blank(id, dir) {
|
|
977
|
+
const daily = {};
|
|
734
978
|
return {
|
|
735
979
|
id,
|
|
736
980
|
dir,
|
|
@@ -740,8 +984,9 @@ var AntigravityAdapter = class {
|
|
|
740
984
|
projectVotesAt: -1,
|
|
741
985
|
steps: 0,
|
|
742
986
|
turnSteps: 0,
|
|
743
|
-
timer: new TaskTimer(),
|
|
744
|
-
recent: []
|
|
987
|
+
timer: new TaskTimer((at) => addTaskDone(daily, at)),
|
|
988
|
+
recent: [],
|
|
989
|
+
daily
|
|
745
990
|
};
|
|
746
991
|
}
|
|
747
992
|
async discover(ctx) {
|
|
@@ -770,11 +1015,13 @@ var AntigravityAdapter = class {
|
|
|
770
1015
|
const o = rec;
|
|
771
1016
|
const at = parseTime(o.created_at) ?? st.updatedAt;
|
|
772
1017
|
st.steps += 1;
|
|
1018
|
+
const type = String(o.type ?? "");
|
|
773
1019
|
if (at) {
|
|
774
1020
|
if (st.startedAt === void 0 || at < st.startedAt) st.startedAt = at;
|
|
775
1021
|
if (at > st.updatedAt) st.updatedAt = at;
|
|
1022
|
+
if (type !== "USER_INPUT") addWork(st.daily, st.lastStepAt, at);
|
|
1023
|
+
if (st.lastStepAt === void 0 || at > st.lastStepAt) st.lastStepAt = at;
|
|
776
1024
|
}
|
|
777
|
-
const type = String(o.type ?? "");
|
|
778
1025
|
const status = String(o.status ?? "");
|
|
779
1026
|
const source = String(o.source ?? "");
|
|
780
1027
|
const tools = [];
|
|
@@ -921,6 +1168,7 @@ var AntigravityAdapter = class {
|
|
|
921
1168
|
updatedAt: st.updatedAt,
|
|
922
1169
|
tasks,
|
|
923
1170
|
activity,
|
|
1171
|
+
daily: Object.keys(st.daily).length ? st.daily : void 0,
|
|
924
1172
|
sources: [path2.join(st.dir, "task.md"), st.tail.path]
|
|
925
1173
|
};
|
|
926
1174
|
}
|
|
@@ -928,6 +1176,63 @@ var AntigravityAdapter = class {
|
|
|
928
1176
|
|
|
929
1177
|
// ../core/src/adapters/claude-code.ts
|
|
930
1178
|
import path3 from "node:path";
|
|
1179
|
+
|
|
1180
|
+
// ../core/src/util/loop-watch.ts
|
|
1181
|
+
var SAME_ERROR_RUNS = 4;
|
|
1182
|
+
var ANY_ERROR_RUNS = 8;
|
|
1183
|
+
var FORGET_MS = 30 * 6e4;
|
|
1184
|
+
function errorSignature(text) {
|
|
1185
|
+
const tail = text.slice(-600).toLowerCase().replace(/\d+(?:\.\d+)?/g, "#").replace(/\s+/g, " ").trim();
|
|
1186
|
+
let h = 2166136261;
|
|
1187
|
+
for (let i = 0; i < tail.length; i++) {
|
|
1188
|
+
h ^= tail.charCodeAt(i);
|
|
1189
|
+
h = Math.imul(h, 16777619);
|
|
1190
|
+
}
|
|
1191
|
+
return (h >>> 0).toString(36);
|
|
1192
|
+
}
|
|
1193
|
+
var LoopWatch = class {
|
|
1194
|
+
streaks = /* @__PURE__ */ new Map();
|
|
1195
|
+
/**
|
|
1196
|
+
* One finished call. `key` names the action ("command:pnpm test", "Edit:src/a.ts"); `error`
|
|
1197
|
+
* is the failure's text, or undefined when the call worked, which ends that action's streak.
|
|
1198
|
+
*/
|
|
1199
|
+
observe(key, what, error, at, tokens) {
|
|
1200
|
+
if (error === void 0) {
|
|
1201
|
+
this.streaks.delete(key);
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
const sig = errorSignature(error);
|
|
1205
|
+
const s = this.streaks.get(key);
|
|
1206
|
+
if (!s || at - s.last > FORGET_MS) {
|
|
1207
|
+
this.streaks.set(key, { label: what.label, detail: what.detail, count: 1, same: 1, sig, since: at, last: at, tokens });
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
s.count += 1;
|
|
1211
|
+
s.same = s.sig === sig ? s.same + 1 : 1;
|
|
1212
|
+
s.sig = sig;
|
|
1213
|
+
s.last = at;
|
|
1214
|
+
s.label = what.label;
|
|
1215
|
+
}
|
|
1216
|
+
/** The person spoke (or stopped the agent): whatever it was stuck on is theirs to judge now. */
|
|
1217
|
+
reset() {
|
|
1218
|
+
this.streaks.clear();
|
|
1219
|
+
}
|
|
1220
|
+
/** The longest streak that counts as a loop, if any. */
|
|
1221
|
+
current(now) {
|
|
1222
|
+
let best;
|
|
1223
|
+
for (const s of this.streaks.values()) {
|
|
1224
|
+
if (now - s.last > FORGET_MS) continue;
|
|
1225
|
+
if (s.same < SAME_ERROR_RUNS && s.count < ANY_ERROR_RUNS) continue;
|
|
1226
|
+
if (!best || s.count > best.count) best = s;
|
|
1227
|
+
}
|
|
1228
|
+
return best ? { label: best.label, detail: best.detail, count: best.count, sameError: best.same >= SAME_ERROR_RUNS, since: best.since, tokensAtStart: best.tokens } : void 0;
|
|
1229
|
+
}
|
|
1230
|
+
};
|
|
1231
|
+
function loopKey(a) {
|
|
1232
|
+
return a.kind === "command" ? `command:${a.detail ?? a.label}` : `${a.label}:${a.detail ?? ""}`;
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
// ../core/src/adapters/claude-code.ts
|
|
931
1236
|
var PULSE_FRESH_MS = 3e4;
|
|
932
1237
|
var PULSE_ACTIVE = /* @__PURE__ */ new Set(["requesting", "thinking", "writing", "tool-input", "running", "needs-you", "stalled"]);
|
|
933
1238
|
var WAITING_NOTIFICATIONS = /* @__PURE__ */ new Set([
|
|
@@ -1033,6 +1338,8 @@ var ClaudeCodeAdapter = class {
|
|
|
1033
1338
|
dirCache = /* @__PURE__ */ new Map();
|
|
1034
1339
|
lastDiscovery = 0;
|
|
1035
1340
|
lastFullScan = 0;
|
|
1341
|
+
/** The subscription's usage windows, from every session's plugin heartbeat. */
|
|
1342
|
+
limitBook = new LimitBook();
|
|
1036
1343
|
configDir(ctx) {
|
|
1037
1344
|
const fromEnv = ctx.env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim();
|
|
1038
1345
|
return fromEnv || path3.join(ctx.home, ".claude");
|
|
@@ -1109,6 +1416,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1109
1416
|
for (const file of [...this.legacyAgents.keys()]) if (!keepLegacy.has(file)) this.legacyAgents.delete(file);
|
|
1110
1417
|
}
|
|
1111
1418
|
createState(file) {
|
|
1419
|
+
const daily = {};
|
|
1112
1420
|
return {
|
|
1113
1421
|
file,
|
|
1114
1422
|
sessionId: path3.basename(file, ".jsonl"),
|
|
@@ -1118,7 +1426,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1118
1426
|
tokens: emptyTokens(),
|
|
1119
1427
|
costUsd: 0,
|
|
1120
1428
|
pricedAll: true,
|
|
1121
|
-
daily
|
|
1429
|
+
daily,
|
|
1122
1430
|
maxContext: 0,
|
|
1123
1431
|
tasks: /* @__PURE__ */ new Map(),
|
|
1124
1432
|
pendingCreates: /* @__PURE__ */ new Map(),
|
|
@@ -1130,7 +1438,8 @@ var ClaudeCodeAdapter = class {
|
|
|
1130
1438
|
turnOpen: false,
|
|
1131
1439
|
subagents: /* @__PURE__ */ new Map(),
|
|
1132
1440
|
background: /* @__PURE__ */ new Map(),
|
|
1133
|
-
|
|
1441
|
+
loops: new LoopWatch(),
|
|
1442
|
+
timer: new TaskTimer((at) => addTaskDone(daily, at)),
|
|
1134
1443
|
recent: [],
|
|
1135
1444
|
lastSubagentScan: 0
|
|
1136
1445
|
};
|
|
@@ -1147,8 +1456,12 @@ var ClaudeCodeAdapter = class {
|
|
|
1147
1456
|
if (ts !== void 0) {
|
|
1148
1457
|
if (st.startedAt === void 0 || ts < st.startedAt) st.startedAt = ts;
|
|
1149
1458
|
if (ts > st.updatedAt) st.updatedAt = ts;
|
|
1459
|
+
const agentWrote = o.type === "assistant" && !o.isSidechain || o.type === "user" && Array.isArray(o.message?.content) && o.message.content.some((b) => b?.type === "tool_result");
|
|
1460
|
+
if (agentWrote) addWork(st.daily, st.lastRecordAt, ts);
|
|
1461
|
+
if (st.lastRecordAt === void 0 || ts > st.lastRecordAt) st.lastRecordAt = ts;
|
|
1150
1462
|
}
|
|
1151
1463
|
if (typeof o.version === "string") st.version = o.version;
|
|
1464
|
+
if (typeof o.entrypoint === "string") st.entrypoint = o.entrypoint;
|
|
1152
1465
|
if (typeof o.cwd === "string" && o.cwd) {
|
|
1153
1466
|
st.cwd = o.cwd;
|
|
1154
1467
|
st.launchCwd ??= o.cwd;
|
|
@@ -1346,7 +1659,10 @@ var ClaudeCodeAdapter = class {
|
|
|
1346
1659
|
st.pendingCreates.delete(b.tool_use_id);
|
|
1347
1660
|
}
|
|
1348
1661
|
const done = st.open.get(b.tool_use_id);
|
|
1349
|
-
if (done)
|
|
1662
|
+
if (done) {
|
|
1663
|
+
done.endedAt = ts;
|
|
1664
|
+
st.loops.observe(loopKey(done), done, b.is_error === true ? contentText(b.content) || "error" : void 0, ts, totalTokens(st.tokens));
|
|
1665
|
+
}
|
|
1350
1666
|
st.open.delete(b.tool_use_id);
|
|
1351
1667
|
}
|
|
1352
1668
|
const launched = o.toolUseResult;
|
|
@@ -1377,6 +1693,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1377
1693
|
st.phase = "interrupted";
|
|
1378
1694
|
st.phaseAt = ts;
|
|
1379
1695
|
st.open.clear();
|
|
1696
|
+
st.loops.reset();
|
|
1380
1697
|
this.endTurn(st, ts, void 0);
|
|
1381
1698
|
return;
|
|
1382
1699
|
}
|
|
@@ -1392,6 +1709,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1392
1709
|
st.turnStartedAt = ts;
|
|
1393
1710
|
st.turnOpen = true;
|
|
1394
1711
|
st.turnEndedBy = void 0;
|
|
1712
|
+
st.loops.reset();
|
|
1395
1713
|
}
|
|
1396
1714
|
if (!isCommand) {
|
|
1397
1715
|
st.phase = "working";
|
|
@@ -1443,6 +1761,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1443
1761
|
else if (pst.mtimeMs !== st.pulse?.mtimeMs) {
|
|
1444
1762
|
const pulse = await readJsonSafe(pulseFile);
|
|
1445
1763
|
st.pulse = pulse && typeof pulse.at === "number" && typeof pulse.phase === "string" ? { ...pulse, mtimeMs: pst.mtimeMs } : void 0;
|
|
1764
|
+
if (st.pulse?.limits) this.addLimits(st.pulse.limits);
|
|
1446
1765
|
}
|
|
1447
1766
|
const now = ctx.now();
|
|
1448
1767
|
if (now - st.lastSubagentScan >= 5e3) {
|
|
@@ -1460,6 +1779,27 @@ var ClaudeCodeAdapter = class {
|
|
|
1460
1779
|
}
|
|
1461
1780
|
for (const [, sub] of st.subagents) await sub.tail.read((rec) => this.onRecord(st, rec, ctx, true));
|
|
1462
1781
|
}
|
|
1782
|
+
/** The subscription's windows (account-wide), as any session's plugin reported them. */
|
|
1783
|
+
limits(ctx) {
|
|
1784
|
+
const windows = this.limitBook.windows(ctx.now());
|
|
1785
|
+
return windows.length ? { agent: this.id, agentLabel: this.label, windows } : void 0;
|
|
1786
|
+
}
|
|
1787
|
+
addLimits(l) {
|
|
1788
|
+
if (typeof l.at !== "number" || !Array.isArray(l.windows)) return;
|
|
1789
|
+
for (const w of l.windows) {
|
|
1790
|
+
if (!w || typeof w.kind !== "string" || typeof w.percentUsed !== "number") continue;
|
|
1791
|
+
const { label, windowMinutes } = claudeWindowLabel(w.kind);
|
|
1792
|
+
const reset = typeof w.resetsAt === "string" ? Date.parse(w.resetsAt) : w.resetsAt;
|
|
1793
|
+
const resetsAt = typeof reset === "number" && Number.isFinite(reset) ? reset : void 0;
|
|
1794
|
+
const series = l.samples?.[w.kind];
|
|
1795
|
+
if (Array.isArray(series)) {
|
|
1796
|
+
for (const pt of series) {
|
|
1797
|
+
if (Array.isArray(pt) && typeof pt[0] === "number" && typeof pt[1] === "number") this.limitBook.add({ label, usedPercent: pt[1], resetsAt, windowMinutes }, pt[0]);
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
this.limitBook.add({ label, usedPercent: w.percentUsed, resetsAt, windowMinutes }, l.at);
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1463
1803
|
/** Older Claude Code versions wrote subagents as top-level agent-*.jsonl files that reference the parent session. */
|
|
1464
1804
|
async readLegacyAgents(ctx) {
|
|
1465
1805
|
if (this.legacyAgents.size === 0) return;
|
|
@@ -1506,7 +1846,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1506
1846
|
status = allDone ? "done" : "idle";
|
|
1507
1847
|
}
|
|
1508
1848
|
let lastSignal = st.updatedAt;
|
|
1509
|
-
const live = st.live;
|
|
1849
|
+
const live = st.pulse ? void 0 : st.live;
|
|
1510
1850
|
if (live?.at && live.at >= st.phaseAt - 1e3) {
|
|
1511
1851
|
lastSignal = Math.max(lastSignal, live.at);
|
|
1512
1852
|
const type = live.notificationType;
|
|
@@ -1576,6 +1916,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1576
1916
|
const ownTitle = st.customTitle || st.aiTitle || st.summary;
|
|
1577
1917
|
const title = ownTitle || st.firstPrompt || "Untitled session";
|
|
1578
1918
|
let activity = status === "working" ? background ?? st.activity : void 0;
|
|
1919
|
+
const loop = status === "working" || status === "stale" ? st.loops.current(now) : void 0;
|
|
1579
1920
|
if (status === "working" && st.phase === "tool" && st.open.size > 0) activity = [...st.open.values()].pop();
|
|
1580
1921
|
return {
|
|
1581
1922
|
key: `claude-code:${st.sessionId}`,
|
|
@@ -1588,6 +1929,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1588
1929
|
cwd: st.launchCwd,
|
|
1589
1930
|
model: st.model,
|
|
1590
1931
|
agentVersion: st.version,
|
|
1932
|
+
host: st.entrypoint === void 0 ? void 0 : st.entrypoint === "cli" ? "terminal" : /vscode|jetbrains|ide/.test(st.entrypoint) ? "editor" : "app",
|
|
1591
1933
|
status,
|
|
1592
1934
|
statusDetail: detail,
|
|
1593
1935
|
startedAt: st.startedAt,
|
|
@@ -1602,6 +1944,14 @@ var ClaudeCodeAdapter = class {
|
|
|
1602
1944
|
turns: st.turns,
|
|
1603
1945
|
turn: st.turnStartedAt !== void 0 ? { steps: st.turnSteps, startedAt: st.turnStartedAt } : void 0,
|
|
1604
1946
|
current: status === "working" || status === "waiting" || status === "stale" ? st.timer.current(tasks) : void 0,
|
|
1947
|
+
loop: loop ? {
|
|
1948
|
+
label: loop.label,
|
|
1949
|
+
detail: loop.detail,
|
|
1950
|
+
count: loop.count,
|
|
1951
|
+
sameError: loop.sameError,
|
|
1952
|
+
since: loop.since,
|
|
1953
|
+
tokens: loop.tokensAtStart !== void 0 ? totalTokens(st.tokens) - loop.tokensAtStart : void 0
|
|
1954
|
+
} : void 0,
|
|
1605
1955
|
recent: st.recent.slice(0, 5),
|
|
1606
1956
|
trouble: status === "working" || status === "stale" ? st.trouble : void 0,
|
|
1607
1957
|
pulse,
|
|
@@ -1611,8 +1961,947 @@ var ClaudeCodeAdapter = class {
|
|
|
1611
1961
|
}
|
|
1612
1962
|
};
|
|
1613
1963
|
|
|
1614
|
-
// ../core/src/adapters/
|
|
1964
|
+
// ../core/src/adapters/cline.ts
|
|
1965
|
+
import path5 from "node:path";
|
|
1966
|
+
import { promises as fsp3 } from "node:fs";
|
|
1967
|
+
|
|
1968
|
+
// ../core/src/util/editors.ts
|
|
1615
1969
|
import path4 from "node:path";
|
|
1970
|
+
var EDITOR_APPS = [
|
|
1971
|
+
"Code",
|
|
1972
|
+
"Code - Insiders",
|
|
1973
|
+
"Code - OSS",
|
|
1974
|
+
"VSCodium",
|
|
1975
|
+
"VSCodium - Insiders",
|
|
1976
|
+
"Cursor",
|
|
1977
|
+
"Windsurf",
|
|
1978
|
+
"Windsurf - Next",
|
|
1979
|
+
"Antigravity",
|
|
1980
|
+
"Trae",
|
|
1981
|
+
"Kiro",
|
|
1982
|
+
"Positron",
|
|
1983
|
+
"Void"
|
|
1984
|
+
];
|
|
1985
|
+
var SERVER_DIRS = [
|
|
1986
|
+
".vscode-server",
|
|
1987
|
+
".vscode-server-insiders",
|
|
1988
|
+
".vscodium-server",
|
|
1989
|
+
".cursor-server",
|
|
1990
|
+
".windsurf-server",
|
|
1991
|
+
".antigravity-server",
|
|
1992
|
+
".trae-server",
|
|
1993
|
+
".kiro-server",
|
|
1994
|
+
".positron-server"
|
|
1995
|
+
];
|
|
1996
|
+
function editorUserDataDirs(home, env, platform = process.platform) {
|
|
1997
|
+
const out = [];
|
|
1998
|
+
if (env.VSCODE_PORTABLE) out.push(path4.join(env.VSCODE_PORTABLE, "user-data"));
|
|
1999
|
+
const base = platform === "darwin" ? path4.join(home, "Library", "Application Support") : platform === "win32" ? env.APPDATA ?? path4.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME ?? path4.join(home, ".config");
|
|
2000
|
+
for (const app of EDITOR_APPS) out.push(path4.join(base, app));
|
|
2001
|
+
for (const dir of SERVER_DIRS) out.push(path4.join(home, dir, "data"));
|
|
2002
|
+
return out;
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
// ../core/src/adapters/cline.ts
|
|
2006
|
+
var WAIT_ASKS = {
|
|
2007
|
+
followup: () => "Asked you a question",
|
|
2008
|
+
plan_mode_respond: () => "Plan ready for your review",
|
|
2009
|
+
act_mode_respond: () => "Waiting for your reply",
|
|
2010
|
+
command: (m) => `Needs approval: run ${summarizeCommand(stripReqApp(m.text ?? ""), 60) ?? "a command"}`,
|
|
2011
|
+
tool: (m) => `Needs approval: ${toolActivity(m)?.label ?? "a tool"}`,
|
|
2012
|
+
use_mcp_server: (m) => `Needs approval: ${toolActivity(m)?.label ?? "an MCP tool"}`,
|
|
2013
|
+
browser_action_launch: () => "Needs approval: open the browser",
|
|
2014
|
+
use_subagents: () => "Needs approval: start subagents",
|
|
2015
|
+
new_task: () => "Wants to start a new task",
|
|
2016
|
+
condense: () => "Wants to condense the conversation",
|
|
2017
|
+
summarize_task: () => "Wants to summarize the task",
|
|
2018
|
+
report_bug: () => "Wants to report a bug",
|
|
2019
|
+
auto_approval_max_req_reached: (_m, label) => `${label} reached its auto-approve limit`
|
|
2020
|
+
};
|
|
2021
|
+
var QUIET_SAYS = /* @__PURE__ */ new Set([
|
|
2022
|
+
"checkpoint_created",
|
|
2023
|
+
"checkpoint_saved",
|
|
2024
|
+
"hook_status",
|
|
2025
|
+
"hook_output_stream",
|
|
2026
|
+
"conditional_rules_applied",
|
|
2027
|
+
"api_req_finished",
|
|
2028
|
+
"shell_integration_warning",
|
|
2029
|
+
"shell_integration_warning_with_suggestion",
|
|
2030
|
+
"too_many_tools_warning",
|
|
2031
|
+
"info"
|
|
2032
|
+
]);
|
|
2033
|
+
var FAILURE_SAYS = /* @__PURE__ */ new Set(["error", "diff_error", "clineignore_error", "rooignore_error", "command_permission_denied"]);
|
|
2034
|
+
var ASK_GRACE_MS = 3e3;
|
|
2035
|
+
function parseJson(text) {
|
|
2036
|
+
if (!text || text[0] !== "{" && text[0] !== "[") return void 0;
|
|
2037
|
+
try {
|
|
2038
|
+
return JSON.parse(text);
|
|
2039
|
+
} catch {
|
|
2040
|
+
return void 0;
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
function stripReqApp(cmd) {
|
|
2044
|
+
return cmd.replace(/\s*REQ_APP\s*$/, "");
|
|
2045
|
+
}
|
|
2046
|
+
var TOOL_LABELS = {
|
|
2047
|
+
editedExistingFile: "Edit",
|
|
2048
|
+
appliedDiff: "Edit",
|
|
2049
|
+
insertContent: "Edit",
|
|
2050
|
+
searchAndReplace: "Edit",
|
|
2051
|
+
newFileCreated: "Write",
|
|
2052
|
+
fileDeleted: "Delete",
|
|
2053
|
+
readFile: "Read",
|
|
2054
|
+
readCommandOutput: "Read output",
|
|
2055
|
+
listFilesTopLevel: "List files",
|
|
2056
|
+
listFilesRecursive: "List files",
|
|
2057
|
+
listCodeDefinitionNames: "List definitions",
|
|
2058
|
+
searchFiles: "Search",
|
|
2059
|
+
codebaseSearch: "Search codebase",
|
|
2060
|
+
webFetch: "Fetch",
|
|
2061
|
+
webSearch: "Web search",
|
|
2062
|
+
summarizeTask: "Summarize",
|
|
2063
|
+
useSkill: "Skill",
|
|
2064
|
+
skill: "Skill",
|
|
2065
|
+
switchMode: "Switch mode",
|
|
2066
|
+
newTask: "Start a subtask",
|
|
2067
|
+
finishTask: "Finish subtask",
|
|
2068
|
+
generateImage: "Generate image",
|
|
2069
|
+
imageGenerated: "Generate image",
|
|
2070
|
+
runSlashCommand: "Slash command",
|
|
2071
|
+
updateTodoList: "Update plan"
|
|
2072
|
+
};
|
|
2073
|
+
function toolActivity(m) {
|
|
2074
|
+
const kind = m.type === "ask" ? m.ask : m.say;
|
|
2075
|
+
const at = m.ts;
|
|
2076
|
+
switch (kind) {
|
|
2077
|
+
case "command": {
|
|
2078
|
+
const cmd = stripReqApp(m.text ?? "");
|
|
2079
|
+
return { kind: "command", label: "Shell", detail: summarizeCommand(cmd), startedAt: at };
|
|
2080
|
+
}
|
|
2081
|
+
case "tool": {
|
|
2082
|
+
const t = parseJson(m.text);
|
|
2083
|
+
if (!t || typeof t.tool !== "string") return void 0;
|
|
2084
|
+
const label = TOOL_LABELS[t.tool] ?? t.tool;
|
|
2085
|
+
const target = typeof t.path === "string" ? t.path : typeof t.regex === "string" ? t.regex : typeof t.query === "string" ? t.query : void 0;
|
|
2086
|
+
return { kind: "tool", label, detail: target ? truncate(target, 80) : void 0, startedAt: at };
|
|
2087
|
+
}
|
|
2088
|
+
case "use_mcp_server": {
|
|
2089
|
+
const t = parseJson(m.text);
|
|
2090
|
+
if (!t) return { kind: "tool", label: "MCP", startedAt: at };
|
|
2091
|
+
const server = typeof t.serverName === "string" ? t.serverName : "MCP";
|
|
2092
|
+
const what = t.type === "access_mcp_resource" ? "resource" : typeof t.toolName === "string" ? t.toolName : "tool";
|
|
2093
|
+
return { kind: "tool", label: `${server}: ${what}`, detail: typeof t.uri === "string" ? truncate(t.uri, 80) : void 0, startedAt: at };
|
|
2094
|
+
}
|
|
2095
|
+
case "browser_action_launch":
|
|
2096
|
+
return { kind: "tool", label: "Browser", detail: m.text ? truncate(m.text, 80) : void 0, startedAt: at };
|
|
2097
|
+
case "browser_action": {
|
|
2098
|
+
const t = parseJson(m.text);
|
|
2099
|
+
return { kind: "tool", label: "Browser", detail: typeof t?.action === "string" ? t.action : void 0, startedAt: at };
|
|
2100
|
+
}
|
|
2101
|
+
case "use_subagents": {
|
|
2102
|
+
const t = parseJson(m.text);
|
|
2103
|
+
const n = Array.isArray(t?.prompts) ? t.prompts.length : 0;
|
|
2104
|
+
return { kind: "subagent", label: "Subagents", detail: n ? `${n} subagent${n === 1 ? "" : "s"}` : void 0, startedAt: at };
|
|
2105
|
+
}
|
|
2106
|
+
default:
|
|
2107
|
+
return void 0;
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
function todoStatus(s) {
|
|
2111
|
+
return s === "completed" ? "completed" : s === "in_progress" ? "in_progress" : "pending";
|
|
2112
|
+
}
|
|
2113
|
+
function withCurrentStep(tasks) {
|
|
2114
|
+
if (tasks.some((t) => t.status === "in_progress")) return tasks;
|
|
2115
|
+
const next = tasks.findIndex((t) => t.status === "pending");
|
|
2116
|
+
if (next === -1) return tasks;
|
|
2117
|
+
return tasks.map((t, i) => i === next ? { ...t, status: "in_progress" } : t);
|
|
2118
|
+
}
|
|
2119
|
+
function foldClineMessages(messages, flavor, pricing) {
|
|
2120
|
+
const daily = {};
|
|
2121
|
+
const tokens = emptyTokens();
|
|
2122
|
+
let costUsd = 0;
|
|
2123
|
+
const fold = {
|
|
2124
|
+
startedAt: 0,
|
|
2125
|
+
lastTs: 0,
|
|
2126
|
+
tokens,
|
|
2127
|
+
daily,
|
|
2128
|
+
tasks: [],
|
|
2129
|
+
timer: new TaskTimer((at) => addTaskDone(daily, at)),
|
|
2130
|
+
recent: [],
|
|
2131
|
+
loops: new LoopWatch(),
|
|
2132
|
+
turns: 0
|
|
2133
|
+
};
|
|
2134
|
+
let prevTs;
|
|
2135
|
+
let pending;
|
|
2136
|
+
let turnStart;
|
|
2137
|
+
let steps = 0;
|
|
2138
|
+
const settle = () => {
|
|
2139
|
+
if (pending && !pending.failed) fold.loops.observe(pending.key, pending.what, void 0, pending.what.startedAt);
|
|
2140
|
+
pending = void 0;
|
|
2141
|
+
};
|
|
2142
|
+
for (let i = 0; i < messages.length; i += 1) {
|
|
2143
|
+
const m = messages[i];
|
|
2144
|
+
if (!m || typeof m !== "object" || typeof m.ts !== "number") continue;
|
|
2145
|
+
const kind = m.type === "ask" ? m.ask : m.say;
|
|
2146
|
+
if (!fold.startedAt || m.ts < fold.startedAt) fold.startedAt = m.ts;
|
|
2147
|
+
if (m.ts > fold.lastTs) fold.lastTs = m.ts;
|
|
2148
|
+
if (m.modelInfo?.modelId) fold.model = m.modelInfo.modelId;
|
|
2149
|
+
const fromPerson = i === 0 || kind === "user_feedback" || kind === "user_feedback_diff";
|
|
2150
|
+
if (i === 0 && m.type === "say" && (kind === "task" || kind === "text") && m.text?.trim()) fold.title = firstLine(m.text, 100);
|
|
2151
|
+
if (fromPerson) {
|
|
2152
|
+
turnStart = m.ts;
|
|
2153
|
+
steps = 0;
|
|
2154
|
+
fold.turns += 1;
|
|
2155
|
+
fold.loops.reset();
|
|
2156
|
+
pending = void 0;
|
|
2157
|
+
prevTs = m.ts;
|
|
2158
|
+
} else if (kind !== "resume_task" && kind !== "resume_completed_task") {
|
|
2159
|
+
addWork(daily, prevTs, m.ts);
|
|
2160
|
+
prevTs = Math.max(prevTs ?? 0, m.ts);
|
|
2161
|
+
}
|
|
2162
|
+
if (m.type === "say" && (kind === "api_req_started" || kind === "deleted_api_reqs" || kind === "api_req_deleted")) {
|
|
2163
|
+
const info = parseJson(m.text);
|
|
2164
|
+
if (info && (info.tokensIn !== void 0 || info.tokensOut !== void 0 || info.cost !== void 0)) {
|
|
2165
|
+
const cacheReads = Number(info.cacheReads) || 0;
|
|
2166
|
+
const cacheWrites = Number(info.cacheWrites) || 0;
|
|
2167
|
+
let input = Number(info.tokensIn) || 0;
|
|
2168
|
+
if (flavor === "roo" && info.apiProtocol !== void 0) input = Math.max(0, input - cacheReads - cacheWrites);
|
|
2169
|
+
const output = Number(info.tokensOut) || 0;
|
|
2170
|
+
tokens.input += input;
|
|
2171
|
+
tokens.output += output;
|
|
2172
|
+
tokens.cacheRead += cacheReads;
|
|
2173
|
+
tokens.cacheWrite += cacheWrites;
|
|
2174
|
+
let cost = typeof info.cost === "number" && Number.isFinite(info.cost) ? info.cost : void 0;
|
|
2175
|
+
if (cost === void 0) cost = pricing.cost(fold.model, { input, output, cacheRead: cacheReads, cacheWrite5m: cacheWrites, cacheWrite1h: 0 });
|
|
2176
|
+
if (cost === void 0) {
|
|
2177
|
+
if (input + output > 0) costUsd = void 0;
|
|
2178
|
+
} else if (costUsd !== void 0) costUsd += cost;
|
|
2179
|
+
const b = daily[dayKey(m.ts)] ??= { tokens: 0, costUsd: 0 };
|
|
2180
|
+
b.tokens += input + output + cacheReads + cacheWrites;
|
|
2181
|
+
b.costUsd += cost ?? 0;
|
|
2182
|
+
if (kind === "api_req_started" && input + cacheReads + cacheWrites > 0) fold.context = input + cacheReads + cacheWrites;
|
|
2183
|
+
}
|
|
2184
|
+
} else if (kind === "condense_context" && typeof m.contextCondense?.cost === "number") {
|
|
2185
|
+
if (costUsd !== void 0) costUsd += m.contextCondense.cost;
|
|
2186
|
+
const b = daily[dayKey(m.ts)] ??= { tokens: 0, costUsd: 0 };
|
|
2187
|
+
b.costUsd += m.contextCondense.cost;
|
|
2188
|
+
}
|
|
2189
|
+
if (!m.partial) {
|
|
2190
|
+
let plan;
|
|
2191
|
+
if (kind === "task_progress" && m.text) plan = withCurrentStep(parseChecklist(m.text).tasks);
|
|
2192
|
+
else if (kind === "tool" && m.type === "ask" || kind === "user_edit_todos") {
|
|
2193
|
+
const t2 = parseJson(m.text);
|
|
2194
|
+
if (t2?.tool === "updateTodoList" && Array.isArray(t2.todos)) {
|
|
2195
|
+
plan = t2.todos.map((todo, n) => ({
|
|
2196
|
+
id: typeof todo?.id === "string" ? todo.id : String(n + 1),
|
|
2197
|
+
title: String(todo?.content ?? ""),
|
|
2198
|
+
status: todoStatus(todo?.status)
|
|
2199
|
+
}));
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
if (plan) {
|
|
2203
|
+
fold.tasks = plan;
|
|
2204
|
+
fold.timer.observe(plan, m.ts);
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
const act = m.partial ? void 0 : toolActivity(m);
|
|
2208
|
+
if (act) {
|
|
2209
|
+
settle();
|
|
2210
|
+
steps += 1;
|
|
2211
|
+
fold.timer.step();
|
|
2212
|
+
pending = { key: loopKey(act), what: act, failed: false };
|
|
2213
|
+
if (fold.recent[0]) fold.recent[0].endedAt ??= m.ts;
|
|
2214
|
+
fold.recent.unshift(act);
|
|
2215
|
+
if (fold.recent.length > 6) fold.recent.length = 6;
|
|
2216
|
+
} else if (m.type === "say" && kind && FAILURE_SAYS.has(kind) && pending && !pending.failed) {
|
|
2217
|
+
pending.failed = true;
|
|
2218
|
+
fold.loops.observe(pending.key, pending.what, m.text || kind, m.ts, totalTokens(tokens));
|
|
2219
|
+
} else if (kind === "api_req_started" && fold.recent[0] && fold.recent[0].endedAt === void 0) {
|
|
2220
|
+
fold.recent[0].endedAt = m.ts;
|
|
2221
|
+
}
|
|
2222
|
+
if (m.type === "ask" && kind && WAIT_ASKS[kind] && !m.partial) prevTs = void 0;
|
|
2223
|
+
if (!(m.type === "say" && kind && QUIET_SAYS.has(kind))) fold.tail = m;
|
|
2224
|
+
}
|
|
2225
|
+
settle();
|
|
2226
|
+
fold.costUsd = costUsd;
|
|
2227
|
+
if (turnStart !== void 0) fold.turn = { steps, startedAt: turnStart };
|
|
2228
|
+
const t = fold.tail;
|
|
2229
|
+
if (t?.type === "say" && t.say === "api_req_started") fold.tailRequest = parseJson(t.text);
|
|
2230
|
+
return fold;
|
|
2231
|
+
}
|
|
2232
|
+
function clineStatus(fold, label, now) {
|
|
2233
|
+
const t = fold.tail;
|
|
2234
|
+
if (!t) return { status: "idle" };
|
|
2235
|
+
const kind = t.type === "ask" ? t.ask : t.say;
|
|
2236
|
+
const prog = progressOf(fold.tasks);
|
|
2237
|
+
const finished = (detail) => prog.total > 0 && prog.done < prog.total ? { status: "idle", detail } : { status: "done", detail };
|
|
2238
|
+
const working = (detail, trouble) => ({ status: "working", detail, trouble, activity: fold.recent[0] });
|
|
2239
|
+
if (t.type === "ask" && kind) {
|
|
2240
|
+
if (t.partial) return working();
|
|
2241
|
+
const wait = WAIT_ASKS[kind];
|
|
2242
|
+
if (wait) {
|
|
2243
|
+
if (t.isAnswered || now - t.ts < ASK_GRACE_MS) return working();
|
|
2244
|
+
return { status: "waiting", detail: wait(t, label), activity: kind === "command" || kind === "tool" || kind === "use_mcp_server" ? toolActivity(t) : void 0 };
|
|
2245
|
+
}
|
|
2246
|
+
switch (kind) {
|
|
2247
|
+
case "command_output":
|
|
2248
|
+
return working("Running a command");
|
|
2249
|
+
case "completion_result":
|
|
2250
|
+
case "resume_completed_task":
|
|
2251
|
+
return finished("Task completed");
|
|
2252
|
+
case "resume_task":
|
|
2253
|
+
return { status: "idle", detail: "Paused" };
|
|
2254
|
+
case "api_req_failed":
|
|
2255
|
+
return { status: "error", detail: firstLine(t.text || "The API request failed", 140) };
|
|
2256
|
+
case "mistake_limit_reached":
|
|
2257
|
+
return { status: "error", detail: `${label} stopped after repeated mistakes and asks for guidance` };
|
|
2258
|
+
default:
|
|
2259
|
+
return working();
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
switch (kind) {
|
|
2263
|
+
case "api_req_started": {
|
|
2264
|
+
const info = fold.tailRequest;
|
|
2265
|
+
if (info?.cancelReason === "user_cancelled") return { status: "idle", detail: "Stopped" };
|
|
2266
|
+
if (info?.cancelReason === "streaming_failed" || info?.cancelReason === "retries_exhausted") {
|
|
2267
|
+
return { status: "error", detail: firstLine(info.streamingFailedMessage || "The request failed", 140) };
|
|
2268
|
+
}
|
|
2269
|
+
if (info?.retryStatus) {
|
|
2270
|
+
const r = info.retryStatus;
|
|
2271
|
+
return working(void 0, {
|
|
2272
|
+
message: firstLine(r.errorSnippet || "Retrying the request", 120),
|
|
2273
|
+
at: t.ts,
|
|
2274
|
+
attempt: r.attempt,
|
|
2275
|
+
maxAttempts: r.maxAttempts
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
return working();
|
|
2279
|
+
}
|
|
2280
|
+
case "api_req_retry_delayed":
|
|
2281
|
+
return working(void 0, { message: firstLine((t.text ?? "").replace(/<retry_timer>\d+<\/retry_timer>/g, "").trim() || "Retrying the request", 120), at: t.ts });
|
|
2282
|
+
case "api_req_rate_limit_wait":
|
|
2283
|
+
return working(void 0, { message: "Waiting out a rate limit", at: t.ts });
|
|
2284
|
+
case "completion_result":
|
|
2285
|
+
return finished("Task completed");
|
|
2286
|
+
default:
|
|
2287
|
+
return working();
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
var SWEEP_MS = 3e4;
|
|
2291
|
+
var DISCOVERY_MS = 5e3;
|
|
2292
|
+
var MODEL_CHECK_MS = 15e3;
|
|
2293
|
+
var BIG_FILE_BYTES = 8 << 20;
|
|
2294
|
+
var BIG_FILE_EVERY_MS = 1e4;
|
|
2295
|
+
var HISTORY_EVERY_MS = 15e3;
|
|
2296
|
+
var ClineFamilyAdapter = class {
|
|
2297
|
+
options;
|
|
2298
|
+
stores = /* @__PURE__ */ new Map();
|
|
2299
|
+
tracked = /* @__PURE__ */ new Map();
|
|
2300
|
+
lastDiscovery = 0;
|
|
2301
|
+
lastRootScan = 0;
|
|
2302
|
+
constructor(options = {}) {
|
|
2303
|
+
this.options = options;
|
|
2304
|
+
}
|
|
2305
|
+
/** Folders outside the editors that hold the agent's `tasks/` (Cline's standalone builds). */
|
|
2306
|
+
standaloneDirs(_ctx) {
|
|
2307
|
+
return [];
|
|
2308
|
+
}
|
|
2309
|
+
/** A setting that moves the storage (Roo Code's `customStoragePath`), read from the editors' settings. */
|
|
2310
|
+
customStorageDirs(_ctx) {
|
|
2311
|
+
return Promise.resolve([]);
|
|
2312
|
+
}
|
|
2313
|
+
async poll(ctx) {
|
|
2314
|
+
const now = ctx.now();
|
|
2315
|
+
if (now - this.lastRootScan >= 6e4 || this.stores.size === 0) {
|
|
2316
|
+
this.lastRootScan = now;
|
|
2317
|
+
await this.findStores(ctx);
|
|
2318
|
+
}
|
|
2319
|
+
if (now - this.lastDiscovery >= DISCOVERY_MS || this.tracked.size === 0) {
|
|
2320
|
+
this.lastDiscovery = now;
|
|
2321
|
+
await this.discover(ctx);
|
|
2322
|
+
}
|
|
2323
|
+
const out = [];
|
|
2324
|
+
const byId = /* @__PURE__ */ new Map();
|
|
2325
|
+
for (const t of this.tracked.values()) {
|
|
2326
|
+
await this.refresh(t, ctx);
|
|
2327
|
+
if (!t.fold) continue;
|
|
2328
|
+
const s = this.toSession(t, ctx);
|
|
2329
|
+
if (s) {
|
|
2330
|
+
out.push(s);
|
|
2331
|
+
byId.set(t.id, s);
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
for (const t of this.tracked.values()) {
|
|
2335
|
+
const child = t.history?.value?.delegatedToId ?? t.history?.value?.awaitingChildId;
|
|
2336
|
+
const s = byId.get(t.id);
|
|
2337
|
+
if (!s || typeof child !== "string" || t.history?.value?.status !== "delegated") continue;
|
|
2338
|
+
const c = byId.get(child);
|
|
2339
|
+
if (c && (c.status === "working" || c.status === "waiting")) {
|
|
2340
|
+
s.status = "working";
|
|
2341
|
+
s.statusDetail = "A subtask is running";
|
|
2342
|
+
s.activity = { kind: "subagent", label: "Subtask", detail: truncate(c.title, 80), startedAt: c.startedAt };
|
|
2343
|
+
s.activeSubagents = 1;
|
|
2344
|
+
} else {
|
|
2345
|
+
s.status = "idle";
|
|
2346
|
+
s.statusDetail = "Waits for its subtask";
|
|
2347
|
+
s.activity = void 0;
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
return out;
|
|
2351
|
+
}
|
|
2352
|
+
/** The extension folders that exist, in every editor and profile. */
|
|
2353
|
+
async findStores(ctx) {
|
|
2354
|
+
const dirs = /* @__PURE__ */ new Set();
|
|
2355
|
+
const storageRoots = [];
|
|
2356
|
+
for (const userData of editorUserDataDirs(ctx.home, ctx.env, this.options.platform)) {
|
|
2357
|
+
const user = path5.join(userData, "User");
|
|
2358
|
+
storageRoots.push(path5.join(user, "globalStorage"));
|
|
2359
|
+
for (const p2 of await listDir(path5.join(user, "profiles"))) if (p2.isDirectory()) storageRoots.push(path5.join(user, "profiles", p2.name, "globalStorage"));
|
|
2360
|
+
}
|
|
2361
|
+
for (const extra of this.options.extraStorageDirs ?? []) storageRoots.push(extra);
|
|
2362
|
+
for (const root of storageRoots) {
|
|
2363
|
+
for (const e of await listDir(root)) {
|
|
2364
|
+
if (e.isDirectory() && this.extensions.includes(e.name.toLowerCase())) dirs.add(path5.join(root, e.name));
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
for (const d of this.standaloneDirs(ctx)) dirs.add(d);
|
|
2368
|
+
for (const d of await this.customStorageDirs(ctx)) dirs.add(d);
|
|
2369
|
+
for (const d of dirs) if (!this.stores.has(d)) this.stores.set(d, { dir: d, seen: /* @__PURE__ */ new Map(), lastSweep: 0, indexMtime: -1 });
|
|
2370
|
+
for (const d of [...this.stores.keys()]) if (!dirs.has(d)) this.stores.delete(d);
|
|
2371
|
+
}
|
|
2372
|
+
/** Which tasks changed recently: a new folder at once, the others every 30 s or when the task list changed. */
|
|
2373
|
+
async discover(ctx) {
|
|
2374
|
+
const now = ctx.now();
|
|
2375
|
+
const found = [];
|
|
2376
|
+
for (const store of this.stores.values()) {
|
|
2377
|
+
const tasksDir = path5.join(store.dir, "tasks");
|
|
2378
|
+
const names = (await listDir(tasksDir)).filter((e) => e.isDirectory() && !e.name.startsWith(".") && !e.name.startsWith("_")).map((e) => e.name);
|
|
2379
|
+
const index = this.flavor === "roo" ? path5.join(tasksDir, "_index.json") : path5.join(store.dir, "state", "taskHistory.json");
|
|
2380
|
+
const indexMtime = (await statSafe(index))?.mtimeMs ?? 0;
|
|
2381
|
+
const sweep = now - store.lastSweep >= SWEEP_MS || indexMtime !== store.indexMtime;
|
|
2382
|
+
if (sweep) {
|
|
2383
|
+
store.lastSweep = now;
|
|
2384
|
+
store.indexMtime = indexMtime;
|
|
2385
|
+
}
|
|
2386
|
+
const present = new Set(names);
|
|
2387
|
+
for (const id of [...store.seen.keys()]) if (!present.has(id)) store.seen.delete(id);
|
|
2388
|
+
const toStat = names.filter((id) => sweep || !store.seen.has(id));
|
|
2389
|
+
for (let i = 0; i < toStat.length; i += 64) {
|
|
2390
|
+
await Promise.all(
|
|
2391
|
+
toStat.slice(i, i + 64).map(async (id) => {
|
|
2392
|
+
const st = await statSafe(path5.join(tasksDir, id, "ui_messages.json"));
|
|
2393
|
+
store.seen.set(id, st?.mtimeMs ?? 0);
|
|
2394
|
+
})
|
|
2395
|
+
);
|
|
2396
|
+
}
|
|
2397
|
+
for (const [id, mtimeMs] of store.seen) if (mtimeMs && now - mtimeMs <= ctx.activeWindowMs) found.push({ store, id, mtimeMs });
|
|
2398
|
+
}
|
|
2399
|
+
found.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
2400
|
+
const keep = new Map(found.slice(0, ctx.maxSessionsPerAgent).map((f) => [path5.join(f.store.dir, "tasks", f.id), f]));
|
|
2401
|
+
for (const [dir, f] of keep) {
|
|
2402
|
+
if (this.tracked.has(dir)) continue;
|
|
2403
|
+
this.tracked.set(dir, { id: f.id, dir, file: path5.join(dir, "ui_messages.json"), mtimeMs: -1, size: -1, readAt: 0, store: f.store });
|
|
2404
|
+
}
|
|
2405
|
+
for (const dir of [...this.tracked.keys()]) if (!keep.has(dir)) this.tracked.delete(dir);
|
|
2406
|
+
}
|
|
2407
|
+
/** Re-reads what changed: the messages, and the side files that say where the task runs. */
|
|
2408
|
+
async refresh(t, ctx) {
|
|
2409
|
+
const st = await statSafe(t.file);
|
|
2410
|
+
const due = !t.fold || st === void 0 || st.size < BIG_FILE_BYTES || ctx.now() - t.readAt >= BIG_FILE_EVERY_MS;
|
|
2411
|
+
if (st && due && (st.mtimeMs !== t.mtimeMs || st.size !== t.size)) {
|
|
2412
|
+
t.readAt = ctx.now();
|
|
2413
|
+
const text = await readTextSafe(t.file, 128 << 20);
|
|
2414
|
+
if (text !== void 0) {
|
|
2415
|
+
try {
|
|
2416
|
+
const messages = JSON.parse(text);
|
|
2417
|
+
if (Array.isArray(messages)) {
|
|
2418
|
+
t.fold = foldClineMessages(messages, this.flavor, ctx.pricing);
|
|
2419
|
+
t.mtimeMs = st.mtimeMs;
|
|
2420
|
+
t.size = st.size;
|
|
2421
|
+
t.store.seen.set(t.id, st.mtimeMs);
|
|
2422
|
+
}
|
|
2423
|
+
} catch {
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
if (this.flavor === "roo") {
|
|
2428
|
+
const hf = path5.join(t.dir, "history_item.json");
|
|
2429
|
+
const hs = await statSafe(hf);
|
|
2430
|
+
if (hs && hs.mtimeMs !== t.history?.mtimeMs) {
|
|
2431
|
+
const value = await readJsonSafe(hf, 4 << 20);
|
|
2432
|
+
if (value) t.history = { mtimeMs: hs.mtimeMs, value };
|
|
2433
|
+
}
|
|
2434
|
+
const now = ctx.now();
|
|
2435
|
+
if (!t.modelFile || now - t.modelFile.checkedAt >= MODEL_CHECK_MS) {
|
|
2436
|
+
const mf = path5.join(t.dir, "api_conversation_history.json");
|
|
2437
|
+
const ms = await statSafe(mf);
|
|
2438
|
+
const prev = t.modelFile;
|
|
2439
|
+
t.modelFile = { mtimeMs: ms?.mtimeMs ?? 0, checkedAt: now, model: prev?.model };
|
|
2440
|
+
if (ms && ms.mtimeMs !== prev?.mtimeMs) t.modelFile.model = await lastModelIn(mf, ms.size) ?? prev?.model;
|
|
2441
|
+
}
|
|
2442
|
+
} else {
|
|
2443
|
+
await this.readClineHistory(t.store, t.id, ctx.now());
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
/** Cline's task list, re-read when it changes (or sooner for a task it did not list yet). */
|
|
2447
|
+
async readClineHistory(store, id, now) {
|
|
2448
|
+
if (store.history && store.history.byId.has(id) && now - store.history.readAt < HISTORY_EVERY_MS) return;
|
|
2449
|
+
if (store.history && now - store.history.readAt < 2e3) return;
|
|
2450
|
+
const file = path5.join(store.dir, "state", "taskHistory.json");
|
|
2451
|
+
const st = await statSafe(file);
|
|
2452
|
+
if (!st || st.mtimeMs === store.history?.mtimeMs) return;
|
|
2453
|
+
const items = await readJsonSafe(file, 64 << 20);
|
|
2454
|
+
if (!Array.isArray(items)) return;
|
|
2455
|
+
const byId = /* @__PURE__ */ new Map();
|
|
2456
|
+
for (const it of items) {
|
|
2457
|
+
if (it && typeof it.id === "string") {
|
|
2458
|
+
byId.set(it.id, {
|
|
2459
|
+
cwd: typeof it.cwdOnTaskInitialization === "string" ? it.cwdOnTaskInitialization : void 0,
|
|
2460
|
+
model: typeof it.modelId === "string" ? it.modelId : void 0
|
|
2461
|
+
});
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
store.history = { mtimeMs: st.mtimeMs, readAt: now, byId };
|
|
2465
|
+
}
|
|
2466
|
+
info(t) {
|
|
2467
|
+
if (this.flavor === "roo") {
|
|
2468
|
+
const h2 = t.history?.value;
|
|
2469
|
+
return { cwd: typeof h2?.workspace === "string" && h2.workspace ? h2.workspace : void 0, model: t.modelFile?.model };
|
|
2470
|
+
}
|
|
2471
|
+
const h = t.store.history?.byId.get(t.id);
|
|
2472
|
+
return { cwd: h?.cwd, model: h?.model };
|
|
2473
|
+
}
|
|
2474
|
+
toSession(t, ctx) {
|
|
2475
|
+
const f = t.fold;
|
|
2476
|
+
if (!f || !f.startedAt) return void 0;
|
|
2477
|
+
const info = this.info(t);
|
|
2478
|
+
const now = ctx.now();
|
|
2479
|
+
let { status, detail, trouble, activity } = clineStatus(f, this.label, now);
|
|
2480
|
+
const updatedAt = Math.max(f.lastTs, t.mtimeMs > 0 ? Math.min(t.mtimeMs, now) : 0);
|
|
2481
|
+
if (status === "working") {
|
|
2482
|
+
const stale = staleness(updatedAt, ctx);
|
|
2483
|
+
if (stale) {
|
|
2484
|
+
status = "stale";
|
|
2485
|
+
detail = stale;
|
|
2486
|
+
activity = void 0;
|
|
2487
|
+
trouble = void 0;
|
|
2488
|
+
}
|
|
2489
|
+
} else if (status !== "waiting") activity = void 0;
|
|
2490
|
+
const loop = status === "working" || status === "stale" ? f.loops.current(now) : void 0;
|
|
2491
|
+
const cwd = info.cwd;
|
|
2492
|
+
return {
|
|
2493
|
+
key: `${this.id}:${t.id}`,
|
|
2494
|
+
agent: this.id,
|
|
2495
|
+
agentLabel: this.label,
|
|
2496
|
+
id: t.id,
|
|
2497
|
+
title: f.title ?? "Untitled task",
|
|
2498
|
+
titleFromPrompt: f.title !== void 0 ? true : void 0,
|
|
2499
|
+
projectPath: cwd ? findGitRoot(cwd) ?? cwd : void 0,
|
|
2500
|
+
cwd,
|
|
2501
|
+
model: f.model ?? info.model,
|
|
2502
|
+
host: "editor",
|
|
2503
|
+
status,
|
|
2504
|
+
statusDetail: detail,
|
|
2505
|
+
startedAt: f.startedAt,
|
|
2506
|
+
updatedAt,
|
|
2507
|
+
tasks: f.tasks,
|
|
2508
|
+
activity,
|
|
2509
|
+
turn: f.turn,
|
|
2510
|
+
turns: f.turns,
|
|
2511
|
+
current: status === "working" || status === "stale" ? f.timer.current(f.tasks) : void 0,
|
|
2512
|
+
recent: f.recent.slice(0, 5),
|
|
2513
|
+
loop: loop ? {
|
|
2514
|
+
label: loop.label,
|
|
2515
|
+
detail: loop.detail,
|
|
2516
|
+
count: loop.count,
|
|
2517
|
+
sameError: loop.sameError,
|
|
2518
|
+
since: loop.since,
|
|
2519
|
+
tokens: loop.tokensAtStart !== void 0 ? totalTokens(f.tokens) - loop.tokensAtStart : void 0
|
|
2520
|
+
} : void 0,
|
|
2521
|
+
trouble,
|
|
2522
|
+
tokens: { ...f.tokens },
|
|
2523
|
+
costUsd: f.costUsd,
|
|
2524
|
+
daily: f.daily,
|
|
2525
|
+
context: f.context ? { used: f.context } : void 0,
|
|
2526
|
+
sources: [t.file]
|
|
2527
|
+
};
|
|
2528
|
+
}
|
|
2529
|
+
};
|
|
2530
|
+
async function lastModelIn(file, size) {
|
|
2531
|
+
const len = Math.min(size, 512 << 10);
|
|
2532
|
+
if (len <= 0) return void 0;
|
|
2533
|
+
let fh;
|
|
2534
|
+
try {
|
|
2535
|
+
fh = await fsp3.open(file, "r");
|
|
2536
|
+
const buf = Buffer.alloc(len);
|
|
2537
|
+
await fh.read(buf, 0, len, size - len);
|
|
2538
|
+
const text = buf.toString("utf8");
|
|
2539
|
+
const all = [...text.matchAll(/<model>([^<]{1,200})<\/model>/g)];
|
|
2540
|
+
return all.length ? all[all.length - 1][1].trim() : void 0;
|
|
2541
|
+
} catch {
|
|
2542
|
+
return void 0;
|
|
2543
|
+
} finally {
|
|
2544
|
+
await fh?.close().catch(() => {
|
|
2545
|
+
});
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
function clineDataDir(home, env) {
|
|
2549
|
+
if (env.CLINE_DATA_DIR) return env.CLINE_DATA_DIR;
|
|
2550
|
+
if (env.CLINE_DIR) return path5.join(env.CLINE_DIR, "data");
|
|
2551
|
+
return path5.join(home, ".cline", "data");
|
|
2552
|
+
}
|
|
2553
|
+
var ClineAdapter = class extends ClineFamilyAdapter {
|
|
2554
|
+
id = "cline";
|
|
2555
|
+
label = "Cline";
|
|
2556
|
+
flavor = "cline";
|
|
2557
|
+
extensions = ["saoudrizwan.claude-dev", "saoudrizwan.cline-nightly"];
|
|
2558
|
+
sdk = new ClineSdkSessions();
|
|
2559
|
+
standaloneDirs(ctx) {
|
|
2560
|
+
return [clineDataDir(ctx.home, ctx.env)];
|
|
2561
|
+
}
|
|
2562
|
+
async poll(ctx) {
|
|
2563
|
+
return [...await super.poll(ctx), ...await this.sdk.poll(ctx, this.label)];
|
|
2564
|
+
}
|
|
2565
|
+
};
|
|
2566
|
+
var RooCodeAdapter = class extends ClineFamilyAdapter {
|
|
2567
|
+
id = "roo-code";
|
|
2568
|
+
label = "Roo Code";
|
|
2569
|
+
flavor = "roo";
|
|
2570
|
+
extensions = ["rooveterinaryinc.roo-cline", "rooveterinaryinc.roo-code-nightly"];
|
|
2571
|
+
/** `roo-cline.customStoragePath` in the editors' user settings moves the whole folder. */
|
|
2572
|
+
async customStorageDirs(ctx) {
|
|
2573
|
+
const out = [];
|
|
2574
|
+
for (const userData of editorUserDataDirs(ctx.home, ctx.env, this.options.platform)) {
|
|
2575
|
+
const text = await readTextSafe(path5.join(userData, "User", "settings.json"), 2 << 20);
|
|
2576
|
+
const m = text && /"roo-cline\.customStoragePath"\s*:\s*"((?:[^"\\]|\\.)+)"/.exec(text);
|
|
2577
|
+
if (m) {
|
|
2578
|
+
try {
|
|
2579
|
+
out.push(JSON.parse(`"${m[1]}"`));
|
|
2580
|
+
} catch {
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
return out;
|
|
2585
|
+
}
|
|
2586
|
+
};
|
|
2587
|
+
var SDK_TOOL_LABELS = {
|
|
2588
|
+
read_files: "Read",
|
|
2589
|
+
search_codebase: "Search",
|
|
2590
|
+
run_commands: "Shell",
|
|
2591
|
+
fetch_web_content: "Fetch",
|
|
2592
|
+
apply_patch: "Edit",
|
|
2593
|
+
editor: "Edit",
|
|
2594
|
+
skills: "Skill",
|
|
2595
|
+
ask_question: "Question",
|
|
2596
|
+
submit_and_exit: "Finishing",
|
|
2597
|
+
attempt_completion: "Finishing",
|
|
2598
|
+
execute_command: "Shell",
|
|
2599
|
+
read_file: "Read",
|
|
2600
|
+
write_to_file: "Write",
|
|
2601
|
+
replace_in_file: "Edit"
|
|
2602
|
+
};
|
|
2603
|
+
function sdkActivity(block, at) {
|
|
2604
|
+
const name = String(block.name ?? "tool");
|
|
2605
|
+
const input = block.input && typeof block.input === "object" ? block.input : {};
|
|
2606
|
+
if (name === "run_commands" || name === "execute_command") {
|
|
2607
|
+
const cmds = Array.isArray(input.commands) ? input.commands : [input.command];
|
|
2608
|
+
const first = cmds[0];
|
|
2609
|
+
const text = typeof first === "string" ? first : first && typeof first === "object" ? [first.command, ...Array.isArray(first.args) ? first.args : []].join(" ") : void 0;
|
|
2610
|
+
return { kind: "command", label: "Shell", detail: summarizeCommand(text), startedAt: at };
|
|
2611
|
+
}
|
|
2612
|
+
const mcp = /^(.+?)__(.+)$/.exec(name);
|
|
2613
|
+
if (mcp) return { kind: "tool", label: `${mcp[1]}: ${mcp[2]}`, startedAt: at };
|
|
2614
|
+
const files = Array.isArray(input.files) ? input.files : void 0;
|
|
2615
|
+
const target = typeof input.path === "string" ? input.path : typeof files?.[0]?.path === "string" ? files[0].path : typeof input.query === "string" ? input.query : void 0;
|
|
2616
|
+
return { kind: "tool", label: SDK_TOOL_LABELS[name] ?? name, detail: target ? truncate(target, 80) : void 0, startedAt: at };
|
|
2617
|
+
}
|
|
2618
|
+
function sdkFailure(result) {
|
|
2619
|
+
if (result.is_error) return contentText(result.content) || (typeof result.content === "string" ? result.content : "Tool error");
|
|
2620
|
+
let content = result.content;
|
|
2621
|
+
if (typeof content === "string" && content.startsWith("[")) {
|
|
2622
|
+
try {
|
|
2623
|
+
content = JSON.parse(content);
|
|
2624
|
+
} catch {
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
if (!Array.isArray(content)) return void 0;
|
|
2628
|
+
const failed = content.find((c) => c && typeof c === "object" && c.success === false);
|
|
2629
|
+
return failed ? String(failed.error ?? failed.result ?? "Command failed") : void 0;
|
|
2630
|
+
}
|
|
2631
|
+
function sdkUserText(content) {
|
|
2632
|
+
const text = contentText(content);
|
|
2633
|
+
const m = /<user_input[^>]*>([\s\S]*?)<\/user_input>/.exec(text);
|
|
2634
|
+
return (m ? m[1] : text).trim();
|
|
2635
|
+
}
|
|
2636
|
+
function foldClineSdkMessages(messages) {
|
|
2637
|
+
const daily = {};
|
|
2638
|
+
const fold = { lastTs: 0, tokens: emptyTokens(), costUsd: 0, daily, recent: [], turns: 0, loops: new LoopWatch() };
|
|
2639
|
+
const calls = /* @__PURE__ */ new Map();
|
|
2640
|
+
let prevTs;
|
|
2641
|
+
let steps = 0;
|
|
2642
|
+
let turnStart;
|
|
2643
|
+
for (const m of messages) {
|
|
2644
|
+
if (!m || typeof m !== "object") continue;
|
|
2645
|
+
const ts = parseTime(m.ts) ?? 0;
|
|
2646
|
+
if (ts) {
|
|
2647
|
+
if (fold.startedAt === void 0 || ts < fold.startedAt) fold.startedAt = ts;
|
|
2648
|
+
if (ts > fold.lastTs) fold.lastTs = ts;
|
|
2649
|
+
}
|
|
2650
|
+
const blocks = Array.isArray(m.content) ? m.content.filter((b) => b && typeof b === "object") : [];
|
|
2651
|
+
const meta = m.metadata && typeof m.metadata === "object" ? m.metadata : {};
|
|
2652
|
+
if (m.role === "user") {
|
|
2653
|
+
const results = blocks.filter((b) => b.type === "tool_result");
|
|
2654
|
+
if (results.length === 0 && !meta.kind) {
|
|
2655
|
+
const text = sdkUserText(m.content);
|
|
2656
|
+
if (text) {
|
|
2657
|
+
if (!fold.title) fold.title = firstLine(text, 100);
|
|
2658
|
+
turnStart = ts || turnStart;
|
|
2659
|
+
steps = 0;
|
|
2660
|
+
fold.turns += 1;
|
|
2661
|
+
fold.loops.reset();
|
|
2662
|
+
prevTs = ts || prevTs;
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
for (const r of results) {
|
|
2666
|
+
const act = calls.get(String(r.tool_use_id));
|
|
2667
|
+
if (!act) continue;
|
|
2668
|
+
act.endedAt ??= ts || void 0;
|
|
2669
|
+
fold.loops.observe(loopKey(act), act, sdkFailure(r), ts, totalTokens(fold.tokens));
|
|
2670
|
+
}
|
|
2671
|
+
if (results.length && ts) {
|
|
2672
|
+
addWork(daily, prevTs, ts);
|
|
2673
|
+
prevTs = Math.max(prevTs ?? 0, ts);
|
|
2674
|
+
}
|
|
2675
|
+
continue;
|
|
2676
|
+
}
|
|
2677
|
+
if (m.role !== "assistant") continue;
|
|
2678
|
+
if (ts) {
|
|
2679
|
+
addWork(daily, prevTs, ts);
|
|
2680
|
+
prevTs = Math.max(prevTs ?? 0, ts);
|
|
2681
|
+
}
|
|
2682
|
+
if (meta.displayRole === "error") fold.lastError = firstLine(contentText(m.content) || "Error", 140);
|
|
2683
|
+
else if (!meta.displayOnly) fold.lastError = void 0;
|
|
2684
|
+
const model = m.modelInfo?.id;
|
|
2685
|
+
if (typeof model === "string") fold.model = model;
|
|
2686
|
+
const u = m.metrics;
|
|
2687
|
+
if (u && typeof u === "object") {
|
|
2688
|
+
const cacheRead = Number(u.cacheReadTokens) || 0;
|
|
2689
|
+
const cacheWrite = Number(u.cacheWriteTokens) || 0;
|
|
2690
|
+
const prompt = Number(u.inputTokens) || 0;
|
|
2691
|
+
const input = Math.max(0, prompt - cacheRead - cacheWrite);
|
|
2692
|
+
const output = Number(u.outputTokens) || 0;
|
|
2693
|
+
fold.tokens.input += input;
|
|
2694
|
+
fold.tokens.output += output;
|
|
2695
|
+
fold.tokens.cacheRead += cacheRead;
|
|
2696
|
+
fold.tokens.cacheWrite += cacheWrite;
|
|
2697
|
+
const cost = typeof u.cost === "number" ? u.cost : void 0;
|
|
2698
|
+
if (cost === void 0) {
|
|
2699
|
+
if (input + output > 0) fold.costUsd = void 0;
|
|
2700
|
+
} else if (fold.costUsd !== void 0) fold.costUsd += cost;
|
|
2701
|
+
const b = daily[dayKey(ts || Date.now())] ??= { tokens: 0, costUsd: 0 };
|
|
2702
|
+
b.tokens += input + output + cacheRead + cacheWrite;
|
|
2703
|
+
b.costUsd += cost ?? 0;
|
|
2704
|
+
if (prompt > 0) fold.context = prompt;
|
|
2705
|
+
}
|
|
2706
|
+
for (const b of blocks) {
|
|
2707
|
+
if (b.type !== "tool_use") continue;
|
|
2708
|
+
const act = sdkActivity(b, ts);
|
|
2709
|
+
calls.set(String(b.id), act);
|
|
2710
|
+
steps += 1;
|
|
2711
|
+
if (fold.recent[0]) fold.recent[0].endedAt ??= ts || void 0;
|
|
2712
|
+
fold.recent.unshift(act);
|
|
2713
|
+
if (fold.recent.length > 6) fold.recent.length = 6;
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
if (turnStart !== void 0) fold.turn = { steps, startedAt: turnStart };
|
|
2717
|
+
return fold;
|
|
2718
|
+
}
|
|
2719
|
+
function pidAlive(pid) {
|
|
2720
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return void 0;
|
|
2721
|
+
try {
|
|
2722
|
+
process.kill(pid, 0);
|
|
2723
|
+
return true;
|
|
2724
|
+
} catch (e) {
|
|
2725
|
+
return e.code === "EPERM";
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
2728
|
+
var ClineSdkSessions = class {
|
|
2729
|
+
tracked = /* @__PURE__ */ new Map();
|
|
2730
|
+
lastDiscovery = 0;
|
|
2731
|
+
root(ctx) {
|
|
2732
|
+
return ctx.env.CLINE_SESSION_DATA_DIR || path5.join(clineDataDir(ctx.home, ctx.env), "sessions");
|
|
2733
|
+
}
|
|
2734
|
+
async poll(ctx, label) {
|
|
2735
|
+
const now = ctx.now();
|
|
2736
|
+
if (now - this.lastDiscovery >= DISCOVERY_MS || this.tracked.size === 0) {
|
|
2737
|
+
this.lastDiscovery = now;
|
|
2738
|
+
await this.discover(ctx);
|
|
2739
|
+
}
|
|
2740
|
+
const out = [];
|
|
2741
|
+
for (const t of this.tracked.values()) {
|
|
2742
|
+
await this.refresh(t);
|
|
2743
|
+
const s = this.toSession(t, ctx, label);
|
|
2744
|
+
if (s) out.push(s);
|
|
2745
|
+
}
|
|
2746
|
+
return out;
|
|
2747
|
+
}
|
|
2748
|
+
async discover(ctx) {
|
|
2749
|
+
const root = this.root(ctx);
|
|
2750
|
+
const now = ctx.now();
|
|
2751
|
+
const found = [];
|
|
2752
|
+
for (const e of await listDir(root)) {
|
|
2753
|
+
if (!e.isDirectory() || e.name.includes("__") || e.name.startsWith(".")) continue;
|
|
2754
|
+
const dir = path5.join(root, e.name);
|
|
2755
|
+
const manifest = await statSafe(path5.join(dir, `${e.name}.json`));
|
|
2756
|
+
const messages = await statSafe(path5.join(dir, `${e.name}.messages.json`));
|
|
2757
|
+
const mtimeMs = Math.max(manifest?.mtimeMs ?? 0, messages?.mtimeMs ?? 0);
|
|
2758
|
+
if (mtimeMs && now - mtimeMs <= ctx.activeWindowMs) found.push({ dir, id: e.name, mtimeMs });
|
|
2759
|
+
}
|
|
2760
|
+
found.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
2761
|
+
const keep = new Map(found.slice(0, ctx.maxSessionsPerAgent).map((f) => [f.dir, f]));
|
|
2762
|
+
for (const [dir, f] of keep) {
|
|
2763
|
+
if (!this.tracked.has(dir)) {
|
|
2764
|
+
this.tracked.set(dir, { dir, id: f.id, manifestFile: path5.join(dir, `${f.id}.json`), manifestMtime: -1, messagesMtime: -1, messagesSize: -1 });
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
for (const dir of [...this.tracked.keys()]) if (!keep.has(dir)) this.tracked.delete(dir);
|
|
2768
|
+
}
|
|
2769
|
+
async refresh(t) {
|
|
2770
|
+
const ms = await statSafe(t.manifestFile);
|
|
2771
|
+
if (ms && ms.mtimeMs !== t.manifestMtime) {
|
|
2772
|
+
const m = await readJsonSafe(t.manifestFile, 8 << 20);
|
|
2773
|
+
if (m) {
|
|
2774
|
+
t.manifest = m;
|
|
2775
|
+
t.manifestMtime = ms.mtimeMs;
|
|
2776
|
+
}
|
|
2777
|
+
}
|
|
2778
|
+
const declared = typeof t.manifest?.messages_path === "string" ? t.manifest.messages_path : void 0;
|
|
2779
|
+
let file = path5.join(t.dir, `${t.id}.messages.json`);
|
|
2780
|
+
let st = await statSafe(file);
|
|
2781
|
+
if (!st && declared) {
|
|
2782
|
+
st = await statSafe(declared);
|
|
2783
|
+
if (st) file = declared;
|
|
2784
|
+
}
|
|
2785
|
+
t.messagesFile = file;
|
|
2786
|
+
if (st && (st.mtimeMs !== t.messagesMtime || st.size !== t.messagesSize)) {
|
|
2787
|
+
const doc = await readJsonSafe(t.messagesFile, 128 << 20);
|
|
2788
|
+
if (doc && Array.isArray(doc.messages)) {
|
|
2789
|
+
t.fold = foldClineSdkMessages(doc.messages);
|
|
2790
|
+
t.messagesMtime = st.mtimeMs;
|
|
2791
|
+
t.messagesSize = st.size;
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
}
|
|
2795
|
+
toSession(t, ctx, label) {
|
|
2796
|
+
const m = t.manifest;
|
|
2797
|
+
if (!m) return void 0;
|
|
2798
|
+
if (m.is_subagent === true || m.is_subagent === 1) return void 0;
|
|
2799
|
+
const f = t.fold;
|
|
2800
|
+
const now = ctx.now();
|
|
2801
|
+
const meta = m.metadata && typeof m.metadata === "object" ? m.metadata : {};
|
|
2802
|
+
const startedAt = parseTime(m.started_at) ?? f?.startedAt ?? Math.min(t.manifestMtime, now);
|
|
2803
|
+
const updatedAt = Math.max(f?.lastTs ?? 0, parseTime(m.ended_at) ?? 0, Math.min(Math.max(t.manifestMtime, t.messagesMtime), now));
|
|
2804
|
+
let status;
|
|
2805
|
+
let detail;
|
|
2806
|
+
switch (m.status) {
|
|
2807
|
+
case "running":
|
|
2808
|
+
case "pending":
|
|
2809
|
+
status = "working";
|
|
2810
|
+
if (m.status === "pending") detail = "Queued";
|
|
2811
|
+
if (pidAlive(m.pid) === false) {
|
|
2812
|
+
status = "idle";
|
|
2813
|
+
detail = `${label} was closed`;
|
|
2814
|
+
}
|
|
2815
|
+
break;
|
|
2816
|
+
case "completed":
|
|
2817
|
+
status = "done";
|
|
2818
|
+
break;
|
|
2819
|
+
case "failed":
|
|
2820
|
+
status = "error";
|
|
2821
|
+
detail = f?.lastError ?? (typeof meta.terminal_marker_reason === "string" ? meta.terminal_marker_reason : "The session failed");
|
|
2822
|
+
break;
|
|
2823
|
+
case "cancelled":
|
|
2824
|
+
status = "idle";
|
|
2825
|
+
detail = "Stopped";
|
|
2826
|
+
break;
|
|
2827
|
+
default:
|
|
2828
|
+
status = f?.lastError ? "error" : "idle";
|
|
2829
|
+
detail = f?.lastError;
|
|
2830
|
+
}
|
|
2831
|
+
let activity = status === "working" ? f?.recent[0] : void 0;
|
|
2832
|
+
if (status === "working") {
|
|
2833
|
+
const stale = staleness(updatedAt, ctx);
|
|
2834
|
+
if (stale) {
|
|
2835
|
+
status = "stale";
|
|
2836
|
+
detail = stale;
|
|
2837
|
+
activity = void 0;
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
const usage = meta.aggregateUsage ?? meta.usage;
|
|
2841
|
+
const cwd = typeof m.cwd === "string" ? m.cwd : typeof m.workspace_root === "string" ? m.workspace_root : void 0;
|
|
2842
|
+
const root = typeof m.workspace_root === "string" ? m.workspace_root : void 0;
|
|
2843
|
+
const title = typeof meta.title === "string" && meta.title.trim() ? firstLine(meta.title, 100) : f?.title ?? (typeof m.prompt === "string" ? firstLine(sdkUserText(m.prompt), 100) : void 0);
|
|
2844
|
+
const loop = status === "working" || status === "stale" ? f?.loops.current(now) : void 0;
|
|
2845
|
+
let costUsd = f?.costUsd;
|
|
2846
|
+
if (typeof usage?.totalCost === "number" && (costUsd === void 0 || usage.totalCost > costUsd)) costUsd = usage.totalCost;
|
|
2847
|
+
return {
|
|
2848
|
+
key: `cline:${t.id}`,
|
|
2849
|
+
agent: "cline",
|
|
2850
|
+
agentLabel: label,
|
|
2851
|
+
id: t.id,
|
|
2852
|
+
title: title ?? "Untitled task",
|
|
2853
|
+
titleFromPrompt: title !== void 0 ? true : void 0,
|
|
2854
|
+
projectPath: root ? findGitRoot(root) ?? root : cwd ? findGitRoot(cwd) ?? cwd : void 0,
|
|
2855
|
+
cwd,
|
|
2856
|
+
model: f?.model ?? (typeof m.model === "string" ? m.model : void 0),
|
|
2857
|
+
host: m.source === "vscode" ? "editor" : m.source === "cli" ? "terminal" : m.source ? "app" : void 0,
|
|
2858
|
+
pid: typeof m.pid === "number" && pidAlive(m.pid) ? m.pid : void 0,
|
|
2859
|
+
status,
|
|
2860
|
+
statusDetail: detail,
|
|
2861
|
+
startedAt,
|
|
2862
|
+
updatedAt,
|
|
2863
|
+
tasks: [],
|
|
2864
|
+
activity,
|
|
2865
|
+
turn: f?.turn,
|
|
2866
|
+
turns: f?.turns,
|
|
2867
|
+
recent: f?.recent.slice(0, 5),
|
|
2868
|
+
loop: loop ? {
|
|
2869
|
+
label: loop.label,
|
|
2870
|
+
detail: loop.detail,
|
|
2871
|
+
count: loop.count,
|
|
2872
|
+
sameError: loop.sameError,
|
|
2873
|
+
since: loop.since,
|
|
2874
|
+
tokens: loop.tokensAtStart !== void 0 && f ? totalTokens(f.tokens) - loop.tokensAtStart : void 0
|
|
2875
|
+
} : void 0,
|
|
2876
|
+
tokens: f ? { ...f.tokens } : void 0,
|
|
2877
|
+
costUsd,
|
|
2878
|
+
daily: f?.daily,
|
|
2879
|
+
context: f?.context ? { used: f.context } : void 0,
|
|
2880
|
+
sources: [t.messagesFile ?? t.manifestFile, t.manifestFile].filter((x, i, a) => a.indexOf(x) === i)
|
|
2881
|
+
};
|
|
2882
|
+
}
|
|
2883
|
+
};
|
|
2884
|
+
|
|
2885
|
+
// ../core/src/adapters/codex.ts
|
|
2886
|
+
import path6 from "node:path";
|
|
2887
|
+
function codexFailure(output) {
|
|
2888
|
+
let text = typeof output === "string" ? output : output && typeof output === "object" ? JSON.stringify(output) : "";
|
|
2889
|
+
if (!text) return void 0;
|
|
2890
|
+
let code;
|
|
2891
|
+
try {
|
|
2892
|
+
const j = JSON.parse(text);
|
|
2893
|
+
if (j && typeof j === "object" && typeof j.metadata?.exit_code === "number") {
|
|
2894
|
+
code = j.metadata.exit_code;
|
|
2895
|
+
if (typeof j.output === "string") text = j.output;
|
|
2896
|
+
}
|
|
2897
|
+
} catch {
|
|
2898
|
+
}
|
|
2899
|
+
if (code === void 0) {
|
|
2900
|
+
const m = /^(?:Exit code:|Process exited with code)\s*(-?\d+)/m.exec(text);
|
|
2901
|
+
if (m) code = Number(m[1]);
|
|
2902
|
+
}
|
|
2903
|
+
return code !== void 0 && code !== 0 ? text : void 0;
|
|
2904
|
+
}
|
|
1616
2905
|
function planStatus(s) {
|
|
1617
2906
|
if (s === "completed") return "completed";
|
|
1618
2907
|
if (s === "in_progress") return "in_progress";
|
|
@@ -1649,25 +2938,31 @@ function describeCodexCall(name, args, at) {
|
|
|
1649
2938
|
return { kind: "tool", label: name, startedAt: at };
|
|
1650
2939
|
}
|
|
1651
2940
|
var CodexAdapter = class extends JsonlSessionAdapter {
|
|
2941
|
+
/** The account's plan windows, from every session's readings. */
|
|
2942
|
+
limitBook = new LimitBook();
|
|
2943
|
+
limits(ctx) {
|
|
2944
|
+
const windows = this.limitBook.windows(ctx.now());
|
|
2945
|
+
return windows.length ? { agent: this.id, agentLabel: this.label, windows } : void 0;
|
|
2946
|
+
}
|
|
1652
2947
|
id = "codex";
|
|
1653
2948
|
label = "Codex";
|
|
1654
2949
|
async discover(ctx) {
|
|
1655
|
-
const home = ctx.env.CODEX_HOME ||
|
|
1656
|
-
const root =
|
|
2950
|
+
const home = ctx.env.CODEX_HOME || path6.join(ctx.home, ".codex");
|
|
2951
|
+
const root = path6.join(home, "sessions");
|
|
1657
2952
|
const now = ctx.now();
|
|
1658
2953
|
const days = Math.max(1, Math.ceil(ctx.activeWindowMs / 864e5) + 1);
|
|
1659
2954
|
const dirs = /* @__PURE__ */ new Set();
|
|
1660
2955
|
for (let i = 0; i <= days; i += 1) {
|
|
1661
2956
|
const d = new Date(now - i * 864e5);
|
|
1662
2957
|
const pad = (n) => String(n).padStart(2, "0");
|
|
1663
|
-
dirs.add(
|
|
1664
|
-
dirs.add(
|
|
2958
|
+
dirs.add(path6.join(root, String(d.getFullYear()), pad(d.getMonth() + 1), pad(d.getDate())));
|
|
2959
|
+
dirs.add(path6.join(root, String(d.getUTCFullYear()), pad(d.getUTCMonth() + 1), pad(d.getUTCDate())));
|
|
1665
2960
|
}
|
|
1666
2961
|
const out = [];
|
|
1667
2962
|
for (const dir of dirs) {
|
|
1668
2963
|
for (const f of await listDir(dir)) {
|
|
1669
2964
|
if (!f.isFile() || !f.name.startsWith("rollout-") || !f.name.endsWith(".jsonl")) continue;
|
|
1670
|
-
const file =
|
|
2965
|
+
const file = path6.join(dir, f.name);
|
|
1671
2966
|
const st = await statSafe(file);
|
|
1672
2967
|
if (st) out.push({ path: file, mtimeMs: st.mtimeMs });
|
|
1673
2968
|
}
|
|
@@ -1676,22 +2971,24 @@ var CodexAdapter = class extends JsonlSessionAdapter {
|
|
|
1676
2971
|
}
|
|
1677
2972
|
createState(file) {
|
|
1678
2973
|
const m = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(file);
|
|
2974
|
+
const daily = {};
|
|
1679
2975
|
return {
|
|
1680
2976
|
file,
|
|
1681
|
-
id: m ? m[1] :
|
|
2977
|
+
id: m ? m[1] : path6.basename(file, ".jsonl"),
|
|
1682
2978
|
isSubagent: false,
|
|
1683
2979
|
updatedAt: 0,
|
|
1684
2980
|
prevTotal: 0,
|
|
1685
2981
|
prevCost: 0,
|
|
1686
|
-
daily
|
|
2982
|
+
daily,
|
|
1687
2983
|
tasks: [],
|
|
1688
2984
|
open: /* @__PURE__ */ new Map(),
|
|
1689
2985
|
phase: "idle",
|
|
1690
2986
|
phaseAt: 0,
|
|
1691
2987
|
turns: 0,
|
|
1692
2988
|
turnSteps: 0,
|
|
1693
|
-
timer: new TaskTimer(),
|
|
1694
|
-
recent: []
|
|
2989
|
+
timer: new TaskTimer((at) => addTaskDone(daily, at)),
|
|
2990
|
+
recent: [],
|
|
2991
|
+
loops: new LoopWatch()
|
|
1695
2992
|
};
|
|
1696
2993
|
}
|
|
1697
2994
|
onRecord(st, rec, ctx) {
|
|
@@ -1704,11 +3001,18 @@ var CodexAdapter = class extends JsonlSessionAdapter {
|
|
|
1704
3001
|
}
|
|
1705
3002
|
const p2 = o.payload;
|
|
1706
3003
|
if (!p2 || typeof p2 !== "object") return;
|
|
3004
|
+
if (ts) {
|
|
3005
|
+
const agentWrote = o.type === "response_item" && !(p2.type === "message" && p2.role === "user");
|
|
3006
|
+
if (agentWrote) addWork(st.daily, st.lastRecordAt, ts);
|
|
3007
|
+
if (st.lastRecordAt === void 0 || ts > st.lastRecordAt) st.lastRecordAt = ts;
|
|
3008
|
+
}
|
|
1707
3009
|
switch (o.type) {
|
|
1708
3010
|
case "session_meta": {
|
|
1709
3011
|
if (typeof p2.id === "string") st.id = p2.id;
|
|
1710
3012
|
if (typeof p2.cwd === "string") st.cwd = p2.cwd;
|
|
1711
3013
|
if (typeof p2.cli_version === "string") st.version = p2.cli_version;
|
|
3014
|
+
if (typeof p2.originator === "string") st.originator = p2.originator;
|
|
3015
|
+
else if (typeof p2.source === "string") st.originator = p2.source;
|
|
1712
3016
|
if (p2.parent_thread_id || p2.agent_role || p2.agent_nickname) st.isSubagent = true;
|
|
1713
3017
|
const started = parseTime(p2.timestamp);
|
|
1714
3018
|
if (started) st.startedAt = Math.min(st.startedAt ?? started, started);
|
|
@@ -1749,6 +3053,7 @@ var CodexAdapter = class extends JsonlSessionAdapter {
|
|
|
1749
3053
|
st.phase = "interrupted";
|
|
1750
3054
|
st.phaseAt = ts;
|
|
1751
3055
|
st.open.clear();
|
|
3056
|
+
st.loops.reset();
|
|
1752
3057
|
return;
|
|
1753
3058
|
case "error":
|
|
1754
3059
|
st.phase = "error";
|
|
@@ -1758,6 +3063,7 @@ var CodexAdapter = class extends JsonlSessionAdapter {
|
|
|
1758
3063
|
case "user_message":
|
|
1759
3064
|
if (typeof p2.message === "string" && p2.message.trim()) {
|
|
1760
3065
|
st.title ??= firstLine(p2.message, 100);
|
|
3066
|
+
st.loops.reset();
|
|
1761
3067
|
if (st.phase !== "working") {
|
|
1762
3068
|
st.phase = "working";
|
|
1763
3069
|
st.phaseAt = ts;
|
|
@@ -1825,7 +3131,10 @@ var CodexAdapter = class extends JsonlSessionAdapter {
|
|
|
1825
3131
|
windowMinutes: typeof w.window_minutes === "number" ? w.window_minutes : void 0
|
|
1826
3132
|
});
|
|
1827
3133
|
}
|
|
1828
|
-
if (windows.length)
|
|
3134
|
+
if (windows.length) {
|
|
3135
|
+
st.rateLimits = windows;
|
|
3136
|
+
for (const w of windows) this.limitBook.add(w, ts);
|
|
3137
|
+
}
|
|
1829
3138
|
}
|
|
1830
3139
|
}
|
|
1831
3140
|
onItem(st, p2, ts) {
|
|
@@ -1869,7 +3178,10 @@ var CodexAdapter = class extends JsonlSessionAdapter {
|
|
|
1869
3178
|
case "function_call_output":
|
|
1870
3179
|
case "custom_tool_call_output": {
|
|
1871
3180
|
const done = typeof p2.call_id === "string" ? st.open.get(p2.call_id) : void 0;
|
|
1872
|
-
if (done)
|
|
3181
|
+
if (done) {
|
|
3182
|
+
done.endedAt = ts;
|
|
3183
|
+
st.loops.observe(loopKey(done), done, codexFailure(p2.output), ts, st.tokens ? totalTokens(st.tokens) : void 0);
|
|
3184
|
+
}
|
|
1873
3185
|
if (typeof p2.call_id === "string") st.open.delete(p2.call_id);
|
|
1874
3186
|
st.activity = { kind: "thinking", label: "Thinking", startedAt: ts };
|
|
1875
3187
|
return;
|
|
@@ -1922,36 +3234,611 @@ var CodexAdapter = class extends JsonlSessionAdapter {
|
|
|
1922
3234
|
agent: "codex",
|
|
1923
3235
|
agentLabel: this.label,
|
|
1924
3236
|
id: st.id,
|
|
1925
|
-
title: st.title ?? "Untitled session",
|
|
1926
|
-
titleFromPrompt: st.title !== void 0 ? true : void 0,
|
|
1927
|
-
projectPath: st.cwd ? findGitRoot(st.cwd) ?? st.cwd : void 0,
|
|
3237
|
+
title: st.title ?? "Untitled session",
|
|
3238
|
+
titleFromPrompt: st.title !== void 0 ? true : void 0,
|
|
3239
|
+
projectPath: st.cwd ? findGitRoot(st.cwd) ?? st.cwd : void 0,
|
|
3240
|
+
cwd: st.cwd,
|
|
3241
|
+
model: st.model,
|
|
3242
|
+
agentVersion: st.version,
|
|
3243
|
+
host: st.originator === void 0 ? void 0 : /vscode|ide/.test(st.originator) ? "editor" : /exec|mcp|sdk/.test(st.originator) ? "app" : "terminal",
|
|
3244
|
+
status,
|
|
3245
|
+
statusDetail: detail,
|
|
3246
|
+
startedAt: st.startedAt,
|
|
3247
|
+
updatedAt: st.updatedAt,
|
|
3248
|
+
tasks: st.tasks,
|
|
3249
|
+
activity,
|
|
3250
|
+
tokens: st.tokens ? { ...st.tokens } : void 0,
|
|
3251
|
+
costUsd: st.costUsd,
|
|
3252
|
+
daily: st.daily,
|
|
3253
|
+
context: st.context,
|
|
3254
|
+
rateLimits: st.rateLimits,
|
|
3255
|
+
turns: st.turns,
|
|
3256
|
+
turn: st.turnStartedAt !== void 0 ? { steps: st.turnSteps, startedAt: st.turnStartedAt } : void 0,
|
|
3257
|
+
current: status === "working" || status === "stale" ? st.timer.current(st.tasks) : void 0,
|
|
3258
|
+
loop: loopOf(st, status, ctx.now()),
|
|
3259
|
+
recent: st.recent.slice(0, 5),
|
|
3260
|
+
sources: [st.file]
|
|
3261
|
+
};
|
|
3262
|
+
}
|
|
3263
|
+
};
|
|
3264
|
+
function loopOf(st, status, now) {
|
|
3265
|
+
const l = status === "working" || status === "stale" ? st.loops.current(now) : void 0;
|
|
3266
|
+
if (!l) return void 0;
|
|
3267
|
+
return {
|
|
3268
|
+
label: l.label,
|
|
3269
|
+
detail: l.detail,
|
|
3270
|
+
count: l.count,
|
|
3271
|
+
sameError: l.sameError,
|
|
3272
|
+
since: l.since,
|
|
3273
|
+
tokens: l.tokensAtStart !== void 0 && st.tokens ? totalTokens(st.tokens) - l.tokensAtStart : void 0
|
|
3274
|
+
};
|
|
3275
|
+
}
|
|
3276
|
+
|
|
3277
|
+
// ../core/src/adapters/copilot.ts
|
|
3278
|
+
import path7 from "node:path";
|
|
3279
|
+
|
|
3280
|
+
// ../core/src/util/sqlite.ts
|
|
3281
|
+
var loaded;
|
|
3282
|
+
function sqliteModule() {
|
|
3283
|
+
if (loaded !== void 0) return loaded;
|
|
3284
|
+
loaded = null;
|
|
3285
|
+
const [major, minor] = process.versions.node.split(".").map(Number);
|
|
3286
|
+
if (major < 22 || major === 22 && minor < 13) return loaded;
|
|
3287
|
+
const get = process.getBuiltinModule;
|
|
3288
|
+
if (typeof get !== "function") return loaded;
|
|
3289
|
+
const emit = process.emitWarning;
|
|
3290
|
+
process.emitWarning = ((warning, ...rest) => {
|
|
3291
|
+
const text = typeof warning === "string" ? warning : warning?.message;
|
|
3292
|
+
if (typeof text === "string" && /sqlite/i.test(text)) return;
|
|
3293
|
+
return emit.call(process, warning, ...rest);
|
|
3294
|
+
});
|
|
3295
|
+
try {
|
|
3296
|
+
const mod = get.call(process, "node:sqlite");
|
|
3297
|
+
if (mod && typeof mod.DatabaseSync === "function") loaded = mod;
|
|
3298
|
+
} catch {
|
|
3299
|
+
loaded = null;
|
|
3300
|
+
} finally {
|
|
3301
|
+
process.emitWarning = emit;
|
|
3302
|
+
}
|
|
3303
|
+
return loaded;
|
|
3304
|
+
}
|
|
3305
|
+
var ReadOnlyDb = class _ReadOnlyDb {
|
|
3306
|
+
file;
|
|
3307
|
+
db;
|
|
3308
|
+
statements = /* @__PURE__ */ new Map();
|
|
3309
|
+
lastDataVersion;
|
|
3310
|
+
constructor(file, db) {
|
|
3311
|
+
this.file = file;
|
|
3312
|
+
this.db = db;
|
|
3313
|
+
}
|
|
3314
|
+
static open(file) {
|
|
3315
|
+
const mod = sqliteModule();
|
|
3316
|
+
if (!mod) return void 0;
|
|
3317
|
+
try {
|
|
3318
|
+
const db = new mod.DatabaseSync(file, { readOnly: true });
|
|
3319
|
+
try {
|
|
3320
|
+
db.exec("PRAGMA busy_timeout = 1000");
|
|
3321
|
+
} catch {
|
|
3322
|
+
}
|
|
3323
|
+
return new _ReadOnlyDb(file, db);
|
|
3324
|
+
} catch {
|
|
3325
|
+
return void 0;
|
|
3326
|
+
}
|
|
3327
|
+
}
|
|
3328
|
+
all(sql, ...params) {
|
|
3329
|
+
try {
|
|
3330
|
+
return this.statement(sql).all(...params);
|
|
3331
|
+
} catch {
|
|
3332
|
+
return [];
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
get(sql, ...params) {
|
|
3336
|
+
try {
|
|
3337
|
+
return this.statement(sql).get(...params);
|
|
3338
|
+
} catch {
|
|
3339
|
+
return void 0;
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
/** Table name → its columns, for the tables that exist. */
|
|
3343
|
+
schema() {
|
|
3344
|
+
const out = /* @__PURE__ */ new Map();
|
|
3345
|
+
for (const t of this.all("SELECT name FROM sqlite_master WHERE type = 'table'")) {
|
|
3346
|
+
const name = String(t.name);
|
|
3347
|
+
out.set(name, new Set(this.all(`PRAGMA table_info("${name.replace(/"/g, '""')}")`).map((c) => String(c.name))));
|
|
3348
|
+
}
|
|
3349
|
+
return out;
|
|
3350
|
+
}
|
|
3351
|
+
/**
|
|
3352
|
+
* Whether another connection changed the database since the last call (`PRAGMA data_version`).
|
|
3353
|
+
* The first call says yes.
|
|
3354
|
+
*/
|
|
3355
|
+
changed() {
|
|
3356
|
+
const v = Number(this.get("PRAGMA data_version")?.data_version);
|
|
3357
|
+
if (!Number.isFinite(v)) return true;
|
|
3358
|
+
const changed = v !== this.lastDataVersion;
|
|
3359
|
+
this.lastDataVersion = v;
|
|
3360
|
+
return changed;
|
|
3361
|
+
}
|
|
3362
|
+
close() {
|
|
3363
|
+
this.statements.clear();
|
|
3364
|
+
try {
|
|
3365
|
+
this.db.close();
|
|
3366
|
+
} catch {
|
|
3367
|
+
}
|
|
3368
|
+
}
|
|
3369
|
+
statement(sql) {
|
|
3370
|
+
let st = this.statements.get(sql);
|
|
3371
|
+
if (!st) {
|
|
3372
|
+
st = this.db.prepare(sql);
|
|
3373
|
+
this.statements.set(sql, st);
|
|
3374
|
+
}
|
|
3375
|
+
return st;
|
|
3376
|
+
}
|
|
3377
|
+
};
|
|
3378
|
+
|
|
3379
|
+
// ../core/src/adapters/copilot.ts
|
|
3380
|
+
var SHELLS = /* @__PURE__ */ new Set(["bash", "powershell", "local_shell"]);
|
|
3381
|
+
function toolActivity2(name, args, title, at) {
|
|
3382
|
+
if (SHELLS.has(name)) return { kind: "command", label: "Shell", detail: summarizeCommand(args.command), startedAt: at };
|
|
3383
|
+
const file = typeof args.path === "string" ? args.path : typeof args.file_path === "string" ? args.file_path : void 0;
|
|
3384
|
+
const d = (s) => s ? truncate(s, 80) : void 0;
|
|
3385
|
+
switch (name) {
|
|
3386
|
+
case "view":
|
|
3387
|
+
return { kind: "tool", label: "Read", detail: d(file), startedAt: at };
|
|
3388
|
+
case "create":
|
|
3389
|
+
return { kind: "tool", label: "Write", detail: d(file), startedAt: at };
|
|
3390
|
+
case "edit":
|
|
3391
|
+
case "str_replace_editor":
|
|
3392
|
+
case "apply_patch":
|
|
3393
|
+
return { kind: "tool", label: "Edit", detail: d(file), startedAt: at };
|
|
3394
|
+
case "grep":
|
|
3395
|
+
case "glob":
|
|
3396
|
+
return { kind: "tool", label: "Search", detail: d(typeof args.pattern === "string" ? args.pattern : void 0), startedAt: at };
|
|
3397
|
+
case "web_fetch":
|
|
3398
|
+
return { kind: "tool", label: "Fetch", detail: d(typeof args.url === "string" ? args.url : void 0), startedAt: at };
|
|
3399
|
+
case "task":
|
|
3400
|
+
return { kind: "subagent", label: "Subagent", detail: d(typeof args.description === "string" ? args.description : void 0), startedAt: at };
|
|
3401
|
+
case "update_todo":
|
|
3402
|
+
return { kind: "tool", label: "Update plan", startedAt: at };
|
|
3403
|
+
case "ask_user":
|
|
3404
|
+
return { kind: "tool", label: "Question", startedAt: at };
|
|
3405
|
+
case "exit_plan_mode":
|
|
3406
|
+
return { kind: "tool", label: "Plan", startedAt: at };
|
|
3407
|
+
case "read_bash":
|
|
3408
|
+
case "write_bash":
|
|
3409
|
+
case "stop_bash":
|
|
3410
|
+
case "list_bash":
|
|
3411
|
+
return { kind: "command", label: "Shell", detail: "background command", startedAt: at };
|
|
3412
|
+
default:
|
|
3413
|
+
return { kind: "tool", label: title || name, detail: d(file), startedAt: at };
|
|
3414
|
+
}
|
|
3415
|
+
}
|
|
3416
|
+
function permissionLabel(r) {
|
|
3417
|
+
switch (r?.kind) {
|
|
3418
|
+
case "shell":
|
|
3419
|
+
return `run ${summarizeCommand(r.fullCommandText, 60) ?? "a command"}`;
|
|
3420
|
+
case "write":
|
|
3421
|
+
return typeof r.fileName === "string" ? `edit ${basename(r.fileName)}` : "edit a file";
|
|
3422
|
+
case "read":
|
|
3423
|
+
return typeof r.path === "string" ? `read ${basename(r.path)}` : "read a file";
|
|
3424
|
+
case "url": {
|
|
3425
|
+
try {
|
|
3426
|
+
return `fetch ${new URL(String(r.url)).host}`;
|
|
3427
|
+
} catch {
|
|
3428
|
+
return "fetch a page";
|
|
3429
|
+
}
|
|
3430
|
+
}
|
|
3431
|
+
case "mcp":
|
|
3432
|
+
return `${r.serverName ?? "MCP"}: ${r.toolTitle ?? r.toolName ?? "tool"}`;
|
|
3433
|
+
case "custom-tool":
|
|
3434
|
+
return String(r.toolName ?? "a tool");
|
|
3435
|
+
default:
|
|
3436
|
+
return typeof r?.kind === "string" ? r.kind : "a tool";
|
|
3437
|
+
}
|
|
3438
|
+
}
|
|
3439
|
+
function todoMarkdown(md) {
|
|
3440
|
+
return parseChecklist(md.replace(/^(\s*(?:[-*+]|\d+[.)])\s*)\[[-~]\]/gm, "$1[/]")).tasks;
|
|
3441
|
+
}
|
|
3442
|
+
function dbStatus(s) {
|
|
3443
|
+
return s === "done" ? "completed" : s === "in_progress" ? "in_progress" : s === "blocked" ? "blocked" : "pending";
|
|
3444
|
+
}
|
|
3445
|
+
function createState(file) {
|
|
3446
|
+
const dir = path7.dirname(file);
|
|
3447
|
+
const daily = {};
|
|
3448
|
+
return {
|
|
3449
|
+
file,
|
|
3450
|
+
dir,
|
|
3451
|
+
id: path7.basename(dir),
|
|
3452
|
+
updatedAt: 0,
|
|
3453
|
+
workspaceMtime: -1,
|
|
3454
|
+
turnOpen: false,
|
|
3455
|
+
wantsTools: false,
|
|
3456
|
+
open: /* @__PURE__ */ new Map(),
|
|
3457
|
+
permissions: /* @__PURE__ */ new Map(),
|
|
3458
|
+
stopped: false,
|
|
3459
|
+
shutdown: false,
|
|
3460
|
+
taskComplete: false,
|
|
3461
|
+
tokens: emptyTokens(),
|
|
3462
|
+
costUsd: 0,
|
|
3463
|
+
priced: false,
|
|
3464
|
+
usageRecords: 0,
|
|
3465
|
+
shutdownTokens: emptyTokens(),
|
|
3466
|
+
daily,
|
|
3467
|
+
tasks: [],
|
|
3468
|
+
tasksAt: 0,
|
|
3469
|
+
dbMtime: -1,
|
|
3470
|
+
timer: new TaskTimer((at) => addTaskDone(daily, at)),
|
|
3471
|
+
loops: new LoopWatch(),
|
|
3472
|
+
recent: [],
|
|
3473
|
+
turns: 0,
|
|
3474
|
+
subagents: /* @__PURE__ */ new Set(),
|
|
3475
|
+
aliveCheckedAt: 0
|
|
3476
|
+
};
|
|
3477
|
+
}
|
|
3478
|
+
function applyCopilotEvent(st, rec, price) {
|
|
3479
|
+
if (!rec || typeof rec !== "object") return;
|
|
3480
|
+
const r = rec;
|
|
3481
|
+
const type = r.type;
|
|
3482
|
+
if (typeof type !== "string") return;
|
|
3483
|
+
const d = r.data && typeof r.data === "object" ? r.data : {};
|
|
3484
|
+
const at = parseTime(r.timestamp) ?? st.updatedAt;
|
|
3485
|
+
if (r.agentId) return;
|
|
3486
|
+
if (at > st.updatedAt) st.updatedAt = at;
|
|
3487
|
+
const work = () => {
|
|
3488
|
+
addWork(st.daily, st.lastRecordAt, at);
|
|
3489
|
+
st.lastRecordAt = Math.max(st.lastRecordAt ?? 0, at);
|
|
3490
|
+
};
|
|
3491
|
+
switch (type) {
|
|
3492
|
+
case "session.start": {
|
|
3493
|
+
st.startedAt = parseTime(d.startTime) ?? at;
|
|
3494
|
+
if (typeof d.copilotVersion === "string") st.version = d.copilotVersion;
|
|
3495
|
+
if (typeof d.selectedModel === "string") st.model = d.selectedModel;
|
|
3496
|
+
if (d.context?.cwd) st.cwd = String(d.context.cwd);
|
|
3497
|
+
if (d.context?.gitRoot) st.gitRoot = String(d.context.gitRoot);
|
|
3498
|
+
return;
|
|
3499
|
+
}
|
|
3500
|
+
case "session.resume": {
|
|
3501
|
+
st.startedAt ??= at;
|
|
3502
|
+
if (typeof d.selectedModel === "string") st.model = d.selectedModel;
|
|
3503
|
+
if (d.context?.cwd) st.cwd = String(d.context.cwd);
|
|
3504
|
+
if (d.context?.gitRoot) st.gitRoot = String(d.context.gitRoot);
|
|
3505
|
+
st.shutdown = false;
|
|
3506
|
+
if (!d.continuePendingWork) {
|
|
3507
|
+
st.open.clear();
|
|
3508
|
+
st.permissions.clear();
|
|
3509
|
+
st.turnOpen = false;
|
|
3510
|
+
st.wantsTools = false;
|
|
3511
|
+
}
|
|
3512
|
+
return;
|
|
3513
|
+
}
|
|
3514
|
+
case "session.model_change":
|
|
3515
|
+
if (typeof d.newModel === "string") st.model = d.newModel;
|
|
3516
|
+
return;
|
|
3517
|
+
case "session.context_changed":
|
|
3518
|
+
if (typeof d.cwd === "string") st.cwd = d.cwd;
|
|
3519
|
+
if (typeof d.gitRoot === "string") st.gitRoot = d.gitRoot;
|
|
3520
|
+
return;
|
|
3521
|
+
case "user.message": {
|
|
3522
|
+
const text = typeof d.content === "string" ? d.content.trim() : "";
|
|
3523
|
+
if (d.isAutopilotContinuation || typeof d.source === "string" && d.source !== "user") return;
|
|
3524
|
+
if (text && !st.firstPrompt && !text.startsWith("/")) st.firstPrompt = firstLine(text, 100);
|
|
3525
|
+
st.turn = { steps: 0, startedAt: at };
|
|
3526
|
+
st.turns += 1;
|
|
3527
|
+
st.loops.reset();
|
|
3528
|
+
st.error = void 0;
|
|
3529
|
+
st.stopped = false;
|
|
3530
|
+
st.taskComplete = false;
|
|
3531
|
+
st.wantsTools = true;
|
|
3532
|
+
st.lastRecordAt = at;
|
|
3533
|
+
return;
|
|
3534
|
+
}
|
|
3535
|
+
case "assistant.turn_start":
|
|
3536
|
+
st.turnOpen = true;
|
|
3537
|
+
st.error = void 0;
|
|
3538
|
+
st.stopped = false;
|
|
3539
|
+
if (typeof d.model === "string") st.model = d.model;
|
|
3540
|
+
return;
|
|
3541
|
+
case "assistant.message":
|
|
3542
|
+
work();
|
|
3543
|
+
if (typeof d.model === "string") st.model = d.model;
|
|
3544
|
+
st.wantsTools = Array.isArray(d.toolRequests) && d.toolRequests.length > 0;
|
|
3545
|
+
return;
|
|
3546
|
+
case "assistant.turn_end":
|
|
3547
|
+
work();
|
|
3548
|
+
st.turnOpen = false;
|
|
3549
|
+
return;
|
|
3550
|
+
case "tool.execution_start": {
|
|
3551
|
+
const id = String(d.toolCallId ?? "");
|
|
3552
|
+
const name = String(d.toolName ?? "tool");
|
|
3553
|
+
const args = d.arguments && typeof d.arguments === "object" ? d.arguments : {};
|
|
3554
|
+
const act = toolActivity2(name, args, typeof d.toolTitle === "string" ? d.toolTitle : void 0, at);
|
|
3555
|
+
st.open.set(id, { name, act });
|
|
3556
|
+
if (st.turn) st.turn.steps += 1;
|
|
3557
|
+
st.timer.step();
|
|
3558
|
+
if (st.recent[0]) st.recent[0].endedAt ??= at;
|
|
3559
|
+
st.recent.unshift(act);
|
|
3560
|
+
if (st.recent.length > 6) st.recent.length = 6;
|
|
3561
|
+
if (name === "update_todo" && typeof args.todos === "string") {
|
|
3562
|
+
st.tasks = todoMarkdown(args.todos);
|
|
3563
|
+
st.tasksAt = at;
|
|
3564
|
+
st.timer.observe(st.tasks, at);
|
|
3565
|
+
}
|
|
3566
|
+
return;
|
|
3567
|
+
}
|
|
3568
|
+
case "tool.execution_complete": {
|
|
3569
|
+
work();
|
|
3570
|
+
const id = String(d.toolCallId ?? "");
|
|
3571
|
+
const open = st.open.get(id);
|
|
3572
|
+
st.open.delete(id);
|
|
3573
|
+
if (!open) return;
|
|
3574
|
+
open.act.endedAt = at;
|
|
3575
|
+
const contents = Array.isArray(d.result?.contents) ? d.result.contents : [];
|
|
3576
|
+
const exit = typeof d.shellExecution?.exitCode === "number" ? d.shellExecution.exitCode : contents.find((c) => c?.type === "shell_exit" || c?.type === "terminal")?.exitCode;
|
|
3577
|
+
const text = typeof d.result?.content === "string" ? d.result.content.slice(-600) : "";
|
|
3578
|
+
let failure;
|
|
3579
|
+
if (d.success === false) failure = String(d.error?.message ?? d.error?.code ?? "Tool error");
|
|
3580
|
+
else if (SHELLS.has(open.name) && typeof exit === "number" && exit !== 0) failure = `Exit code ${exit}
|
|
3581
|
+
${text}`;
|
|
3582
|
+
st.loops.observe(loopKey(open.act), open.act, failure, at, totalTokens(st.tokens));
|
|
3583
|
+
return;
|
|
3584
|
+
}
|
|
3585
|
+
case "permission.requested":
|
|
3586
|
+
if (!d.resolvedByHook && d.requestId) st.permissions.set(String(d.requestId), permissionLabel(d.permissionRequest ?? {}));
|
|
3587
|
+
return;
|
|
3588
|
+
case "permission.completed":
|
|
3589
|
+
if (d.requestId) st.permissions.delete(String(d.requestId));
|
|
3590
|
+
return;
|
|
3591
|
+
case "session.error":
|
|
3592
|
+
st.error = { message: firstLine(String(d.message ?? d.errorType ?? "Error"), 140), at };
|
|
3593
|
+
st.turnOpen = false;
|
|
3594
|
+
st.wantsTools = false;
|
|
3595
|
+
return;
|
|
3596
|
+
case "abort":
|
|
3597
|
+
st.stopped = true;
|
|
3598
|
+
st.turnOpen = false;
|
|
3599
|
+
st.wantsTools = false;
|
|
3600
|
+
st.open.clear();
|
|
3601
|
+
st.permissions.clear();
|
|
3602
|
+
return;
|
|
3603
|
+
case "session.task_complete":
|
|
3604
|
+
if (d.success !== false) st.taskComplete = true;
|
|
3605
|
+
return;
|
|
3606
|
+
case "subagent.started":
|
|
3607
|
+
if (d.toolCallId) st.subagents.add(String(d.toolCallId));
|
|
3608
|
+
return;
|
|
3609
|
+
case "subagent.completed":
|
|
3610
|
+
case "subagent.failed":
|
|
3611
|
+
if (d.toolCallId) st.subagents.delete(String(d.toolCallId));
|
|
3612
|
+
return;
|
|
3613
|
+
case "session.usage_record": {
|
|
3614
|
+
const u = d.usage;
|
|
3615
|
+
if (!u || typeof u !== "object") return;
|
|
3616
|
+
work();
|
|
3617
|
+
st.usageRecords += 1;
|
|
3618
|
+
const cacheRead = Number(u.cacheReadTokens) || 0;
|
|
3619
|
+
const cacheWrite = Number(u.cacheWriteTokens) || 0;
|
|
3620
|
+
const inTok = Number(u.inputTokens) || 0;
|
|
3621
|
+
const reasoning = Number(u.reasoningTokens) || 0;
|
|
3622
|
+
const input = inTok >= cacheRead + cacheWrite ? inTok - cacheRead - cacheWrite : inTok;
|
|
3623
|
+
const usage = { input, output: Number(u.outputTokens) || 0, cacheRead, cacheWrite, reasoning };
|
|
3624
|
+
st.tokens.input += usage.input;
|
|
3625
|
+
st.tokens.output += usage.output;
|
|
3626
|
+
st.tokens.cacheRead += cacheRead;
|
|
3627
|
+
st.tokens.cacheWrite += cacheWrite;
|
|
3628
|
+
st.tokens.reasoning = (st.tokens.reasoning ?? 0) + reasoning;
|
|
3629
|
+
const model = typeof u.model === "string" ? u.model : st.model;
|
|
3630
|
+
const cost = price(model, usage);
|
|
3631
|
+
if (cost !== void 0) {
|
|
3632
|
+
st.priced = true;
|
|
3633
|
+
st.costUsd += cost;
|
|
3634
|
+
}
|
|
3635
|
+
const b = st.daily[dayKey(at)] ??= { tokens: 0, costUsd: 0 };
|
|
3636
|
+
b.tokens += totalTokens(usage);
|
|
3637
|
+
b.costUsd += cost ?? 0;
|
|
3638
|
+
if (!u.parentToolCallId) st.context = inTok >= cacheRead + cacheWrite ? inTok : inTok + cacheRead + cacheWrite;
|
|
3639
|
+
return;
|
|
3640
|
+
}
|
|
3641
|
+
case "session.shutdown": {
|
|
3642
|
+
st.shutdown = true;
|
|
3643
|
+
st.turnOpen = false;
|
|
3644
|
+
st.wantsTools = false;
|
|
3645
|
+
st.open.clear();
|
|
3646
|
+
st.permissions.clear();
|
|
3647
|
+
for (const m of Object.values(d.modelMetrics ?? {})) {
|
|
3648
|
+
const u = m?.usage;
|
|
3649
|
+
if (!u) continue;
|
|
3650
|
+
const cacheRead = Number(u.cacheReadTokens) || 0;
|
|
3651
|
+
const cacheWrite = Number(u.cacheWriteTokens) || 0;
|
|
3652
|
+
const inTok = Number(u.inputTokens) || 0;
|
|
3653
|
+
st.shutdownTokens.input += inTok >= cacheRead + cacheWrite ? inTok - cacheRead - cacheWrite : inTok;
|
|
3654
|
+
st.shutdownTokens.output += Number(u.outputTokens) || 0;
|
|
3655
|
+
st.shutdownTokens.cacheRead += cacheRead;
|
|
3656
|
+
st.shutdownTokens.cacheWrite += cacheWrite;
|
|
3657
|
+
st.shutdownTokens.reasoning = (st.shutdownTokens.reasoning ?? 0) + (Number(u.reasoningTokens) || 0);
|
|
3658
|
+
}
|
|
3659
|
+
return;
|
|
3660
|
+
}
|
|
3661
|
+
default:
|
|
3662
|
+
return;
|
|
3663
|
+
}
|
|
3664
|
+
}
|
|
3665
|
+
function parseWorkspaceYaml(text) {
|
|
3666
|
+
const out = {};
|
|
3667
|
+
for (const line of text.split("\n")) {
|
|
3668
|
+
const m = /^([A-Za-z_][\w-]*):[ \t]*(.*?)\s*$/.exec(line);
|
|
3669
|
+
if (!m || !m[2] || m[2] === "|" || m[2] === ">") continue;
|
|
3670
|
+
let v = m[2];
|
|
3671
|
+
if (v.startsWith('"')) {
|
|
3672
|
+
try {
|
|
3673
|
+
v = JSON.parse(v);
|
|
3674
|
+
} catch {
|
|
3675
|
+
v = v.slice(1, -1);
|
|
3676
|
+
}
|
|
3677
|
+
} else if (v.startsWith("'") && v.endsWith("'")) v = v.slice(1, -1).replace(/''/g, "'");
|
|
3678
|
+
if (v === "null" || v === "~") continue;
|
|
3679
|
+
out[m[1]] = v;
|
|
3680
|
+
}
|
|
3681
|
+
return out;
|
|
3682
|
+
}
|
|
3683
|
+
function pidAlive2(pid) {
|
|
3684
|
+
try {
|
|
3685
|
+
process.kill(pid, 0);
|
|
3686
|
+
return true;
|
|
3687
|
+
} catch (e) {
|
|
3688
|
+
return e.code === "EPERM";
|
|
3689
|
+
}
|
|
3690
|
+
}
|
|
3691
|
+
var CopilotAdapter = class extends JsonlSessionAdapter {
|
|
3692
|
+
id = "copilot";
|
|
3693
|
+
label = "Copilot";
|
|
3694
|
+
root(ctx) {
|
|
3695
|
+
return ctx.env.COPILOT_HOME || path7.join(ctx.home, ".copilot");
|
|
3696
|
+
}
|
|
3697
|
+
async discover(ctx) {
|
|
3698
|
+
const dir = path7.join(this.root(ctx), "session-state");
|
|
3699
|
+
const out = [];
|
|
3700
|
+
for (const e of await listDir(dir)) {
|
|
3701
|
+
if (!e.isDirectory()) continue;
|
|
3702
|
+
const file = path7.join(dir, e.name, "events.jsonl");
|
|
3703
|
+
const st = await statSafe(file);
|
|
3704
|
+
if (st) out.push({ path: file, mtimeMs: st.mtimeMs });
|
|
3705
|
+
}
|
|
3706
|
+
return out;
|
|
3707
|
+
}
|
|
3708
|
+
createState(file) {
|
|
3709
|
+
return createState(file);
|
|
3710
|
+
}
|
|
3711
|
+
onRecord(st, record, ctx) {
|
|
3712
|
+
applyCopilotEvent(
|
|
3713
|
+
st,
|
|
3714
|
+
record,
|
|
3715
|
+
(model, u) => ctx.pricing.cost(model, { input: u.input, output: u.output, cacheRead: u.cacheRead, cacheWrite5m: u.cacheWrite, cacheWrite1h: 0 })
|
|
3716
|
+
);
|
|
3717
|
+
}
|
|
3718
|
+
async afterRead(st, ctx) {
|
|
3719
|
+
const now = ctx.now();
|
|
3720
|
+
const ws = path7.join(st.dir, "workspace.yaml");
|
|
3721
|
+
const wst = await statSafe(ws);
|
|
3722
|
+
if (wst && wst.mtimeMs !== st.workspaceMtime) {
|
|
3723
|
+
st.workspaceMtime = wst.mtimeMs;
|
|
3724
|
+
const y = parseWorkspaceYaml(await readTextSafe(ws, 256 << 10) ?? "");
|
|
3725
|
+
if (y.name) st.name = y.name;
|
|
3726
|
+
if (y.client_name) st.client = y.client_name;
|
|
3727
|
+
if (y.cwd) st.cwd ??= y.cwd;
|
|
3728
|
+
if (y.git_root) st.gitRoot ??= y.git_root;
|
|
3729
|
+
}
|
|
3730
|
+
if (now - st.aliveCheckedAt >= 5e3) {
|
|
3731
|
+
st.aliveCheckedAt = now;
|
|
3732
|
+
const locks = (await listDir(st.dir)).map((e) => /^inuse\.(\d+)\.lock$/.exec(e.name)).filter((m) => !!m);
|
|
3733
|
+
const live = locks.map((m) => Number(m[1])).filter((pid) => pidAlive2(pid));
|
|
3734
|
+
st.alive = locks.length ? live.length > 0 : void 0;
|
|
3735
|
+
st.pid = live[0];
|
|
3736
|
+
}
|
|
3737
|
+
const dbFile = path7.join(st.dir, "session.db");
|
|
3738
|
+
const dbm = Math.max((await statSafe(dbFile))?.mtimeMs ?? 0, (await statSafe(`${dbFile}-wal`))?.mtimeMs ?? 0);
|
|
3739
|
+
if (dbm && dbm !== st.dbMtime) {
|
|
3740
|
+
st.dbMtime = dbm;
|
|
3741
|
+
const db = ReadOnlyDb.open(dbFile);
|
|
3742
|
+
if (db) {
|
|
3743
|
+
try {
|
|
3744
|
+
const rows = db.all("SELECT id, title, status FROM todos ORDER BY created_at, rowid");
|
|
3745
|
+
st.dbTasks = rows.length ? { tasks: rows.map((r, i) => ({ id: String(r.id ?? i + 1), title: String(r.title ?? ""), status: dbStatus(r.status) })), at: Math.min(dbm, now) } : void 0;
|
|
3746
|
+
if (st.dbTasks && st.dbTasks.at >= st.tasksAt) st.timer.observe(st.dbTasks.tasks, st.dbTasks.at);
|
|
3747
|
+
} finally {
|
|
3748
|
+
db.close();
|
|
3749
|
+
}
|
|
3750
|
+
}
|
|
3751
|
+
}
|
|
3752
|
+
}
|
|
3753
|
+
toSession(st, ctx) {
|
|
3754
|
+
if (!st.startedAt && !st.firstPrompt) return void 0;
|
|
3755
|
+
const now = ctx.now();
|
|
3756
|
+
const tasks = st.dbTasks && st.dbTasks.at >= st.tasksAt ? st.dbTasks.tasks : st.tasks;
|
|
3757
|
+
const prog = progressOf(tasks);
|
|
3758
|
+
const closed = st.shutdown || st.alive === false;
|
|
3759
|
+
let status;
|
|
3760
|
+
let detail;
|
|
3761
|
+
let activity;
|
|
3762
|
+
const open = [...st.open.values()];
|
|
3763
|
+
const asking = open.find((t) => t.name === "ask_user" || t.name === "exit_plan_mode");
|
|
3764
|
+
if (st.error) {
|
|
3765
|
+
status = "error";
|
|
3766
|
+
detail = st.error.message;
|
|
3767
|
+
} else if (st.stopped) {
|
|
3768
|
+
status = "idle";
|
|
3769
|
+
detail = "Stopped";
|
|
3770
|
+
} else if (closed) {
|
|
3771
|
+
status = st.taskComplete || prog.total > 0 && prog.done === prog.total ? "done" : "idle";
|
|
3772
|
+
if (st.alive === false && !st.shutdown && (st.turnOpen || open.length)) detail = "Copilot was closed";
|
|
3773
|
+
} else if (st.permissions.size) {
|
|
3774
|
+
status = "waiting";
|
|
3775
|
+
detail = `Needs approval: ${[...st.permissions.values()].pop()}`;
|
|
3776
|
+
activity = open[open.length - 1]?.act;
|
|
3777
|
+
} else if (asking) {
|
|
3778
|
+
status = "waiting";
|
|
3779
|
+
detail = asking.name === "exit_plan_mode" ? "Plan ready for your review" : "Asked you a question";
|
|
3780
|
+
activity = asking.act;
|
|
3781
|
+
} else if (st.turnOpen || open.length || st.wantsTools) {
|
|
3782
|
+
status = "working";
|
|
3783
|
+
activity = open[open.length - 1]?.act ?? { kind: "thinking", label: "Thinking", startedAt: st.updatedAt };
|
|
3784
|
+
const stale = staleness(st.updatedAt, ctx);
|
|
3785
|
+
if (stale) {
|
|
3786
|
+
status = "stale";
|
|
3787
|
+
detail = stale;
|
|
3788
|
+
activity = void 0;
|
|
3789
|
+
}
|
|
3790
|
+
} else {
|
|
3791
|
+
status = st.taskComplete || prog.total > 0 && prog.done === prog.total ? "done" : "idle";
|
|
3792
|
+
}
|
|
3793
|
+
const tokens = st.usageRecords ? { ...st.tokens } : totalTokens(st.shutdownTokens) ? { ...st.shutdownTokens } : void 0;
|
|
3794
|
+
const loop = status === "working" || status === "stale" ? st.loops.current(now) : void 0;
|
|
3795
|
+
const root = st.gitRoot || (st.cwd ? findGitRoot(st.cwd) : void 0) || st.cwd;
|
|
3796
|
+
const title = st.name || st.firstPrompt;
|
|
3797
|
+
return {
|
|
3798
|
+
key: `copilot:${st.id}`,
|
|
3799
|
+
agent: "copilot",
|
|
3800
|
+
agentLabel: this.label,
|
|
3801
|
+
id: st.id,
|
|
3802
|
+
title: title ?? "Untitled session",
|
|
3803
|
+
titleFromPrompt: !st.name && st.firstPrompt ? true : void 0,
|
|
3804
|
+
projectPath: root,
|
|
1928
3805
|
cwd: st.cwd,
|
|
1929
3806
|
model: st.model,
|
|
1930
3807
|
agentVersion: st.version,
|
|
3808
|
+
host: st.client && /vscode|ide/i.test(st.client) ? "editor" : "terminal",
|
|
3809
|
+
pid: st.pid,
|
|
1931
3810
|
status,
|
|
1932
3811
|
statusDetail: detail,
|
|
1933
|
-
startedAt: st.startedAt,
|
|
3812
|
+
startedAt: st.startedAt ?? st.updatedAt,
|
|
1934
3813
|
updatedAt: st.updatedAt,
|
|
1935
|
-
tasks
|
|
3814
|
+
tasks,
|
|
1936
3815
|
activity,
|
|
1937
|
-
|
|
1938
|
-
costUsd: st.costUsd,
|
|
1939
|
-
daily: st.daily,
|
|
1940
|
-
context: st.context,
|
|
1941
|
-
rateLimits: st.rateLimits,
|
|
3816
|
+
turn: st.turn,
|
|
1942
3817
|
turns: st.turns,
|
|
1943
|
-
|
|
1944
|
-
current: status === "working" || status === "stale" ? st.timer.current(st.tasks) : void 0,
|
|
3818
|
+
current: status === "working" || status === "stale" ? st.timer.current(tasks) : void 0,
|
|
1945
3819
|
recent: st.recent.slice(0, 5),
|
|
3820
|
+
loop: loop ? {
|
|
3821
|
+
label: loop.label,
|
|
3822
|
+
detail: loop.detail,
|
|
3823
|
+
count: loop.count,
|
|
3824
|
+
sameError: loop.sameError,
|
|
3825
|
+
since: loop.since,
|
|
3826
|
+
tokens: loop.tokensAtStart !== void 0 ? totalTokens(st.tokens) - loop.tokensAtStart : void 0
|
|
3827
|
+
} : void 0,
|
|
3828
|
+
tokens,
|
|
3829
|
+
costUsd: st.priced ? st.costUsd : void 0,
|
|
3830
|
+
daily: st.daily,
|
|
3831
|
+
context: st.context ? { used: st.context } : void 0,
|
|
3832
|
+
activeSubagents: status === "working" && st.subagents.size ? st.subagents.size : void 0,
|
|
1946
3833
|
sources: [st.file]
|
|
1947
3834
|
};
|
|
1948
3835
|
}
|
|
1949
3836
|
};
|
|
1950
3837
|
|
|
1951
3838
|
// ../core/src/adapters/gemini-cli.ts
|
|
1952
|
-
import
|
|
3839
|
+
import path8 from "node:path";
|
|
1953
3840
|
var PENDING_TOOL = /* @__PURE__ */ new Set(["scheduled", "validating", "executing"]);
|
|
1954
|
-
function
|
|
3841
|
+
function todoStatus2(s) {
|
|
1955
3842
|
switch (s) {
|
|
1956
3843
|
case "completed":
|
|
1957
3844
|
return "completed";
|
|
@@ -2023,8 +3910,8 @@ var GeminiCliAdapter = class {
|
|
|
2023
3910
|
const homes = [ctx.env.GEMINI_CLI_HOME, ctx.home].filter((h) => !!h);
|
|
2024
3911
|
const out = /* @__PURE__ */ new Set();
|
|
2025
3912
|
for (const h of homes) {
|
|
2026
|
-
out.add(
|
|
2027
|
-
out.add(
|
|
3913
|
+
out.add(path8.join(h, ".gemini", "tmp"));
|
|
3914
|
+
out.add(path8.join(h, ".cache", ".gemini", "tmp"));
|
|
2028
3915
|
}
|
|
2029
3916
|
return [...out];
|
|
2030
3917
|
}
|
|
@@ -2072,18 +3959,18 @@ var GeminiCliAdapter = class {
|
|
|
2072
3959
|
for (const root of this.roots(ctx)) {
|
|
2073
3960
|
for (const proj of await listDir(root)) {
|
|
2074
3961
|
if (!proj.isDirectory()) continue;
|
|
2075
|
-
const projDir =
|
|
2076
|
-
const chats =
|
|
3962
|
+
const projDir = path8.join(root, proj.name);
|
|
3963
|
+
const chats = path8.join(projDir, "chats");
|
|
2077
3964
|
const files = (await listDir(chats)).filter(
|
|
2078
3965
|
(f) => f.isFile() && f.name.startsWith("session-") && (f.name.endsWith(".jsonl") || f.name.endsWith(".json"))
|
|
2079
3966
|
);
|
|
2080
3967
|
if (files.length === 0) continue;
|
|
2081
3968
|
let project;
|
|
2082
3969
|
for (const f of files) {
|
|
2083
|
-
const file =
|
|
3970
|
+
const file = path8.join(chats, f.name);
|
|
2084
3971
|
const st = await statSafe(file);
|
|
2085
3972
|
if (!st || now - st.mtimeMs > ctx.activeWindowMs) continue;
|
|
2086
|
-
if (project === void 0) project = (await readTextSafe(
|
|
3973
|
+
if (project === void 0) project = (await readTextSafe(path8.join(projDir, ".project_root"), 8192))?.trim() || "";
|
|
2087
3974
|
found.push({ file, mtimeMs: st.mtimeMs, project: project || void 0 });
|
|
2088
3975
|
}
|
|
2089
3976
|
}
|
|
@@ -2118,11 +4005,15 @@ var GeminiCliAdapter = class {
|
|
|
2118
4005
|
let updatedAt = 0;
|
|
2119
4006
|
let lastActivity;
|
|
2120
4007
|
let costUsd = 0;
|
|
4008
|
+
let prevTs;
|
|
4009
|
+
const todoStatusSeen = /* @__PURE__ */ new Map();
|
|
2121
4010
|
for (const m of msgs) {
|
|
2122
4011
|
const ts = parseTime(m.timestamp) ?? 0;
|
|
2123
4012
|
if (ts) {
|
|
2124
4013
|
if (startedAt === void 0 || ts < startedAt) startedAt = ts;
|
|
2125
4014
|
if (ts > updatedAt) updatedAt = ts;
|
|
4015
|
+
if (m.type === "gemini") addWork(daily, prevTs, ts);
|
|
4016
|
+
prevTs = Math.max(prevTs ?? 0, ts);
|
|
2126
4017
|
}
|
|
2127
4018
|
if (m.type === "user" && !title) {
|
|
2128
4019
|
const text = contentText(m.content);
|
|
@@ -2158,8 +4049,13 @@ var GeminiCliAdapter = class {
|
|
|
2158
4049
|
tasks = tc.args.todos.map((todo, i) => ({
|
|
2159
4050
|
id: String(i + 1),
|
|
2160
4051
|
title: String(todo?.description ?? ""),
|
|
2161
|
-
status:
|
|
4052
|
+
status: todoStatus2(todo?.status)
|
|
2162
4053
|
}));
|
|
4054
|
+
for (const t2 of tasks) {
|
|
4055
|
+
const before = todoStatusSeen.get(t2.title);
|
|
4056
|
+
if (t2.status === "completed" && before !== void 0 && before !== "completed" && ts) addTaskDone(daily, ts);
|
|
4057
|
+
todoStatusSeen.set(t2.title, t2.status);
|
|
4058
|
+
}
|
|
2163
4059
|
}
|
|
2164
4060
|
}
|
|
2165
4061
|
}
|
|
@@ -2204,7 +4100,7 @@ var GeminiCliAdapter = class {
|
|
|
2204
4100
|
key: `gemini-cli:${st.sessionId ?? st.file}`,
|
|
2205
4101
|
agent: "gemini-cli",
|
|
2206
4102
|
agentLabel: this.label,
|
|
2207
|
-
id: st.sessionId ??
|
|
4103
|
+
id: st.sessionId ?? path8.basename(st.file),
|
|
2208
4104
|
title: st.summary ? truncate(st.summary, 100) : title ?? "Untitled session",
|
|
2209
4105
|
titleFromPrompt: !st.summary && title !== void 0 ? true : void 0,
|
|
2210
4106
|
projectPath: st.projectPath,
|
|
@@ -2220,6 +4116,7 @@ var GeminiCliAdapter = class {
|
|
|
2220
4116
|
costUsd,
|
|
2221
4117
|
daily,
|
|
2222
4118
|
context: context !== void 0 ? { used: context, window: 1048576 } : void 0,
|
|
4119
|
+
host: "terminal",
|
|
2223
4120
|
sources: [st.file]
|
|
2224
4121
|
};
|
|
2225
4122
|
st.cached = session;
|
|
@@ -2233,8 +4130,698 @@ var GeminiCliAdapter = class {
|
|
|
2233
4130
|
}
|
|
2234
4131
|
};
|
|
2235
4132
|
|
|
4133
|
+
// ../core/src/adapters/opencode.ts
|
|
4134
|
+
import path9 from "node:path";
|
|
4135
|
+
var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : Number(v) || 0;
|
|
4136
|
+
function parseData(v) {
|
|
4137
|
+
if (v && typeof v === "object") return v;
|
|
4138
|
+
if (typeof v !== "string" || !v) return void 0;
|
|
4139
|
+
try {
|
|
4140
|
+
const o = JSON.parse(v);
|
|
4141
|
+
return o && typeof o === "object" ? o : void 0;
|
|
4142
|
+
} catch {
|
|
4143
|
+
return void 0;
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
function tokensOf(t) {
|
|
4147
|
+
if (!t || typeof t !== "object") return void 0;
|
|
4148
|
+
const reasoning = num(t.reasoning);
|
|
4149
|
+
return { input: num(t.input), output: num(t.output) + reasoning, cacheRead: num(t.cache?.read), cacheWrite: num(t.cache?.write), reasoning };
|
|
4150
|
+
}
|
|
4151
|
+
function todoStatus3(s) {
|
|
4152
|
+
switch (s) {
|
|
4153
|
+
case "completed":
|
|
4154
|
+
return "completed";
|
|
4155
|
+
case "in_progress":
|
|
4156
|
+
return "in_progress";
|
|
4157
|
+
case "cancelled":
|
|
4158
|
+
return "cancelled";
|
|
4159
|
+
default:
|
|
4160
|
+
return "pending";
|
|
4161
|
+
}
|
|
4162
|
+
}
|
|
4163
|
+
function todosOf(list) {
|
|
4164
|
+
if (!Array.isArray(list)) return void 0;
|
|
4165
|
+
return list.filter((t) => t && typeof t.content === "string" && t.content.trim()).map((t, i) => ({ id: typeof t.id === "string" ? t.id : String(i + 1), title: t.content.trim(), status: todoStatus3(t.status) }));
|
|
4166
|
+
}
|
|
4167
|
+
var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "bash"]);
|
|
4168
|
+
function toolAct(name, input, at) {
|
|
4169
|
+
if (SHELL_TOOLS.has(name)) return { kind: "command", label: "Shell", detail: summarizeCommand(input.command), startedAt: at };
|
|
4170
|
+
const file = typeof input.filePath === "string" ? input.filePath : typeof input.path === "string" ? input.path : void 0;
|
|
4171
|
+
const short = (p2) => p2 ? truncate(p2, 80) : void 0;
|
|
4172
|
+
switch (name) {
|
|
4173
|
+
case "read":
|
|
4174
|
+
return { kind: "tool", label: "Read", detail: short(file), startedAt: at };
|
|
4175
|
+
case "write":
|
|
4176
|
+
return { kind: "tool", label: "Write", detail: short(file), startedAt: at };
|
|
4177
|
+
case "edit":
|
|
4178
|
+
case "multiedit":
|
|
4179
|
+
case "patch":
|
|
4180
|
+
case "apply_patch":
|
|
4181
|
+
return { kind: "tool", label: "Edit", detail: short(file), startedAt: at };
|
|
4182
|
+
case "grep":
|
|
4183
|
+
case "glob":
|
|
4184
|
+
case "codesearch":
|
|
4185
|
+
return { kind: "tool", label: "Search", detail: short(typeof input.pattern === "string" ? input.pattern : typeof input.query === "string" ? input.query : void 0), startedAt: at };
|
|
4186
|
+
case "list":
|
|
4187
|
+
return { kind: "tool", label: "List files", detail: short(file), startedAt: at };
|
|
4188
|
+
case "webfetch":
|
|
4189
|
+
return { kind: "tool", label: "Fetch", detail: short(typeof input.url === "string" ? input.url : void 0), startedAt: at };
|
|
4190
|
+
case "websearch":
|
|
4191
|
+
return { kind: "tool", label: "Web search", detail: short(typeof input.query === "string" ? input.query : void 0), startedAt: at };
|
|
4192
|
+
case "task":
|
|
4193
|
+
case "subagent":
|
|
4194
|
+
return { kind: "subagent", label: "Subagent", detail: short(typeof input.description === "string" ? input.description : void 0), startedAt: at };
|
|
4195
|
+
case "todowrite":
|
|
4196
|
+
return { kind: "tool", label: "Update plan", startedAt: at };
|
|
4197
|
+
case "question":
|
|
4198
|
+
return { kind: "tool", label: "Question", startedAt: at };
|
|
4199
|
+
default:
|
|
4200
|
+
return { kind: "tool", label: name, detail: short(file), startedAt: at };
|
|
4201
|
+
}
|
|
4202
|
+
}
|
|
4203
|
+
function failureOf(name, state, contentText2) {
|
|
4204
|
+
if (state.status === "error") {
|
|
4205
|
+
const e = state.error;
|
|
4206
|
+
return typeof e === "string" ? e : typeof e?.message === "string" ? e.message : "Tool error";
|
|
4207
|
+
}
|
|
4208
|
+
if (state.status !== "completed" || !SHELL_TOOLS.has(name)) return void 0;
|
|
4209
|
+
const m = state.metadata ?? {};
|
|
4210
|
+
if (m.timeout === true) return `Timed out
|
|
4211
|
+
${contentText2()}`;
|
|
4212
|
+
if (typeof m.exit === "number" && m.exit !== 0) return `Exit code ${m.exit}
|
|
4213
|
+
${contentText2()}`;
|
|
4214
|
+
return void 0;
|
|
4215
|
+
}
|
|
4216
|
+
function summarizeV2Tool(item) {
|
|
4217
|
+
if (item?.type !== "tool" || typeof item.name !== "string") return void 0;
|
|
4218
|
+
const state = item.state && typeof item.state === "object" ? item.state : {};
|
|
4219
|
+
const created = num(item.time?.created);
|
|
4220
|
+
const input = state.input && typeof state.input === "object" ? state.input : {};
|
|
4221
|
+
const text = () => Array.isArray(state.content) ? contentText(state.content.filter((c) => c?.type === "text")).slice(-600) : "";
|
|
4222
|
+
return {
|
|
4223
|
+
name: item.name,
|
|
4224
|
+
status: String(state.status ?? "running"),
|
|
4225
|
+
created,
|
|
4226
|
+
completed: item.time?.completed !== void 0 ? num(item.time.completed) : void 0,
|
|
4227
|
+
act: toolAct(item.name, input, created),
|
|
4228
|
+
failure: failureOf(item.name, state, text),
|
|
4229
|
+
todos: item.name === "todowrite" && state.status === "completed" ? todosOf(input.todos) : void 0
|
|
4230
|
+
};
|
|
4231
|
+
}
|
|
4232
|
+
function summarizeV1Tool(part) {
|
|
4233
|
+
if (part?.type !== "tool" || typeof part.tool !== "string") return void 0;
|
|
4234
|
+
const state = part.state && typeof part.state === "object" ? part.state : {};
|
|
4235
|
+
const created = num(state.time?.start);
|
|
4236
|
+
const input = state.input && typeof state.input === "object" ? state.input : {};
|
|
4237
|
+
const text = () => typeof state.output === "string" ? state.output.slice(-600) : "";
|
|
4238
|
+
return {
|
|
4239
|
+
name: part.tool,
|
|
4240
|
+
status: String(state.status ?? "pending"),
|
|
4241
|
+
created,
|
|
4242
|
+
completed: state.time?.end !== void 0 ? num(state.time.end) : void 0,
|
|
4243
|
+
act: toolAct(part.tool, input, created),
|
|
4244
|
+
failure: failureOf(part.tool, state, text),
|
|
4245
|
+
todos: part.tool === "todowrite" && state.status === "completed" ? todosOf(input.todos) : void 0
|
|
4246
|
+
};
|
|
4247
|
+
}
|
|
4248
|
+
function summarizeV2Message(row) {
|
|
4249
|
+
const d = parseData(row.data) ?? {};
|
|
4250
|
+
const created = num(d.time?.created) || num(row.time_created);
|
|
4251
|
+
const s = { id: row.id, order: num(row.seq) || created, type: row.type, created, tools: [] };
|
|
4252
|
+
switch (row.type) {
|
|
4253
|
+
case "user":
|
|
4254
|
+
if (typeof d.text === "string") s.text = d.text;
|
|
4255
|
+
break;
|
|
4256
|
+
case "assistant":
|
|
4257
|
+
case "compaction": {
|
|
4258
|
+
s.model = typeof d.model?.id === "string" ? d.model.id : void 0;
|
|
4259
|
+
s.tokens = tokensOf(d.tokens);
|
|
4260
|
+
s.cost = typeof d.cost === "number" ? d.cost : void 0;
|
|
4261
|
+
if (d.time?.completed !== void 0) s.completed = num(d.time.completed);
|
|
4262
|
+
if (d.error && typeof d.error === "object") s.error = { type: d.error.type, message: String(d.error.message ?? d.error.type ?? "Error") };
|
|
4263
|
+
if (d.retry && typeof d.retry === "object") s.retry = { attempt: num(d.retry.attempt) || void 0, message: String(d.retry.error?.message ?? "Retrying"), at: num(d.retry.at) };
|
|
4264
|
+
if (row.type === "compaction") s.completed = d.status === "running" ? void 0 : created;
|
|
4265
|
+
for (const item of Array.isArray(d.content) ? d.content : []) {
|
|
4266
|
+
const t = summarizeV2Tool(item);
|
|
4267
|
+
if (t) s.tools.push(t);
|
|
4268
|
+
}
|
|
4269
|
+
break;
|
|
4270
|
+
}
|
|
4271
|
+
case "idle":
|
|
4272
|
+
s.outcome = typeof d.outcome === "string" ? d.outcome : void 0;
|
|
4273
|
+
if (d.error && typeof d.error === "object") s.error = { type: d.error.type, message: String(d.error.message ?? "Error") };
|
|
4274
|
+
break;
|
|
4275
|
+
case "synthetic":
|
|
4276
|
+
s.synthetic = true;
|
|
4277
|
+
break;
|
|
4278
|
+
default:
|
|
4279
|
+
break;
|
|
4280
|
+
}
|
|
4281
|
+
return s;
|
|
4282
|
+
}
|
|
4283
|
+
function summarizeV1Message(row) {
|
|
4284
|
+
const d = parseData(row.data) ?? {};
|
|
4285
|
+
const created = num(d.time?.created) || num(row.time_created);
|
|
4286
|
+
const s = { id: row.id, order: created, type: d.role === "assistant" ? "assistant" : "user", created, tools: [] };
|
|
4287
|
+
if (d.role === "assistant") {
|
|
4288
|
+
s.model = typeof d.modelID === "string" ? d.modelID : void 0;
|
|
4289
|
+
s.tokens = tokensOf(d.tokens);
|
|
4290
|
+
s.cost = typeof d.cost === "number" ? d.cost : void 0;
|
|
4291
|
+
if (d.time?.completed !== void 0) s.completed = num(d.time.completed);
|
|
4292
|
+
if (d.error && typeof d.error === "object") {
|
|
4293
|
+
s.error = { type: d.error.name, message: String(d.error.data?.message ?? d.error.message ?? d.error.name ?? "Error") };
|
|
4294
|
+
}
|
|
4295
|
+
}
|
|
4296
|
+
return s;
|
|
4297
|
+
}
|
|
4298
|
+
function foldOpenCode(messages, pricing, explicitTodos) {
|
|
4299
|
+
const daily = {};
|
|
4300
|
+
const f = {
|
|
4301
|
+
lastAt: 0,
|
|
4302
|
+
tokens: emptyTokens(),
|
|
4303
|
+
costUsd: 0,
|
|
4304
|
+
priced: false,
|
|
4305
|
+
daily,
|
|
4306
|
+
tasks: [],
|
|
4307
|
+
timer: new TaskTimer((at) => addTaskDone(daily, at)),
|
|
4308
|
+
recent: [],
|
|
4309
|
+
turns: 0,
|
|
4310
|
+
loops: new LoopWatch(),
|
|
4311
|
+
open: [],
|
|
4312
|
+
afterIdle: false
|
|
4313
|
+
};
|
|
4314
|
+
let prevAt;
|
|
4315
|
+
let steps = 0;
|
|
4316
|
+
let turnStart;
|
|
4317
|
+
for (const m of messages) {
|
|
4318
|
+
if (m.created) {
|
|
4319
|
+
if (f.startedAt === void 0 || m.created < f.startedAt) f.startedAt = m.created;
|
|
4320
|
+
f.lastAt = Math.max(f.lastAt, m.created, m.completed ?? 0);
|
|
4321
|
+
}
|
|
4322
|
+
if (m.type === "user" && !m.synthetic) {
|
|
4323
|
+
const text = m.text?.trim();
|
|
4324
|
+
if (text && !f.title) f.title = firstLine(text, 100);
|
|
4325
|
+
turnStart = m.created;
|
|
4326
|
+
steps = 0;
|
|
4327
|
+
f.turns += 1;
|
|
4328
|
+
f.loops.reset();
|
|
4329
|
+
prevAt = m.created;
|
|
4330
|
+
f.afterIdle = true;
|
|
4331
|
+
continue;
|
|
4332
|
+
}
|
|
4333
|
+
if (m.type === "idle") {
|
|
4334
|
+
f.lastIdle = m;
|
|
4335
|
+
f.afterIdle = false;
|
|
4336
|
+
continue;
|
|
4337
|
+
}
|
|
4338
|
+
if (m.type !== "assistant" && m.type !== "compaction") continue;
|
|
4339
|
+
f.afterIdle = true;
|
|
4340
|
+
f.last = m;
|
|
4341
|
+
if (m.model) f.model = m.model;
|
|
4342
|
+
if (m.tokens) {
|
|
4343
|
+
const u = m.tokens;
|
|
4344
|
+
f.tokens.input += u.input;
|
|
4345
|
+
f.tokens.output += u.output;
|
|
4346
|
+
f.tokens.cacheRead += u.cacheRead;
|
|
4347
|
+
f.tokens.cacheWrite += u.cacheWrite;
|
|
4348
|
+
f.tokens.reasoning = (f.tokens.reasoning ?? 0) + (u.reasoning ?? 0);
|
|
4349
|
+
let cost = m.cost;
|
|
4350
|
+
if (!cost) {
|
|
4351
|
+
const est = pricing.cost(m.model ?? f.model, { input: u.input, output: u.output, cacheRead: u.cacheRead, cacheWrite5m: u.cacheWrite, cacheWrite1h: 0 });
|
|
4352
|
+
if (est !== void 0) cost = est;
|
|
4353
|
+
}
|
|
4354
|
+
if (cost !== void 0) f.priced = true;
|
|
4355
|
+
f.costUsd += cost ?? 0;
|
|
4356
|
+
const b = daily[dayKey(m.created || Date.now())] ??= { tokens: 0, costUsd: 0 };
|
|
4357
|
+
b.tokens += totalTokens(u);
|
|
4358
|
+
b.costUsd += cost ?? 0;
|
|
4359
|
+
if (m.type === "assistant" && u.input + u.cacheRead + u.cacheWrite > 0) f.context = u.input + u.cacheRead + u.cacheWrite;
|
|
4360
|
+
}
|
|
4361
|
+
const end2 = m.completed ?? Math.max(m.created, ...m.tools.map((t) => t.completed ?? t.created));
|
|
4362
|
+
if (end2) {
|
|
4363
|
+
addWork(daily, prevAt, end2);
|
|
4364
|
+
prevAt = Math.max(prevAt ?? 0, end2);
|
|
4365
|
+
}
|
|
4366
|
+
for (const t of m.tools) {
|
|
4367
|
+
steps += 1;
|
|
4368
|
+
f.timer.step();
|
|
4369
|
+
if (f.recent[0]) f.recent[0].endedAt ??= t.created || void 0;
|
|
4370
|
+
f.recent.unshift({ ...t.act, endedAt: t.completed });
|
|
4371
|
+
if (f.recent.length > 6) f.recent.length = 6;
|
|
4372
|
+
if (t.status === "completed" || t.status === "error") f.loops.observe(loopKey(t.act), t.act, t.failure, t.completed ?? t.created, totalTokens(f.tokens));
|
|
4373
|
+
if (t.todos && !explicitTodos) {
|
|
4374
|
+
f.tasks = t.todos;
|
|
4375
|
+
f.timer.observe(t.todos, t.completed ?? t.created);
|
|
4376
|
+
}
|
|
4377
|
+
}
|
|
4378
|
+
}
|
|
4379
|
+
if (explicitTodos) {
|
|
4380
|
+
f.tasks = explicitTodos.tasks;
|
|
4381
|
+
f.timer.observe(explicitTodos.tasks, explicitTodos.at);
|
|
4382
|
+
}
|
|
4383
|
+
if (f.last && f.last.completed === void 0 && !f.last.error) f.open = f.last.tools.filter((t) => t.status === "running" || t.status === "streaming" || t.status === "pending");
|
|
4384
|
+
if (turnStart !== void 0) f.turn = { steps, startedAt: turnStart };
|
|
4385
|
+
return f;
|
|
4386
|
+
}
|
|
4387
|
+
function rowBusy(row) {
|
|
4388
|
+
if (!("time_busy" in row)) return void 0;
|
|
4389
|
+
const busy = row.time_busy == null ? void 0 : num(row.time_busy);
|
|
4390
|
+
const idle = row.time_idle == null ? void 0 : num(row.time_idle);
|
|
4391
|
+
if (busy === void 0) return false;
|
|
4392
|
+
return idle === void 0 || busy > idle;
|
|
4393
|
+
}
|
|
4394
|
+
function openCodeStatus(f, row, layout, label, live) {
|
|
4395
|
+
const last = f.last;
|
|
4396
|
+
const busy = isBusy(f, row, layout);
|
|
4397
|
+
const prog = progressOf(f.tasks);
|
|
4398
|
+
if (busy) {
|
|
4399
|
+
if (live?.permission) return { status: "waiting", detail: `Needs approval: ${live.permission}`, activity: f.open[f.open.length - 1]?.act };
|
|
4400
|
+
const question = f.open.find((t) => t.name === "question");
|
|
4401
|
+
if (live?.question || question) return { status: "waiting", detail: "Asked you a question", activity: question?.act };
|
|
4402
|
+
const activity = f.open[f.open.length - 1]?.act ?? (last && last.completed === void 0 ? { kind: "thinking", label: "Thinking", startedAt: last.created } : void 0);
|
|
4403
|
+
const retry = last && last.completed === void 0 ? last.retry : void 0;
|
|
4404
|
+
return { status: "working", activity, trouble: retry ? { message: firstLine(retry.message, 120), at: retry.at || last.created, attempt: retry.attempt } : void 0 };
|
|
4405
|
+
}
|
|
4406
|
+
const finished = { status: prog.total > 0 && prog.done === prog.total ? "done" : "idle" };
|
|
4407
|
+
const outcome = layout === "v2" ? typeof row.idle_outcome === "string" ? row.idle_outcome : f.lastIdle?.outcome : void 0;
|
|
4408
|
+
if (outcome === "failed") return { status: "error", detail: firstLine(f.lastIdle?.error?.message ?? last?.error?.message ?? "The turn failed", 140) };
|
|
4409
|
+
if (outcome === "interrupted") return { status: "idle", detail: "Stopped" };
|
|
4410
|
+
if (outcome === "succeeded") return finished;
|
|
4411
|
+
if (last?.error) {
|
|
4412
|
+
const aborted = last.error.type === "MessageAbortedError" || last.error.type === "aborted";
|
|
4413
|
+
if (aborted) return { status: "idle", detail: "Stopped" };
|
|
4414
|
+
return { status: "error", detail: firstLine(last.error.message, 140) };
|
|
4415
|
+
}
|
|
4416
|
+
return finished;
|
|
4417
|
+
}
|
|
4418
|
+
function isBusy(f, row, layout) {
|
|
4419
|
+
if (layout === "v2") {
|
|
4420
|
+
return rowBusy(row) ?? f.afterIdle;
|
|
4421
|
+
}
|
|
4422
|
+
if (f.last && f.last.completed === void 0 && !f.last.error) return true;
|
|
4423
|
+
return f.turn !== void 0 && (!f.last || f.last.created < f.turn.startedAt);
|
|
4424
|
+
}
|
|
4425
|
+
var SLACK_MS = 2e3;
|
|
4426
|
+
var FULL_RELOAD_MS = 6e4;
|
|
4427
|
+
var OpenCodeFamilyAdapter = class {
|
|
4428
|
+
/** Ask the agent's local service for open permission prompts (OpenCode 2.x). */
|
|
4429
|
+
probeService = false;
|
|
4430
|
+
options;
|
|
4431
|
+
db;
|
|
4432
|
+
dbFile;
|
|
4433
|
+
layout;
|
|
4434
|
+
columns = /* @__PURE__ */ new Map();
|
|
4435
|
+
lastOpenTry = 0;
|
|
4436
|
+
cache = /* @__PURE__ */ new Map();
|
|
4437
|
+
sessions = [];
|
|
4438
|
+
lastQuery = 0;
|
|
4439
|
+
busyChildren = /* @__PURE__ */ new Map();
|
|
4440
|
+
warned = false;
|
|
4441
|
+
live = new LiveProbe();
|
|
4442
|
+
constructor(options = {}) {
|
|
4443
|
+
this.options = options;
|
|
4444
|
+
}
|
|
4445
|
+
dataDir(ctx) {
|
|
4446
|
+
return path9.join(ctx.env.XDG_DATA_HOME || path9.join(ctx.home, ".local", "share"), this.app);
|
|
4447
|
+
}
|
|
4448
|
+
databaseFile(ctx) {
|
|
4449
|
+
if (this.options.dbFile) return this.options.dbFile;
|
|
4450
|
+
const override = ctx.env[this.dbEnv];
|
|
4451
|
+
if (override && override !== ":memory:") return path9.isAbsolute(override) ? override : path9.join(this.dataDir(ctx), override);
|
|
4452
|
+
return path9.join(this.dataDir(ctx), `${this.app}.db`);
|
|
4453
|
+
}
|
|
4454
|
+
async poll(ctx) {
|
|
4455
|
+
const now = ctx.now();
|
|
4456
|
+
if (!this.db) {
|
|
4457
|
+
if (now - this.lastOpenTry < 3e4 && this.lastOpenTry) return [];
|
|
4458
|
+
this.lastOpenTry = now;
|
|
4459
|
+
const file = this.databaseFile(ctx);
|
|
4460
|
+
if (!await statSafe(file)) return [];
|
|
4461
|
+
if (!sqliteModule()) {
|
|
4462
|
+
if (!this.warned) ctx.log(`${this.label}: this runtime has no built-in SQLite (node:sqlite, Node 22.13+), so its sessions cannot be read here.`);
|
|
4463
|
+
this.warned = true;
|
|
4464
|
+
return [];
|
|
4465
|
+
}
|
|
4466
|
+
this.db = ReadOnlyDb.open(file);
|
|
4467
|
+
this.dbFile = file;
|
|
4468
|
+
if (!this.db) return [];
|
|
4469
|
+
this.columns = this.db.schema();
|
|
4470
|
+
this.layout = this.columns.has("session_v2") && this.columns.has("session_message") ? "v2" : this.columns.has("session") && this.columns.has("message") ? "v1" : void 0;
|
|
4471
|
+
if (!this.layout) {
|
|
4472
|
+
this.dispose();
|
|
4473
|
+
return [];
|
|
4474
|
+
}
|
|
4475
|
+
}
|
|
4476
|
+
const db = this.db;
|
|
4477
|
+
if (db.changed() || now - this.lastQuery >= 1e4) {
|
|
4478
|
+
this.lastQuery = now;
|
|
4479
|
+
if (this.layout === "v1" && db.get("SELECT 1 AS x FROM sqlite_master WHERE name = 'session_v2'")) {
|
|
4480
|
+
this.columns = db.schema();
|
|
4481
|
+
this.layout = "v2";
|
|
4482
|
+
this.cache.clear();
|
|
4483
|
+
}
|
|
4484
|
+
this.query(db, ctx);
|
|
4485
|
+
}
|
|
4486
|
+
this.sessions = [...this.cache.values()].map((c) => this.toSession(c, ctx)).filter((s) => !!s);
|
|
4487
|
+
if (this.probeService) await this.live.refresh(ctx, this.sessions.filter((s) => s.status === "working" || s.status === "waiting").map((s) => s.id));
|
|
4488
|
+
return this.sessions;
|
|
4489
|
+
}
|
|
4490
|
+
dispose() {
|
|
4491
|
+
this.db?.close();
|
|
4492
|
+
this.db = void 0;
|
|
4493
|
+
this.cache.clear();
|
|
4494
|
+
}
|
|
4495
|
+
sessionTable() {
|
|
4496
|
+
return this.layout === "v2" ? "session_v2" : "session";
|
|
4497
|
+
}
|
|
4498
|
+
query(db, ctx) {
|
|
4499
|
+
const now = ctx.now();
|
|
4500
|
+
const table = this.sessionTable();
|
|
4501
|
+
const have = this.columns.get(table) ?? /* @__PURE__ */ new Set();
|
|
4502
|
+
const wanted = [
|
|
4503
|
+
"id",
|
|
4504
|
+
"parent_id",
|
|
4505
|
+
"directory",
|
|
4506
|
+
"title",
|
|
4507
|
+
"cost",
|
|
4508
|
+
"tokens_input",
|
|
4509
|
+
"tokens_output",
|
|
4510
|
+
"tokens_reasoning",
|
|
4511
|
+
"tokens_cache_read",
|
|
4512
|
+
"tokens_cache_write",
|
|
4513
|
+
"model",
|
|
4514
|
+
"agent",
|
|
4515
|
+
"version",
|
|
4516
|
+
"revert",
|
|
4517
|
+
"time_created",
|
|
4518
|
+
"time_updated",
|
|
4519
|
+
"time_busy",
|
|
4520
|
+
"time_idle",
|
|
4521
|
+
"idle_outcome",
|
|
4522
|
+
"time_suspended",
|
|
4523
|
+
"time_archived"
|
|
4524
|
+
].filter((c) => have.has(c));
|
|
4525
|
+
if (!have.has("id") || !have.has("time_updated")) return;
|
|
4526
|
+
const where = [`time_updated >= ?`, have.has("parent_id") ? "parent_id IS NULL" : "", have.has("time_archived") ? "time_archived IS NULL" : ""].filter(Boolean).join(" AND ");
|
|
4527
|
+
const rows = db.all(`SELECT ${wanted.join(", ")} FROM ${table} WHERE ${where} ORDER BY time_updated DESC LIMIT ?`, now - ctx.activeWindowMs, ctx.maxSessionsPerAgent);
|
|
4528
|
+
const keep = /* @__PURE__ */ new Set();
|
|
4529
|
+
for (const row of rows) {
|
|
4530
|
+
const id = String(row.id);
|
|
4531
|
+
keep.add(id);
|
|
4532
|
+
let c = this.cache.get(id);
|
|
4533
|
+
const updated = num(row.time_updated);
|
|
4534
|
+
if (!c) {
|
|
4535
|
+
c = { id, row, rowUpdated: -1, msgs: /* @__PURE__ */ new Map(), parts: /* @__PURE__ */ new Map(), maxMsgUpdated: 0, maxPartUpdated: 0, lastFull: 0 };
|
|
4536
|
+
this.cache.set(id, c);
|
|
4537
|
+
}
|
|
4538
|
+
const wasBusy = c.fold ? openCodeStatus(c.fold, c.row, this.layout, this.label, void 0).status === "working" : true;
|
|
4539
|
+
const revertChanged = String(c.row.revert ?? "") !== String(row.revert ?? "");
|
|
4540
|
+
c.row = row;
|
|
4541
|
+
if (updated !== c.rowUpdated || wasBusy || rowBusy(row) || revertChanged) {
|
|
4542
|
+
if (revertChanged || now - c.lastFull >= FULL_RELOAD_MS) this.reload(db, c, now);
|
|
4543
|
+
else this.readChanges(db, c);
|
|
4544
|
+
c.rowUpdated = updated;
|
|
4545
|
+
c.fold = void 0;
|
|
4546
|
+
}
|
|
4547
|
+
}
|
|
4548
|
+
for (const id of [...this.cache.keys()]) if (!keep.has(id)) this.cache.delete(id);
|
|
4549
|
+
this.busyChildren = this.countBusyChildren(db, now);
|
|
4550
|
+
}
|
|
4551
|
+
reload(db, c, now) {
|
|
4552
|
+
c.msgs.clear();
|
|
4553
|
+
c.parts.clear();
|
|
4554
|
+
c.maxMsgUpdated = 0;
|
|
4555
|
+
c.maxPartUpdated = 0;
|
|
4556
|
+
c.lastFull = now;
|
|
4557
|
+
this.readChanges(db, c);
|
|
4558
|
+
}
|
|
4559
|
+
/** Reads the rows of the session written since the last read. */
|
|
4560
|
+
readChanges(db, c) {
|
|
4561
|
+
if (this.layout === "v2") {
|
|
4562
|
+
for (const r of db.all("SELECT id, type, seq, time_created, time_updated, data FROM session_message WHERE session_id = ? AND time_updated >= ?", c.id, c.maxMsgUpdated - SLACK_MS)) {
|
|
4563
|
+
c.msgs.set(String(r.id), summarizeV2Message({ id: String(r.id), type: String(r.type), seq: r.seq, time_created: r.time_created, data: r.data }));
|
|
4564
|
+
c.maxMsgUpdated = Math.max(c.maxMsgUpdated, num(r.time_updated));
|
|
4565
|
+
}
|
|
4566
|
+
if (this.columns.has("session_part")) {
|
|
4567
|
+
for (const r of db.all("SELECT message_id, ordinal, time_updated, data FROM session_part WHERE session_id = ? AND time_updated >= ?", c.id, c.maxPartUpdated - SLACK_MS)) {
|
|
4568
|
+
const tool = summarizeV2Tool(parseData(r.data) ?? {});
|
|
4569
|
+
c.parts.set(`${r.message_id}:${r.ordinal}`, { messageId: String(r.message_id), order: num(r.ordinal), tool });
|
|
4570
|
+
c.maxPartUpdated = Math.max(c.maxPartUpdated, num(r.time_updated));
|
|
4571
|
+
}
|
|
4572
|
+
}
|
|
4573
|
+
const n2 = num(db.get("SELECT count(*) AS n FROM session_message WHERE session_id = ?", c.id)?.n);
|
|
4574
|
+
if (n2 < c.msgs.size) this.reload(db, c, c.lastFull);
|
|
4575
|
+
return;
|
|
4576
|
+
}
|
|
4577
|
+
for (const r of db.all("SELECT id, time_created, time_updated, data FROM message WHERE session_id = ? AND time_updated >= ?", c.id, c.maxMsgUpdated - SLACK_MS)) {
|
|
4578
|
+
c.msgs.set(String(r.id), summarizeV1Message({ id: String(r.id), time_created: r.time_created, data: r.data }));
|
|
4579
|
+
c.maxMsgUpdated = Math.max(c.maxMsgUpdated, num(r.time_updated));
|
|
4580
|
+
}
|
|
4581
|
+
for (const r of db.all("SELECT id, message_id, time_updated, data FROM part WHERE session_id = ? AND time_updated >= ?", c.id, c.maxPartUpdated - SLACK_MS)) {
|
|
4582
|
+
const d = parseData(r.data) ?? {};
|
|
4583
|
+
const p2 = { messageId: String(r.message_id), order: String(r.id) };
|
|
4584
|
+
if (d.type === "tool") p2.tool = summarizeV1Tool(d);
|
|
4585
|
+
else if (d.type === "text" && typeof d.text === "string") {
|
|
4586
|
+
p2.text = d.text;
|
|
4587
|
+
p2.synthetic = d.synthetic === true;
|
|
4588
|
+
} else if (d.type === "retry") p2.retry = { attempt: num(d.attempt) || void 0, message: String(d.error?.data?.message ?? d.error?.message ?? "Retrying"), at: num(d.time?.created) };
|
|
4589
|
+
c.parts.set(String(r.id), p2);
|
|
4590
|
+
c.maxPartUpdated = Math.max(c.maxPartUpdated, num(r.time_updated));
|
|
4591
|
+
}
|
|
4592
|
+
const n = num(db.get("SELECT count(*) AS n FROM message WHERE session_id = ?", c.id)?.n);
|
|
4593
|
+
if (n < c.msgs.size) this.reload(db, c, c.lastFull);
|
|
4594
|
+
if (this.columns.has("todo")) {
|
|
4595
|
+
const rows = db.all("SELECT content, status, position, time_updated FROM todo WHERE session_id = ? ORDER BY position", c.id);
|
|
4596
|
+
const sig = JSON.stringify(rows);
|
|
4597
|
+
if (sig !== c.todoSig) {
|
|
4598
|
+
c.todoSig = sig;
|
|
4599
|
+
c.todos = rows.length ? { tasks: todosOf(rows) ?? [], at: Math.max(...rows.map((r) => num(r.time_updated))) } : void 0;
|
|
4600
|
+
}
|
|
4601
|
+
}
|
|
4602
|
+
}
|
|
4603
|
+
/** Subagent sessions at work, per parent. */
|
|
4604
|
+
countBusyChildren(db, now) {
|
|
4605
|
+
const out = /* @__PURE__ */ new Map();
|
|
4606
|
+
const table = this.sessionTable();
|
|
4607
|
+
const have = this.columns.get(table) ?? /* @__PURE__ */ new Set();
|
|
4608
|
+
if (!have.has("parent_id")) return out;
|
|
4609
|
+
let rows = [];
|
|
4610
|
+
if (this.layout === "v2" && have.has("time_busy")) {
|
|
4611
|
+
rows = db.all(`SELECT parent_id, count(*) AS n FROM ${table} WHERE parent_id IS NOT NULL AND time_updated >= ? AND time_busy IS NOT NULL AND (time_idle IS NULL OR time_busy > time_idle) GROUP BY parent_id`, now - 36e5);
|
|
4612
|
+
} else if (this.layout === "v1") {
|
|
4613
|
+
rows = db.all(
|
|
4614
|
+
`SELECT s.parent_id AS parent_id, count(*) AS n FROM session s WHERE s.parent_id IS NOT NULL AND s.time_updated >= ? AND EXISTS (
|
|
4615
|
+
SELECT 1 FROM message m WHERE m.session_id = s.id AND json_extract(m.data, '$.role') = 'assistant'
|
|
4616
|
+
AND json_extract(m.data, '$.time.completed') IS NULL AND json_extract(m.data, '$.error') IS NULL) GROUP BY s.parent_id`,
|
|
4617
|
+
now - 6e5
|
|
4618
|
+
);
|
|
4619
|
+
}
|
|
4620
|
+
for (const r of rows) out.set(String(r.parent_id), num(r.n));
|
|
4621
|
+
return out;
|
|
4622
|
+
}
|
|
4623
|
+
/** The session's messages in order, each with its tool calls (parts first, then inline items). */
|
|
4624
|
+
ordered(c) {
|
|
4625
|
+
const partsBy = /* @__PURE__ */ new Map();
|
|
4626
|
+
for (const p2 of c.parts.values()) {
|
|
4627
|
+
const list = partsBy.get(p2.messageId);
|
|
4628
|
+
if (list) list.push(p2);
|
|
4629
|
+
else partsBy.set(p2.messageId, [p2]);
|
|
4630
|
+
}
|
|
4631
|
+
const revert = parseData(c.row.revert);
|
|
4632
|
+
const cut = typeof revert?.messageID === "string" ? revert.messageID : void 0;
|
|
4633
|
+
const out = [];
|
|
4634
|
+
for (const m of c.msgs.values()) {
|
|
4635
|
+
if (cut && m.id >= cut) continue;
|
|
4636
|
+
const parts = (partsBy.get(m.id) ?? []).sort((a, b) => a.order < b.order ? -1 : a.order > b.order ? 1 : 0);
|
|
4637
|
+
if (!parts.length) {
|
|
4638
|
+
out.push(m);
|
|
4639
|
+
continue;
|
|
4640
|
+
}
|
|
4641
|
+
const copy = { ...m, tools: [...parts.map((p2) => p2.tool).filter((t) => !!t), ...m.tools] };
|
|
4642
|
+
if (m.type === "user" && copy.text === void 0) {
|
|
4643
|
+
const texts = parts.filter((p2) => p2.text !== void 0 && !p2.synthetic).map((p2) => p2.text);
|
|
4644
|
+
if (texts.length) copy.text = texts.join("\n");
|
|
4645
|
+
else if (parts.some((p2) => p2.synthetic)) copy.synthetic = true;
|
|
4646
|
+
}
|
|
4647
|
+
const retry = parts.filter((p2) => p2.retry).pop()?.retry;
|
|
4648
|
+
if (retry && !copy.retry) copy.retry = retry;
|
|
4649
|
+
out.push(copy);
|
|
4650
|
+
}
|
|
4651
|
+
return out.sort((a, b) => a.order - b.order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
4652
|
+
}
|
|
4653
|
+
toSession(c, ctx) {
|
|
4654
|
+
const layout = this.layout;
|
|
4655
|
+
c.fold ??= foldOpenCode(this.ordered(c), ctx.pricing, c.todos);
|
|
4656
|
+
const f = c.fold;
|
|
4657
|
+
const row = c.row;
|
|
4658
|
+
const now = ctx.now();
|
|
4659
|
+
const live = this.probeService ? this.live.get(c.id, now) : void 0;
|
|
4660
|
+
let { status, detail, activity, trouble } = openCodeStatus(f, row, layout, this.label, live);
|
|
4661
|
+
const updatedAt = Math.max(num(row.time_updated), f.lastAt);
|
|
4662
|
+
if (status === "working") {
|
|
4663
|
+
if (this.probeService && this.live.serviceGone()) {
|
|
4664
|
+
status = "idle";
|
|
4665
|
+
detail = `${this.label} was closed`;
|
|
4666
|
+
activity = void 0;
|
|
4667
|
+
} else {
|
|
4668
|
+
const stale = staleness(updatedAt, ctx);
|
|
4669
|
+
if (stale) {
|
|
4670
|
+
status = "stale";
|
|
4671
|
+
detail = stale;
|
|
4672
|
+
activity = void 0;
|
|
4673
|
+
trouble = void 0;
|
|
4674
|
+
}
|
|
4675
|
+
}
|
|
4676
|
+
}
|
|
4677
|
+
const rowTitle = typeof row.title === "string" ? row.title.trim() : "";
|
|
4678
|
+
const untitled = !rowTitle || /^(New session|Child session)( - \d{4}-\d\d-\d\dT[\d:.]+Z?)?$/.test(rowTitle);
|
|
4679
|
+
const title = untitled ? f.title : truncate(rowTitle, 100);
|
|
4680
|
+
const model = parseData(row.model);
|
|
4681
|
+
const dir = typeof row.directory === "string" && row.directory ? row.directory.replace(/\//g, path9.sep === "\\" ? "\\" : "/") : void 0;
|
|
4682
|
+
const rowTokens = "tokens_input" in row ? {
|
|
4683
|
+
input: num(row.tokens_input),
|
|
4684
|
+
output: num(row.tokens_output) + num(row.tokens_reasoning),
|
|
4685
|
+
cacheRead: num(row.tokens_cache_read),
|
|
4686
|
+
cacheWrite: num(row.tokens_cache_write),
|
|
4687
|
+
reasoning: num(row.tokens_reasoning)
|
|
4688
|
+
} : void 0;
|
|
4689
|
+
const tokens = rowTokens && totalTokens(rowTokens) >= totalTokens(f.tokens) ? rowTokens : { ...f.tokens };
|
|
4690
|
+
const rowCost = num(row.cost);
|
|
4691
|
+
const loop = status === "working" || status === "stale" ? f.loops.current(now) : void 0;
|
|
4692
|
+
const children = this.busyChildren.get(c.id);
|
|
4693
|
+
return {
|
|
4694
|
+
key: `${this.id}:${c.id}`,
|
|
4695
|
+
agent: this.id,
|
|
4696
|
+
agentLabel: this.label,
|
|
4697
|
+
id: c.id,
|
|
4698
|
+
title: title ?? "Untitled session",
|
|
4699
|
+
titleFromPrompt: untitled && title !== void 0 ? true : void 0,
|
|
4700
|
+
projectPath: dir ? findGitRoot(dir) ?? dir : void 0,
|
|
4701
|
+
cwd: dir,
|
|
4702
|
+
model: f.model ?? (typeof model?.id === "string" ? model.id : void 0),
|
|
4703
|
+
agentVersion: typeof row.version === "string" ? row.version : void 0,
|
|
4704
|
+
status,
|
|
4705
|
+
statusDetail: detail,
|
|
4706
|
+
startedAt: num(row.time_created) || f.startedAt || updatedAt,
|
|
4707
|
+
updatedAt,
|
|
4708
|
+
tasks: f.tasks,
|
|
4709
|
+
activity: status === "working" || status === "waiting" ? activity : void 0,
|
|
4710
|
+
turn: f.turn,
|
|
4711
|
+
turns: f.turns,
|
|
4712
|
+
current: status === "working" || status === "stale" ? f.timer.current(f.tasks) : void 0,
|
|
4713
|
+
recent: f.recent.slice(0, 5),
|
|
4714
|
+
loop: loop ? {
|
|
4715
|
+
label: loop.label,
|
|
4716
|
+
detail: loop.detail,
|
|
4717
|
+
count: loop.count,
|
|
4718
|
+
sameError: loop.sameError,
|
|
4719
|
+
since: loop.since,
|
|
4720
|
+
tokens: loop.tokensAtStart !== void 0 ? totalTokens(f.tokens) - loop.tokensAtStart : void 0
|
|
4721
|
+
} : void 0,
|
|
4722
|
+
trouble,
|
|
4723
|
+
tokens,
|
|
4724
|
+
costUsd: f.priced || rowCost > 0 ? Math.max(rowCost, f.costUsd) : void 0,
|
|
4725
|
+
daily: f.daily,
|
|
4726
|
+
context: f.context ? { used: f.context } : void 0,
|
|
4727
|
+
activeSubagents: children || void 0,
|
|
4728
|
+
sources: [this.dbFile ?? this.databaseFile(ctx)]
|
|
4729
|
+
};
|
|
4730
|
+
}
|
|
4731
|
+
};
|
|
4732
|
+
var LiveProbe = class {
|
|
4733
|
+
service;
|
|
4734
|
+
waits = /* @__PURE__ */ new Map();
|
|
4735
|
+
inFlight = false;
|
|
4736
|
+
lastAsk = 0;
|
|
4737
|
+
serviceGone() {
|
|
4738
|
+
return this.service?.alive === false;
|
|
4739
|
+
}
|
|
4740
|
+
get(id, now) {
|
|
4741
|
+
const w = this.waits.get(id);
|
|
4742
|
+
return w && now - w.at < 1e4 ? w.wait : void 0;
|
|
4743
|
+
}
|
|
4744
|
+
async refresh(ctx, busy) {
|
|
4745
|
+
const now = ctx.now();
|
|
4746
|
+
if (!this.service || now - this.service.checkedAt >= 1e4) await this.readService(ctx);
|
|
4747
|
+
const s = this.service;
|
|
4748
|
+
if (!s?.url || s.alive === false || !busy.length || this.inFlight || now - this.lastAsk < 2500) return;
|
|
4749
|
+
this.inFlight = true;
|
|
4750
|
+
this.lastAsk = now;
|
|
4751
|
+
void Promise.all(busy.slice(0, 8).map((id) => this.ask(s, id, now))).finally(() => {
|
|
4752
|
+
this.inFlight = false;
|
|
4753
|
+
});
|
|
4754
|
+
}
|
|
4755
|
+
async readService(ctx) {
|
|
4756
|
+
const file = path9.join(ctx.env.XDG_STATE_HOME || path9.join(ctx.home, ".local", "state"), "opencode", "service.json");
|
|
4757
|
+
const info = await readJsonSafe(file, 64 << 10);
|
|
4758
|
+
const now = ctx.now();
|
|
4759
|
+
if (!info || typeof info.url !== "string") {
|
|
4760
|
+
this.service = { url: "", checkedAt: now };
|
|
4761
|
+
return;
|
|
4762
|
+
}
|
|
4763
|
+
let loopback = false;
|
|
4764
|
+
try {
|
|
4765
|
+
const u = new URL(info.url);
|
|
4766
|
+
loopback = u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]", "::1"].includes(u.hostname);
|
|
4767
|
+
} catch {
|
|
4768
|
+
loopback = false;
|
|
4769
|
+
}
|
|
4770
|
+
const pid = typeof info.pid === "number" ? info.pid : void 0;
|
|
4771
|
+
let alive;
|
|
4772
|
+
if (pid) {
|
|
4773
|
+
try {
|
|
4774
|
+
process.kill(pid, 0);
|
|
4775
|
+
alive = true;
|
|
4776
|
+
} catch (e) {
|
|
4777
|
+
alive = e.code === "EPERM";
|
|
4778
|
+
}
|
|
4779
|
+
}
|
|
4780
|
+
this.service = {
|
|
4781
|
+
url: loopback ? info.url : "",
|
|
4782
|
+
auth: typeof info.password === "string" ? `Basic ${Buffer.from(`opencode:${info.password}`).toString("base64")}` : void 0,
|
|
4783
|
+
pid,
|
|
4784
|
+
alive,
|
|
4785
|
+
checkedAt: now
|
|
4786
|
+
};
|
|
4787
|
+
}
|
|
4788
|
+
async ask(s, id, now) {
|
|
4789
|
+
const headers = { accept: "application/json" };
|
|
4790
|
+
if (s.auth) headers.authorization = s.auth;
|
|
4791
|
+
const get = async (p3) => {
|
|
4792
|
+
try {
|
|
4793
|
+
const res = await fetch(new URL(p3, s.url), { headers, signal: AbortSignal.timeout(1500) });
|
|
4794
|
+
if (!res.ok) return void 0;
|
|
4795
|
+
const body = await res.json();
|
|
4796
|
+
return Array.isArray(body?.data) ? body.data : void 0;
|
|
4797
|
+
} catch {
|
|
4798
|
+
return void 0;
|
|
4799
|
+
}
|
|
4800
|
+
};
|
|
4801
|
+
const enc = encodeURIComponent(id);
|
|
4802
|
+
const [perms, forms] = await Promise.all([get(`/api/session/${enc}/permission`), get(`/api/session/${enc}/form`)]);
|
|
4803
|
+
if (perms === void 0 && forms === void 0) return;
|
|
4804
|
+
const p2 = perms?.[0];
|
|
4805
|
+
const what = p2 ? [String(p2.action ?? "a tool"), Array.isArray(p2.resources) && typeof p2.resources[0] === "string" ? truncate(p2.resources[0], 60) : ""].filter(Boolean).join(" ") : void 0;
|
|
4806
|
+
this.waits.set(id, { at: now, wait: { permission: what, question: !!forms?.length } });
|
|
4807
|
+
}
|
|
4808
|
+
};
|
|
4809
|
+
var OpenCodeAdapter = class extends OpenCodeFamilyAdapter {
|
|
4810
|
+
id = "opencode";
|
|
4811
|
+
label = "OpenCode";
|
|
4812
|
+
app = "opencode";
|
|
4813
|
+
dbEnv = "OPENCODE_DB";
|
|
4814
|
+
probeService = true;
|
|
4815
|
+
};
|
|
4816
|
+
var KiloCodeAdapter = class extends OpenCodeFamilyAdapter {
|
|
4817
|
+
id = "kilo-code";
|
|
4818
|
+
label = "Kilo Code";
|
|
4819
|
+
app = "kilo";
|
|
4820
|
+
dbEnv = "KILO_DB";
|
|
4821
|
+
};
|
|
4822
|
+
|
|
2236
4823
|
// ../core/src/adapters/progress-file.ts
|
|
2237
|
-
import
|
|
4824
|
+
import path10 from "node:path";
|
|
2238
4825
|
var STATUS_WORDS = {
|
|
2239
4826
|
working: "working",
|
|
2240
4827
|
running: "working",
|
|
@@ -2257,10 +4844,10 @@ var ProgressFileAdapter = class {
|
|
|
2257
4844
|
async poll(ctx) {
|
|
2258
4845
|
const files = [];
|
|
2259
4846
|
for (const root of ctx.workspaceRoots) {
|
|
2260
|
-
const agentsDir =
|
|
2261
|
-
files.push({ file:
|
|
2262
|
-
for (const f of await listDir(
|
|
2263
|
-
if (f.isFile() && f.name.endsWith(".md")) files.push({ file:
|
|
4847
|
+
const agentsDir = path10.join(root, ".agents");
|
|
4848
|
+
files.push({ file: path10.join(agentsDir, "progress.md"), root });
|
|
4849
|
+
for (const f of await listDir(path10.join(agentsDir, "progress"))) {
|
|
4850
|
+
if (f.isFile() && f.name.endsWith(".md")) files.push({ file: path10.join(agentsDir, "progress", f.name), root });
|
|
2264
4851
|
}
|
|
2265
4852
|
}
|
|
2266
4853
|
const out = [];
|
|
@@ -2325,7 +4912,7 @@ var ProgressFileAdapter = class {
|
|
|
2325
4912
|
|
|
2326
4913
|
// ../core/src/engine.ts
|
|
2327
4914
|
function defaultLiveDir(home = os.homedir()) {
|
|
2328
|
-
return
|
|
4915
|
+
return path11.join(home, ".kvali", "live");
|
|
2329
4916
|
}
|
|
2330
4917
|
function createDefaultAdapters(opts = {}) {
|
|
2331
4918
|
return [
|
|
@@ -2333,6 +4920,11 @@ function createDefaultAdapters(opts = {}) {
|
|
|
2333
4920
|
new CodexAdapter(),
|
|
2334
4921
|
new GeminiCliAdapter(),
|
|
2335
4922
|
new AntigravityAdapter(opts.extraAntigravityBrainDirs),
|
|
4923
|
+
new CopilotAdapter(),
|
|
4924
|
+
new ClineAdapter({ extraStorageDirs: opts.extraEditorStorageDirs }),
|
|
4925
|
+
new RooCodeAdapter({ extraStorageDirs: opts.extraEditorStorageDirs }),
|
|
4926
|
+
new OpenCodeAdapter(),
|
|
4927
|
+
new KiloCodeAdapter(),
|
|
2336
4928
|
new ProgressFileAdapter()
|
|
2337
4929
|
];
|
|
2338
4930
|
}
|
|
@@ -2363,6 +4955,14 @@ function mergeProgressFiles(sessions) {
|
|
|
2363
4955
|
function sortSessions(sessions) {
|
|
2364
4956
|
return sessions.sort((a, b) => STATUS_PRIORITY[a.status] - STATUS_PRIORITY[b.status] || b.updatedAt - a.updatedAt);
|
|
2365
4957
|
}
|
|
4958
|
+
async function weekSnapshot(opts = {}) {
|
|
4959
|
+
const engine = new Engine({ ...opts, adapters: opts.adapters ?? createDefaultAdapters(opts), activeWindowMs: 8 * 864e5, maxSessionsPerAgent: 5e3 });
|
|
4960
|
+
try {
|
|
4961
|
+
return await engine.tick();
|
|
4962
|
+
} finally {
|
|
4963
|
+
engine.dispose();
|
|
4964
|
+
}
|
|
4965
|
+
}
|
|
2366
4966
|
var Engine = class {
|
|
2367
4967
|
adapters;
|
|
2368
4968
|
ctx;
|
|
@@ -2444,10 +5044,13 @@ var Engine = class {
|
|
|
2444
5044
|
try {
|
|
2445
5045
|
const sessions = [];
|
|
2446
5046
|
const errors = [];
|
|
5047
|
+
const limits = [];
|
|
2447
5048
|
for (const a of this.adapters) {
|
|
2448
5049
|
if (this.disabled.has(a.id)) continue;
|
|
2449
5050
|
try {
|
|
2450
5051
|
sessions.push(...await a.poll(this.ctx));
|
|
5052
|
+
const l = a.limits?.(this.ctx);
|
|
5053
|
+
if (l?.windows.length) limits.push(l);
|
|
2451
5054
|
} catch (err) {
|
|
2452
5055
|
const message = err instanceof Error ? err.message : String(err);
|
|
2453
5056
|
errors.push({ agent: a.id, message });
|
|
@@ -2456,10 +5059,10 @@ var Engine = class {
|
|
|
2456
5059
|
}
|
|
2457
5060
|
const merged = mergeProgressFiles(sessions);
|
|
2458
5061
|
sortSessions(merged);
|
|
2459
|
-
const signature = JSON.stringify([merged, errors]);
|
|
5062
|
+
const signature = JSON.stringify([merged, errors, limits]);
|
|
2460
5063
|
if (signature !== this.lastSignature) {
|
|
2461
5064
|
this.lastSignature = signature;
|
|
2462
|
-
this.current = { generatedAt: this.ctx.now(), sessions: merged, errors };
|
|
5065
|
+
this.current = { generatedAt: this.ctx.now(), sessions: merged, errors, ...limits.length ? { limits } : {} };
|
|
2463
5066
|
for (const l of this.listeners) {
|
|
2464
5067
|
try {
|
|
2465
5068
|
l(this.current);
|
|
@@ -2476,9 +5079,9 @@ var Engine = class {
|
|
|
2476
5079
|
};
|
|
2477
5080
|
|
|
2478
5081
|
// ../core/src/hooks/hub.ts
|
|
2479
|
-
import { promises as
|
|
5082
|
+
import { promises as fsp4 } from "node:fs";
|
|
2480
5083
|
import http from "node:http";
|
|
2481
|
-
import
|
|
5084
|
+
import path12 from "node:path";
|
|
2482
5085
|
var DEFAULT_HOOK_PORT = 47821;
|
|
2483
5086
|
var MAX_BODY = 1 << 20;
|
|
2484
5087
|
var SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
|
|
@@ -2603,19 +5206,19 @@ var HookHub = class {
|
|
|
2603
5206
|
}
|
|
2604
5207
|
}
|
|
2605
5208
|
async store(agent, ev) {
|
|
2606
|
-
const dir =
|
|
2607
|
-
await
|
|
2608
|
-
const file =
|
|
5209
|
+
const dir = path12.join(this.opts.liveDir, agent);
|
|
5210
|
+
await fsp4.mkdir(dir, { recursive: true });
|
|
5211
|
+
const file = path12.join(dir, `${ev.sessionId}.json`);
|
|
2609
5212
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
2610
|
-
await
|
|
2611
|
-
await
|
|
5213
|
+
await fsp4.writeFile(tmp, JSON.stringify(ev));
|
|
5214
|
+
await fsp4.rename(tmp, file);
|
|
2612
5215
|
}
|
|
2613
5216
|
};
|
|
2614
5217
|
|
|
2615
5218
|
// ../core/src/hooks/claude-install.ts
|
|
2616
|
-
import { promises as
|
|
5219
|
+
import { promises as fsp5 } from "node:fs";
|
|
2617
5220
|
import os2 from "node:os";
|
|
2618
|
-
import
|
|
5221
|
+
import path13 from "node:path";
|
|
2619
5222
|
var CLAUDE_HOOKS = [
|
|
2620
5223
|
{ event: "UserPromptSubmit", sync: true },
|
|
2621
5224
|
{ event: "Notification", sync: false },
|
|
@@ -2625,8 +5228,8 @@ var CLAUDE_HOOKS = [
|
|
|
2625
5228
|
var CLAUDE_HOOK_EVENTS = CLAUDE_HOOKS.map((h) => h.event);
|
|
2626
5229
|
var MARKER = "/v1/events/claude-code";
|
|
2627
5230
|
function claudeSettingsPath(home = os2.homedir(), env = process.env) {
|
|
2628
|
-
const dir = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() ||
|
|
2629
|
-
return
|
|
5231
|
+
const dir = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() || path13.join(home, ".claude");
|
|
5232
|
+
return path13.join(dir, "settings.json");
|
|
2630
5233
|
}
|
|
2631
5234
|
function claudeHookCommand(port = DEFAULT_HOOK_PORT, sync = false) {
|
|
2632
5235
|
const url = `http://127.0.0.1:${port}${MARKER}`;
|
|
@@ -2638,7 +5241,7 @@ function hookEntry(spec, port) {
|
|
|
2638
5241
|
async function readSettings(file) {
|
|
2639
5242
|
let text;
|
|
2640
5243
|
try {
|
|
2641
|
-
text = await
|
|
5244
|
+
text = await fsp5.readFile(file, "utf8");
|
|
2642
5245
|
} catch (err) {
|
|
2643
5246
|
if (err.code === "ENOENT") return {};
|
|
2644
5247
|
throw err;
|
|
@@ -2695,27 +5298,35 @@ async function claudeHooksStatus(file = claudeSettingsPath(), port = DEFAULT_HOO
|
|
|
2695
5298
|
return current === CLAUDE_HOOKS.length && total === CLAUDE_HOOKS.length ? "installed" : "outdated";
|
|
2696
5299
|
}
|
|
2697
5300
|
async function writeWithBackup(file, before, settings) {
|
|
2698
|
-
await
|
|
5301
|
+
await fsp5.mkdir(path13.dirname(file), { recursive: true });
|
|
2699
5302
|
let backup;
|
|
2700
5303
|
if (before !== void 0) {
|
|
2701
5304
|
backup = `${file}.kvali-backup`;
|
|
2702
|
-
await
|
|
5305
|
+
await fsp5.writeFile(backup, before);
|
|
2703
5306
|
}
|
|
2704
|
-
await
|
|
5307
|
+
await fsp5.writeFile(file, JSON.stringify(settings, null, 2) + "\n");
|
|
2705
5308
|
return backup;
|
|
2706
5309
|
}
|
|
5310
|
+
function canonical(v) {
|
|
5311
|
+
return JSON.stringify(
|
|
5312
|
+
v,
|
|
5313
|
+
(_k, x) => x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x
|
|
5314
|
+
);
|
|
5315
|
+
}
|
|
2707
5316
|
async function installClaudeHooks(file = claudeSettingsPath(), port = DEFAULT_HOOK_PORT) {
|
|
2708
|
-
const before = await
|
|
2709
|
-
const
|
|
5317
|
+
const before = await fsp5.readFile(file, "utf8").catch(() => void 0);
|
|
5318
|
+
const current = await readSettings(file);
|
|
5319
|
+
const settings = withoutKvali(current);
|
|
2710
5320
|
settings.hooks = settings.hooks && typeof settings.hooks === "object" ? settings.hooks : {};
|
|
2711
5321
|
for (const spec of CLAUDE_HOOKS) {
|
|
2712
5322
|
const groups = Array.isArray(settings.hooks[spec.event]) ? settings.hooks[spec.event] : [];
|
|
2713
5323
|
settings.hooks[spec.event] = [...groups, { hooks: [hookEntry(spec, port)] }];
|
|
2714
5324
|
}
|
|
2715
|
-
|
|
5325
|
+
if (before !== void 0 && canonical(settings) === canonical(current)) return { changed: false };
|
|
5326
|
+
return { backup: await writeWithBackup(file, before, settings), changed: true };
|
|
2716
5327
|
}
|
|
2717
5328
|
async function uninstallClaudeHooks(file = claudeSettingsPath()) {
|
|
2718
|
-
const before = await
|
|
5329
|
+
const before = await fsp5.readFile(file, "utf8").catch(() => void 0);
|
|
2719
5330
|
if (before === void 0) return { changed: false };
|
|
2720
5331
|
const settings = await readSettings(file);
|
|
2721
5332
|
const next = withoutKvali(settings);
|
|
@@ -2724,8 +5335,8 @@ async function uninstallClaudeHooks(file = claudeSettingsPath()) {
|
|
|
2724
5335
|
}
|
|
2725
5336
|
|
|
2726
5337
|
// ../core/src/protocol.ts
|
|
2727
|
-
import { promises as
|
|
2728
|
-
import
|
|
5338
|
+
import { promises as fsp6 } from "node:fs";
|
|
5339
|
+
import path14 from "node:path";
|
|
2729
5340
|
var PROGRESS_PROTOCOL_MARKER = "<!-- kvali:progress-protocol v2 -->";
|
|
2730
5341
|
function progressProtocolSnippet() {
|
|
2731
5342
|
return `${PROGRESS_PROTOCOL_MARKER}
|
|
@@ -2751,12 +5362,12 @@ For any task that takes more than two steps, keep your plan visible so the user
|
|
|
2751
5362
|
<!-- /kvali:progress-protocol -->
|
|
2752
5363
|
`;
|
|
2753
5364
|
}
|
|
2754
|
-
var PLAN_RULE_MARKER = "<!-- kvali:plan-rule
|
|
5365
|
+
var PLAN_RULE_MARKER = "<!-- kvali:plan-rule v2 -->";
|
|
2755
5366
|
function planRuleSnippet() {
|
|
2756
5367
|
return `${PLAN_RULE_MARKER}
|
|
2757
5368
|
## Keep a visible plan
|
|
2758
5369
|
|
|
2759
|
-
For any task that takes more than two steps, create a task list with your built-in plan tool before you start (Claude Code: TaskCreate/TaskUpdate or TodoWrite; Codex: update_plan; Gemini CLI: write_todos; Antigravity: task.md), keep exactly one item in progress, and mark each item done as soon as it is finished. The user follows your progress from this list.
|
|
5370
|
+
For any task that takes more than two steps, create a task list with your built-in plan tool before you start (Claude Code: TaskCreate/TaskUpdate or TodoWrite, whichever it has, loaded with ToolSearch when not in your tool list; Codex: update_plan; Gemini CLI: write_todos; Antigravity: task.md), keep exactly one item in progress, and mark each item done as soon as it is finished. The user follows your progress from this list.
|
|
2760
5371
|
<!-- /kvali:plan-rule -->
|
|
2761
5372
|
`;
|
|
2762
5373
|
}
|
|
@@ -2777,13 +5388,13 @@ function withBlock(text, name, snippet) {
|
|
|
2777
5388
|
return { text: `${text}${sep}${snippet}`, result: "added" };
|
|
2778
5389
|
}
|
|
2779
5390
|
function globalInstructionFiles(home, env = {}) {
|
|
2780
|
-
const claude = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() ||
|
|
2781
|
-
const codex = env.CODEX_HOME ||
|
|
2782
|
-
const gemini =
|
|
5391
|
+
const claude = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() || path14.join(home, ".claude");
|
|
5392
|
+
const codex = env.CODEX_HOME || path14.join(home, ".codex");
|
|
5393
|
+
const gemini = path14.join(home, ".gemini");
|
|
2783
5394
|
return [
|
|
2784
|
-
{ id: "claude-code", agent: "Claude Code", dir: claude, file:
|
|
2785
|
-
{ id: "codex", agent: "Codex", dir: codex, file:
|
|
2786
|
-
{ id: "gemini", agent: "Gemini CLI / Antigravity", dir: gemini, file:
|
|
5395
|
+
{ id: "claude-code", agent: "Claude Code", dir: claude, file: path14.join(claude, "CLAUDE.md") },
|
|
5396
|
+
{ id: "codex", agent: "Codex", dir: codex, file: path14.join(codex, "AGENTS.md") },
|
|
5397
|
+
{ id: "gemini", agent: "Gemini CLI / Antigravity", dir: gemini, file: path14.join(gemini, "GEMINI.md") }
|
|
2787
5398
|
];
|
|
2788
5399
|
}
|
|
2789
5400
|
var PLAN_RULE_END = "<!-- /kvali:plan-rule -->";
|
|
@@ -2792,7 +5403,7 @@ async function removeGlobalPlanRule(home, env = {}) {
|
|
|
2792
5403
|
for (const target of globalInstructionFiles(home, env)) {
|
|
2793
5404
|
let text;
|
|
2794
5405
|
try {
|
|
2795
|
-
text = await
|
|
5406
|
+
text = await fsp6.readFile(target.file, "utf8");
|
|
2796
5407
|
} catch {
|
|
2797
5408
|
continue;
|
|
2798
5409
|
}
|
|
@@ -2801,15 +5412,15 @@ async function removeGlobalPlanRule(home, env = {}) {
|
|
|
2801
5412
|
const endAt = text.indexOf(PLAN_RULE_END, start);
|
|
2802
5413
|
const end2 = endAt === -1 ? text.length : endAt + PLAN_RULE_END.length;
|
|
2803
5414
|
const next = (text.slice(0, start).replace(/\n+$/, "\n") + text.slice(end2).replace(/^\n+/, "")).replace(/^\n+$/, "");
|
|
2804
|
-
if (next.trim() === "") await
|
|
2805
|
-
else await
|
|
5415
|
+
if (next.trim() === "") await fsp6.unlink(target.file);
|
|
5416
|
+
else await fsp6.writeFile(target.file, next);
|
|
2806
5417
|
changed.push(target.file);
|
|
2807
5418
|
}
|
|
2808
5419
|
return changed;
|
|
2809
5420
|
}
|
|
2810
5421
|
async function readOptional(file) {
|
|
2811
5422
|
try {
|
|
2812
|
-
return await
|
|
5423
|
+
return await fsp6.readFile(file, "utf8");
|
|
2813
5424
|
} catch {
|
|
2814
5425
|
return void 0;
|
|
2815
5426
|
}
|
|
@@ -2819,32 +5430,32 @@ async function addGlobalPlanRule(home, env = {}, only) {
|
|
|
2819
5430
|
for (const target of globalInstructionFiles(home, env)) {
|
|
2820
5431
|
if (only && !only.includes(target.id)) continue;
|
|
2821
5432
|
try {
|
|
2822
|
-
const st = await
|
|
5433
|
+
const st = await fsp6.stat(target.dir);
|
|
2823
5434
|
if (!st.isDirectory()) continue;
|
|
2824
5435
|
} catch {
|
|
2825
5436
|
continue;
|
|
2826
5437
|
}
|
|
2827
5438
|
const next = withBlock(await readOptional(target.file), "plan-rule", planRuleSnippet());
|
|
2828
|
-
if (next.result !== "exists") await
|
|
5439
|
+
if (next.result !== "exists") await fsp6.writeFile(target.file, next.text);
|
|
2829
5440
|
out.push({ agent: target.agent, file: target.file, result: next.result });
|
|
2830
5441
|
}
|
|
2831
5442
|
return out;
|
|
2832
5443
|
}
|
|
2833
5444
|
async function addProgressProtocol(root) {
|
|
2834
|
-
const file =
|
|
5445
|
+
const file = path14.join(root, "AGENTS.md");
|
|
2835
5446
|
const current = await readOptional(file);
|
|
2836
5447
|
const next = withBlock(current ?? "# AGENTS.md\n\n", "progress-protocol", progressProtocolSnippet());
|
|
2837
|
-
if (next.result !== "exists") await
|
|
5448
|
+
if (next.result !== "exists") await fsp6.writeFile(file, next.text);
|
|
2838
5449
|
return { file, result: current === void 0 ? "created" : next.result };
|
|
2839
5450
|
}
|
|
2840
5451
|
|
|
2841
5452
|
// ../core/src/hooks/replies.ts
|
|
2842
5453
|
import { existsSync as existsSync2 } from "node:fs";
|
|
2843
|
-
import
|
|
2844
|
-
var CLAUDE_PLAN_CONTEXT = "Progress tracking (Kvali): if this request takes more than two steps, start by creating a task list with TaskCreate
|
|
5454
|
+
import path15 from "node:path";
|
|
5455
|
+
var CLAUDE_PLAN_CONTEXT = "Progress tracking (Kvali): if this request takes more than two steps, start by creating a task list with TaskCreate or TodoWrite, whichever you have (if neither is in your tool list, load one with ToolSearch first), keep exactly one task in_progress, and mark each task completed as soon as it is done. The user follows your progress from that list, so keep it current.";
|
|
2845
5456
|
function pluginRunsIn(liveDir, sessionId) {
|
|
2846
5457
|
if (!/^[A-Za-z0-9-]{8,80}$/.test(sessionId)) return false;
|
|
2847
|
-
return existsSync2(
|
|
5458
|
+
return existsSync2(path15.join(liveDir, "claude-code", `${sessionId}.mod.json`));
|
|
2848
5459
|
}
|
|
2849
5460
|
function claudeHookReply(ev, session, pluginRuns = false) {
|
|
2850
5461
|
if (ev.event !== "UserPromptSubmit") return void 0;
|
|
@@ -2857,32 +5468,32 @@ function claudeHookReply(ev, session, pluginRuns = false) {
|
|
|
2857
5468
|
}
|
|
2858
5469
|
|
|
2859
5470
|
// ../core/src/setup.ts
|
|
2860
|
-
import { promises as
|
|
2861
|
-
import
|
|
5471
|
+
import { promises as fsp8 } from "node:fs";
|
|
5472
|
+
import path17 from "node:path";
|
|
2862
5473
|
|
|
2863
5474
|
// ../core/src/hooks/claude-plugin.ts
|
|
2864
5475
|
import { execFile } from "node:child_process";
|
|
2865
5476
|
import { createHash } from "node:crypto";
|
|
2866
|
-
import { constants as fsc, promises as
|
|
2867
|
-
import
|
|
5477
|
+
import { constants as fsc, promises as fsp7 } from "node:fs";
|
|
5478
|
+
import path16 from "node:path";
|
|
2868
5479
|
var CLAUDE_PLUGIN_ID = "kvali@kvali";
|
|
2869
5480
|
var CLAUDE_MARKETPLACE = "kvali";
|
|
2870
|
-
var kvaliPluginDir = (home) =>
|
|
2871
|
-
var stateFile = (home) =>
|
|
5481
|
+
var kvaliPluginDir = (home) => path16.join(home, ".kvali", "claude-plugin");
|
|
5482
|
+
var stateFile = (home) => path16.join(home, ".kvali", "state.json");
|
|
2872
5483
|
async function filesUnder(dir, base = dir) {
|
|
2873
5484
|
const out = [];
|
|
2874
5485
|
let entries;
|
|
2875
5486
|
try {
|
|
2876
|
-
entries = await
|
|
5487
|
+
entries = await fsp7.readdir(dir, { withFileTypes: true });
|
|
2877
5488
|
} catch {
|
|
2878
5489
|
return out;
|
|
2879
5490
|
}
|
|
2880
5491
|
for (const e of entries) {
|
|
2881
|
-
const full =
|
|
5492
|
+
const full = path16.join(dir, e.name);
|
|
2882
5493
|
if (e.isDirectory()) {
|
|
2883
|
-
if (
|
|
5494
|
+
if (path16.relative(base, full) === path16.join(".claude-plugin", "types")) continue;
|
|
2884
5495
|
out.push(...await filesUnder(full, base));
|
|
2885
|
-
} else if (e.isFile()) out.push(
|
|
5496
|
+
} else if (e.isFile()) out.push(path16.relative(base, full));
|
|
2886
5497
|
}
|
|
2887
5498
|
return out.sort();
|
|
2888
5499
|
}
|
|
@@ -2891,9 +5502,9 @@ async function pluginFingerprint(dir) {
|
|
|
2891
5502
|
if (!files.length) return void 0;
|
|
2892
5503
|
const h = createHash("sha256");
|
|
2893
5504
|
for (const f of files) {
|
|
2894
|
-
h.update(f.split(
|
|
5505
|
+
h.update(f.split(path16.sep).join("/"));
|
|
2895
5506
|
h.update("\0");
|
|
2896
|
-
h.update(await
|
|
5507
|
+
h.update(await fsp7.readFile(path16.join(dir, f)));
|
|
2897
5508
|
h.update("\0");
|
|
2898
5509
|
}
|
|
2899
5510
|
return h.digest("hex");
|
|
@@ -2904,28 +5515,28 @@ async function syncClaudePlugin(bundledDir, home) {
|
|
|
2904
5515
|
if (!want) throw new Error(`the Claude Code plugin is missing from ${bundledDir}`);
|
|
2905
5516
|
if (want === have) return false;
|
|
2906
5517
|
const next = `${target}.next`;
|
|
2907
|
-
await
|
|
2908
|
-
await
|
|
2909
|
-
await
|
|
2910
|
-
await
|
|
2911
|
-
await
|
|
5518
|
+
await fsp7.rm(next, { recursive: true, force: true });
|
|
5519
|
+
await fsp7.mkdir(path16.dirname(target), { recursive: true });
|
|
5520
|
+
await fsp7.cp(bundledDir, next, { recursive: true });
|
|
5521
|
+
await fsp7.rm(target, { recursive: true, force: true });
|
|
5522
|
+
await fsp7.rename(next, target);
|
|
2912
5523
|
return true;
|
|
2913
5524
|
}
|
|
2914
5525
|
async function claudeExtensionDirs(home) {
|
|
2915
5526
|
const roots = [".vscode", ".vscode-insiders", ".vscode-oss", ".cursor", ".windsurf", ".antigravity", ".antigravity-ide", ".kiro"].map(
|
|
2916
|
-
(d) =>
|
|
5527
|
+
(d) => path16.join(home, d, "extensions")
|
|
2917
5528
|
);
|
|
2918
5529
|
const found = [];
|
|
2919
5530
|
for (const root of roots) {
|
|
2920
5531
|
let names = [];
|
|
2921
5532
|
try {
|
|
2922
|
-
names = await
|
|
5533
|
+
names = await fsp7.readdir(root);
|
|
2923
5534
|
} catch {
|
|
2924
5535
|
continue;
|
|
2925
5536
|
}
|
|
2926
|
-
for (const n of names) if (n.toLowerCase().startsWith("anthropic.claude-code-")) found.push(
|
|
5537
|
+
for (const n of names) if (n.toLowerCase().startsWith("anthropic.claude-code-")) found.push(path16.join(root, n));
|
|
2927
5538
|
}
|
|
2928
|
-
const ver = (p2) => (/-(\d+)\.(\d+)\.(\d+)/.exec(
|
|
5539
|
+
const ver = (p2) => (/-(\d+)\.(\d+)\.(\d+)/.exec(path16.basename(p2)) ?? []).slice(1).map(Number);
|
|
2929
5540
|
return found.sort((a, b) => {
|
|
2930
5541
|
const [x, y] = [ver(a), ver(b)];
|
|
2931
5542
|
for (let i = 0; i < 3; i += 1) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (y[i] ?? 0) - (x[i] ?? 0);
|
|
@@ -2937,23 +5548,23 @@ async function findClaudeBinary(opts) {
|
|
|
2937
5548
|
const names = win ? ["claude.exe", "claude.cmd"] : ["claude"];
|
|
2938
5549
|
const candidates = [];
|
|
2939
5550
|
for (const d of opts.extensionDirs ?? []) {
|
|
2940
|
-
const bin =
|
|
5551
|
+
const bin = path16.join(d, "resources", "native-binary");
|
|
2941
5552
|
let inside = [];
|
|
2942
5553
|
try {
|
|
2943
|
-
inside = await
|
|
5554
|
+
inside = await fsp7.readdir(bin);
|
|
2944
5555
|
} catch {
|
|
2945
5556
|
continue;
|
|
2946
5557
|
}
|
|
2947
5558
|
const ranked = inside.filter((n) => /^claude([-.].*)?$/i.test(n) && !/\.(json|md|txt|map)$/i.test(n)).sort((x, y) => x.length - y.length);
|
|
2948
|
-
for (const n of ranked) candidates.push(
|
|
5559
|
+
for (const n of ranked) candidates.push(path16.join(bin, n));
|
|
2949
5560
|
}
|
|
2950
|
-
for (const dir of (opts.env?.PATH ?? opts.env?.Path ?? "").split(
|
|
2951
|
-
candidates.push(
|
|
5561
|
+
for (const dir of (opts.env?.PATH ?? opts.env?.Path ?? "").split(path16.delimiter)) if (dir) for (const n of names) candidates.push(path16.join(dir, n));
|
|
5562
|
+
candidates.push(path16.join(opts.home, ".claude", "local", names[0]), path16.join(opts.home, ".local", "bin", names[0]));
|
|
2952
5563
|
if (!win) candidates.push("/opt/homebrew/bin/claude", "/usr/local/bin/claude");
|
|
2953
5564
|
for (const c of candidates) {
|
|
2954
5565
|
try {
|
|
2955
|
-
await
|
|
2956
|
-
if ((await
|
|
5566
|
+
await fsp7.access(c, win ? fsc.F_OK : fsc.X_OK);
|
|
5567
|
+
if ((await fsp7.stat(c)).isFile()) return c;
|
|
2957
5568
|
} catch {
|
|
2958
5569
|
}
|
|
2959
5570
|
}
|
|
@@ -3006,7 +5617,7 @@ async function installClaudePlugin(bin, dir, env) {
|
|
|
3006
5617
|
}
|
|
3007
5618
|
async function claudePluginEnabled(settingsFile) {
|
|
3008
5619
|
try {
|
|
3009
|
-
const s = JSON.parse(await
|
|
5620
|
+
const s = JSON.parse(await fsp7.readFile(settingsFile, "utf8"));
|
|
3010
5621
|
return s?.enabledPlugins?.[CLAUDE_PLUGIN_ID] === true;
|
|
3011
5622
|
} catch {
|
|
3012
5623
|
return false;
|
|
@@ -3014,15 +5625,15 @@ async function claudePluginEnabled(settingsFile) {
|
|
|
3014
5625
|
}
|
|
3015
5626
|
async function readKvaliState(home) {
|
|
3016
5627
|
try {
|
|
3017
|
-
return JSON.parse(await
|
|
5628
|
+
return JSON.parse(await fsp7.readFile(stateFile(home), "utf8")) ?? {};
|
|
3018
5629
|
} catch {
|
|
3019
5630
|
return {};
|
|
3020
5631
|
}
|
|
3021
5632
|
}
|
|
3022
5633
|
async function writeKvaliState(home, patch) {
|
|
3023
5634
|
const next = { ...await readKvaliState(home), ...patch };
|
|
3024
|
-
await
|
|
3025
|
-
await
|
|
5635
|
+
await fsp7.mkdir(path16.dirname(stateFile(home)), { recursive: true });
|
|
5636
|
+
await fsp7.writeFile(stateFile(home), `${JSON.stringify(next, null, 2)}
|
|
3026
5637
|
`);
|
|
3027
5638
|
}
|
|
3028
5639
|
async function removeClaudePlugin(opts) {
|
|
@@ -3034,12 +5645,12 @@ async function removeClaudePlugin(opts) {
|
|
|
3034
5645
|
const list = await runClaude(opts.bin, ["plugin", "marketplace", "list", "--json"], opts.env);
|
|
3035
5646
|
try {
|
|
3036
5647
|
const mk = JSON.parse(list.out.slice(list.out.indexOf("["))).find((m) => m.name === CLAUDE_MARKETPLACE);
|
|
3037
|
-
if (mk && mk.path &&
|
|
5648
|
+
if (mk && mk.path && path16.resolve(mk.path) === path16.resolve(dir)) await runClaude(opts.bin, ["plugin", "marketplace", "remove", CLAUDE_MARKETPLACE], opts.env);
|
|
3038
5649
|
} catch {
|
|
3039
5650
|
}
|
|
3040
5651
|
} else {
|
|
3041
5652
|
try {
|
|
3042
|
-
const raw = await
|
|
5653
|
+
const raw = await fsp7.readFile(opts.settingsFile, "utf8");
|
|
3043
5654
|
const s = JSON.parse(raw);
|
|
3044
5655
|
let changed = false;
|
|
3045
5656
|
if (s.enabledPlugins && CLAUDE_PLUGIN_ID in s.enabledPlugins) {
|
|
@@ -3047,16 +5658,16 @@ async function removeClaudePlugin(opts) {
|
|
|
3047
5658
|
changed = true;
|
|
3048
5659
|
}
|
|
3049
5660
|
const mk = s.extraKnownMarketplaces?.[CLAUDE_MARKETPLACE];
|
|
3050
|
-
if (mk?.source?.path &&
|
|
5661
|
+
if (mk?.source?.path && path16.resolve(mk.source.path) === path16.resolve(dir)) {
|
|
3051
5662
|
delete s.extraKnownMarketplaces[CLAUDE_MARKETPLACE];
|
|
3052
5663
|
changed = true;
|
|
3053
5664
|
}
|
|
3054
|
-
if (changed) await
|
|
5665
|
+
if (changed) await fsp7.writeFile(opts.settingsFile, `${JSON.stringify(s, null, 2)}
|
|
3055
5666
|
`);
|
|
3056
5667
|
} catch {
|
|
3057
5668
|
}
|
|
3058
5669
|
}
|
|
3059
|
-
await
|
|
5670
|
+
await fsp7.rm(dir, { recursive: true, force: true });
|
|
3060
5671
|
await writeKvaliState(opts.home, { claudePlugin: false });
|
|
3061
5672
|
return true;
|
|
3062
5673
|
}
|
|
@@ -3064,19 +5675,19 @@ async function removeClaudePlugin(opts) {
|
|
|
3064
5675
|
// ../core/src/setup.ts
|
|
3065
5676
|
async function isDir(p2) {
|
|
3066
5677
|
try {
|
|
3067
|
-
return (await
|
|
5678
|
+
return (await fsp8.stat(p2)).isDirectory();
|
|
3068
5679
|
} catch {
|
|
3069
5680
|
return false;
|
|
3070
5681
|
}
|
|
3071
5682
|
}
|
|
3072
5683
|
async function detectAgents(home, env = {}) {
|
|
3073
|
-
const claudeDir = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() ||
|
|
5684
|
+
const claudeDir = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() || path17.join(home, ".claude");
|
|
3074
5685
|
const [claude, codex, gemini, ag1, ag2] = await Promise.all([
|
|
3075
5686
|
isDir(claudeDir),
|
|
3076
|
-
isDir(env.CODEX_HOME ||
|
|
3077
|
-
isDir(
|
|
3078
|
-
isDir(
|
|
3079
|
-
isDir(
|
|
5687
|
+
isDir(env.CODEX_HOME || path17.join(home, ".codex")),
|
|
5688
|
+
isDir(path17.join(home, ".gemini")),
|
|
5689
|
+
isDir(path17.join(home, ".gemini", "antigravity")),
|
|
5690
|
+
isDir(path17.join(home, ".gemini", "antigravity-ide"))
|
|
3080
5691
|
]);
|
|
3081
5692
|
return { claude, codex, gemini, antigravity: ag1 || ag2 };
|
|
3082
5693
|
}
|
|
@@ -3108,7 +5719,7 @@ async function applySetup(home, env = {}, port = DEFAULT_HOOK_PORT, d, opts = {}
|
|
|
3108
5719
|
const settings = claudeSettingsPath(home, env);
|
|
3109
5720
|
const plugin = opts.pluginDir ? await setupClaudePlugin(home, env, opts) : { ok: false, note: void 0 };
|
|
3110
5721
|
if (plugin.ok) {
|
|
3111
|
-
await
|
|
5722
|
+
await installClaudeHooks(settings, port);
|
|
3112
5723
|
result.claude = "plugin";
|
|
3113
5724
|
} else {
|
|
3114
5725
|
await installClaudeHooks(settings, port);
|
|
@@ -3132,30 +5743,56 @@ async function removeSetup(home, env = {}, opts = {}) {
|
|
|
3132
5743
|
|
|
3133
5744
|
// ../core/src/phone.ts
|
|
3134
5745
|
import { randomBytes } from "node:crypto";
|
|
3135
|
-
import { promises as
|
|
3136
|
-
import
|
|
3137
|
-
var PHONE_EVENTS = ["needs-you", "done", "steps", "actions", "error", "stuck"];
|
|
3138
|
-
var DEFAULT_PHONE_EVENTS = ["needs-you", "done", "error", "stuck", "steps"];
|
|
5746
|
+
import { promises as fsp9 } from "node:fs";
|
|
5747
|
+
import path18 from "node:path";
|
|
5748
|
+
var PHONE_EVENTS = ["needs-you", "done", "steps", "actions", "error", "stuck", "limits"];
|
|
5749
|
+
var DEFAULT_PHONE_EVENTS = ["needs-you", "done", "error", "stuck", "steps", "limits"];
|
|
3139
5750
|
var DEFAULT_EVENTS_V1 = ["needs-you", "done", "error", "stuck"];
|
|
3140
|
-
var
|
|
5751
|
+
var DEFAULT_EVENTS_V2 = ["needs-you", "done", "error", "stuck", "steps"];
|
|
5752
|
+
var PHONE_CONFIG_VERSION = 3;
|
|
3141
5753
|
var DEFAULT_NTFY_SERVER = "https://ntfy.sh";
|
|
3142
5754
|
var DEFAULT_DONE_AFTER_SEC = 120;
|
|
3143
|
-
var kvaliConfigFile = (home) =>
|
|
5755
|
+
var kvaliConfigFile = (home) => path18.join(home, ".kvali", "config.json");
|
|
3144
5756
|
var TOPIC_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
5757
|
+
var TELEGRAM_TOKEN_RE = /^\d{5,15}:[A-Za-z0-9_-]{30,64}$/;
|
|
5758
|
+
var DISCORD_WEBHOOK_RE = /^https:\/\/(?:(?:ptb|canary)\.)?discord(?:app)?\.com\/api\/webhooks\/\d{5,25}\/[A-Za-z0-9_-]{20,120}$/;
|
|
5759
|
+
function normalizeTelegram(raw) {
|
|
5760
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
5761
|
+
const t = raw;
|
|
5762
|
+
const chatId = typeof t.chatId === "number" ? String(t.chatId) : t.chatId;
|
|
5763
|
+
if (typeof t.token !== "string" || !TELEGRAM_TOKEN_RE.test(t.token) || typeof chatId !== "string" || !/^-?\d{1,20}$/.test(chatId)) return void 0;
|
|
5764
|
+
return { token: t.token, chatId, ...typeof t.bot === "string" && /^\w{3,64}$/.test(t.bot) ? { bot: t.bot } : {} };
|
|
5765
|
+
}
|
|
5766
|
+
function normalizeDiscord(raw) {
|
|
5767
|
+
const w = raw && typeof raw === "object" ? raw.webhook : void 0;
|
|
5768
|
+
return typeof w === "string" && DISCORD_WEBHOOK_RE.test(w) ? { webhook: w } : void 0;
|
|
5769
|
+
}
|
|
3145
5770
|
function normalizePhoneConfig(raw) {
|
|
3146
5771
|
if (!raw || typeof raw !== "object") return void 0;
|
|
3147
5772
|
const r = raw;
|
|
3148
|
-
|
|
5773
|
+
const topic = typeof r.topic === "string" && TOPIC_RE.test(r.topic) ? r.topic : void 0;
|
|
5774
|
+
const telegram = normalizeTelegram(r.telegram);
|
|
5775
|
+
const discord = normalizeDiscord(r.discord);
|
|
5776
|
+
if (!topic && !telegram && !discord) return void 0;
|
|
3149
5777
|
const server = typeof r.server === "string" && /^https?:\/\/[^\s/]/.test(r.server) ? r.server.replace(/\/+$/, "") : DEFAULT_NTFY_SERVER;
|
|
3150
5778
|
let events = Array.isArray(r.events) ? r.events.filter((e) => PHONE_EVENTS.includes(e)) : [...DEFAULT_PHONE_EVENTS];
|
|
3151
|
-
const
|
|
3152
|
-
if (r.v === void 0 &&
|
|
5779
|
+
const same = (list) => events.length === list.length && list.every((e) => events.includes(e));
|
|
5780
|
+
if (r.v === void 0 && same(DEFAULT_EVENTS_V1) || r.v === 2 && same(DEFAULT_EVENTS_V2)) events = [...DEFAULT_PHONE_EVENTS];
|
|
3153
5781
|
const doneAfterSec = typeof r.doneAfter === "number" && Number.isFinite(r.doneAfter) && r.doneAfter >= 0 ? Math.min(Math.round(r.doneAfter), 86400) : DEFAULT_DONE_AFTER_SEC;
|
|
3154
|
-
return {
|
|
5782
|
+
return {
|
|
5783
|
+
server,
|
|
5784
|
+
...topic ? { topic } : {},
|
|
5785
|
+
token: typeof r.token === "string" && r.token ? r.token : void 0,
|
|
5786
|
+
...telegram ? { telegram } : {},
|
|
5787
|
+
...discord ? { discord } : {},
|
|
5788
|
+
events,
|
|
5789
|
+
details: r.details !== false,
|
|
5790
|
+
doneAfterSec
|
|
5791
|
+
};
|
|
3155
5792
|
}
|
|
3156
5793
|
async function readPhoneConfig(home) {
|
|
3157
5794
|
try {
|
|
3158
|
-
const all = JSON.parse(await
|
|
5795
|
+
const all = JSON.parse(await fsp9.readFile(kvaliConfigFile(home), "utf8"));
|
|
3159
5796
|
return normalizePhoneConfig(all?.phone);
|
|
3160
5797
|
} catch {
|
|
3161
5798
|
return void 0;
|
|
@@ -3165,7 +5802,7 @@ async function writePhoneConfig(home, cfg) {
|
|
|
3165
5802
|
const file = kvaliConfigFile(home);
|
|
3166
5803
|
let all = {};
|
|
3167
5804
|
try {
|
|
3168
|
-
const parsed = JSON.parse(await
|
|
5805
|
+
const parsed = JSON.parse(await fsp9.readFile(file, "utf8"));
|
|
3169
5806
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) all = parsed;
|
|
3170
5807
|
} catch {
|
|
3171
5808
|
}
|
|
@@ -3173,17 +5810,19 @@ async function writePhoneConfig(home, cfg) {
|
|
|
3173
5810
|
all.phone = {
|
|
3174
5811
|
v: PHONE_CONFIG_VERSION,
|
|
3175
5812
|
server: cfg.server,
|
|
3176
|
-
topic: cfg.topic,
|
|
5813
|
+
...cfg.topic ? { topic: cfg.topic } : {},
|
|
3177
5814
|
...cfg.token ? { token: cfg.token } : {},
|
|
5815
|
+
...cfg.telegram ? { telegram: cfg.telegram } : {},
|
|
5816
|
+
...cfg.discord ? { discord: cfg.discord } : {},
|
|
3178
5817
|
events: cfg.events,
|
|
3179
5818
|
details: cfg.details,
|
|
3180
5819
|
doneAfter: cfg.doneAfterSec ?? DEFAULT_DONE_AFTER_SEC
|
|
3181
5820
|
};
|
|
3182
5821
|
else delete all.phone;
|
|
3183
|
-
await
|
|
3184
|
-
await
|
|
5822
|
+
await fsp9.mkdir(path18.dirname(file), { recursive: true });
|
|
5823
|
+
await fsp9.writeFile(file, `${JSON.stringify(all, null, 2)}
|
|
3185
5824
|
`, { mode: 384 });
|
|
3186
|
-
await
|
|
5825
|
+
await fsp9.chmod(file, 384).catch(() => void 0);
|
|
3187
5826
|
}
|
|
3188
5827
|
function newTopic() {
|
|
3189
5828
|
const alphabet = "abcdefghijkmnpqrstuvwxyz23456789";
|
|
@@ -3224,16 +5863,201 @@ function sequenceTag(key) {
|
|
|
3224
5863
|
}
|
|
3225
5864
|
return (h >>> 0).toString(36);
|
|
3226
5865
|
}
|
|
5866
|
+
async function answerOf(res, host) {
|
|
5867
|
+
const text = (await res.text().catch(() => "")).replace(/\s+/g, " ").slice(0, 160);
|
|
5868
|
+
return `${host} answered ${res.status}${text ? `: ${text}` : ""}`;
|
|
5869
|
+
}
|
|
5870
|
+
function unreachable(err, host) {
|
|
5871
|
+
const e = err;
|
|
5872
|
+
return `could not reach ${host}: ${e.cause?.code ?? e.cause?.message ?? e.message}`;
|
|
5873
|
+
}
|
|
5874
|
+
var TAG_EMOJI = {
|
|
5875
|
+
white_check_mark: "\u2705",
|
|
5876
|
+
bell: "\u{1F514}",
|
|
5877
|
+
x: "\u274C",
|
|
5878
|
+
raised_hand: "\u270B",
|
|
5879
|
+
warning: "\u26A0\uFE0F",
|
|
5880
|
+
hourglass: "\u23F3",
|
|
5881
|
+
hourglass_flowing_sand: "\u23F3",
|
|
5882
|
+
repeat: "\u{1F501}",
|
|
5883
|
+
arrow_forward: "\u25B6\uFE0F"
|
|
5884
|
+
};
|
|
5885
|
+
var emojiOf = (push) => push.tags.map((t) => TAG_EMOJI[t]).find(Boolean);
|
|
5886
|
+
var EVENT_COLOR = {
|
|
5887
|
+
"needs-you": 13801762,
|
|
5888
|
+
done: 4176208,
|
|
5889
|
+
steps: 5809919,
|
|
5890
|
+
actions: 5809919,
|
|
5891
|
+
error: 16273737,
|
|
5892
|
+
stuck: 14380328,
|
|
5893
|
+
limits: 13801762
|
|
5894
|
+
};
|
|
5895
|
+
var escapeHtml = (t) => t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
5896
|
+
function telegramText(push) {
|
|
5897
|
+
const emoji = emojiOf(push);
|
|
5898
|
+
return `${emoji ? `${emoji} ` : ""}<b>${escapeHtml(push.title)}</b>${push.message ? `
|
|
5899
|
+
${escapeHtml(push.message)}` : ""}`;
|
|
5900
|
+
}
|
|
5901
|
+
function discordBody(push) {
|
|
5902
|
+
const emoji = emojiOf(push);
|
|
5903
|
+
return {
|
|
5904
|
+
username: "Kvali",
|
|
5905
|
+
allowed_mentions: { parse: [] },
|
|
5906
|
+
embeds: [{ title: `${emoji ? `${emoji} ` : ""}${push.title}`.slice(0, 256), description: push.message.slice(0, 4e3), color: EVENT_COLOR[push.event] }],
|
|
5907
|
+
...push.priority <= 2 ? { flags: 4096 } : {}
|
|
5908
|
+
};
|
|
5909
|
+
}
|
|
5910
|
+
var PushSender = class {
|
|
5911
|
+
telegramIds = /* @__PURE__ */ new Map();
|
|
5912
|
+
discordIds = /* @__PURE__ */ new Map();
|
|
5913
|
+
fetchImpl;
|
|
5914
|
+
constructor(fetchImpl = fetch) {
|
|
5915
|
+
this.fetchImpl = fetchImpl;
|
|
5916
|
+
}
|
|
5917
|
+
async send(cfg, push) {
|
|
5918
|
+
const errors = [];
|
|
5919
|
+
if (cfg.topic) {
|
|
5920
|
+
const e = await this.ntfy(cfg, push);
|
|
5921
|
+
if (e) errors.push(e);
|
|
5922
|
+
}
|
|
5923
|
+
if (cfg.telegram) {
|
|
5924
|
+
const e = await this.telegram(cfg.telegram, push);
|
|
5925
|
+
if (e) errors.push(e);
|
|
5926
|
+
}
|
|
5927
|
+
if (cfg.discord) {
|
|
5928
|
+
const e = await this.discord(cfg.discord, push);
|
|
5929
|
+
if (e) errors.push(e);
|
|
5930
|
+
}
|
|
5931
|
+
this.trim();
|
|
5932
|
+
return errors.length ? { ok: false, error: errors.join("; ") } : { ok: true };
|
|
5933
|
+
}
|
|
5934
|
+
async ntfy(cfg, push) {
|
|
5935
|
+
const req = ntfyRequest(cfg, push);
|
|
5936
|
+
const host = new URL(cfg.server).host;
|
|
5937
|
+
try {
|
|
5938
|
+
const res = await this.fetchImpl(req.url, { method: req.method, headers: req.headers, body: req.body, signal: AbortSignal.timeout(1e4) });
|
|
5939
|
+
return res.ok ? void 0 : await answerOf(res, host);
|
|
5940
|
+
} catch (err) {
|
|
5941
|
+
return unreachable(err, host);
|
|
5942
|
+
}
|
|
5943
|
+
}
|
|
5944
|
+
async telegramCall(token, method, body) {
|
|
5945
|
+
const host = "api.telegram.org";
|
|
5946
|
+
try {
|
|
5947
|
+
const res = await this.fetchImpl(`https://${host}/bot${token}/${method}`, {
|
|
5948
|
+
method: "POST",
|
|
5949
|
+
headers: { "Content-Type": "application/json" },
|
|
5950
|
+
body: JSON.stringify(body),
|
|
5951
|
+
signal: AbortSignal.timeout(1e4)
|
|
5952
|
+
});
|
|
5953
|
+
if (res.ok) return { ok: true, result: (await res.json().catch(() => ({}))).result };
|
|
5954
|
+
return { ok: false, error: await answerOf(res, host) };
|
|
5955
|
+
} catch (err) {
|
|
5956
|
+
return { ok: false, error: unreachable(err, host) };
|
|
5957
|
+
}
|
|
5958
|
+
}
|
|
5959
|
+
async telegram(t, push) {
|
|
5960
|
+
const text = telegramText(push);
|
|
5961
|
+
const prev = push.sequence ? this.telegramIds.get(push.sequence) : void 0;
|
|
5962
|
+
if (prev !== void 0 && push.priority <= 2) {
|
|
5963
|
+
const r2 = await this.telegramCall(t.token, "editMessageText", { chat_id: t.chatId, message_id: prev, text, parse_mode: "HTML", link_preview_options: { is_disabled: true } });
|
|
5964
|
+
if (r2.ok || /not modified/i.test(r2.error ?? "")) return void 0;
|
|
5965
|
+
} else if (prev !== void 0) {
|
|
5966
|
+
await this.telegramCall(t.token, "deleteMessage", { chat_id: t.chatId, message_id: prev });
|
|
5967
|
+
}
|
|
5968
|
+
const r = await this.telegramCall(t.token, "sendMessage", {
|
|
5969
|
+
chat_id: t.chatId,
|
|
5970
|
+
text,
|
|
5971
|
+
parse_mode: "HTML",
|
|
5972
|
+
disable_notification: push.priority <= 2,
|
|
5973
|
+
link_preview_options: { is_disabled: true }
|
|
5974
|
+
});
|
|
5975
|
+
if (!r.ok) return r.error;
|
|
5976
|
+
if (push.sequence && typeof r.result?.message_id === "number") this.telegramIds.set(push.sequence, r.result.message_id);
|
|
5977
|
+
return void 0;
|
|
5978
|
+
}
|
|
5979
|
+
async discord(d, push) {
|
|
5980
|
+
const host = "discord.com";
|
|
5981
|
+
const body = discordBody(push);
|
|
5982
|
+
const prev = push.sequence ? this.discordIds.get(push.sequence) : void 0;
|
|
5983
|
+
const call = (url, method, json) => this.fetchImpl(url, { method, headers: { "Content-Type": "application/json" }, ...json ? { body: JSON.stringify(json) } : {}, signal: AbortSignal.timeout(1e4) });
|
|
5984
|
+
try {
|
|
5985
|
+
if (prev !== void 0 && push.priority <= 2) {
|
|
5986
|
+
const { flags: _silent, ...edit } = body;
|
|
5987
|
+
const res2 = await call(`${d.webhook}/messages/${prev}`, "PATCH", edit);
|
|
5988
|
+
if (res2.ok) return void 0;
|
|
5989
|
+
} else if (prev !== void 0) {
|
|
5990
|
+
await call(`${d.webhook}/messages/${prev}`, "DELETE").catch(() => void 0);
|
|
5991
|
+
}
|
|
5992
|
+
const res = await call(`${d.webhook}?wait=true`, "POST", body);
|
|
5993
|
+
if (!res.ok) return await answerOf(res, host);
|
|
5994
|
+
const id = (await res.json().catch(() => ({}))).id;
|
|
5995
|
+
if (push.sequence && typeof id === "string") this.discordIds.set(push.sequence, id);
|
|
5996
|
+
return void 0;
|
|
5997
|
+
} catch (err) {
|
|
5998
|
+
return unreachable(err, host);
|
|
5999
|
+
}
|
|
6000
|
+
}
|
|
6001
|
+
/** Message ids of old sequences are forgotten: only the latest tasks are ever updated. */
|
|
6002
|
+
trim() {
|
|
6003
|
+
for (const m of [this.telegramIds, this.discordIds]) {
|
|
6004
|
+
while (m.size > 50) m.delete(m.keys().next().value);
|
|
6005
|
+
}
|
|
6006
|
+
}
|
|
6007
|
+
};
|
|
3227
6008
|
async function sendPush(cfg, push, fetchImpl = fetch) {
|
|
3228
|
-
|
|
6009
|
+
return new PushSender(fetchImpl).send(cfg, push);
|
|
6010
|
+
}
|
|
6011
|
+
function channelNames(cfg) {
|
|
6012
|
+
return [cfg.topic ? "ntfy" : void 0, cfg.telegram ? "Telegram" : void 0, cfg.discord ? "Discord" : void 0].filter(Boolean).join(", ");
|
|
6013
|
+
}
|
|
6014
|
+
async function telegramBot(token, fetchImpl = fetch) {
|
|
6015
|
+
if (!TELEGRAM_TOKEN_RE.test(token)) return { ok: false, error: "that is not a bot token (it looks like 123456789:AAF\u2026)" };
|
|
3229
6016
|
try {
|
|
3230
|
-
const res = await fetchImpl(
|
|
3231
|
-
if (res.ok) return { ok:
|
|
3232
|
-
const
|
|
3233
|
-
return { ok:
|
|
6017
|
+
const res = await fetchImpl(`https://api.telegram.org/bot${token}/getMe`, { signal: AbortSignal.timeout(1e4) });
|
|
6018
|
+
if (!res.ok) return { ok: false, error: res.status === 401 || res.status === 404 ? "Telegram does not know this token" : await answerOf(res, "api.telegram.org") };
|
|
6019
|
+
const me = (await res.json()).result;
|
|
6020
|
+
return typeof me?.username === "string" ? { ok: true, username: me.username } : { ok: false, error: "Telegram sent no bot name" };
|
|
3234
6021
|
} catch (err) {
|
|
3235
|
-
|
|
3236
|
-
|
|
6022
|
+
return { ok: false, error: unreachable(err, "api.telegram.org") };
|
|
6023
|
+
}
|
|
6024
|
+
}
|
|
6025
|
+
async function telegramFindChat(token, waitMs = 12e4, fetchImpl = fetch, signal) {
|
|
6026
|
+
const until = Date.now() + waitMs;
|
|
6027
|
+
let offset;
|
|
6028
|
+
while (Date.now() < until && !signal?.aborted) {
|
|
6029
|
+
const timeout = Math.max(1, Math.min(25, Math.round((until - Date.now()) / 1e3)));
|
|
6030
|
+
const askedAt = Date.now();
|
|
6031
|
+
let updates = [];
|
|
6032
|
+
try {
|
|
6033
|
+
const res = await fetchImpl(`https://api.telegram.org/bot${token}/getUpdates?timeout=${timeout}${offset !== void 0 ? `&offset=${offset}` : ""}`, {
|
|
6034
|
+
signal: AbortSignal.timeout((timeout + 10) * 1e3)
|
|
6035
|
+
});
|
|
6036
|
+
if (!res.ok) return void 0;
|
|
6037
|
+
updates = (await res.json()).result ?? [];
|
|
6038
|
+
} catch {
|
|
6039
|
+
await new Promise((r) => setTimeout(r, 2e3));
|
|
6040
|
+
continue;
|
|
6041
|
+
}
|
|
6042
|
+
const chat = [...updates].reverse().find((u) => u.message?.chat?.type === "private" && typeof u.message.chat.id === "number")?.message?.chat?.id;
|
|
6043
|
+
if (updates.length) offset = updates[updates.length - 1].update_id + 1;
|
|
6044
|
+
if (chat !== void 0) {
|
|
6045
|
+
await fetchImpl(`https://api.telegram.org/bot${token}/getUpdates?timeout=0&offset=${offset}`, { signal: AbortSignal.timeout(1e4) }).catch(() => void 0);
|
|
6046
|
+
return String(chat);
|
|
6047
|
+
}
|
|
6048
|
+
if (Date.now() - askedAt < 1e3) await new Promise((r) => setTimeout(r, 1e3));
|
|
6049
|
+
}
|
|
6050
|
+
return void 0;
|
|
6051
|
+
}
|
|
6052
|
+
async function discordCheck(webhook, fetchImpl = fetch) {
|
|
6053
|
+
if (!DISCORD_WEBHOOK_RE.test(webhook)) return { ok: false, error: "that is not a Discord webhook URL (https://discord.com/api/webhooks/\u2026)" };
|
|
6054
|
+
try {
|
|
6055
|
+
const res = await fetchImpl(webhook, { signal: AbortSignal.timeout(1e4) });
|
|
6056
|
+
if (!res.ok) return { ok: false, error: res.status === 401 || res.status === 404 ? "Discord does not know this webhook" : await answerOf(res, "discord.com") };
|
|
6057
|
+
const w = await res.json().catch(() => ({}));
|
|
6058
|
+
return { ok: true, name: typeof w.name === "string" ? w.name : void 0 };
|
|
6059
|
+
} catch (err) {
|
|
6060
|
+
return { ok: false, error: unreachable(err, "discord.com") };
|
|
3237
6061
|
}
|
|
3238
6062
|
}
|
|
3239
6063
|
function testPush() {
|
|
@@ -3308,6 +6132,18 @@ function formatPush(kind, s, details, extra = {}) {
|
|
|
3308
6132
|
tags: ["warning"]
|
|
3309
6133
|
};
|
|
3310
6134
|
}
|
|
6135
|
+
case "loop": {
|
|
6136
|
+
const l = s.loop;
|
|
6137
|
+
const what = l ? details ? `\u201C${clip(l.detail ?? l.label, 80)}\u201D` : "The same action" : "An action";
|
|
6138
|
+
const facts = l ? [`failed ${l.count} times in a row${l.sameError ? " with the same error" : ""}`, `for ${fmtDuration((extra.now ?? Date.now()) - l.since)}`, l.tokens ? `${fmtTokens(l.tokens)} tokens` : void 0] : ["keeps failing"];
|
|
6139
|
+
return {
|
|
6140
|
+
event: "stuck",
|
|
6141
|
+
title: `${agent} is going in circles${where}`,
|
|
6142
|
+
message: lines(`${what} ${facts.filter(Boolean).join(" \xB7 ")}. It may need a hint from you.`, title),
|
|
6143
|
+
priority: 4,
|
|
6144
|
+
tags: ["repeat"]
|
|
6145
|
+
};
|
|
6146
|
+
}
|
|
3311
6147
|
case "quiet":
|
|
3312
6148
|
return {
|
|
3313
6149
|
event: "stuck",
|
|
@@ -3319,18 +6155,47 @@ function formatPush(kind, s, details, extra = {}) {
|
|
|
3319
6155
|
case "step": {
|
|
3320
6156
|
const doing = extra.action && s.activity && !s.activity.endedAt ? s.activity.label : void 0;
|
|
3321
6157
|
const stepLine = details ? stepName ? `Now: ${clip(stepName, 120)}` : nextName ? `Next: ${clip(nextName, 120)}` : void 0 : void 0;
|
|
6158
|
+
const eta = extra.now !== void 0 ? planEta(s, extra.now) : void 0;
|
|
3322
6159
|
return {
|
|
3323
6160
|
event: extra.action ? "actions" : "steps",
|
|
3324
6161
|
title: p2.total ? `${agent}${where} \xB7 ${p2.done}/${p2.total}` : `${agent}${where} \xB7 working`,
|
|
3325
|
-
message: lines(
|
|
6162
|
+
message: lines(
|
|
6163
|
+
p2.total ? `${phoneBar(p2.done, p2.total)} ${p2.percent}%${eta !== void 0 ? ` \xB7 ${fmtEta(eta)}` : ""}` : void 0,
|
|
6164
|
+
stepLine,
|
|
6165
|
+
details && doing ? `Doing: ${clip(doing, 120)}` : void 0
|
|
6166
|
+
) || "Working",
|
|
3326
6167
|
priority: 2,
|
|
3327
6168
|
tags: ["arrow_forward"]
|
|
3328
6169
|
};
|
|
3329
6170
|
}
|
|
3330
6171
|
}
|
|
3331
6172
|
}
|
|
6173
|
+
function limitPush(l, w, now) {
|
|
6174
|
+
const used = `${Math.round(w.usedPercent)}% used`;
|
|
6175
|
+
const reset = w.resetsAt !== void 0 && w.resetsAt > now ? `it resets at ${fmtClock(w.resetsAt)}` : void 0;
|
|
6176
|
+
if (w.runsOutAt !== void 0) {
|
|
6177
|
+
return {
|
|
6178
|
+
event: "limits",
|
|
6179
|
+
title: `${l.agentLabel}: ${w.label} limit runs out in ${fmtAbout(w.runsOutAt - now)}`,
|
|
6180
|
+
message: `${used}. At the pace of the last hour it is used up around ${fmtClock(w.runsOutAt)}${reset ? `; ${reset}` : ""}.`,
|
|
6181
|
+
priority: 4,
|
|
6182
|
+
tags: ["hourglass_flowing_sand"]
|
|
6183
|
+
};
|
|
6184
|
+
}
|
|
6185
|
+
return {
|
|
6186
|
+
event: "limits",
|
|
6187
|
+
title: `${l.agentLabel}: ${w.label} limit ${used}`,
|
|
6188
|
+
message: reset ? `${reset[0].toUpperCase()}${reset.slice(1)}.` : "Most of this usage window is used.",
|
|
6189
|
+
priority: 3,
|
|
6190
|
+
tags: ["warning"]
|
|
6191
|
+
};
|
|
6192
|
+
}
|
|
6193
|
+
var LIMIT_SOON_MS = 60 * 6e4;
|
|
6194
|
+
var LIMIT_HIGH_PCT = 90;
|
|
3332
6195
|
var PushPlanner = class {
|
|
3333
6196
|
tracks = /* @__PURE__ */ new Map();
|
|
6197
|
+
/** Usage windows seen (agent, label, reset), and whether each was pushed. */
|
|
6198
|
+
limitsSeen = /* @__PURE__ */ new Map();
|
|
3334
6199
|
now;
|
|
3335
6200
|
startedAt;
|
|
3336
6201
|
minWorkMs;
|
|
@@ -3409,6 +6274,10 @@ var PushPlanner = class {
|
|
|
3409
6274
|
t.troubleSince = void 0;
|
|
3410
6275
|
t.troublePushed = false;
|
|
3411
6276
|
}
|
|
6277
|
+
if (want("stuck") && mine && s.loop && t.loopPushedFor !== s.loop.since) {
|
|
6278
|
+
t.loopPushedFor = s.loop.since;
|
|
6279
|
+
out.push(formatPush("loop", s, cfg.details, { now }));
|
|
6280
|
+
}
|
|
3412
6281
|
if (want("stuck") && (s.status === "working" || s.status === "stale")) {
|
|
3413
6282
|
if (s.pulse?.phase === "gone") {
|
|
3414
6283
|
if (t.gonePushedFor !== s.pulse.at) {
|
|
@@ -3445,11 +6314,35 @@ var PushPlanner = class {
|
|
|
3445
6314
|
}
|
|
3446
6315
|
if (actionKey !== void 0) t.sentAction = actionKey;
|
|
3447
6316
|
t.progressSent = true;
|
|
3448
|
-
out.push({ ...formatPush("step", s, cfg.details, { action: want("actions") }), sequence: t.episode });
|
|
6317
|
+
out.push({ ...formatPush("step", s, cfg.details, { action: want("actions"), now }), sequence: t.episode });
|
|
3449
6318
|
}
|
|
3450
6319
|
t.status = s.status;
|
|
3451
6320
|
}
|
|
3452
6321
|
for (const k of [...this.tracks.keys()]) if (!seen.has(k)) this.tracks.delete(k);
|
|
6322
|
+
out.push(...this.observeLimits(snapshot.limits, now, want("limits")));
|
|
6323
|
+
return out;
|
|
6324
|
+
}
|
|
6325
|
+
/**
|
|
6326
|
+
* One push per usage window: when its forecast end comes within the hour before it resets,
|
|
6327
|
+
* or when it passes 90%. A window already low when Kvali starts is not news.
|
|
6328
|
+
*/
|
|
6329
|
+
observeLimits(limits, now, wanted) {
|
|
6330
|
+
const out = [];
|
|
6331
|
+
for (const l of limits ?? []) {
|
|
6332
|
+
for (const w of l.windows) {
|
|
6333
|
+
const key = `${l.agent}|${w.label}|${w.resetsAt === void 0 ? "" : Math.round(w.resetsAt / 6e5)}`;
|
|
6334
|
+
const pressing = w.runsOutAt !== void 0 && w.runsOutAt - now <= LIMIT_SOON_MS || w.usedPercent >= LIMIT_HIGH_PCT && w.usedPercent < 100;
|
|
6335
|
+
const pushed = this.limitsSeen.get(key);
|
|
6336
|
+
if (pushed === void 0) {
|
|
6337
|
+
this.limitsSeen.set(key, pressing);
|
|
6338
|
+
continue;
|
|
6339
|
+
}
|
|
6340
|
+
if (pushed || !pressing) continue;
|
|
6341
|
+
this.limitsSeen.set(key, true);
|
|
6342
|
+
if (wanted) out.push(limitPush(l, w, now));
|
|
6343
|
+
}
|
|
6344
|
+
}
|
|
6345
|
+
if (this.limitsSeen.size > 64) for (const k of [...this.limitsSeen.keys()].slice(0, this.limitsSeen.size - 64)) this.limitsSeen.delete(k);
|
|
3453
6346
|
return out;
|
|
3454
6347
|
}
|
|
3455
6348
|
};
|
|
@@ -3487,6 +6380,7 @@ var PhoneNotifier = class {
|
|
|
3487
6380
|
leftAt = -Infinity;
|
|
3488
6381
|
quietPaused = false;
|
|
3489
6382
|
planner;
|
|
6383
|
+
sender = new PushSender();
|
|
3490
6384
|
opts;
|
|
3491
6385
|
constructor(opts) {
|
|
3492
6386
|
this.opts = opts;
|
|
@@ -3500,7 +6394,7 @@ var PhoneNotifier = class {
|
|
|
3500
6394
|
const now = Date.now();
|
|
3501
6395
|
if (!force && now - this.checkedAt < 5e3) return;
|
|
3502
6396
|
this.checkedAt = now;
|
|
3503
|
-
const st = await
|
|
6397
|
+
const st = await fsp9.stat(kvaliConfigFile(this.opts.home)).catch(() => void 0);
|
|
3504
6398
|
const mtime = st?.mtimeMs ?? 0;
|
|
3505
6399
|
if (!force && mtime === this.mtime) return;
|
|
3506
6400
|
this.mtime = mtime;
|
|
@@ -3544,7 +6438,7 @@ var PhoneNotifier = class {
|
|
|
3544
6438
|
if (!cfg) return;
|
|
3545
6439
|
const pushes = this.planner.observe(this.opts.snapshot(), cfg);
|
|
3546
6440
|
if (!pushes.length || !this.opts.canSend()) return;
|
|
3547
|
-
const send = this.opts.send ??
|
|
6441
|
+
const send = this.opts.send ?? ((c, p2) => this.sender.send(c, p2));
|
|
3548
6442
|
for (const p2 of pushes) {
|
|
3549
6443
|
if (p2.priority <= 2 && !await this.quietAllowed(cfg)) continue;
|
|
3550
6444
|
const r = await send(cfg, p2);
|
|
@@ -3552,8 +6446,9 @@ var PhoneNotifier = class {
|
|
|
3552
6446
|
this.opts.report?.(r.ok ? p2.title : `${p2.title}: ${r.error}`, r.ok);
|
|
3553
6447
|
}
|
|
3554
6448
|
}
|
|
3555
|
-
/** Silent updates are worth a message only while the day's allowance keeps room for alerts. */
|
|
6449
|
+
/** Silent updates are worth a message only while the day's ntfy allowance keeps room for alerts. */
|
|
3556
6450
|
async quietAllowed(cfg) {
|
|
6451
|
+
if (!cfg.topic) return true;
|
|
3557
6452
|
const now = Date.now();
|
|
3558
6453
|
if (now - this.leftAt >= 6e4) {
|
|
3559
6454
|
this.leftAt = now;
|
|
@@ -4440,18 +7335,18 @@ var QRMath = (function() {
|
|
|
4440
7335
|
};
|
|
4441
7336
|
return _this;
|
|
4442
7337
|
})();
|
|
4443
|
-
var qrPolynomial = function(
|
|
4444
|
-
if (typeof
|
|
4445
|
-
throw
|
|
7338
|
+
var qrPolynomial = function(num2, shift) {
|
|
7339
|
+
if (typeof num2.length == "undefined") {
|
|
7340
|
+
throw num2.length + "/" + shift;
|
|
4446
7341
|
}
|
|
4447
7342
|
const _num = (function() {
|
|
4448
7343
|
let offset = 0;
|
|
4449
|
-
while (offset <
|
|
7344
|
+
while (offset < num2.length && num2[offset] == 0) {
|
|
4450
7345
|
offset += 1;
|
|
4451
7346
|
}
|
|
4452
|
-
const _num2 = new Array(
|
|
4453
|
-
for (let i = 0; i <
|
|
4454
|
-
_num2[i] =
|
|
7347
|
+
const _num2 = new Array(num2.length - offset + shift);
|
|
7348
|
+
for (let i = 0; i < num2.length - offset; i += 1) {
|
|
7349
|
+
_num2[i] = num2[i + offset];
|
|
4455
7350
|
}
|
|
4456
7351
|
return _num2;
|
|
4457
7352
|
})();
|
|
@@ -4463,27 +7358,27 @@ var qrPolynomial = function(num, shift) {
|
|
|
4463
7358
|
return _num.length;
|
|
4464
7359
|
};
|
|
4465
7360
|
_this.multiply = function(e) {
|
|
4466
|
-
const
|
|
7361
|
+
const num3 = new Array(_this.getLength() + e.getLength() - 1);
|
|
4467
7362
|
for (let i = 0; i < _this.getLength(); i += 1) {
|
|
4468
7363
|
for (let j = 0; j < e.getLength(); j += 1) {
|
|
4469
|
-
|
|
7364
|
+
num3[i + j] ^= QRMath.gexp(QRMath.glog(_this.getAt(i)) + QRMath.glog(e.getAt(j)));
|
|
4470
7365
|
}
|
|
4471
7366
|
}
|
|
4472
|
-
return qrPolynomial(
|
|
7367
|
+
return qrPolynomial(num3, 0);
|
|
4473
7368
|
};
|
|
4474
7369
|
_this.mod = function(e) {
|
|
4475
7370
|
if (_this.getLength() - e.getLength() < 0) {
|
|
4476
7371
|
return _this;
|
|
4477
7372
|
}
|
|
4478
7373
|
const ratio = QRMath.glog(_this.getAt(0)) - QRMath.glog(e.getAt(0));
|
|
4479
|
-
const
|
|
7374
|
+
const num3 = new Array(_this.getLength());
|
|
4480
7375
|
for (let i = 0; i < _this.getLength(); i += 1) {
|
|
4481
|
-
|
|
7376
|
+
num3[i] = _this.getAt(i);
|
|
4482
7377
|
}
|
|
4483
7378
|
for (let i = 0; i < e.getLength(); i += 1) {
|
|
4484
|
-
|
|
7379
|
+
num3[i] ^= QRMath.gexp(QRMath.glog(e.getAt(i)) + ratio);
|
|
4485
7380
|
}
|
|
4486
|
-
return qrPolynomial(
|
|
7381
|
+
return qrPolynomial(num3, 0).mod(e);
|
|
4487
7382
|
};
|
|
4488
7383
|
return _this;
|
|
4489
7384
|
};
|
|
@@ -4745,9 +7640,9 @@ var qrBitBuffer = function() {
|
|
|
4745
7640
|
const bufIndex = Math.floor(index / 8);
|
|
4746
7641
|
return (_buffer[bufIndex] >>> 7 - index % 8 & 1) == 1;
|
|
4747
7642
|
};
|
|
4748
|
-
_this.put = function(
|
|
7643
|
+
_this.put = function(num2, length) {
|
|
4749
7644
|
for (let i = 0; i < length; i += 1) {
|
|
4750
|
-
_this.putBit((
|
|
7645
|
+
_this.putBit((num2 >>> length - i - 1 & 1) == 1);
|
|
4751
7646
|
}
|
|
4752
7647
|
};
|
|
4753
7648
|
_this.getLengthInBits = function() {
|
|
@@ -4791,11 +7686,11 @@ var qrNumber = function(data) {
|
|
|
4791
7686
|
}
|
|
4792
7687
|
};
|
|
4793
7688
|
const strToNum = function(s) {
|
|
4794
|
-
let
|
|
7689
|
+
let num2 = 0;
|
|
4795
7690
|
for (let i = 0; i < s.length; i += 1) {
|
|
4796
|
-
|
|
7691
|
+
num2 = num2 * 10 + chatToNum(s.charAt(i));
|
|
4797
7692
|
}
|
|
4798
|
-
return
|
|
7693
|
+
return num2;
|
|
4799
7694
|
};
|
|
4800
7695
|
const chatToNum = function(c) {
|
|
4801
7696
|
if ("0" <= c && c <= "9") {
|
|
@@ -5239,7 +8134,7 @@ function qrTerminal(text, color = true) {
|
|
|
5239
8134
|
}
|
|
5240
8135
|
|
|
5241
8136
|
// src/index.ts
|
|
5242
|
-
var VERSION = "0.
|
|
8137
|
+
var VERSION = "0.7.0";
|
|
5243
8138
|
function parse(argv) {
|
|
5244
8139
|
const opts = {
|
|
5245
8140
|
json: false,
|
|
@@ -5272,7 +8167,7 @@ function parse(argv) {
|
|
|
5272
8167
|
break;
|
|
5273
8168
|
case "--project":
|
|
5274
8169
|
case "-p":
|
|
5275
|
-
opts.project =
|
|
8170
|
+
opts.project = path19.resolve(next());
|
|
5276
8171
|
break;
|
|
5277
8172
|
case "--here":
|
|
5278
8173
|
opts.project = process2.cwd();
|
|
@@ -5281,10 +8176,10 @@ function parse(argv) {
|
|
|
5281
8176
|
opts.windowHours = Number(next());
|
|
5282
8177
|
break;
|
|
5283
8178
|
case "--home":
|
|
5284
|
-
opts.home =
|
|
8179
|
+
opts.home = path19.resolve(next());
|
|
5285
8180
|
break;
|
|
5286
8181
|
case "--brain-dir":
|
|
5287
|
-
opts.brainDirs.push(
|
|
8182
|
+
opts.brainDirs.push(path19.resolve(next()));
|
|
5288
8183
|
break;
|
|
5289
8184
|
case "--port":
|
|
5290
8185
|
opts.port = Number(next());
|
|
@@ -5324,6 +8219,9 @@ function parse(argv) {
|
|
|
5324
8219
|
opts.doneAfter = Math.round(sec);
|
|
5325
8220
|
break;
|
|
5326
8221
|
}
|
|
8222
|
+
case "--svg":
|
|
8223
|
+
opts.svg = argv[i + 1] !== void 0 && !argv[i + 1].startsWith("-") ? argv[++i] : "";
|
|
8224
|
+
break;
|
|
5327
8225
|
case "--version":
|
|
5328
8226
|
case "-v":
|
|
5329
8227
|
console.log(VERSION);
|
|
@@ -5356,7 +8254,10 @@ Usage
|
|
|
5356
8254
|
kvali plan-rule ask every installed agent to always keep a plan (global)
|
|
5357
8255
|
kvali phone notifications on your phone through ntfy: shows a QR code, sends a test
|
|
5358
8256
|
kvali phone test | off send a test notification | stop phone notifications
|
|
8257
|
+
kvali phone telegram [off] notifications from a Telegram bot of your own (asks for its token)
|
|
8258
|
+
kvali phone discord [off] notifications in a Discord channel (asks for its webhook URL)
|
|
5359
8259
|
kvali watch run without a dashboard: hooks and phone notifications (e.g. in the background)
|
|
8260
|
+
kvali week [--svg [file]] your agents' last seven days, a post to share them, and the card as SVG
|
|
5360
8261
|
|
|
5361
8262
|
Options
|
|
5362
8263
|
-p, --project <dir> only sessions inside <dir> --here same, for the current directory
|
|
@@ -5367,7 +8268,7 @@ Options
|
|
|
5367
8268
|
--no-hub do not listen for hook events (and send no phone notifications)
|
|
5368
8269
|
--no-color
|
|
5369
8270
|
kvali phone options: --server <url> (self-hosted ntfy) --token <token> --private (no project or step names)
|
|
5370
|
-
--events needs-you,done,steps,actions,error,stuck (what to hear about) --done-after <seconds> (shortest task worth a notification; 0: every task) --no-steps`;
|
|
8271
|
+
--events needs-you,done,steps,actions,error,stuck,limits (what to hear about) --done-after <seconds> (shortest task worth a notification; 0: every task) --no-steps`;
|
|
5371
8272
|
function fail(msg) {
|
|
5372
8273
|
console.error(`kvali: ${msg}`);
|
|
5373
8274
|
process2.exit(2);
|
|
@@ -5435,7 +8336,12 @@ function agentTag(s, c) {
|
|
|
5435
8336
|
"claude-code": c.yellow,
|
|
5436
8337
|
codex: c.magenta,
|
|
5437
8338
|
"gemini-cli": c.blue,
|
|
5438
|
-
antigravity: c.green
|
|
8339
|
+
antigravity: c.green,
|
|
8340
|
+
copilot: c.cyan,
|
|
8341
|
+
cline: c.cyan,
|
|
8342
|
+
"roo-code": c.magenta,
|
|
8343
|
+
"kilo-code": c.yellow,
|
|
8344
|
+
opencode: c.green
|
|
5439
8345
|
};
|
|
5440
8346
|
return (colors[s.agent] ?? c.cyan)(s.agentLabel.padEnd(12).slice(0, 12));
|
|
5441
8347
|
}
|
|
@@ -5450,21 +8356,21 @@ function render(snap, opts, width = process2.stdout.columns || 100) {
|
|
|
5450
8356
|
lines.push(
|
|
5451
8357
|
`${c.bold("kvali")} ${c.gray(`\xB7 ${sessions.length} session${sessions.length === 1 ? "" : "s"} \xB7 today ${fmtTokens(today.tokens)} tokens${today.priced ? ` \xB7 API value ${fmtUsd(today.costUsd)}` : ""}`)}`
|
|
5452
8358
|
);
|
|
5453
|
-
const
|
|
5454
|
-
|
|
5455
|
-
for (const s of limits.values()) {
|
|
5456
|
-
const parts = s.rateLimits.map((r) => {
|
|
8359
|
+
for (const l of snap.limits ?? []) {
|
|
8360
|
+
const parts = l.windows.map((r) => {
|
|
5457
8361
|
const pct = Math.round(r.usedPercent);
|
|
5458
|
-
const color = pct >= 90 ? c.red : pct >= 70 ? c.yellow : c.green;
|
|
5459
|
-
const
|
|
5460
|
-
|
|
8362
|
+
const color = pct >= 90 || r.runsOutAt !== void 0 ? c.red : pct >= 70 ? c.yellow : c.green;
|
|
8363
|
+
const out = r.runsOutAt !== void 0 ? c.red(r.runsOutAt <= now ? " used up" : ` runs out in ${fmtAbout(r.runsOutAt - now)}`) : "";
|
|
8364
|
+
const reset = r.resetsAt && r.resetsAt > now ? c.gray(` resets in ${fmtDuration(r.resetsAt - now)}`) : "";
|
|
8365
|
+
return `${r.label} ${color(`${pct}%`)}${out}${reset}`;
|
|
5461
8366
|
});
|
|
5462
|
-
|
|
8367
|
+
const tag = agentTag({ agent: l.agent, agentLabel: l.agentLabel }, c).trim();
|
|
8368
|
+
lines.push(`${c.gray("limits")} ${tag} ${parts.join(c.gray(" \xB7 "))}`);
|
|
5463
8369
|
}
|
|
5464
8370
|
if (sessions.length === 0) {
|
|
5465
8371
|
lines.push("", c.gray(`No agent sessions in the last ${opts.windowHours}h${opts.project ? ` under ${opts.project}` : ""}.`));
|
|
5466
|
-
lines.push(c.gray("Start Claude Code, Codex, Gemini CLI or
|
|
5467
|
-
lines.push(c.gray("Other agents (Cursor,
|
|
8372
|
+
lines.push(c.gray("Start Claude Code, Codex, Gemini CLI, Antigravity, Copilot, Cline, Roo Code, Kilo Code or OpenCode and sessions appear here automatically."));
|
|
8373
|
+
lines.push(c.gray("Other agents (Cursor, Windsurf, Aider, \u2026): run `kvali protocol` in your repo to add the AGENTS.md progress protocol."));
|
|
5468
8374
|
}
|
|
5469
8375
|
const barWidth = 14;
|
|
5470
8376
|
for (const g of groupByProject(sessions, roots, now)) {
|
|
@@ -5481,6 +8387,9 @@ function render(snap, opts, width = process2.stdout.columns || 100) {
|
|
|
5481
8387
|
const doing = [];
|
|
5482
8388
|
if (s.status === "waiting" || s.status === "error") doing.push((s.status === "waiting" ? c.yellow : c.red)(s.statusDetail ?? STATUS_LABEL[s.status]));
|
|
5483
8389
|
else if (step) doing.push(`\u21B3 ${step.activeTitle ?? step.title}`);
|
|
8390
|
+
const eta = s.status === "working" ? planEta(s, now) : void 0;
|
|
8391
|
+
if (eta !== void 0) doing.push(c.cyan(fmtEta(eta)));
|
|
8392
|
+
if (s.loop) doing.push(c.red(`\u27F3 going in circles: ${s.loop.detail ?? s.loop.label} failed ${s.loop.count}\xD7`));
|
|
5484
8393
|
if (s.status === "working" && s.activity) {
|
|
5485
8394
|
const a = s.activity;
|
|
5486
8395
|
doing.push(c.gray(`${a.label}${a.detail ? `: ${a.detail}` : ""} \xB7 ${fmtDuration(now - a.startedAt)}`));
|
|
@@ -5508,20 +8417,48 @@ function makeEngine(opts) {
|
|
|
5508
8417
|
activeWindowMs: opts.windowHours * 36e5,
|
|
5509
8418
|
workspaceRoots: opts.project ? [opts.project] : [process2.cwd()],
|
|
5510
8419
|
liveDir: defaultLiveDir(opts.home),
|
|
5511
|
-
adapters:
|
|
5512
|
-
|
|
5513
|
-
|
|
5514
|
-
|
|
5515
|
-
|
|
5516
|
-
|
|
5517
|
-
|
|
8420
|
+
adapters: createDefaultAdapters({ extraAntigravityBrainDirs: opts.brainDirs })
|
|
8421
|
+
});
|
|
8422
|
+
}
|
|
8423
|
+
async function week(opts, svgFile) {
|
|
8424
|
+
const c = paint(opts.color);
|
|
8425
|
+
const snap = await weekSnapshot({
|
|
8426
|
+
home: opts.home,
|
|
8427
|
+
liveDir: defaultLiveDir(opts.home),
|
|
8428
|
+
adapters: createDefaultAdapters({ extraAntigravityBrainDirs: opts.brainDirs }),
|
|
8429
|
+
workspaceRoots: [process2.cwd()]
|
|
5518
8430
|
});
|
|
8431
|
+
const w = weekStats(snap.sessions, Date.now());
|
|
8432
|
+
if (opts.json) {
|
|
8433
|
+
console.log(JSON.stringify(w, null, 2));
|
|
8434
|
+
return;
|
|
8435
|
+
}
|
|
8436
|
+
const max = Math.max(1, ...w.days.map((d) => d.activeMs));
|
|
8437
|
+
console.log(
|
|
8438
|
+
[
|
|
8439
|
+
`${c.bold("kvali week")} ${c.gray(`\xB7 ${weekRange(w)}`)}`,
|
|
8440
|
+
"",
|
|
8441
|
+
` ${c.bold(fmtWork(w.activeMs))} of agent work \xB7 ${w.tasksDone} tasks done \xB7 ${fmtTokens(w.tokens)} tokens${w.priced && w.costUsd ? ` \xB7 API value ${fmtUsd(w.costUsd)}` : ""}`,
|
|
8442
|
+
` ${w.sessions} session${w.sessions === 1 ? "" : "s"} in ${w.projects} project${w.projects === 1 ? "" : "s"}${w.agents.length ? ` \xB7 ${w.agents.join(", ")}` : ""}`,
|
|
8443
|
+
"",
|
|
8444
|
+
...w.days.map((d) => ` ${weekdayShort(d.day)} ${c.cyan("\u2588".repeat(Math.round(d.activeMs / max * 30)) || c.gray("\xB7"))} ${c.gray(d.activeMs ? fmtWork(d.activeMs) : "")}`),
|
|
8445
|
+
"",
|
|
8446
|
+
c.gray(" To share:"),
|
|
8447
|
+
...weekShareText(w).split("\n").map((l) => ` ${l}`)
|
|
8448
|
+
].join("\n")
|
|
8449
|
+
);
|
|
8450
|
+
if (svgFile !== void 0) {
|
|
8451
|
+
const file = path19.resolve(svgFile || `kvali-week-${w.days[w.days.length - 1].day}.svg`);
|
|
8452
|
+
await writeFile(file, weekSvg(w));
|
|
8453
|
+
console.log(`
|
|
8454
|
+
Card: ${file} ${c.gray("(1200\xD7630 SVG; open it in a browser to save as PNG)")}`);
|
|
8455
|
+
}
|
|
5519
8456
|
}
|
|
5520
8457
|
async function hooks(sub, opts) {
|
|
5521
8458
|
const file = claudeSettingsPath(opts.home);
|
|
5522
8459
|
if (sub === "install") {
|
|
5523
|
-
const { backup } = await installClaudeHooks(file, opts.port);
|
|
5524
|
-
console.log(`Installed Kvali hooks in ${file}${backup ? ` (backup: ${backup})` : ""}.`);
|
|
8460
|
+
const { backup, changed } = await installClaudeHooks(file, opts.port);
|
|
8461
|
+
console.log(changed ? `Installed Kvali hooks in ${file}${backup ? ` (backup: ${backup})` : ""}.` : `Kvali hooks are already installed in ${file}.`);
|
|
5525
8462
|
console.log("Keep `kvali` or the Kvali editor extension running to receive events.");
|
|
5526
8463
|
} else if (sub === "uninstall") {
|
|
5527
8464
|
const r = await uninstallClaudeHooks(file);
|
|
@@ -5549,15 +8486,80 @@ function phoneEventsText(cfg) {
|
|
|
5549
8486
|
steps: "each finished step (silent)",
|
|
5550
8487
|
actions: "every action, live (silent)",
|
|
5551
8488
|
error: "errors",
|
|
5552
|
-
stuck: "an agent gone silent"
|
|
8489
|
+
stuck: "an agent gone silent or going in circles",
|
|
8490
|
+
limits: "a plan limit running out"
|
|
5553
8491
|
};
|
|
5554
8492
|
return cfg.events.length ? PHONE_EVENTS.filter((e) => cfg.events.includes(e)).map((e) => words[e]).join(", ") : "nothing (no event chosen)";
|
|
5555
8493
|
}
|
|
5556
|
-
async function
|
|
8494
|
+
async function askSecret(question) {
|
|
8495
|
+
if (!process2.stdin.isTTY) fail("this step asks for a token: run it in a terminal");
|
|
8496
|
+
process2.stdout.write(question);
|
|
8497
|
+
process2.stdin.setRawMode(true);
|
|
8498
|
+
process2.stdin.resume();
|
|
8499
|
+
process2.stdin.setEncoding("utf8");
|
|
8500
|
+
return new Promise((resolve) => {
|
|
8501
|
+
let text = "";
|
|
8502
|
+
const onData = (ch) => {
|
|
8503
|
+
for (const k of ch) {
|
|
8504
|
+
if (k === "\r" || k === "\n") {
|
|
8505
|
+
process2.stdin.setRawMode(false);
|
|
8506
|
+
process2.stdin.pause();
|
|
8507
|
+
process2.stdin.off("data", onData);
|
|
8508
|
+
process2.stdout.write("\n");
|
|
8509
|
+
resolve(text.trim());
|
|
8510
|
+
return;
|
|
8511
|
+
}
|
|
8512
|
+
if (k === "") {
|
|
8513
|
+
process2.stdout.write("\n");
|
|
8514
|
+
process2.exit(130);
|
|
8515
|
+
}
|
|
8516
|
+
if (k === "\x7F" || k === "\b") text = text.slice(0, -1);
|
|
8517
|
+
else text += k;
|
|
8518
|
+
}
|
|
8519
|
+
};
|
|
8520
|
+
process2.stdin.on("data", onData);
|
|
8521
|
+
});
|
|
8522
|
+
}
|
|
8523
|
+
async function phoneChannel(which, off, opts) {
|
|
8524
|
+
const c = paint(opts.color);
|
|
8525
|
+
const cfg = await readPhoneConfig(opts.home);
|
|
8526
|
+
if (off) {
|
|
8527
|
+
if (!cfg?.[which]) return void console.log(`${which === "telegram" ? "Telegram" : "Discord"} is not set up.`);
|
|
8528
|
+
const rest = { ...cfg, [which]: void 0 };
|
|
8529
|
+
await writePhoneConfig(opts.home, rest.topic || rest.telegram || rest.discord ? rest : void 0);
|
|
8530
|
+
console.log(which === "telegram" ? "Kvali no longer writes to Telegram." : "Kvali no longer posts to Discord.");
|
|
8531
|
+
return;
|
|
8532
|
+
}
|
|
8533
|
+
const base = cfg ?? { server: DEFAULT_NTFY_SERVER, events: [...DEFAULT_PHONE_EVENTS], details: true, doneAfterSec: DEFAULT_DONE_AFTER_SEC };
|
|
8534
|
+
let only;
|
|
8535
|
+
if (which === "telegram") {
|
|
8536
|
+
console.log([c.bold("Kvali \u2192 Telegram"), "", " 1. In Telegram, open @BotFather, send /newbot and choose a name.", " 2. Paste the token it gives you (it stays on this computer):"].join("\n"));
|
|
8537
|
+
const token = await askSecret(" Token: ");
|
|
8538
|
+
const me = await telegramBot(token);
|
|
8539
|
+
if (!me.ok) fail(`could not use this bot: ${me.error}`);
|
|
8540
|
+
console.log(` 3. Now send any message to @${me.username} (https://t.me/${me.username}). Waiting up to 3 minutes\u2026`);
|
|
8541
|
+
const chatId = await telegramFindChat(token, 18e4);
|
|
8542
|
+
if (!chatId) fail(`no message reached @${me.username}; run \`kvali phone telegram\` again and write to the bot while Kvali waits`);
|
|
8543
|
+
only = { telegram: { token, chatId, bot: me.username } };
|
|
8544
|
+
} else {
|
|
8545
|
+
console.log([c.bold("Kvali \u2192 Discord"), "", " In Discord: Edit Channel \u2192 Integrations \u2192 Webhooks \u2192 New Webhook \u2192 Copy Webhook URL.", " Paste it here (it stays on this computer):"].join("\n"));
|
|
8546
|
+
const webhook = await askSecret(" Webhook URL: ");
|
|
8547
|
+
const check = await discordCheck(webhook);
|
|
8548
|
+
if (!check.ok) fail(`could not use this webhook: ${check.error}`);
|
|
8549
|
+
only = { discord: { webhook } };
|
|
8550
|
+
}
|
|
8551
|
+
const next = { ...base, ...only };
|
|
8552
|
+
await writePhoneConfig(opts.home, next);
|
|
8553
|
+
const r = await sendPush({ ...next, topic: void 0, telegram: void 0, discord: void 0, ...only }, testPush());
|
|
8554
|
+
console.log(r.ok ? c.green(` Connected (${channelNames(next)}). Sent a test notification.`) : c.yellow(` Saved, but the test was not sent: ${r.error}`));
|
|
8555
|
+
console.log(c.gray(` Stop: kvali phone ${which} off`));
|
|
8556
|
+
}
|
|
8557
|
+
async function phone(sub, opts, arg) {
|
|
5557
8558
|
const c = paint(opts.color);
|
|
8559
|
+
if (sub === "telegram" || sub === "discord") return phoneChannel(sub, arg === "off", opts);
|
|
5558
8560
|
if (sub === "off") {
|
|
5559
8561
|
await writePhoneConfig(opts.home, void 0);
|
|
5560
|
-
console.log("Phone notifications are off. You can remove the Kvali topic from the ntfy app too.");
|
|
8562
|
+
console.log("Phone notifications are off (ntfy, Telegram and Discord). You can remove the Kvali topic from the ntfy app too.");
|
|
5561
8563
|
return;
|
|
5562
8564
|
}
|
|
5563
8565
|
let cfg = await readPhoneConfig(opts.home);
|
|
@@ -5568,9 +8570,10 @@ async function phone(sub, opts) {
|
|
|
5568
8570
|
if (!r2.ok) process2.exitCode = 1;
|
|
5569
8571
|
return;
|
|
5570
8572
|
}
|
|
5571
|
-
if (sub) fail(`unknown phone command "${sub}" (phone, phone test, phone off)`);
|
|
5572
|
-
const fresh = !cfg;
|
|
5573
|
-
cfg
|
|
8573
|
+
if (sub) fail(`unknown phone command "${sub}" (phone, phone test, phone off, phone telegram, phone discord)`);
|
|
8574
|
+
const fresh = !cfg?.topic;
|
|
8575
|
+
cfg = cfg ? { ...cfg, topic: cfg.topic ?? newTopic() } : newPhoneConfig(opts.server);
|
|
8576
|
+
const topic = cfg.topic;
|
|
5574
8577
|
if (opts.server) cfg.server = opts.server.replace(/\/+$/, "");
|
|
5575
8578
|
if (opts.token) cfg.token = opts.token;
|
|
5576
8579
|
if (opts.private) cfg.details = false;
|
|
@@ -5587,9 +8590,9 @@ async function phone(sub, opts) {
|
|
|
5587
8590
|
" 1. Install the free ntfy app (iPhone or Android): https://ntfy.sh",
|
|
5588
8591
|
` 2. Android: scan this code. iPhone: in ntfy tap + and enter the topic${self ? ` (server ${cfg.server})` : ""}.`,
|
|
5589
8592
|
"",
|
|
5590
|
-
qrTerminal(subscribeLink(cfg), opts.color),
|
|
8593
|
+
qrTerminal(subscribeLink({ server: cfg.server, topic }), opts.color),
|
|
5591
8594
|
"",
|
|
5592
|
-
` Topic: ${c.bold(
|
|
8595
|
+
` Topic: ${c.bold(topic)}${fresh ? c.gray(" (new; keep it to yourself: the name is the key)") : ""}`,
|
|
5593
8596
|
""
|
|
5594
8597
|
].join("\n")
|
|
5595
8598
|
);
|
|
@@ -5599,9 +8602,10 @@ async function phone(sub, opts) {
|
|
|
5599
8602
|
[
|
|
5600
8603
|
"",
|
|
5601
8604
|
` You will hear about: ${phoneEventsText(cfg)}.`,
|
|
5602
|
-
" Choose with --events needs-you,done,steps,actions,error,stuck and --done-after <seconds>.",
|
|
8605
|
+
" Choose with --events needs-you,done,steps,actions,error,stuck,limits and --done-after <seconds>.",
|
|
5603
8606
|
" They are sent while Kvali runs: the editor extension, `kvali`, or `kvali watch` in the background.",
|
|
5604
8607
|
" Kvali's Claude Code plugin sends them for its own sessions by itself.",
|
|
8608
|
+
` ${c.gray("Also on Telegram or Discord: kvali phone telegram \xB7 kvali phone discord")}`,
|
|
5605
8609
|
` ${c.gray("Test: kvali phone test \xB7 Stop: kvali phone off")}`
|
|
5606
8610
|
].join("\n")
|
|
5607
8611
|
);
|
|
@@ -5618,7 +8622,7 @@ async function main() {
|
|
|
5618
8622
|
const d = await detectAgents(opts.home, process2.env);
|
|
5619
8623
|
const changes = setupChanges(d);
|
|
5620
8624
|
if (!changes.length) fail("no supported agent found (~/.claude, ~/.codex, ~/.gemini)");
|
|
5621
|
-
const pluginDir =
|
|
8625
|
+
const pluginDir = path19.join(path19.dirname(fileURLToPath(import.meta.url)), "claude-plugin");
|
|
5622
8626
|
const r = await applySetup(opts.home, process2.env, opts.port, d, { pluginDir });
|
|
5623
8627
|
const lines = changes.map((c) => ` \u2022 ${c}`);
|
|
5624
8628
|
if (r.claude === "plugin") lines.push(" Claude Code: new sessions show the Kvali pane; type /reload-plugins in sessions already open.");
|
|
@@ -5626,14 +8630,15 @@ async function main() {
|
|
|
5626
8630
|
console.log(["Kvali is on:", ...lines, "Undo with `kvali setup off`."].join("\n"));
|
|
5627
8631
|
return;
|
|
5628
8632
|
}
|
|
5629
|
-
if (cmd[0] === "phone") return phone(cmd[1], opts);
|
|
8633
|
+
if (cmd[0] === "phone") return phone(cmd[1], opts, cmd[2]);
|
|
5630
8634
|
if (cmd[0] === "watch") return watch(opts);
|
|
8635
|
+
if (cmd[0] === "week") return week(opts, opts.svg);
|
|
5631
8636
|
if (cmd[0] === "plan-rule") {
|
|
5632
8637
|
for (const r of await addGlobalPlanRule(opts.home, process2.env)) console.log(`${r.agent}: ${r.result} (${r.file})`);
|
|
5633
8638
|
return;
|
|
5634
8639
|
}
|
|
5635
8640
|
if (cmd[0] === "protocol") {
|
|
5636
|
-
const r = await addProgressProtocol(
|
|
8641
|
+
const r = await addProgressProtocol(path19.resolve(cmd[1] ?? "."));
|
|
5637
8642
|
const said = {
|
|
5638
8643
|
created: `Created ${r.file} with the progress protocol.`,
|
|
5639
8644
|
added: `Added the progress protocol to ${r.file}.`,
|
|
@@ -5704,7 +8709,7 @@ async function watch(opts) {
|
|
|
5704
8709
|
startPhone(engine, hub, opts.home, say);
|
|
5705
8710
|
engine.start();
|
|
5706
8711
|
const cfg = await readPhoneConfig(opts.home);
|
|
5707
|
-
say(cfg ? `watching agents; phone notifications go to ${cfg
|
|
8712
|
+
say(cfg ? `watching agents; phone notifications go to ${channelNames(cfg)}` : "watching agents; phone notifications are not set up (run `kvali phone`)");
|
|
5708
8713
|
const stop = () => {
|
|
5709
8714
|
hub.dispose();
|
|
5710
8715
|
engine.dispose();
|