@cloop/runner 0.2.6 → 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,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",
@@ -618,27 +810,52 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
618
810
  * Subscribe to the thread and resubscribe whenever the stream ends. A thread
619
811
  * that settled while nobody watched shows a terminal run in its first
620
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.
621
819
  */
622
820
  watch(threadId, onEvent) {
623
821
  let stopped = false;
624
822
  let finishing = false;
625
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
+ };
626
842
  const retry = () => {
627
843
  if (stopped) return;
628
844
  const timer = setTimeout(() => void follow(), this.deps.retryMs ?? 1e4);
629
845
  timer.unref?.();
630
846
  };
631
- const finish = async () => {
632
- 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
+ }
633
853
  finishing = true;
634
854
  let outcome;
855
+ let p;
635
856
  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
- }
857
+ p = await this.readProjection(threadId);
858
+ outcome = outcomeOf(p);
642
859
  } catch (err) {
643
860
  this.log(
644
861
  `read failed thread=${threadId}: ${err instanceof Error ? err.message : String(err)}`
@@ -654,11 +871,47 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
654
871
  if (!live) void follow();
655
872
  return;
656
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();
657
906
  stopped = true;
658
907
  live?.close();
659
908
  const pr = outcome.pr_url ? { pr_url: outcome.pr_url } : {};
660
909
  if (outcome.kind === "failed") {
661
- 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
+ });
662
915
  } else {
663
916
  onEvent({
664
917
  kind: "settled",
@@ -671,18 +924,24 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
671
924
  const follow = async () => {
672
925
  if (stopped || live) return;
673
926
  const runs = /* @__PURE__ */ new Map();
927
+ const messages = /* @__PURE__ */ new Map();
674
928
  const requests = /* @__PURE__ */ new Map();
675
929
  const asks = /* @__PURE__ */ new Map();
676
930
  const keepAsk = (item) => {
677
- 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);
678
933
  };
679
934
  let settledByHand = false;
680
935
  let stream;
681
936
  try {
682
937
  stream = await this.t3.stream("orchestration.subscribeThread", { threadId }, (raw) => {
938
+ if (stopped) return;
683
939
  const item = raw;
940
+ let said = false;
684
941
  if (item.kind === "snapshot" && "projection" in item) {
685
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);
686
945
  for (const r of item.projection.runtimeRequests ?? []) requests.set(r.id, r);
687
946
  for (const t of item.projection.turnItems ?? []) keepAsk(t);
688
947
  settledByHand ||= Boolean(item.projection.thread?.settledAt);
@@ -690,6 +949,9 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
690
949
  const { type, payload } = item.event;
691
950
  if (type.startsWith("run.") && typeof payload?.id === "string") {
692
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;
693
955
  } else if (type === "runtime-request.updated" && typeof payload?.id === "string") {
694
956
  requests.set(payload.id, payload);
695
957
  } else if (type === "turn-item.updated" && payload) {
@@ -698,10 +960,16 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
698
960
  settledByHand = true;
699
961
  } else return;
700
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
+ }
701
968
  if (settledByHand || isTerminal([...runs.values()])) {
702
- void finish();
969
+ if (settledByHand || said || idle?.runId !== latest?.id) void finish();
703
970
  return;
704
971
  }
972
+ speak(runs, messages);
705
973
  const pending = pendingQuestions({
706
974
  runtimeRequests: [...requests.values()],
707
975
  turnItems: [...asks.values()]
@@ -731,6 +999,7 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
731
999
  void follow();
732
1000
  return () => {
733
1001
  stopped = true;
1002
+ wake();
734
1003
  live?.close();
735
1004
  };
736
1005
  }
@@ -808,12 +1077,12 @@ ${RESULT_INSTRUCTION}`, attachments: [] }
808
1077
  };
809
1078
 
810
1079
  // src/runner-config.ts
811
- import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
1080
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
812
1081
  import { homedir } from "os";
813
- import { dirname, join as join2 } from "path";
1082
+ import { dirname as dirname2, join as join3 } from "path";
814
1083
  var BOX_FILE = "box.json";
815
1084
  function boxPath() {
816
- 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);
817
1086
  }
818
1087
  function isLocal(cfg) {
819
1088
  return cfg.driver === "claude-code" || cfg.driver === "codex";
@@ -834,21 +1103,34 @@ function readRunnerConfig() {
834
1103
  }
835
1104
  function writeBoxConfig(cfg) {
836
1105
  const path = boxPath();
837
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
1106
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
838
1107
  const temp = `${path}.${process.pid}.tmp`;
839
1108
  writeFileSync(temp, `${JSON.stringify(cfg, null, 2)}
840
1109
  `, { mode: 384 });
841
- chmodSync(temp, 384);
842
- renameSync(temp, path);
1110
+ chmodSync2(temp, 384);
1111
+ renameSync2(temp, path);
843
1112
  }
844
1113
 
845
1114
  export {
1115
+ RESULT_INSTRUCTION,
1116
+ prUrlIn,
1117
+ resultPrUrl,
1118
+ parseRunResult,
846
1119
  RUNTIME_MODES,
847
1120
  BoxToolError,
848
1121
  CLOOP_THREAD_PREFIX,
849
1122
  questionLine,
850
- RESULT_INSTRUCTION,
851
- parseRunResult,
1123
+ isProgressSentence,
1124
+ nextProgress,
1125
+ isYes,
1126
+ runLogDir,
1127
+ runLogPath,
1128
+ logLineFor,
1129
+ appendRunLog,
1130
+ pruneRunLogs,
1131
+ STOPPED_SUMMARY,
1132
+ endNote,
1133
+ isEndLogLine,
852
1134
  defaultT3BinSources,
853
1135
  t3Candidates,
854
1136
  pickT3Bin,
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ localRunsFilePath,
4
+ readRunRecords
5
+ } from "./chunk-JFCEKATW.js";
2
6
  import {
3
7
  STOPPED_SUMMARY,
4
8
  isEndLogLine,
5
- localRunsFilePath,
6
- readRunRecords,
9
+ isLocal,
10
+ readRunnerConfig,
7
11
  runLogDir,
8
12
  runLogPath
9
- } from "./chunk-E3V2PRVS.js";
13
+ } from "./chunk-LNQLGVYC.js";
10
14
  import {
11
15
  sanitizeLabel,
12
16
  stripControl
13
17
  } from "./chunk-VK6GV757.js";
14
- import {
15
- isLocal,
16
- readRunnerConfig
17
- } from "./chunk-H7ZCXBNW.js";
18
18
 
19
19
  // src/commands/runs.ts
20
20
  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-KH6FK6UQ.js";
9
9
  import {
10
10
  getOrigin,
11
11
  readCredentials,
@@ -9,6 +9,7 @@ import {
9
9
  T3Driver,
10
10
  defaultT3BinSources,
11
11
  isLocal,
12
+ isYes,
12
13
  pickT3Bin,
13
14
  questionLine,
14
15
  readRunnerConfig,
@@ -16,7 +17,7 @@ import {
16
17
  t3BaseDirArgs,
17
18
  t3Candidates,
18
19
  writeBoxConfig
19
- } from "./chunk-H7ZCXBNW.js";
20
+ } from "./chunk-LNQLGVYC.js";
20
21
  import {
21
22
  getMachine,
22
23
  shortMachineName
@@ -27,17 +28,17 @@ import {
27
28
  } from "./chunk-R3CLO2FB.js";
28
29
  import {
29
30
  connectWebhook
30
- } from "./chunk-52VJGOLJ.js";
31
+ } from "./chunk-JZNBZUPZ.js";
31
32
  import {
32
33
  ConnectFailure,
33
34
  connectReport,
34
35
  deviceLogin,
35
36
  newAttempt,
36
37
  sendConnectReport
37
- } from "./chunk-2SZUL2B6.js";
38
+ } from "./chunk-SANEFNTU.js";
38
39
  import {
39
40
  VERSION
40
- } from "./chunk-GTE4QSTR.js";
41
+ } from "./chunk-KH6FK6UQ.js";
41
42
  import {
42
43
  STAGING_ORIGIN,
43
44
  getOrigin
@@ -352,26 +353,6 @@ var SUBSCRIPTIONS = {
352
353
  team: "Claude Team",
353
354
  enterprise: "Claude Enterprise"
354
355
  };
355
- var YES_WORDS = /* @__PURE__ */ new Set([
356
- "y",
357
- "yes",
358
- "yep",
359
- "yeah",
360
- "allow",
361
- "allow it",
362
- "ok",
363
- "okay",
364
- "approve",
365
- "approved",
366
- "go ahead",
367
- "sure",
368
- "do it"
369
- ]);
370
- function isYes(reply) {
371
- return YES_WORDS.has(
372
- reply.trim().toLowerCase().replace(/[.!\s]+$/, "")
373
- );
374
- }
375
356
  function exec(bin, args) {
376
357
  return new Promise(
377
358
  (resolve3) => execFile(