@cloop/runner 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,32 +433,29 @@ 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
- const only = projects.length === 1 ? projects[0] : void 0;
274
455
  if (!repository) {
456
+ const repos = projects.filter((p) => p.repositoryIdentity);
457
+ const pool = repos.length > 0 ? repos : projects;
458
+ const only = pool.length === 1 ? pool[0] : void 0;
275
459
  if (only) return only;
276
460
  throw new BoxToolError("no_project");
277
461
  }
@@ -306,12 +490,53 @@ function orderThreads(threads, limit) {
306
490
  return [...running, ...rest].slice(0, limit);
307
491
  }
308
492
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
493
+ function t3ThreadUrl(base, environmentId, threadId) {
494
+ return `${base.replace(/\/+$/, "")}/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`;
495
+ }
496
+ var LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\])$/;
497
+ function isLoopback(url) {
498
+ try {
499
+ return LOOPBACK_HOST.test(new URL(url).hostname);
500
+ } catch {
501
+ return false;
502
+ }
503
+ }
504
+ function tailscaleServed(statusJson, t3Url) {
505
+ let web;
506
+ let port;
507
+ try {
508
+ web = JSON.parse(statusJson).Web ?? {};
509
+ port = new URL(t3Url).port || "80";
510
+ } catch {
511
+ return null;
512
+ }
513
+ for (const [hostPort, served] of Object.entries(web)) {
514
+ const proxy = served?.Handlers?.["/"]?.Proxy;
515
+ if (!proxy) continue;
516
+ let target;
517
+ try {
518
+ target = new URL(proxy);
519
+ } catch {
520
+ continue;
521
+ }
522
+ if (!LOOPBACK_HOST.test(target.hostname) || (target.port || "80") !== port) continue;
523
+ return hostPort.endsWith(":443") ? `https://${hostPort.slice(0, -4)}` : `https://${hostPort}`;
524
+ }
525
+ return null;
526
+ }
527
+ function reachableBase(t3Url, direct, served) {
528
+ if (!isLoopback(t3Url)) return t3Url;
529
+ const endpoint = direct?.find((e) => e.kind === "tailnet") ?? direct?.find((e) => e.kind === "lan");
530
+ return endpoint?.httpBaseUrl ?? served;
531
+ }
309
532
  var T3Driver = class {
310
533
  constructor(deps) {
311
534
  this.deps = deps;
312
535
  }
313
536
  deps;
314
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();
315
540
  get capabilities() {
316
541
  return boxCapabilities(this.deps.scope?.());
317
542
  }
@@ -441,7 +666,11 @@ var T3Driver = class {
441
666
  ${RESULT_INSTRUCTION}`, attachments: [] }
442
667
  }
443
668
  );
444
- return { thread_id: launched.threadId, resumed: launched.resumed };
669
+ return {
670
+ thread_id: launched.threadId,
671
+ resumed: launched.resumed,
672
+ permission: permissionOf(runtimeMode)
673
+ };
445
674
  }
446
675
  /**
447
676
  * Say something to a thread. While the thread waits on a question, only
@@ -478,7 +707,7 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
478
707
  commandId: a.command_id,
479
708
  threadId: a.thread_id,
480
709
  requestId: question.request_id,
481
- 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])) }
482
711
  });
483
712
  return { sequence: receipt2.sequence, delivered: "answer", question_id: question.request_id };
484
713
  }
@@ -513,7 +742,11 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
513
742
  */
514
743
  async interrupt(threadId, commandId) {
515
744
  const run = activeRun((await this.readProjection(threadId)).runs ?? []);
516
- 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
+ }
517
750
  try {
518
751
  await this.dispatch({
519
752
  type: "run.interrupt",
@@ -529,36 +762,100 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
529
762
  return { ok: true, was_running: true };
530
763
  }
531
764
  async readThread(id) {
532
- const { status, settled, pr_url, last_assistant_text } = outcomeOf(
533
- await this.readProjection(id)
534
- );
535
- return { status, settled, pr_url, last_assistant_text };
765
+ const projection = await this.readProjection(id);
766
+ const { status, settled, pr_url, last_assistant_text } = outcomeOf(projection);
767
+ const open = await this.openTarget(id, projection).catch(() => null);
768
+ return { status, settled, pr_url, last_assistant_text, open };
769
+ }
770
+ /** Where the owner opens this thread: the T3 web app's page for it, or its title and project. */
771
+ async openTarget(id, p) {
772
+ const [cfg, shell] = await this.readT3State();
773
+ const listed = shell.threads?.find((t) => t.id === id);
774
+ const title = p.thread.title ?? listed?.title;
775
+ if (!title) return null;
776
+ const base = this.t3.t3Url;
777
+ const projectId = p.thread.projectId;
778
+ const project = shell.projects?.find((x) => x.id === projectId)?.title ?? null;
779
+ const web = base ? reachableBase(base, cfg.directEndpoints, this.servedBase(base)) : null;
780
+ return {
781
+ url: web ? t3ThreadUrl(web, cfg.environment.environmentId, id) : null,
782
+ base,
783
+ title,
784
+ project
785
+ };
786
+ }
787
+ served = null;
788
+ /** `tailscale serve` changes rarely, and the CLI takes a moment, so its answer is kept 5 minutes. */
789
+ servedBase(t3Url) {
790
+ const kept = this.served;
791
+ if (kept && kept.base === t3Url && Date.now() - kept.at < SESSIONS_TTL_MS) return kept.value;
792
+ let value = null;
793
+ try {
794
+ value = tailscaleServed(
795
+ String(
796
+ (this.deps.exec ?? execFileSync2)("tailscale", ["serve", "status", "--json"], {
797
+ encoding: "utf-8",
798
+ stdio: ["ignore", "pipe", "ignore"],
799
+ timeout: 3e3
800
+ })
801
+ ),
802
+ t3Url
803
+ );
804
+ } catch {
805
+ }
806
+ this.served = { base: t3Url, value, at: Date.now() };
807
+ return value;
536
808
  }
537
809
  /**
538
810
  * Subscribe to the thread and resubscribe whenever the stream ends. A thread
539
811
  * that settled while nobody watched shows a terminal run in its first
540
812
  * snapshot. A question is reported on every update it is still pending.
813
+ *
814
+ * The run ends when its latest turn completes with a result block, when a
815
+ * turn ends any other way (a stop, a failure), or when the owner settles the
816
+ * thread in T3. A turn that completes without a result block holds the run
817
+ * open: a new turn carries it on, and IDLE_SETTLE_MS of nothing settles it
818
+ * with its last words.
541
819
  */
542
820
  watch(threadId, onEvent) {
543
821
  let stopped = false;
544
822
  let finishing = false;
545
823
  let live = null;
824
+ const clock = { lastProgressAt: 0 };
825
+ let spoken = null;
826
+ let idle = null;
827
+ const wake = () => {
828
+ if (idle) clearTimeout(idle.timer);
829
+ idle = null;
830
+ this.held.delete(threadId);
831
+ };
832
+ const speak = (runs, messages) => {
833
+ const latest = [...messages.values()].filter((m) => m.role === "assistant" && m.text?.trim()).at(-1);
834
+ if (!latest?.text || latest.streaming || latest.text === spoken) return;
835
+ const run = latest.runId ? runs.get(latest.runId) : void 0;
836
+ if (run && TERMINAL_RUN.has(run.status)) return;
837
+ spoken = latest.text;
838
+ const now = this.deps.now?.() ?? Date.now();
839
+ const summary = nextProgress(clock, latest.text, now, this.deps.progressMs);
840
+ if (summary) onEvent({ kind: "progress", summary });
841
+ };
546
842
  const retry = () => {
547
843
  if (stopped) return;
548
844
  const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
549
845
  timer.unref?.();
550
846
  };
551
- const finish = async () => {
552
- if (stopped || finishing) return;
847
+ const finish = async (waited) => {
848
+ if (stopped) return;
849
+ if (finishing) {
850
+ if (waited) setTimeout(() => void finish(waited), 1e3).unref?.();
851
+ return;
852
+ }
553
853
  finishing = true;
554
854
  let outcome;
855
+ let p;
555
856
  try {
556
- outcome = outcomeOf(await this.readProjection(threadId));
557
- const grace = this.deps.prGraceMs ?? 6e4;
558
- if (outcome.settled && outcome.kind === "settled" && !outcome.pr_url && grace > 0) {
559
- await sleep(grace);
560
- outcome = outcomeOf(await this.readProjection(threadId));
561
- }
857
+ p = await this.readProjection(threadId);
858
+ outcome = outcomeOf(p);
562
859
  } catch (err) {
563
860
  this.log(
564
861
  `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
@@ -574,11 +871,47 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
574
871
  if (!live) void follow();
575
872
  return;
576
873
  }
874
+ const turn = latestRun(p.runs ?? []);
875
+ if (turn && outcome.kind === "settled" && !outcome.result && !p.thread.settledAt && turn.id !== waited) {
876
+ finishing = false;
877
+ if (idle?.runId === turn.id) return;
878
+ wake();
879
+ const ms = this.deps.idleMs ?? IDLE_SETTLE_MS;
880
+ const now = this.deps.now?.() ?? Date.now();
881
+ const words = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text?.trim()).at(-1)?.text;
882
+ const last = words ? nextProgress(clock, words, now, this.deps.progressMs, true) : null;
883
+ if (last) onEvent({ kind: "progress", summary: last });
884
+ const ended = turn.completedAt ? Date.parse(turn.completedAt) : Number.NaN;
885
+ const wait = Math.max(0, Number.isNaN(ended) ? ms : ended + ms - now);
886
+ const timer = setTimeout(() => {
887
+ idle = null;
888
+ void finish(turn.id);
889
+ }, wait);
890
+ timer.unref?.();
891
+ idle = { runId: turn.id, timer };
892
+ this.held.set(threadId, () => {
893
+ if (stopped) return;
894
+ wake();
895
+ stopped = true;
896
+ live?.close();
897
+ this.log(`stopped a held run thread=${threadId}`);
898
+ onEvent({ kind: "failed", summary: STOPPED_SUMMARY });
899
+ });
900
+ this.log(
901
+ `turn ended without a result thread=${threadId} run=${turn.id}; settling in ${Math.round(wait / 6e4)} min unless a new turn starts`
902
+ );
903
+ return;
904
+ }
905
+ wake();
577
906
  stopped = true;
578
907
  live?.close();
579
908
  const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
580
909
  if (outcome.kind === "failed") {
581
- onEvent({ kind: "failed", summary: `The run ended ${outcome.status}.`, ...pr });
910
+ onEvent({
911
+ kind: "failed",
912
+ summary: `The run ended ${outcome.status}.`,
913
+ ...outcome.result ? pr : {}
914
+ });
582
915
  } else {
583
916
  onEvent({
584
917
  kind: "settled",
@@ -591,18 +924,24 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
591
924
  const follow = async () => {
592
925
  if (stopped || live) return;
593
926
  const runs = /* @__PURE__ */ new Map();
927
+ const messages = /* @__PURE__ */ new Map();
594
928
  const requests = /* @__PURE__ */ new Map();
595
929
  const asks = /* @__PURE__ */ new Map();
596
930
  const keepAsk = (item) => {
597
- if (item.type === "user_input_request" && item.requestId) asks.set(item.requestId, item);
931
+ if ((item.type === "user_input_request" || item.type === "approval_request") && item.requestId)
932
+ asks.set(item.requestId, item);
598
933
  };
599
934
  let settledByHand = false;
600
935
  let stream;
601
936
  try {
602
937
  stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
938
+ if (stopped) return;
603
939
  const item = raw;
940
+ let said = false;
604
941
  if (item.kind === "snapshot" && "projection" in item) {
605
942
  for (const r of item.projection.runs ?? []) runs.set(r.id, r);
943
+ for (const [i, m] of (item.projection.messages ?? []).entries())
944
+ messages.set(m.id ?? `#${i}`, m);
606
945
  for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
607
946
  for (const t of item.projection.turnItems ?? []) keepAsk(t);
608
947
  settledByHand ||= Boolean(item.projection.thread?.settledAt);
@@ -610,6 +949,9 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
610
949
  const { type, payload } = item.event;
611
950
  if (type.startsWith("run.") && typeof payload?.id === "string") {
612
951
  runs.set(payload.id, payload);
952
+ } else if (type === "message.updated" && typeof payload?.id === "string") {
953
+ messages.set(payload.id, payload);
954
+ said = true;
613
955
  } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
614
956
  requests.set(payload.id, payload);
615
957
  } else if (type === "turn-item.updated" && payload) {
@@ -618,10 +960,16 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
618
960
  settledByHand = true;
619
961
  } else return;
620
962
  } else return;
963
+ const latest = latestRun([...runs.values()]);
964
+ if (idle && latest?.id !== idle.runId) {
965
+ this.log(`new turn thread=${threadId} run=${latest?.id}; the run goes on`);
966
+ wake();
967
+ }
621
968
  if (settledByHand || isTerminal([...runs.values()])) {
622
- void finish();
969
+ if (settledByHand || said || idle?.runId !== latest?.id) void finish();
623
970
  return;
624
971
  }
972
+ speak(runs, messages);
625
973
  const pending = pendingQuestions({
626
974
  runtimeRequests: [...requests.values()],
627
975
  turnItems: [...asks.values()]
@@ -651,6 +999,7 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
651
999
  void follow();
652
1000
  return () => {
653
1001
  stopped = true;
1002
+ wake();
654
1003
  live?.close();
655
1004
  };
656
1005
  }
@@ -728,12 +1077,12 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
728
1077
  };
729
1078
 
730
1079
  // src/runner-config.ts
731
- import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
1080
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
732
1081
  import { homedir } from "os";
733
- import { dirname, join as join2 } from "path";
1082
+ import { dirname as dirname2, join as join3 } from "path";
734
1083
  var BOX_FILE = "box.json";
735
1084
  function boxPath() {
736
- return process.env.CLOOP_BOX_FILE ?? join2(homedir(), CONFIG_DIR, BOX_FILE);
1085
+ return process.env.CLOOP_BOX_FILE ?? join3(homedir(), CONFIG_DIR, BOX_FILE);
737
1086
  }
738
1087
  function isLocal(cfg) {
739
1088
  return cfg.driver === "claude-code" || cfg.driver === "codex";
@@ -754,21 +1103,34 @@ function readRunnerConfig() {
754
1103
  }
755
1104
  function writeBoxConfig(cfg) {
756
1105
  const path = boxPath();
757
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
1106
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
758
1107
  const temp = `${path}.${process.pid}.tmp`;
759
1108
  writeFileSync(temp, `${JSON.stringify(cfg, null, 2)}
760
1109
  `, { mode: 384 });
761
- chmodSync(temp, 384);
762
- renameSync(temp, path);
1110
+ chmodSync2(temp, 384);
1111
+ renameSync2(temp, path);
763
1112
  }
764
1113
 
765
1114
  export {
1115
+ RESULT_INSTRUCTION,
1116
+ prUrlIn,
1117
+ resultPrUrl,
1118
+ parseRunResult,
766
1119
  RUNTIME_MODES,
767
1120
  BoxToolError,
768
1121
  CLOOP_THREAD_PREFIX,
769
1122
  questionLine,
770
- RESULT_INSTRUCTION,
771
- parseRunResult,
1123
+ isProgressSentence,
1124
+ nextProgress,
1125
+ isYes,
1126
+ runLogDir,
1127
+ runLogPath,
1128
+ logLineFor,
1129
+ appendRunLog,
1130
+ pruneRunLogs,
1131
+ STOPPED_SUMMARY,
1132
+ endNote,
1133
+ isEndLogLine,
772
1134
  defaultT3BinSources,
773
1135
  t3Candidates,
774
1136
  pickT3Bin,