@cloop/runner 0.2.6 → 0.2.8

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,12 +1,134 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ stripControl
4
+ } from "./chunk-VK6GV757.js";
2
5
  import {
3
6
  CONFIG_DIR
4
7
  } from "./chunk-3DIGCVL4.js";
5
8
 
9
+ // src/run-log.ts
10
+ import {
11
+ appendFileSync,
12
+ chmodSync,
13
+ mkdirSync,
14
+ readdirSync,
15
+ renameSync,
16
+ statSync,
17
+ unlinkSync
18
+ } from "fs";
19
+ import { dirname, join } from "path";
20
+ var RUN_LOG_LINE_MAX = 500;
21
+ var RUN_LOG_MAX_BYTES = 5 * 1024 * 1024;
22
+ var RUN_LOG_KEEP_MS = 14 * 24 * 36e5;
23
+ var SAFE_ID = /^[\w-]{1,100}$/;
24
+ function runLogDir(runsFile) {
25
+ return join(dirname(runsFile), "runs");
26
+ }
27
+ function runLogPath(dir, workId) {
28
+ return SAFE_ID.test(workId) ? join(dir, `${workId}.log`) : null;
29
+ }
30
+ var SECRETS = [
31
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----.*/g, "[redacted private key]"],
32
+ [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [redacted]"],
33
+ [/(:\/\/)[^\s/@:]+:[^\s/@]+@/g, "$1[redacted]@"],
34
+ [
35
+ /([?&](?:access_token|token|key|api_key|apikey|secret|sig|signature|code|password)=)[^&\s"']+/gi,
36
+ "$1[redacted]"
37
+ ],
38
+ [
39
+ /(\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,
40
+ "$1[redacted]"
41
+ ],
42
+ [
43
+ /(--?[\w-]*(?:token|secret|password|api-key|apikey)[\w-]*[ =])["']?[^\s"']{4,}["']?/gi,
44
+ "$1[redacted]"
45
+ ],
46
+ [/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, "[redacted]"],
47
+ [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "[redacted]"],
48
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "[redacted]"],
49
+ [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, "[redacted]"],
50
+ [/\bAIza[0-9A-Za-z_-]{30,}/g, "[redacted]"],
51
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g, "[redacted]"]
52
+ ];
53
+ var OPAQUE = /[A-Za-z0-9_+=-]{32,}/g;
54
+ function redactSecrets(text2) {
55
+ let out = text2;
56
+ for (const [pattern, replacement] of SECRETS) out = out.replace(pattern, replacement);
57
+ return out.replace(
58
+ OPAQUE,
59
+ (run) => /^[0-9a-f-]+$/i.test(run) || !/\d/.test(run) || !/[A-Za-z]/.test(run) ? run : "[redacted]"
60
+ );
61
+ }
62
+ function logText(text2) {
63
+ const flat = redactSecrets(stripControl(text2).replace(/\s+/g, " ").trim());
64
+ return flat.length > RUN_LOG_LINE_MAX ? `${flat.slice(0, RUN_LOG_LINE_MAX - 1)}\u2026` : flat;
65
+ }
66
+ function logLineFor(item) {
67
+ switch (item.type) {
68
+ case "text":
69
+ return item.text;
70
+ case "tool": {
71
+ const input = item.detail ?? item.summary ?? item.target;
72
+ return `> ${item.name}${input ? `: ${input}` : ""}`;
73
+ }
74
+ case "ask":
75
+ return `? ${item.summary}`;
76
+ case "result":
77
+ return item.ok ? `= Result: ${item.text ?? "done"}` : `= Error: ${item.text ?? "no text"}`;
78
+ default:
79
+ return null;
80
+ }
81
+ }
82
+ function appendRunLog(dir, workId, text2, { now = Date.now(), maxBytes = RUN_LOG_MAX_BYTES } = {}) {
83
+ const path = runLogPath(dir, workId);
84
+ if (!path) return;
85
+ const line = `${stamp(now)} ${logText(text2)}
86
+ `;
87
+ mkdirSync(dir, { recursive: true, mode: 448 });
88
+ const size = sizeOf(path);
89
+ if (size > 0 && size + Buffer.byteLength(line) > maxBytes) renameSync(path, `${path}.1`);
90
+ appendFileSync(path, line, { mode: 384 });
91
+ }
92
+ function pruneRunLogs(dir, now = Date.now(), keepMs = RUN_LOG_KEEP_MS) {
93
+ mkdirSync(dir, { recursive: true, mode: 448 });
94
+ chmodSync(dir, 448);
95
+ let removed = 0;
96
+ for (const name of readdirSync(dir)) {
97
+ if (!/\.log(\.1)?$/.test(name)) continue;
98
+ const path = join(dir, name);
99
+ try {
100
+ if (statSync(path).mtimeMs < now - keepMs) {
101
+ unlinkSync(path);
102
+ removed++;
103
+ }
104
+ } catch {
105
+ }
106
+ }
107
+ return removed;
108
+ }
109
+ function sizeOf(path) {
110
+ try {
111
+ return statSync(path).size;
112
+ } catch {
113
+ return 0;
114
+ }
115
+ }
116
+ var STOPPED_SUMMARY = "The run was stopped.";
117
+ function endNote(end) {
118
+ return `= ${end.kind === "settled" ? "Done" : "Ended"}: ${end.summary ?? end.kind}`;
119
+ }
120
+ function isEndLogLine(line) {
121
+ return /^\S+ = (Done|Ended): /.test(line);
122
+ }
123
+ function stamp(now) {
124
+ const d = new Date(now);
125
+ return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":");
126
+ }
127
+
6
128
  // src/t3-bin.ts
7
129
  import { execFileSync } from "child_process";
8
- import { existsSync, readdirSync, statSync } from "fs";
9
- import { join } from "path";
130
+ import { existsSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
131
+ import { join as join2 } from "path";
10
132
  var CLEAN_ENV = () => ({
11
133
  HOME: process.env.HOME,
12
134
  USER: process.env.USER,
@@ -16,14 +138,14 @@ function defaultT3BinSources(home, stored) {
16
138
  return {
17
139
  env: process.env,
18
140
  home,
19
- appDirs: process.platform === "darwin" ? ["/Applications", join(home, "Applications")] : [],
141
+ appDirs: process.platform === "darwin" ? ["/Applications", join2(home, "Applications")] : [],
20
142
  onPath: () => whichAll("t3"),
21
143
  ...stored ? { stored } : {}
22
144
  };
23
145
  }
24
146
  function isExecutable(path) {
25
147
  try {
26
- const s = statSync(path);
148
+ const s = statSync2(path);
27
149
  return s.isFile() && (s.mode & 73) !== 0;
28
150
  } catch {
29
151
  return false;
@@ -32,14 +154,14 @@ function isExecutable(path) {
32
154
  function bundleBinaries(appDir) {
33
155
  let bundles;
34
156
  try {
35
- bundles = readdirSync(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
157
+ bundles = readdirSync2(appDir).filter((name) => /^T3 Code.*\.app$/.test(name));
36
158
  } catch {
37
159
  return [];
38
160
  }
39
161
  return bundles.flatMap((bundle) => {
40
- const root = join(appDir, bundle);
162
+ const root = join2(appDir, bundle);
41
163
  try {
42
- return readdirSync(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join(root, rel)).filter(isExecutable);
164
+ return readdirSync2(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join2(root, rel)).filter(isExecutable);
43
165
  } catch {
44
166
  return [];
45
167
  }
@@ -48,8 +170,8 @@ function bundleBinaries(appDir) {
48
170
  function t3Candidates(serverVersion, sources) {
49
171
  const ordered = [
50
172
  sources.env.T3_BIN,
51
- join(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
52
- join(sources.env.T3CODE_HOME || join(sources.home, ".t3"), "bin", "t3"),
173
+ join2(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
174
+ join2(sources.env.T3CODE_HOME || join2(sources.home, ".t3"), "bin", "t3"),
53
175
  ...sources.appDirs.flatMap(bundleBinaries),
54
176
  ...sources.onPath(),
55
177
  sources.stored
@@ -113,6 +235,16 @@ var https = (v) => {
113
235
  return false;
114
236
  }
115
237
  };
238
+ var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
239
+ function prUrlIn(text2) {
240
+ return text2?.match(PR_URL)?.at(-1) ?? null;
241
+ }
242
+ function resultPrUrl(finalMessage) {
243
+ const result = parseRunResult(finalMessage);
244
+ if (!result) return prUrlIn(finalMessage);
245
+ const prs = result.outputs.flatMap((o) => o.kind === "pr" ? [o.url] : []);
246
+ return prs.at(-1) ?? null;
247
+ }
116
248
  function parseRunResult(message) {
117
249
  const block = [...(message ?? "").matchAll(/```cloop-result\s*\n([\s\S]*?)```/g)].at(-1)?.[1];
118
250
  if (!block) return void 0;
@@ -198,6 +330,37 @@ function questionLine(questions) {
198
330
  (x) => x.options?.length ? `${x.question} (${x.options.map((o) => o.label).join(", ")})` : x.question
199
331
  ).join(" ").slice(0, 500);
200
332
  }
333
+ function isProgressSentence(value) {
334
+ return typeof value === "string" && /\S[ \t]+\S/.test(value.trim().split(/\r?\n/)[0] ?? "");
335
+ }
336
+ var PROGRESS_MS = 3e4;
337
+ function nextProgress(clock, text2, now, ms = PROGRESS_MS, force = false) {
338
+ const summary = (parseRunResult(text2)?.summary ?? text2.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
339
+ if (!isProgressSentence(summary)) return null;
340
+ if (!force && now - clock.lastProgressAt < ms) return null;
341
+ clock.lastProgressAt = now;
342
+ return summary;
343
+ }
344
+ var YES_WORDS = /* @__PURE__ */ new Set([
345
+ "y",
346
+ "yes",
347
+ "yep",
348
+ "yeah",
349
+ "allow",
350
+ "allow it",
351
+ "ok",
352
+ "okay",
353
+ "approve",
354
+ "approved",
355
+ "go ahead",
356
+ "sure",
357
+ "do it"
358
+ ]);
359
+ function isYes(reply) {
360
+ return YES_WORDS.has(
361
+ reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
362
+ );
363
+ }
201
364
 
202
365
  // src/drivers/t3.ts
203
366
  function isUnsettled(t) {
@@ -209,17 +372,41 @@ function isChild(t) {
209
372
  var SESSIONS_TTL_MS = 5 * 6e4;
210
373
  var STATUS_TTL_MS = 3e4;
211
374
  var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
212
- var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
375
+ var IDLE_SETTLE_MS = 20 * 6e4;
376
+ var APPROVAL_WORDS = {
377
+ command: "run a command",
378
+ "file-read": "read a file",
379
+ "file-change": "change files",
380
+ "mcp-elicitation": "answer a request from a tool",
381
+ permission: "use a new permission"
382
+ };
213
383
  function pendingQuestions(p) {
214
384
  const asked = /* @__PURE__ */ new Map();
385
+ const approvals = /* @__PURE__ */ new Map();
215
386
  for (const item of p.turnItems ?? []) {
216
- if (item.type === "user_input_request" && item.requestId && item.questions?.length)
387
+ if (!item.requestId) continue;
388
+ if (item.type === "user_input_request" && item.questions?.length)
217
389
  asked.set(item.requestId, item.questions);
390
+ if (item.type === "approval_request")
391
+ approvals.set(item.requestId, item.prompt?.trim() || null);
218
392
  }
219
- return (p.runtimeRequests ?? []).filter((r) => r.kind === "user_input" && r.status === "pending" && asked.has(r.id)).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")).map((r) => ({ request_id: r.id, questions: asked.get(r.id) ?? [] }));
393
+ return (p.runtimeRequests ?? []).filter((r) => r.status === "pending").sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")).flatMap((r) => {
394
+ const questions = r.kind === "user_input" ? asked.get(r.id) : void 0;
395
+ if (questions) return [{ request_id: r.id, questions }];
396
+ if (Object.hasOwn(APPROVAL_WORDS, r.kind) && approvals.has(r.id))
397
+ return [
398
+ { request_id: r.id, approval: { kind: r.kind, prompt: approvals.get(r.id) ?? null } }
399
+ ];
400
+ return [];
401
+ });
220
402
  }
221
403
  function questionText(q) {
222
- return questionLine(q.questions);
404
+ if (!q.approval) return questionLine(q.questions);
405
+ const words = APPROVAL_WORDS[q.approval.kind] ?? "go on";
406
+ const prompt = q.approval.prompt?.replace(/[\r\n\t]+/g, " ");
407
+ if (!prompt) return `${words}. OK?`;
408
+ return `${words}. OK?
409
+ (${prompt.length > 158 ? `${prompt.slice(0, 157)}\u2026` : prompt})`;
223
410
  }
224
411
  function latestRun(runs) {
225
412
  return runs.reduce(
@@ -246,29 +433,24 @@ function steerableRun(p) {
246
433
  }
247
434
  var STEER_WAIT_MS = 8e3;
248
435
  var STEER_POLL_MS = 500;
249
- function prUrlOf(thread) {
250
- const branch = thread.branch ?? null;
251
- const linked = thread.pullRequests ?? [];
252
- const own = branch ? linked.filter((pr) => pr.snapshot?.headBranch === branch) : [];
253
- const fromLinked = (own.at(-1) ?? linked.at(-1))?.url ?? thread.linkedPullRequest?.url;
254
- if (fromLinked) return fromLinked;
255
- if (branch && !SHARED_BRANCHES.has(branch)) return thread.branchPullRequest?.url ?? null;
256
- return null;
257
- }
258
436
  function outcomeOf(p) {
259
437
  const run = latestRun(p.runs ?? []);
260
438
  const status = run?.status ?? "pending";
261
439
  const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
262
440
  const text2 = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
441
+ const result = parseRunResult(text2);
263
442
  return {
264
443
  status,
265
444
  settled,
266
445
  kind: settled ? status === "completed" || !run ? "settled" : "failed" : null,
267
- pr_url: prUrlOf(p.thread),
446
+ pr_url: resultPrUrl(text2),
268
447
  last_assistant_text: text2 ? text2.slice(0, 300) : null,
269
- ...parseRunResult(text2) ? { result: parseRunResult(text2) } : {}
448
+ ...result ? { result } : {}
270
449
  };
271
450
  }
451
+ function permissionOf(runtimeMode) {
452
+ return runtimeMode === "full-access" ? "full" : "ask";
453
+ }
272
454
  function pickProject(projects, repository) {
273
455
  if (!repository) {
274
456
  const repos = projects.filter((p) => p.repositoryIdentity);
@@ -353,6 +535,8 @@ var T3Driver = class {
353
535
  }
354
536
  deps;
355
537
  name = "t3";
538
+ /** Threads whose turn ended without a result block, by id: ends the held run on a stop. */
539
+ held = /* @__PURE__ */ new Map();
356
540
  get capabilities() {
357
541
  return boxCapabilities(this.deps.scope?.());
358
542
  }
@@ -482,7 +666,11 @@ var T3Driver = class {
482
666
  ${RESULT_INSTRUCTION}`, attachments: [] }
483
667
  }
484
668
  );
485
- return { thread_id: launched.threadId, resumed: launched.resumed };
669
+ return {
670
+ thread_id: launched.threadId,
671
+ resumed: launched.resumed,
672
+ permission: permissionOf(runtimeMode)
673
+ };
486
674
  }
487
675
  /**
488
676
  * Say something to a thread. While the thread waits on a question, only
@@ -519,7 +707,7 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
519
707
  commandId: a.command_id,
520
708
  threadId: a.thread_id,
521
709
  requestId: question.request_id,
522
- answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text]))
710
+ ...question.approval ? { decision: isYes(a.text) ? "accept" : "decline" } : { answers: Object.fromEntries(question.questions.map((q) => [q.id, a.text])) }
523
711
  });
524
712
  return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
525
713
  }
@@ -554,7 +742,11 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
554
742
  */
555
743
  async interrupt(threadId, commandId) {
556
744
  const run = activeRun((await this.readProjection(threadId)).runs ?? []);
557
- if (!run) return { ok: true, was_running: false };
745
+ if (!run) {
746
+ const end = this.held.get(threadId);
747
+ end?.();
748
+ return { ok: true, was_running: Boolean(end) };
749
+ }
558
750
  try {
559
751
  await this.dispatch({
560
752
  type: "run.interrupt",
@@ -575,6 +767,30 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
575
767
  const open = await this.openTarget(id, projection).catch(() => null);
576
768
  return { status, settled, pr_url, last_assistant_text, open };
577
769
  }
770
+ /**
771
+ * The owner's own open threads, the ones Cloop did not start: running
772
+ * first, then the most recent. Each carries where it opens, the same
773
+ * target as a Cloop run's thread: its web page when another device can
774
+ * reach T3, else its project, to find it by title.
775
+ */
776
+ async outsideThreads(limit) {
777
+ const [cfg, shell] = await this.readT3State();
778
+ const base = this.t3.t3Url;
779
+ const web = base ? reachableBase(base, cfg.directEndpoints, this.servedBase(base)) : null;
780
+ const projects = new Map((shell.projects ?? []).map((p) => [p.id, p.title]));
781
+ const mine = (shell.threads ?? []).filter((t) => isUnsettled(t) && !threadView(t).cloop);
782
+ return orderThreads(mine, limit).map((t) => {
783
+ const project = t.projectId ? projects.get(t.projectId) : void 0;
784
+ return {
785
+ id: t.id,
786
+ title: t.title.slice(0, 120),
787
+ updatedAt: t.updatedAt,
788
+ status: t.status,
789
+ ...project ? { project: project.slice(0, 200) } : {},
790
+ ...web ? { url: t3ThreadUrl(web, cfg.environment.environmentId, t.id) } : {}
791
+ };
792
+ });
793
+ }
578
794
  /** Where the owner opens this thread: the T3 web app's page for it, or its title and project. */
579
795
  async openTarget(id, p) {
580
796
  const [cfg, shell] = await this.readT3State();
@@ -618,27 +834,52 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
618
834
  * Subscribe to the thread and resubscribe whenever the stream ends. A thread
619
835
  * that settled while nobody watched shows a terminal run in its first
620
836
  * snapshot. A question is reported on every update it is still pending.
837
+ *
838
+ * The run ends when its latest turn completes with a result block, when a
839
+ * turn ends any other way (a stop, a failure), or when the owner settles the
840
+ * thread in T3. A turn that completes without a result block holds the run
841
+ * open: a new turn carries it on, and IDLE_SETTLE_MS of nothing settles it
842
+ * with its last words.
621
843
  */
622
844
  watch(threadId, onEvent) {
623
845
  let stopped = false;
624
846
  let finishing = false;
625
847
  let live = null;
848
+ const clock = { lastProgressAt: 0 };
849
+ let spoken = null;
850
+ let idle = null;
851
+ const wake = () => {
852
+ if (idle) clearTimeout(idle.timer);
853
+ idle = null;
854
+ this.held.delete(threadId);
855
+ };
856
+ const speak = (runs, messages) => {
857
+ const latest = [...messages.values()].filter((m) => m.role === "assistant" && m.text?.trim()).at(-1);
858
+ if (!latest?.text || latest.streaming || latest.text === spoken) return;
859
+ const run = latest.runId ? runs.get(latest.runId) : void 0;
860
+ if (run && TERMINAL_RUN.has(run.status)) return;
861
+ spoken = latest.text;
862
+ const now = this.deps.now?.() ?? Date.now();
863
+ const summary = nextProgress(clock, latest.text, now, this.deps.progressMs);
864
+ if (summary) onEvent({ kind: "progress", summary });
865
+ };
626
866
  const retry = () => {
627
867
  if (stopped) return;
628
868
  const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
629
869
  timer.unref?.();
630
870
  };
631
- const finish = async () => {
632
- if (stopped || finishing) return;
871
+ const finish = async (waited) => {
872
+ if (stopped) return;
873
+ if (finishing) {
874
+ if (waited) setTimeout(() => void finish(waited), 1e3).unref?.();
875
+ return;
876
+ }
633
877
  finishing = true;
634
878
  let outcome;
879
+ let p;
635
880
  try {
636
- outcome = outcomeOf(await this.readProjection(threadId));
637
- const grace = this.deps.prGraceMs ?? 6e4;
638
- if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
639
- await sleep(grace);
640
- outcome = outcomeOf(await this.readProjection(threadId));
641
- }
881
+ p = await this.readProjection(threadId);
882
+ outcome = outcomeOf(p);
642
883
  } catch (err) {
643
884
  this.log(
644
885
  `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
@@ -654,11 +895,47 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
654
895
  if (!live) void follow();
655
896
  return;
656
897
  }
898
+ const turn = latestRun(p.runs ?? []);
899
+ if (turn && outcome.kind === "settled" && !outcome.result && !p.thread.settledAt && turn.id !== waited) {
900
+ finishing = false;
901
+ if (idle?.runId === turn.id) return;
902
+ wake();
903
+ const ms = this.deps.idleMs ?? IDLE_SETTLE_MS;
904
+ const now = this.deps.now?.() ?? Date.now();
905
+ const words = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text?.trim()).at(-1)?.text;
906
+ const last = words ? nextProgress(clock, words, now, this.deps.progressMs, true) : null;
907
+ if (last) onEvent({ kind: "progress", summary: last });
908
+ const ended = turn.completedAt ? Date.parse(turn.completedAt) : Number.NaN;
909
+ const wait = Math.max(0, Number.isNaN(ended) ? ms : ended + ms - now);
910
+ const timer = setTimeout(() => {
911
+ idle = null;
912
+ void finish(turn.id);
913
+ }, wait);
914
+ timer.unref?.();
915
+ idle = { runId: turn.id, timer };
916
+ this.held.set(threadId, () => {
917
+ if (stopped) return;
918
+ wake();
919
+ stopped = true;
920
+ live?.close();
921
+ this.log(`stopped a held run thread=${threadId}`);
922
+ onEvent({ kind: "failed", summary: STOPPED_SUMMARY });
923
+ });
924
+ this.log(
925
+ `turn ended without a result thread=${threadId} run=${turn.id}; settling in ${Math.round(wait / 6e4)} min unless a new turn starts`
926
+ );
927
+ return;
928
+ }
929
+ wake();
657
930
  stopped = true;
658
931
  live?.close();
659
932
  const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
660
933
  if (outcome.kind === "failed") {
661
- onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
934
+ onEvent({
935
+ kind: "failed",
936
+ summary: `The run ended ${outcome.status}.`,
937
+ ...outcome.result ? pr : {}
938
+ });
662
939
  } else {
663
940
  onEvent({
664
941
  kind: "settled",
@@ -671,18 +948,24 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
671
948
  const follow = async () => {
672
949
  if (stopped || live) return;
673
950
  const runs = /* @__PURE__ */ new Map();
951
+ const messages = /* @__PURE__ */ new Map();
674
952
  const requests = /* @__PURE__ */ new Map();
675
953
  const asks = /* @__PURE__ */ new Map();
676
954
  const keepAsk = (item) => {
677
- if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
955
+ if ((item.type === "user_input_request" || item.type === "approval_request") && item.requestId)
956
+ asks.set(item.requestId, item);
678
957
  };
679
958
  let settledByHand = false;
680
959
  let stream;
681
960
  try {
682
961
  stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
962
+ if (stopped) return;
683
963
  const item = raw;
964
+ let said = false;
684
965
  if (item.kind === "snapshot" && "projection" in item) {
685
966
  for (const r of item.projection.runs ?? []) runs.set(r.id, r);
967
+ for (const [i, m] of (item.projection.messages ?? []).entries())
968
+ messages.set(m.id ?? `#${i}`, m);
686
969
  for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
687
970
  for (const t of item.projection.turnItems ?? []) keepAsk(t);
688
971
  settledByHand ||= Boolean(item.projection.thread?.settledAt);
@@ -690,6 +973,9 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
690
973
  const { type, payload } = item.event;
691
974
  if (type.startsWith("run.") && typeof payload?.id === "string") {
692
975
  runs.set(payload.id, payload);
976
+ } else if (type === "message.updated" && typeof payload?.id === "string") {
977
+ messages.set(payload.id, payload);
978
+ said = true;
693
979
  } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
694
980
  requests.set(payload.id, payload);
695
981
  } else if (type === "turn-item.updated" && payload) {
@@ -698,10 +984,16 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
698
984
  settledByHand = true;
699
985
  } else return;
700
986
  } else return;
987
+ const latest = latestRun([...runs.values()]);
988
+ if (idle && latest?.id !== idle.runId) {
989
+ this.log(`new turn thread=${threadId} run=${latest?.id}; the run goes on`);
990
+ wake();
991
+ }
701
992
  if (settledByHand || isTerminal([...runs.values()])) {
702
- void finish();
993
+ if (settledByHand || said || idle?.runId !== latest?.id) void finish();
703
994
  return;
704
995
  }
996
+ speak(runs, messages);
705
997
  const pending = pendingQuestions({
706
998
  runtimeRequests: [...requests.values()],
707
999
  turnItems: [...asks.values()]
@@ -731,6 +1023,7 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
731
1023
  void follow();
732
1024
  return () => {
733
1025
  stopped = true;
1026
+ wake();
734
1027
  live?.close();
735
1028
  };
736
1029
  }
@@ -808,16 +1101,24 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
808
1101
  };
809
1102
 
810
1103
  // src/runner-config.ts
811
- import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
1104
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
812
1105
  import { homedir } from "os";
813
- import { dirname, join as join2 } from "path";
1106
+ import { dirname as dirname2, join as join3 } from "path";
814
1107
  var BOX_FILE = "box.json";
815
1108
  function boxPath() {
816
- return process.env.CLOOP_BOX_FILE ?? join2(homedir(), CONFIG_DIR, BOX_FILE);
1109
+ return process.env.CLOOP_BOX_FILE ?? join3(homedir(), CONFIG_DIR, BOX_FILE);
817
1110
  }
818
1111
  function isLocal(cfg) {
819
1112
  return cfg.driver === "claude-code" || cfg.driver === "codex";
820
1113
  }
1114
+ function showsOtherThreads(cfg) {
1115
+ return cfg?.hideOtherThreads !== true;
1116
+ }
1117
+ function otherThreadsChoice(argv, previous) {
1118
+ if (argv.includes("--hide-other-threads")) return true;
1119
+ if (argv.includes("--show-other-threads")) return false;
1120
+ return previous?.hideOtherThreads === true;
1121
+ }
821
1122
  function readRunnerConfig() {
822
1123
  let parsed;
823
1124
  try {
@@ -834,21 +1135,34 @@ function readRunnerConfig() {
834
1135
  }
835
1136
  function writeBoxConfig(cfg) {
836
1137
  const path = boxPath();
837
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
1138
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
838
1139
  const temp = `${path}.${process.pid}.tmp`;
839
1140
  writeFileSync(temp, `${JSON.stringify(cfg, null, 2)}
840
1141
  `, { mode: 384 });
841
- chmodSync(temp, 384);
842
- renameSync(temp, path);
1142
+ chmodSync2(temp, 384);
1143
+ renameSync2(temp, path);
843
1144
  }
844
1145
 
845
1146
  export {
1147
+ RESULT_INSTRUCTION,
1148
+ prUrlIn,
1149
+ resultPrUrl,
1150
+ parseRunResult,
846
1151
  RUNTIME_MODES,
847
1152
  BoxToolError,
848
1153
  CLOOP_THREAD_PREFIX,
849
1154
  questionLine,
850
- RESULT_INSTRUCTION,
851
- parseRunResult,
1155
+ isProgressSentence,
1156
+ nextProgress,
1157
+ isYes,
1158
+ runLogDir,
1159
+ runLogPath,
1160
+ logLineFor,
1161
+ appendRunLog,
1162
+ pruneRunLogs,
1163
+ STOPPED_SUMMARY,
1164
+ endNote,
1165
+ isEndLogLine,
852
1166
  defaultT3BinSources,
853
1167
  t3Candidates,
854
1168
  pickT3Bin,
@@ -858,6 +1172,8 @@ export {
858
1172
  T3Driver,
859
1173
  boxPath,
860
1174
  isLocal,
1175
+ showsOtherThreads,
1176
+ otherThreadsChoice,
861
1177
  readRunnerConfig,
862
1178
  writeBoxConfig
863
1179
  };
@@ -1,15 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  findRun
4
- } from "./chunk-UEV7ARIT.js";
4
+ } from "./chunk-GGK4FLAH.js";
5
5
  import {
6
6
  localRunsFilePath,
7
7
  readRunRecords,
8
8
  takeoverSummary
9
- } from "./chunk-E3V2PRVS.js";
10
- import {
11
- sanitizeLabel
12
- } from "./chunk-VK6GV757.js";
9
+ } from "./chunk-5GPCD7HI.js";
13
10
  import {
14
11
  lockThreadsFile,
15
12
  threadsFilePath
@@ -17,10 +14,13 @@ import {
17
14
  import {
18
15
  isLocal,
19
16
  readRunnerConfig
20
- } from "./chunk-H7ZCXBNW.js";
17
+ } from "./chunk-L5R7QXIB.js";
21
18
  import {
22
19
  shortMachineName
23
20
  } from "./chunk-JX6VG5FE.js";
21
+ import {
22
+ sanitizeLabel
23
+ } from "./chunk-VK6GV757.js";
24
24
 
25
25
  // src/commands/takeover.ts
26
26
  import { spawnSync } from "child_process";
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-AG6SI6I2.js";
6
6
  import {
7
7
  VERSION
8
- } from "./chunk-GTE4QSTR.js";
8
+ } from "./chunk-JXVCUFUB.js";
9
9
  import {
10
10
  getOrigin,
11
11
  readCredentials,