@cloop/runner 0.2.3 → 0.2.4

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.
@@ -1,39 +1,42 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  LocalDriver
4
- } from "./chunk-CDG4IEQY.js";
4
+ } from "./chunk-5J4I7DAE.js";
5
5
  import {
6
6
  MeshSocket,
7
7
  defaultSocketFactory
8
8
  } from "./chunk-ZILLDYL4.js";
9
+ import "./chunk-VK6GV757.js";
9
10
  import {
10
11
  BoxWatch,
11
12
  DEFAULT_FALLBACK_MODEL,
12
13
  T3Client,
13
- T3Driver,
14
14
  claudeDialect,
15
15
  codexDialect,
16
16
  connectCommand,
17
- isLocal,
18
17
  lockThreadsFile,
19
18
  mintSession,
20
19
  probeClaude,
21
20
  probeClaudePermissions,
22
21
  probeCodex,
23
- readRunnerConfig,
24
22
  runBoxTool,
25
23
  threadsFilePath,
26
- writeBoxConfig,
27
24
  writeRunnerState
28
- } from "./chunk-KKFRQ4HQ.js";
25
+ } from "./chunk-VEVDJ3H3.js";
26
+ import {
27
+ T3Driver,
28
+ isLocal,
29
+ readRunnerConfig,
30
+ writeBoxConfig
31
+ } from "./chunk-M6U2YVEB.js";
29
32
  import {
30
33
  getMachine
31
34
  } from "./chunk-JX6VG5FE.js";
32
35
  import "./chunk-R3CLO2FB.js";
33
- import "./chunk-TIXA2YXR.js";
34
- import "./chunk-F4WCO6Z4.js";
36
+ import "./chunk-KHYA7GEH.js";
37
+ import "./chunk-ZDUKQWKA.js";
35
38
  import "./chunk-AG6SI6I2.js";
36
- import "./chunk-FW7MMQQV.js";
39
+ import "./chunk-PBOQMFNN.js";
37
40
  import {
38
41
  getMeshUrl,
39
42
  getToken,
@@ -66,10 +69,19 @@ async function listOutsideSessions(root = join(homedir(), ".claude", "projects")
66
69
  const results = [];
67
70
  for (const file of files.sort((a, b) => b.mtime - a.mtime).slice(0, 20)) {
68
71
  let title;
72
+ let cwd;
69
73
  const stream = createReadStream(file.file, { encoding: "utf8" });
70
74
  const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
71
75
  try {
72
76
  for await (const line of lines) {
77
+ if (!cwd && line.includes('"cwd"')) {
78
+ try {
79
+ const record = JSON.parse(line);
80
+ if (typeof record.cwd === "string" && record.cwd.startsWith("/") && record.cwd.length <= 500)
81
+ cwd = record.cwd;
82
+ } catch {
83
+ }
84
+ }
73
85
  if (!/^\s*\{\s*"type"\s*:\s*"(?:summary|custom-title|title)"/.test(line)) continue;
74
86
  try {
75
87
  const record = JSON.parse(line);
@@ -87,6 +99,7 @@ async function listOutsideSessions(root = join(homedir(), ".claude", "projects")
87
99
  project: file.project,
88
100
  updatedAt: new Date(file.mtime).toISOString(),
89
101
  status: "idle",
102
+ ...cwd ? { cwd } : {},
90
103
  ...title ? { title } : {}
91
104
  });
92
105
  }
@@ -1,19 +1,141 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ stripControl
4
+ } from "./chunk-VK6GV757.js";
2
5
  import {
3
6
  BoxToolError,
4
7
  RESULT_INSTRUCTION,
5
8
  orderThreads,
6
9
  parseRunResult
7
- } from "./chunk-KKFRQ4HQ.js";
10
+ } from "./chunk-M6U2YVEB.js";
8
11
  import {
9
12
  CONFIG_DIR
10
13
  } from "./chunk-3DIGCVL4.js";
11
14
 
15
+ // src/run-log.ts
16
+ import {
17
+ appendFileSync,
18
+ chmodSync,
19
+ mkdirSync,
20
+ readdirSync,
21
+ renameSync,
22
+ statSync,
23
+ unlinkSync
24
+ } from "fs";
25
+ import { dirname, join } from "path";
26
+ var RUN_LOG_LINE_MAX = 500;
27
+ var RUN_LOG_MAX_BYTES = 5 * 1024 * 1024;
28
+ var RUN_LOG_KEEP_MS = 14 * 24 * 36e5;
29
+ var SAFE_ID = /^[\w-]{1,100}$/;
30
+ function runLogDir(runsFile) {
31
+ return join(dirname(runsFile), "runs");
32
+ }
33
+ function runLogPath(dir, workId) {
34
+ return SAFE_ID.test(workId) ? join(dir, `${workId}.log`) : null;
35
+ }
36
+ var SECRETS = [
37
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----.*/g, "[redacted private key]"],
38
+ [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [redacted]"],
39
+ [/(:\/\/)[^\s/@:]+:[^\s/@]+@/g, "$1[redacted]@"],
40
+ [
41
+ /([?&](?:access_token|token|key|api_key|apikey|secret|sig|signature|code|password)=)[^&\s"']+/gi,
42
+ "$1[redacted]"
43
+ ],
44
+ [
45
+ /(\b(?:[\w-]*(?:token|secret|passw(?:or)?d|pwd|api[_-]?key|apikey|credential|private[_-]?key)[\w-]*|authorization|auth)["']?\s*[=:]\s*["']?)(?!Bearer\b|Basic\b|\[redacted)[^\s"',;}]{4,}/gi,
46
+ "$1[redacted]"
47
+ ],
48
+ [
49
+ /(--?[\w-]*(?:token|secret|password|api-key|apikey)[\w-]*[ =])["']?[^\s"']{4,}["']?/gi,
50
+ "$1[redacted]"
51
+ ],
52
+ [/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, "[redacted]"],
53
+ [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "[redacted]"],
54
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "[redacted]"],
55
+ [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, "[redacted]"],
56
+ [/\bAIza[0-9A-Za-z_-]{30,}/g, "[redacted]"],
57
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g, "[redacted]"]
58
+ ];
59
+ var OPAQUE = /[A-Za-z0-9_+=-]{32,}/g;
60
+ function redactSecrets(text) {
61
+ let out = text;
62
+ for (const [pattern, replacement] of SECRETS) out = out.replace(pattern, replacement);
63
+ return out.replace(
64
+ OPAQUE,
65
+ (run2) => /^[0-9a-f-]+$/i.test(run2) || !/\d/.test(run2) || !/[A-Za-z]/.test(run2) ? run2 : "[redacted]"
66
+ );
67
+ }
68
+ function logText(text) {
69
+ const flat = redactSecrets(stripControl(text).replace(/\s+/g, " ").trim());
70
+ return flat.length > RUN_LOG_LINE_MAX ? `${flat.slice(0, RUN_LOG_LINE_MAX - 1)}\u2026` : flat;
71
+ }
72
+ function logLineFor(item) {
73
+ switch (item.type) {
74
+ case "text":
75
+ return item.text;
76
+ case "tool": {
77
+ const input = item.detail ?? item.summary ?? item.target;
78
+ return `> ${item.name}${input ? `: ${input}` : ""}`;
79
+ }
80
+ case "ask":
81
+ return `? ${item.summary}`;
82
+ case "result":
83
+ return item.ok ? `= Result: ${item.text ?? "done"}` : `= Error: ${item.text ?? "no text"}`;
84
+ default:
85
+ return null;
86
+ }
87
+ }
88
+ function appendRunLog(dir, workId, text, { now = Date.now(), maxBytes = RUN_LOG_MAX_BYTES } = {}) {
89
+ const path = runLogPath(dir, workId);
90
+ if (!path) return;
91
+ const line = `${stamp(now)} ${logText(text)}
92
+ `;
93
+ mkdirSync(dir, { recursive: true, mode: 448 });
94
+ const size = sizeOf(path);
95
+ if (size > 0 && size + Buffer.byteLength(line) > maxBytes) renameSync(path, `${path}.1`);
96
+ appendFileSync(path, line, { mode: 384 });
97
+ }
98
+ function pruneRunLogs(dir, now = Date.now(), keepMs = RUN_LOG_KEEP_MS) {
99
+ mkdirSync(dir, { recursive: true, mode: 448 });
100
+ chmodSync(dir, 448);
101
+ let removed = 0;
102
+ for (const name of readdirSync(dir)) {
103
+ if (!/\.log(\.1)?$/.test(name)) continue;
104
+ const path = join(dir, name);
105
+ try {
106
+ if (statSync(path).mtimeMs < now - keepMs) {
107
+ unlinkSync(path);
108
+ removed++;
109
+ }
110
+ } catch {
111
+ }
112
+ }
113
+ return removed;
114
+ }
115
+ function sizeOf(path) {
116
+ try {
117
+ return statSync(path).size;
118
+ } catch {
119
+ return 0;
120
+ }
121
+ }
122
+ var STOPPED_SUMMARY = "The run was stopped.";
123
+ function endNote(end) {
124
+ return `= ${end.kind === "settled" ? "Done" : "Ended"}: ${end.summary ?? end.kind}`;
125
+ }
126
+ function isEndLogLine(line) {
127
+ return /^\S+ = (Done|Ended): /.test(line);
128
+ }
129
+ function stamp(now) {
130
+ const d = new Date(now);
131
+ return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":");
132
+ }
133
+
12
134
  // src/drivers/local.ts
13
135
  import { execFile, execFileSync, spawn } from "child_process";
14
- import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
136
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
15
137
  import { homedir, hostname } from "os";
16
- import { basename, dirname, join } from "path";
138
+ import { basename, dirname as dirname2, join as join2 } from "path";
17
139
  import { createInterface } from "readline";
18
140
  var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
19
141
  var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
@@ -39,7 +161,7 @@ function failedEnd(harness, run2) {
39
161
  return { summary: `${lead}${quoted}"`, ...error };
40
162
  }
41
163
  function localRunsFilePath() {
42
- return process.env.CLOOP_LOCAL_RUNS_FILE ?? join(homedir(), CONFIG_DIR, "local-runs.json");
164
+ return process.env.CLOOP_LOCAL_RUNS_FILE ?? join2(homedir(), CONFIG_DIR, "local-runs.json");
43
165
  }
44
166
  function pickRepo(repos, repository) {
45
167
  if (!repository) {
@@ -106,6 +228,13 @@ var LocalDriver = class {
106
228
  this.name = deps.dialect.name;
107
229
  this.capabilities = deps.dialect.capabilities;
108
230
  this.runs = new Map(this.load().map((r) => [r.work_id, r]));
231
+ this.logDir = deps.logDir ?? runLogDir(this.file);
232
+ try {
233
+ const removed = pruneRunLogs(this.logDir, this.now());
234
+ if (removed) this.log(`run logs removed=${removed} older than 14 days`);
235
+ } catch (err) {
236
+ this.log(`run log prune failed: ${err.code ?? "unknown"}`);
237
+ }
109
238
  }
110
239
  deps;
111
240
  name;
@@ -115,6 +244,8 @@ var LocalDriver = class {
115
244
  listeners = /* @__PURE__ */ new Map();
116
245
  recovering = /* @__PURE__ */ new Set();
117
246
  stopping = false;
247
+ logDir;
248
+ logFailed = false;
118
249
  get repo() {
119
250
  return this.deps.repo ?? gitProbe;
120
251
  }
@@ -124,6 +255,16 @@ var LocalDriver = class {
124
255
  log(line) {
125
256
  this.deps.log?.(line);
126
257
  }
258
+ /** One line in the run's own log, for `cloop watch`. A full disk must not stop the run. */
259
+ note(r, text) {
260
+ try {
261
+ appendRunLog(this.logDir, r.work_id, text, { now: this.now() });
262
+ } catch (err) {
263
+ if (this.logFailed) return;
264
+ this.logFailed = true;
265
+ this.log(`run log write failed: ${err.code ?? "unknown"}`);
266
+ }
267
+ }
127
268
  now() {
128
269
  return this.deps.now?.() ?? Date.now();
129
270
  }
@@ -174,7 +315,8 @@ var LocalDriver = class {
174
315
  status: this.statusOf(r),
175
316
  settled: Boolean(r.end),
176
317
  pr_url: r.end?.pr_url ?? null,
177
- last_assistant_text: r.end?.summary ?? r.last_text ?? null
318
+ last_assistant_text: r.end?.summary ?? r.last_text ?? null,
319
+ resume: this.deps.dialect.name === "claude-code" && r.session_id ? { cwd: r.repo, session_id: r.session_id } : null
178
320
  };
179
321
  }
180
322
  async launch(a) {
@@ -239,6 +381,7 @@ var LocalDriver = class {
239
381
  if (!line2) throw new BoxToolError("cannot_steer");
240
382
  live.asks = live.asks.slice(1);
241
383
  this.write(live, line2);
384
+ this.note(r, `< You answered: ${a.text}`);
242
385
  this.remember(r, a.command_id, "answer");
243
386
  this.log(`answer work=${r.work_id}`);
244
387
  this.askNext(r, live);
@@ -266,6 +409,7 @@ ${a.text}` : a.text;
266
409
  if (!line) throw new BoxToolError("cannot_steer");
267
410
  live.outstanding++;
268
411
  this.write(live, line);
412
+ this.note(r, `< You: ${a.text}`);
269
413
  const delivered = a.mode === "queue" ? "queue" : "steer";
270
414
  this.remember(r, a.command_id, delivered);
271
415
  this.log(`${delivered} work=${r.work_id}`);
@@ -283,11 +427,12 @@ ${a.text}` : a.text;
283
427
  } catch {
284
428
  }
285
429
  }
286
- await this.end(r, { kind: "failed", summary: "The run was stopped." });
430
+ await this.end(r, { kind: "failed", summary: STOPPED_SUMMARY });
287
431
  return { ok: true, was_running: orphan };
288
432
  }
289
433
  live.interrupted = true;
290
434
  live.child.kill("SIGINT");
435
+ this.note(r, "= Stop requested.");
291
436
  const timer = setTimeout(() => {
292
437
  if (live.child.exitCode === null && live.child.signalCode === null)
293
438
  live.child.kill("SIGTERM");
@@ -372,6 +517,7 @@ ${a.text}` : a.text;
372
517
  r.pid = child.pid ?? null;
373
518
  this.save();
374
519
  this.log(`spawn work=${r.work_id} pid=${r.pid ?? "none"} ${resume ? "resume" : "new"}`);
520
+ this.note(r, resume ? "= Resumed." : `= Started "${r.title}" in ${r.repo}`);
375
521
  child.stdin?.on("error", () => {
376
522
  });
377
523
  child.stdin?.write(dialect.opening(r, `${prompt}
@@ -391,6 +537,8 @@ ${RESULT_INSTRUCTION}`));
391
537
  child.on("close", (code, signal) => void this.onExit(r, live, code, signal));
392
538
  }
393
539
  onItem(r, live, item) {
540
+ const logged = logLineFor(item);
541
+ if (logged) this.note(r, logged);
394
542
  switch (item.type) {
395
543
  case "session":
396
544
  if (r.session_id !== item.id) {
@@ -403,14 +551,11 @@ ${RESULT_INSTRUCTION}`));
403
551
  this.progress(r, live, item.text, false);
404
552
  return;
405
553
  case "tool": {
554
+ const line = item.summary ?? (item.target ? `${item.name} ${item.target}` : item.name);
555
+ if (!isProgressSentence(line)) return;
406
556
  const changed = item.name !== live.lastTool;
407
557
  live.lastTool = item.name;
408
- this.progress(
409
- r,
410
- live,
411
- item.summary ?? (item.target ? `${item.name} ${item.target}` : item.name),
412
- changed
413
- );
558
+ this.progress(r, live, line, changed);
414
559
  return;
415
560
  }
416
561
  case "ask":
@@ -432,13 +577,12 @@ ${RESULT_INSTRUCTION}`));
432
577
  }
433
578
  }
434
579
  progress(r, live, line, force) {
580
+ const summary = (parseRunResult(line)?.summary ?? line.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
581
+ if (!isProgressSentence(summary)) return;
435
582
  const now = this.now();
436
583
  if (!force && now - live.lastProgressAt < (this.deps.progressMs ?? 3e4)) return;
437
584
  live.lastProgressAt = now;
438
- this.emit(r.work_id, {
439
- kind: "progress",
440
- summary: (parseRunResult(line)?.summary ?? line.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, 200)
441
- });
585
+ this.emit(r.work_id, { kind: "progress", summary });
442
586
  }
443
587
  async onExit(r, live, code, signal) {
444
588
  if (this.lives.get(r.work_id) === live) this.lives.delete(r.work_id);
@@ -448,7 +592,7 @@ ${RESULT_INSTRUCTION}`));
448
592
  `exit work=${r.work_id} ${exit} result=${live.result ? live.result.ok ? "ok" : "error" : "none"}`
449
593
  );
450
594
  if (live.interrupted) {
451
- await this.end(r, { kind: "failed", summary: "The run was stopped." });
595
+ await this.end(r, { kind: "failed", summary: STOPPED_SUMMARY });
452
596
  return;
453
597
  }
454
598
  if (live.next) {
@@ -528,6 +672,7 @@ ${RESULT_INSTRUCTION}`));
528
672
  r.end = { ...end, at: new Date(this.now()).toISOString() };
529
673
  r.pid = null;
530
674
  this.save();
675
+ this.note(r, endNote(end));
531
676
  this.emit(r.work_id, end);
532
677
  }
533
678
  emit(id, event) {
@@ -554,27 +699,38 @@ ${RESULT_INSTRUCTION}`));
554
699
  return r.end.kind === "settled" ? "completed" : "failed";
555
700
  }
556
701
  load() {
557
- try {
558
- const raw = JSON.parse(readFileSync(this.file, "utf-8"));
559
- const cutoff = this.now() - KEEP_MS;
560
- return Array.isArray(raw) ? raw.filter(
561
- (r) => typeof r?.work_id === "string" && typeof r?.repo === "string" && !(r.end && Date.parse(r.end.at) < cutoff)
562
- ) : [];
563
- } catch {
564
- return [];
565
- }
702
+ const cutoff = this.now() - KEEP_MS;
703
+ return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
566
704
  }
567
705
  save() {
568
- mkdirSync(dirname(this.file), { recursive: true, mode: 448 });
706
+ mkdirSync2(dirname2(this.file), { recursive: true, mode: 448 });
569
707
  const tmp = `${this.file}.tmp`;
570
708
  writeFileSync(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
571
709
  `, { mode: 384 });
572
- chmodSync(tmp, 384);
573
- renameSync(tmp, this.file);
710
+ chmodSync2(tmp, 384);
711
+ renameSync2(tmp, this.file);
574
712
  }
575
713
  };
714
+ function readRunRecords(file = localRunsFilePath()) {
715
+ try {
716
+ const raw = JSON.parse(readFileSync(file, "utf-8"));
717
+ return Array.isArray(raw) ? raw.filter(
718
+ (r) => typeof r?.work_id === "string" && typeof r?.repo === "string"
719
+ ) : [];
720
+ } catch {
721
+ return [];
722
+ }
723
+ }
724
+ function isProgressSentence(value) {
725
+ return typeof value === "string" && /\S[ \t]+\S/.test(value.trim().split(/\r?\n/)[0] ?? "");
726
+ }
576
727
 
577
728
  export {
729
+ runLogDir,
730
+ runLogPath,
731
+ STOPPED_SUMMARY,
732
+ isEndLogLine,
578
733
  localRunsFilePath,
579
- LocalDriver
734
+ LocalDriver,
735
+ readRunRecords
580
736
  };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  sanitizeLabel
4
- } from "./chunk-4LFQXBWP.js";
4
+ } from "./chunk-VK6GV757.js";
5
5
  import {
6
6
  CONFIG_DIR
7
7
  } from "./chunk-3DIGCVL4.js";
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  ConnectFailure,
4
4
  deviceLogin
5
- } from "./chunk-F4WCO6Z4.js";
5
+ } from "./chunk-ZDUKQWKA.js";
6
6
  import {
7
7
  ApiError,
8
8
  ReauthError,