@cloop/runner 0.2.2 → 0.2.3

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,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  LocalDriver
4
- } from "./chunk-TFZSCXSS.js";
4
+ } from "./chunk-CDG4IEQY.js";
5
5
  import {
6
6
  MeshSocket,
7
7
  defaultSocketFactory
@@ -25,21 +25,74 @@ import {
25
25
  threadsFilePath,
26
26
  writeBoxConfig,
27
27
  writeRunnerState
28
- } from "./chunk-7PUGLQL2.js";
28
+ } from "./chunk-KKFRQ4HQ.js";
29
29
  import {
30
30
  getMachine
31
31
  } from "./chunk-JX6VG5FE.js";
32
32
  import "./chunk-R3CLO2FB.js";
33
- import "./chunk-M6MHMCV6.js";
34
- import "./chunk-F36GGCXC.js";
33
+ import "./chunk-TIXA2YXR.js";
34
+ import "./chunk-F4WCO6Z4.js";
35
35
  import "./chunk-AG6SI6I2.js";
36
- import "./chunk-7BREDPJD.js";
36
+ import "./chunk-FW7MMQQV.js";
37
37
  import {
38
38
  getMeshUrl,
39
39
  getToken,
40
40
  readCredentials
41
41
  } from "./chunk-3DIGCVL4.js";
42
42
 
43
+ // src/outside-sessions.ts
44
+ import { createReadStream } from "fs";
45
+ import { readdir, stat } from "fs/promises";
46
+ import { homedir } from "os";
47
+ import { join } from "path";
48
+ import { createInterface } from "readline";
49
+ var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
50
+ async function listOutsideSessions(root = join(homedir(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
51
+ const files = [];
52
+ for (const project of await readdir(root, { withFileTypes: true }).catch(() => [])) {
53
+ if (!project.isDirectory()) continue;
54
+ for (const entry of await readdir(join(root, project.name), { withFileTypes: true }).catch(
55
+ () => []
56
+ )) {
57
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
58
+ const id = entry.name.slice(0, -6);
59
+ if (!UUID.test(id) || own.has(id)) continue;
60
+ const path = join(root, project.name, entry.name);
61
+ const info = await stat(path).catch(() => null);
62
+ if (info && info.mtimeMs >= now - 7 * 864e5)
63
+ files.push({ id, project: project.name.slice(0, 200), file: path, mtime: info.mtimeMs });
64
+ }
65
+ }
66
+ const results = [];
67
+ for (const file of files.sort((a, b) => b.mtime - a.mtime).slice(0, 20)) {
68
+ let title;
69
+ const stream = createReadStream(file.file, { encoding: "utf8" });
70
+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
71
+ try {
72
+ for await (const line of lines) {
73
+ if (!/^\s*\{\s*"type"\s*:\s*"(?:summary|custom-title|title)"/.test(line)) continue;
74
+ try {
75
+ const record = JSON.parse(line);
76
+ const value = record.type === "summary" ? record.summary : record.type === "custom-title" ? record.customTitle : record.title;
77
+ if (typeof value === "string" && value.trim()) title = value.trim().slice(0, 120);
78
+ } catch {
79
+ }
80
+ }
81
+ } finally {
82
+ lines.close();
83
+ stream.destroy();
84
+ }
85
+ results.push({
86
+ id: file.id,
87
+ project: file.project,
88
+ updatedAt: new Date(file.mtime).toISOString(),
89
+ status: "idle",
90
+ ...title ? { title } : {}
91
+ });
92
+ }
93
+ return results;
94
+ }
95
+
43
96
  // src/commands/box.ts
44
97
  var BEAT_MS = 6e4;
45
98
  var RESEND_MS = 5 * 6e4;
@@ -68,9 +121,8 @@ async function localDriver(cfg, name) {
68
121
  const bin = cfg.driver === name ? cfg.bin : void 0;
69
122
  return new LocalDriver({
70
123
  dialect: name === "claude-code" ? claudeDialect(bin, cfg.fallbackModels ?? DEFAULT_FALLBACK_MODEL, cfg.askEverything, {
71
- ...await probeClaudePermissions(bin),
72
- fullAccess: cfg.fullAccess
73
- }) : codexDialect(bin, cfg.fullAccess),
124
+ ...await probeClaudePermissions(bin)
125
+ }) : codexDialect(bin),
74
126
  repos: cfg.repos,
75
127
  label: cfg.label,
76
128
  harnesses: () => machineHarnesses(cfg),
@@ -130,7 +182,11 @@ async function run() {
130
182
  const onCall = async (frame) => {
131
183
  const started = Date.now();
132
184
  const result = await runBoxTool(
133
- { driver, onLaunch: (workId, threadId) => watch.add(workId, threadId) },
185
+ {
186
+ driver,
187
+ onLaunch: (workId, threadId) => watch.add(workId, threadId),
188
+ onResume: (threadId) => watch.resume(threadId)
189
+ },
134
190
  frame.tool,
135
191
  frame.args
136
192
  );
@@ -186,6 +242,7 @@ async function run() {
186
242
  ...await mintSession(cfg.t3Url, { stored: cfg.t3Bin }),
187
243
  // Read from disk: `cloop connect` may have replaced it since.
188
244
  deviceToken: disk?.deviceToken ?? cfg.deviceToken,
245
+ showOtherThreads: disk?.showOtherThreads ?? false,
189
246
  ...disk?.origin ?? cfg.origin ? { origin: disk?.origin ?? cfg.origin } : {}
190
247
  };
191
248
  cfg = renewed;
@@ -199,8 +256,26 @@ async function run() {
199
256
  const beat = async () => {
200
257
  await renewT3();
201
258
  let running = 0;
259
+ let outsideThreads = [];
202
260
  try {
203
- running = (await driver.listThreads({ scope: "unsettled", limit: 1 })).running;
261
+ const enabled = readRunnerConfig()?.showOtherThreads === true;
262
+ const listed = await driver.listThreads({
263
+ scope: enabled ? "all" : "unsettled",
264
+ limit: enabled ? 200 : 1
265
+ });
266
+ running = listed.running;
267
+ if (enabled && driver.name === "t3")
268
+ outsideThreads = listed.threads.filter((t) => !t.cloop).slice(0, 20).map((t) => ({
269
+ id: t.id,
270
+ title: t.title.slice(0, 120),
271
+ updatedAt: t.updatedAt,
272
+ status: t.status
273
+ }));
274
+ if (enabled && driver.name === "claude-code")
275
+ outsideThreads = await listOutsideSessions(
276
+ void 0,
277
+ new Set(listed.threads.map((t) => t.id))
278
+ );
204
279
  } catch (err) {
205
280
  log(`${driver.name} unreachable: ${err instanceof Error ? err.message : String(err)}`);
206
281
  }
@@ -211,7 +286,7 @@ async function run() {
211
286
  capabilities: [...driver.capabilities],
212
287
  platform: "workstation",
213
288
  machine,
214
- surface: {},
289
+ surface: { driver: driver.name, outsideThreads },
215
290
  status: running > 0 ? "active" : "idle",
216
291
  event: running > 0 ? `${running} running` : ""
217
292
  });
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  BoxToolError,
4
- orderThreads
5
- } from "./chunk-7PUGLQL2.js";
4
+ RESULT_INSTRUCTION,
5
+ orderThreads,
6
+ parseRunResult
7
+ } from "./chunk-KKFRQ4HQ.js";
6
8
  import {
7
9
  CONFIG_DIR
8
10
  } from "./chunk-3DIGCVL4.js";
@@ -243,7 +245,12 @@ var LocalDriver = class {
243
245
  return { delivered: "answer", question_id: ask.request_id };
244
246
  }
245
247
  if (!live) {
246
- if (r.end) throw new BoxToolError("already_finished");
248
+ if (r.end && !a.resume) throw new BoxToolError("already_finished");
249
+ if (r.end) {
250
+ this.refuseBusy(r.repo);
251
+ r.end = void 0;
252
+ r.last_text = void 0;
253
+ }
247
254
  this.spawnRun(r, a.text, true);
248
255
  this.remember(r, a.command_id, "start");
249
256
  return { delivered: "start" };
@@ -367,7 +374,9 @@ ${a.text}` : a.text;
367
374
  this.log(`spawn work=${r.work_id} pid=${r.pid ?? "none"} ${resume ? "resume" : "new"}`);
368
375
  child.stdin?.on("error", () => {
369
376
  });
370
- child.stdin?.write(dialect.opening(r, prompt));
377
+ child.stdin?.write(dialect.opening(r, `${prompt}
378
+
379
+ ${RESULT_INSTRUCTION}`));
371
380
  if (!dialect.keepsStdin) child.stdin?.end();
372
381
  child.stderr?.on("data", (chunk) => {
373
382
  live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
@@ -390,7 +399,7 @@ ${a.text}` : a.text;
390
399
  }
391
400
  return;
392
401
  case "text":
393
- r.last_text = item.text.slice(0, 300);
402
+ r.last_text = item.text.slice(0, 1e5);
394
403
  this.progress(r, live, item.text, false);
395
404
  return;
396
405
  case "tool": {
@@ -417,7 +426,7 @@ ${a.text}` : a.text;
417
426
  case "result":
418
427
  live.outstanding--;
419
428
  live.result = { ok: item.ok, ...item.text ? { text: item.text } : {} };
420
- if (item.text) r.last_text = item.text.slice(0, 300);
429
+ if (item.text) r.last_text = item.text.slice(0, 1e5);
421
430
  if (live.outstanding <= 0 && live.asks.length === 0) live.child.stdin?.end();
422
431
  return;
423
432
  }
@@ -428,7 +437,7 @@ ${a.text}` : a.text;
428
437
  live.lastProgressAt = now;
429
438
  this.emit(r.work_id, {
430
439
  kind: "progress",
431
- summary: line.replace(/\s+/g, " ").trim().slice(0, 200)
440
+ summary: (parseRunResult(line)?.summary ?? line.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, 200)
432
441
  });
433
442
  }
434
443
  async onExit(r, live, code, signal) {
@@ -448,10 +457,12 @@ ${a.text}` : a.text;
448
457
  }
449
458
  if (code === 0 && live.result?.ok) {
450
459
  const text = live.result.text?.trim() || r.last_text;
460
+ const result = parseRunResult(text);
451
461
  const { pr, note } = await this.outcome(r, text);
452
462
  const summary = [r.switched, note, text].filter(Boolean).join(" ").replace(/\s+/g, " ");
453
463
  await this.end(r, {
454
464
  kind: "settled",
465
+ ...result ? { result } : {},
455
466
  ...summary ? { summary: summary.slice(0, SUMMARY_MAX) } : {},
456
467
  ...pr ? { pr_url: pr } : {}
457
468
  });
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-AG6SI6I2.js";
6
6
  import {
7
7
  VERSION
8
- } from "./chunk-7BREDPJD.js";
8
+ } from "./chunk-FW7MMQQV.js";
9
9
  import {
10
10
  getOrigin,
11
11
  readCredentials,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/version.ts
4
- var VERSION = true ? "0.2.2" : "0.0.0-dev";
4
+ var VERSION = true ? "0.2.3" : "0.0.0-dev";
5
5
 
6
6
  export {
7
7
  VERSION
@@ -9,17 +9,17 @@ import {
9
9
  } from "./chunk-R3CLO2FB.js";
10
10
  import {
11
11
  connectWebhook
12
- } from "./chunk-M6MHMCV6.js";
12
+ } from "./chunk-TIXA2YXR.js";
13
13
  import {
14
14
  ConnectFailure,
15
15
  connectReport,
16
16
  deviceLogin,
17
17
  newAttempt,
18
18
  sendConnectReport
19
- } from "./chunk-F36GGCXC.js";
19
+ } from "./chunk-F4WCO6Z4.js";
20
20
  import {
21
21
  VERSION
22
- } from "./chunk-7BREDPJD.js";
22
+ } from "./chunk-FW7MMQQV.js";
23
23
  import {
24
24
  CONFIG_DIR,
25
25
  STAGING_ORIGIN,
@@ -256,8 +256,8 @@ function parseCommandId(args) {
256
256
  return id;
257
257
  }
258
258
  function parseSendArgs(args) {
259
- const text = typeof args.text === "string" ? args.text.trim() : "";
260
- if (!text || text.length > 8e3) throw new BoxToolError("bad_args");
259
+ const text2 = typeof args.text === "string" ? args.text.trim() : "";
260
+ if (!text2 || text2.length > 8e3) throw new BoxToolError("bad_args");
261
261
  const mode = args.mode ?? "steer";
262
262
  if (mode !== "steer" && mode !== "queue") throw new BoxToolError("bad_args");
263
263
  if (args.answer !== void 0 && typeof args.answer !== "boolean")
@@ -267,10 +267,11 @@ function parseSendArgs(args) {
267
267
  throw new BoxToolError("bad_args");
268
268
  return {
269
269
  thread_id: parseThreadId(args),
270
- text,
270
+ text: text2,
271
271
  mode,
272
272
  command_id: parseCommandId(args),
273
273
  answer: args.answer === true,
274
+ ...args.resume === true ? { resume: true } : {},
274
275
  ...question !== void 0 ? { question_id: question } : {}
275
276
  };
276
277
  }
@@ -287,7 +288,12 @@ var BOX_TOOLS = {
287
288
  onLaunch?.(a.work_id, launched.thread_id);
288
289
  return launched;
289
290
  },
290
- "thread.send": ({ driver }, args) => driver.send(parseSendArgs(args)),
291
+ async "thread.send"({ driver, onResume }, args) {
292
+ const parsed = parseSendArgs(args);
293
+ const result = await driver.send(parsed);
294
+ if (parsed.resume) onResume?.(parsed.thread_id);
295
+ return result;
296
+ },
291
297
  "thread.interrupt": ({ driver }, args) => driver.interrupt(parseThreadId(args), parseCommandId(args))
292
298
  };
293
299
  function classifyError(err, driver = "t3") {
@@ -413,6 +419,15 @@ var BoxWatch = class {
413
419
  this.deps.log(`launch work=${workId} thread=${threadId}`);
414
420
  this.watch(entry);
415
421
  }
422
+ resume(threadId) {
423
+ const entry = this.entries.find((e) => e.thread_id === threadId);
424
+ if (!entry?.settled_at) return;
425
+ entry.settled_at = void 0;
426
+ entry.event = void 0;
427
+ entry.sent_at = void 0;
428
+ this.save();
429
+ this.watch(entry);
430
+ }
416
431
  /** On every socket open and on a timer: send every event the mesh has not acked. */
417
432
  flush() {
418
433
  for (const e of this.entries) {
@@ -463,6 +478,7 @@ var BoxWatch = class {
463
478
  kind,
464
479
  ...event.kind === "question" ? { question_id: event.question_id } : {},
465
480
  ...summary ? { summary: summary.slice(0, 500) } : {},
481
+ ..."result" in event && event.result ? { result: event.result } : {},
466
482
  ..."pr_url" in event && event.pr_url ? { pr_url: event.pr_url } : {},
467
483
  ..."error" in event && event.error ? { error: event.error } : {},
468
484
  at: new Date(this.now()).toISOString()
@@ -592,10 +608,7 @@ function claudeAccount(raw) {
592
608
  }
593
609
  function claudePermissionSupport(help) {
594
610
  const choices = help?.match(/--permission-mode[\s\S]*?\(choices:([^)]*)\)/)?.[1] ?? "";
595
- return {
596
- autoMode: /"auto"/.test(choices),
597
- manualMode: /"manual"/.test(choices) ? "manual" : "default"
598
- };
611
+ return { manualMode: /"manual"/.test(choices) ? "manual" : "default" };
599
612
  }
600
613
  async function probeClaudePermissions(bin = "claude") {
601
614
  return claudePermissionSupport(await exec(bin, ["--help"]));
@@ -627,8 +640,8 @@ function questionsOf(input) {
627
640
  const questions = input?.questions;
628
641
  return Array.isArray(questions) ? questions.filter((q) => typeof q?.question === "string") : [];
629
642
  }
630
- function cut(text, max = 160) {
631
- const line2 = text.replace(/\s+/g, " ").trim();
643
+ function cut(text2, max = 160) {
644
+ const line2 = text2.replace(/\s+/g, " ").trim();
632
645
  return line2.length > max ? `${line2.slice(0, max - 1)}\u2026` : line2;
633
646
  }
634
647
  var TOOL_WORDS = {
@@ -669,10 +682,10 @@ function line(value) {
669
682
  return `${JSON.stringify(value)}
670
683
  `;
671
684
  }
672
- function userMessage(run, text, priority) {
685
+ function userMessage(run, text2, priority) {
673
686
  return {
674
687
  type: "user",
675
- message: { role: "user", content: [{ type: "text", text }] },
688
+ message: { role: "user", content: [{ type: "text", text: text2 }] },
676
689
  parent_tool_use_id: null,
677
690
  session_id: run.session_id ?? run.work_id,
678
691
  ...priority ? { priority } : {}
@@ -743,7 +756,7 @@ function parseClaudeLine(raw, run) {
743
756
  }
744
757
  var DEFAULT_FALLBACK_MODEL = "opus";
745
758
  function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEverything = false, options = {}) {
746
- const permission = () => askEverything ? "ask" : options.fullAccess === true ? "full" : options.autoMode === false ? "acceptEdits" : "auto";
759
+ const permission = () => askEverything ? "ask" : "full";
747
760
  return {
748
761
  permission,
749
762
  name: "claude-code",
@@ -764,7 +777,7 @@ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEve
764
777
  "stdio",
765
778
  ...permission() === "full" ? ["--dangerously-skip-permissions"] : [
766
779
  "--permission-mode",
767
- permission() === "ask" ? options.manualMode ?? "manual" : permission(),
780
+ options.manualMode ?? "manual",
768
781
  "--allowedTools",
769
782
  ...READ_TOOLS,
770
783
  "--settings",
@@ -783,18 +796,18 @@ function claudeDialect(bin = "claude", fallback = DEFAULT_FALLBACK_MODEL, askEve
783
796
  request: { subtype: "initialize" }
784
797
  }) + line(userMessage(run, prompt));
785
798
  },
786
- userLine(run, text, mode) {
787
- return line(userMessage(run, text, mode === "steer" ? "now" : "next"));
799
+ userLine(run, text2, mode) {
800
+ return line(userMessage(run, text2, mode === "steer" ? "now" : "next"));
788
801
  },
789
- answerLine(ask, text) {
802
+ answerLine(ask, text2) {
790
803
  const input = ask.input ?? {};
791
804
  const response = ask.tool === "AskUserQuestion" ? {
792
805
  behavior: "allow",
793
806
  updatedInput: {
794
807
  ...input,
795
- answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text]))
808
+ answers: Object.fromEntries(questionsOf(input).map((q) => [q.question, text2]))
796
809
  }
797
- } : isYes(text) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text };
810
+ } : isYes(text2) ? { behavior: "allow", updatedInput: input } : { behavior: "deny", message: text2 };
798
811
  return line({
799
812
  type: "control_response",
800
813
  response: { subtype: "success", request_id: ask.request_id, response }
@@ -874,8 +887,8 @@ function parseCodexLine(raw) {
874
887
  }
875
888
  return [];
876
889
  }
877
- function codexDialect(bin = "codex", fullAccess = false) {
878
- const permission = () => fullAccess === true ? "full" : "auto";
890
+ function codexDialect(bin = "codex") {
891
+ const permission = () => "full";
879
892
  return {
880
893
  permission,
881
894
  name: "codex",
@@ -885,7 +898,7 @@ function codexDialect(bin = "codex", fullAccess = false) {
885
898
  keepsStdin: false,
886
899
  args(run, resume) {
887
900
  const model = run.model ? ["--model", run.model] : [];
888
- const policy = permission() === "full" ? ["--dangerously-bypass-approvals-and-sandbox"] : ["--approve-for-me", "-c", 'sandbox_mode="workspace-write"'];
901
+ const policy = ["--dangerously-bypass-approvals-and-sandbox"];
889
902
  return resume && run.session_id ? ["exec", ...policy, "resume", run.session_id, "--json", ...model, "-"] : ["exec", "--cd", run.repo, "--json", ...policy, ...model, "-"];
890
903
  },
891
904
  opening: (_run, prompt) => prompt,
@@ -899,6 +912,81 @@ function codexDialect(bin = "codex", fullAccess = false) {
899
912
  // src/drivers/t3.ts
900
913
  import { execFile as execFile3, execFileSync as execFileSync2 } from "child_process";
901
914
 
915
+ // src/run-result.ts
916
+ var RESULT_INSTRUCTION = "When you finish, end your final message with a fenced block tagged cloop-result containing JSON: summary, outputs, checks.";
917
+ var text = (v, max) => typeof v === "string" && v.length <= max;
918
+ var optionalText = (v, max) => v === void 0 || text(v, max);
919
+ var https = (v) => {
920
+ try {
921
+ return typeof v === "string" && new URL(v).protocol === "https:";
922
+ } catch {
923
+ return false;
924
+ }
925
+ };
926
+ function parseRunResult(message) {
927
+ const block = [...(message ?? "").matchAll(/```cloop-result\s*\n([\s\S]*?)```/g)].at(-1)?.[1];
928
+ if (!block) return void 0;
929
+ try {
930
+ const value = JSON.parse(block);
931
+ if (!value || !text(value.summary, 500)) return void 0;
932
+ const outputs = value.outputs ?? [];
933
+ const checks = value.checks ?? [];
934
+ if (!Array.isArray(outputs) || outputs.length > 10 || !Array.isArray(checks) || checks.length > 10)
935
+ return void 0;
936
+ const clean = [];
937
+ for (const o of outputs) {
938
+ if (!o || !text(o.title, 120)) return void 0;
939
+ switch (o.kind) {
940
+ case "pr":
941
+ case "link":
942
+ if (!https(o.url)) return void 0;
943
+ clean.push({ kind: o.kind, title: o.title, url: o.url });
944
+ break;
945
+ case "draft":
946
+ if (!text(o.body, 4e3) || !optionalText(o.to, 200)) return void 0;
947
+ clean.push({
948
+ kind: "draft",
949
+ title: o.title,
950
+ body: o.body,
951
+ ...o.to !== void 0 ? { to: o.to } : {}
952
+ });
953
+ break;
954
+ case "doc":
955
+ if (!optionalText(o.body, 8e3) || o.url !== void 0 && !https(o.url))
956
+ return void 0;
957
+ clean.push({
958
+ kind: "doc",
959
+ title: o.title,
960
+ ...o.url !== void 0 ? { url: o.url } : {},
961
+ ...o.body !== void 0 ? { body: o.body } : {}
962
+ });
963
+ break;
964
+ case "file":
965
+ if (!text(o.path, 400)) return void 0;
966
+ clean.push({ kind: "file", title: o.title, path: o.path });
967
+ break;
968
+ default:
969
+ return void 0;
970
+ }
971
+ }
972
+ if (checks.some(
973
+ (c) => !c || !text(c.name, 80) || !["passed", "failed", "skipped"].includes(c.outcome) || !optionalText(c.detail, 200)
974
+ ))
975
+ return void 0;
976
+ return {
977
+ summary: value.summary,
978
+ outputs: clean,
979
+ checks: checks.map((c) => ({
980
+ name: c.name,
981
+ outcome: c.outcome,
982
+ ...c.detail !== void 0 ? { detail: c.detail } : {}
983
+ }))
984
+ };
985
+ } catch {
986
+ return void 0;
987
+ }
988
+ }
989
+
902
990
  // src/t3-bin.ts
903
991
  import { execFileSync } from "child_process";
904
992
  import { existsSync, readdirSync, statSync } from "fs";
@@ -1002,6 +1090,7 @@ function isChild(t) {
1002
1090
  return t.creationSource === "provider" || Boolean(t.lineage?.parentThreadId);
1003
1091
  }
1004
1092
  var SESSIONS_TTL_MS = 5 * 6e4;
1093
+ var STATUS_TTL_MS = 3e4;
1005
1094
  var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
1006
1095
  var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master"]);
1007
1096
  function pendingQuestions(p) {
@@ -1053,13 +1142,14 @@ function outcomeOf(p) {
1053
1142
  const run = latestRun(p.runs ?? []);
1054
1143
  const status = run?.status ?? "pending";
1055
1144
  const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
1056
- const text = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
1145
+ const text2 = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
1057
1146
  return {
1058
1147
  status,
1059
1148
  settled,
1060
1149
  kind: settled ? status === "completed" || !run ? "settled" : "failed" : null,
1061
1150
  pr_url: prUrlOf(p.thread),
1062
- last_assistant_text: text ? text.slice(0, 300) : null
1151
+ last_assistant_text: text2 ? text2.slice(0, 300) : null,
1152
+ ...parseRunResult(text2) ? { result: parseRunResult(text2) } : {}
1063
1153
  };
1064
1154
  }
1065
1155
  function pickProject(projects, repository) {
@@ -1114,11 +1204,33 @@ var T3Driver = class {
1114
1204
  log(line2) {
1115
1205
  this.deps.log?.(line2);
1116
1206
  }
1207
+ /**
1208
+ * T3's config and shell calls take 2-20 s on a loaded box, past the app's
1209
+ * wait. So status reads them from the last answer at once and refreshes
1210
+ * them in the background, at most once per STATUS_TTL_MS. Only the first
1211
+ * call waits.
1212
+ */
1213
+ t3State = { value: null, at: 0, refreshing: null };
1214
+ readT3State() {
1215
+ const cache = this.t3State;
1216
+ if (!cache.refreshing && Date.now() - cache.at > STATUS_TTL_MS) {
1217
+ cache.refreshing = Promise.all([
1218
+ this.t3.rpc("server.getConfig", {}),
1219
+ this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1220
+ ]).then((value) => {
1221
+ cache.value = value;
1222
+ cache.at = Date.now();
1223
+ return value;
1224
+ }).finally(() => {
1225
+ cache.refreshing = null;
1226
+ });
1227
+ cache.refreshing.catch(() => {
1228
+ });
1229
+ }
1230
+ return cache.value ? Promise.resolve(cache.value) : cache.refreshing;
1231
+ }
1117
1232
  async status() {
1118
- const [cfg, shell] = await Promise.all([
1119
- this.t3.rpc("server.getConfig", {}),
1120
- this.t3.http("/api/orchestration/shell", SHELL_HEADERS)
1121
- ]);
1233
+ const [cfg, shell] = await this.readT3State();
1122
1234
  const sessions = this.listSessions();
1123
1235
  const threads = (shell.threads ?? []).filter((t) => !isChild(t));
1124
1236
  const unsettled = threads.filter(isUnsettled);
@@ -1207,7 +1319,9 @@ var T3Driver = class {
1207
1319
  type: "worktree",
1208
1320
  baseRef: this.baseRefFor(project.workspaceRoot)
1209
1321
  },
1210
- initialMessage: { text: a.prompt, attachments: [] }
1322
+ initialMessage: { text: `${a.prompt}
1323
+
1324
+ ${RESULT_INSTRUCTION}`, attachments: [] }
1211
1325
  }
1212
1326
  );
1213
1327
  return { thread_id: launched.threadId, resumed: launched.resumed };
@@ -1260,7 +1374,7 @@ var T3Driver = class {
1260
1374
  }
1261
1375
  const steer = a.mode === "steer" ? steerableRun(p) : null;
1262
1376
  const active = activeRun(p.runs ?? []);
1263
- if (!active && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
1377
+ if (!active && !a.resume && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
1264
1378
  throw new BoxToolError("already_finished");
1265
1379
  const receipt = await this.dispatch({
1266
1380
  type: "message.dispatch",
@@ -1351,6 +1465,7 @@ var T3Driver = class {
1351
1465
  } else {
1352
1466
  onEvent({
1353
1467
  kind: "settled",
1468
+ ...outcome.result ? { result: outcome.result } : {},
1354
1469
  ...outcome.last_assistant_text ? { summary: outcome.last_assistant_text } : {},
1355
1470
  ...pr
1356
1471
  });
@@ -2064,7 +2179,11 @@ async function connectT3(argv, attempt) {
2064
2179
  });
2065
2180
  return attempt.deviceToken;
2066
2181
  },
2067
- writeBoxConfig: (cfg2) => writeBoxConfig({ ...cfg2, origin: getOrigin() })
2182
+ writeBoxConfig: (cfg2) => writeBoxConfig({
2183
+ ...cfg2,
2184
+ origin: getOrigin(),
2185
+ showOtherThreads: argv.includes("--show-other-threads")
2186
+ })
2068
2187
  });
2069
2188
  await revokeReplaced(previous, "workstation", (t) => revokeOwnDevice(getOrigin(), t), out);
2070
2189
  out(
@@ -2107,13 +2226,13 @@ async function connectLocal(driver, found, argv, attempt) {
2107
2226
  const deviceToken = await deviceLogin({ origin: getOrigin(), deviceName, device });
2108
2227
  attempt.deviceToken = deviceToken;
2109
2228
  const cfg = {
2229
+ showOtherThreads: argv.includes("--show-other-threads"),
2110
2230
  driver,
2111
2231
  environmentId: device.environmentId,
2112
2232
  label: deviceName,
2113
2233
  deviceToken,
2114
2234
  repos,
2115
2235
  bin,
2116
- fullAccess: argv.includes("--full-access"),
2117
2236
  origin: getOrigin(),
2118
2237
  ...fallbackModels ? { fallbackModels } : {},
2119
2238
  ...driver === "claude-code" ? { askEverything: argv.includes("--ask-everything") } : {}
@@ -2127,14 +2246,9 @@ async function connectLocal(driver, found, argv, attempt) {
2127
2246
  `${bold("Cloop runner")} ${deviceName} is a Local runner: ${[harness, ...others].map(harnessLine).join("; ")}.`
2128
2247
  );
2129
2248
  out(` Repos: ${repos.map((r) => `${r.label} (${r.path})`).join(", ")}`);
2130
- const support = driver === "claude-code" ? await probeClaudePermissions(bin) : null;
2131
2249
  out(
2132
- ` ${cfg.askEverything ? "Asks before actions except allowlisted reads." : cfg.fullAccess ? "Full access: every Task runs without permission checks, including Tasks made from email or other people." : "Runs in auto mode: it asks before risky steps."}`
2250
+ ` ${driver === "codex" ? "Full access: Codex always runs every Task without permission checks. --ask-everything applies to Claude Code only." : cfg.askEverything ? "Asks before actions except allowlisted reads." : "Full access: every Task runs without permission checks. Add --ask-everything to approve each step."}`
2133
2251
  );
2134
- if (support && !support.autoMode)
2135
- out(" Auto mode is unavailable. Uses acceptEdits with the read allowlist.");
2136
- if (driver === "codex")
2137
- out(" Codex uses sandboxed automatic review; it cannot send owner approval questions.");
2138
2252
  if (fallbackModels)
2139
2253
  out(
2140
2254
  ` Fallback model: ${fallbackModels}, when Claude Code's default model is at its limit. Change it with --fallback-model.`
@@ -2219,6 +2333,8 @@ export {
2219
2333
  claudeDialect,
2220
2334
  probeCodex,
2221
2335
  codexDialect,
2336
+ RESULT_INSTRUCTION,
2337
+ parseRunResult,
2222
2338
  orderThreads,
2223
2339
  T3Driver,
2224
2340
  boxPath,
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  ConnectFailure,
4
4
  deviceLogin
5
- } from "./chunk-F36GGCXC.js";
5
+ } from "./chunk-F4WCO6Z4.js";
6
6
  import {
7
7
  ApiError,
8
8
  ReauthError,
@@ -28,13 +28,13 @@ import {
28
28
  tilde,
29
29
  unitEnv,
30
30
  unitFor
31
- } from "./chunk-7PUGLQL2.js";
31
+ } from "./chunk-KKFRQ4HQ.js";
32
32
  import "./chunk-JX6VG5FE.js";
33
33
  import "./chunk-R3CLO2FB.js";
34
- import "./chunk-M6MHMCV6.js";
35
- import "./chunk-F36GGCXC.js";
34
+ import "./chunk-TIXA2YXR.js";
35
+ import "./chunk-F4WCO6Z4.js";
36
36
  import "./chunk-AG6SI6I2.js";
37
- import "./chunk-7BREDPJD.js";
37
+ import "./chunk-FW7MMQQV.js";
38
38
  import "./chunk-3DIGCVL4.js";
39
39
  export {
40
40
  DEFAULT_T3_URL,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  localRunsFilePath
4
- } from "./chunk-TFZSCXSS.js";
4
+ } from "./chunk-CDG4IEQY.js";
5
5
  import {
6
6
  boxPath,
7
7
  installedService,
@@ -11,13 +11,13 @@ import {
11
11
  runnerStatePath,
12
12
  threadsFilePath,
13
13
  tokenGone
14
- } from "./chunk-7PUGLQL2.js";
14
+ } from "./chunk-KKFRQ4HQ.js";
15
15
  import "./chunk-JX6VG5FE.js";
16
16
  import "./chunk-R3CLO2FB.js";
17
- import "./chunk-M6MHMCV6.js";
18
- import "./chunk-F36GGCXC.js";
17
+ import "./chunk-TIXA2YXR.js";
18
+ import "./chunk-F4WCO6Z4.js";
19
19
  import "./chunk-AG6SI6I2.js";
20
- import "./chunk-7BREDPJD.js";
20
+ import "./chunk-FW7MMQQV.js";
21
21
  import {
22
22
  getOrigin
23
23
  } from "./chunk-3DIGCVL4.js";
@@ -90,13 +90,19 @@ async function disconnect(plan, opts) {
90
90
  }
91
91
  for (const service of plan.services) {
92
92
  await runSteps(service.steps, run);
93
- let stillRunning = true;
94
- try {
95
- run(service.running);
96
- } catch {
97
- stillRunning = false;
98
- }
99
- if (stillRunning) {
93
+ const stillRunning = async () => {
94
+ const until = Date.now() + (opts.stopWaitMs ?? 1e4);
95
+ for (; ; ) {
96
+ try {
97
+ run(service.running);
98
+ } catch {
99
+ return false;
100
+ }
101
+ if (Date.now() >= until) return true;
102
+ await new Promise((resolve) => setTimeout(resolve, 250));
103
+ }
104
+ };
105
+ if (await stillRunning()) {
100
106
  say(
101
107
  `Could not stop the service in ${service.path}. Nothing was removed. Stop it with \`${service.steps.map((s) => s.command.join(" ")).join(" && ")}\`, then run \`cloop disconnect\` again.`
102
108
  );
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VERSION
4
- } from "./chunk-7BREDPJD.js";
4
+ } from "./chunk-FW7MMQQV.js";
5
5
  import {
6
6
  applyEnvironmentFlag
7
7
  } from "./chunk-3DIGCVL4.js";
@@ -22,7 +22,7 @@ Usage:
22
22
  cloop hook session-start Claude Code SessionStart hook (reads JSON on stdin)
23
23
  cloop hook activity Lifecycle hook: records what this session is doing
24
24
  cloop connect [--repo <path>]... [--driver t3|claude-code|codex] [--fallback-model <list>]
25
- [--no-service] [--no-start] [--ask-everything] [--full-access]
25
+ [--no-service] [--no-start] [--ask-everything]
26
26
  Make this machine a Cloop runner: T3 Code, else
27
27
  Claude Code or Codex in the repos you name
28
28
  cloop disconnect [--yes] Stop being a Cloop runner: revoke this computer on
@@ -43,7 +43,7 @@ async function main() {
43
43
  switch (command) {
44
44
  case "login":
45
45
  case "auth": {
46
- const { loginCommand } = await import("./login-CUQR2MBW.js");
46
+ const { loginCommand } = await import("./login-L6J5HPTR.js");
47
47
  await loginCommand(argv);
48
48
  break;
49
49
  }
@@ -53,32 +53,32 @@ async function main() {
53
53
  break;
54
54
  }
55
55
  case "serve": {
56
- const { startMcpServer } = await import("./mcp-server-YDRR6DYJ.js");
56
+ const { startMcpServer } = await import("./mcp-server-Z6MG3AAS.js");
57
57
  await startMcpServer();
58
58
  break;
59
59
  }
60
60
  case "statusline": {
61
- const { statuslineCommand } = await import("./statusline-SLP4CAFB.js");
61
+ const { statuslineCommand } = await import("./statusline-5HLPYTYU.js");
62
62
  statuslineCommand();
63
63
  break;
64
64
  }
65
65
  case "connect": {
66
- const { connectCommand } = await import("./connect-WRQN37SU.js");
66
+ const { connectCommand } = await import("./connect-B5RZDVIW.js");
67
67
  await connectCommand(argv.slice(1));
68
68
  break;
69
69
  }
70
70
  case "disconnect": {
71
- const { disconnectCommand } = await import("./disconnect-KTII7TXC.js");
71
+ const { disconnectCommand } = await import("./disconnect-MFHVNESG.js");
72
72
  await disconnectCommand(argv.slice(1));
73
73
  break;
74
74
  }
75
75
  case "box": {
76
- const { boxCommand } = await import("./box-BS6BSQUO.js");
76
+ const { boxCommand } = await import("./box-G6HEXSWY.js");
77
77
  await boxCommand(argv.slice(1));
78
78
  break;
79
79
  }
80
80
  case "runner": {
81
- const { runnerCommand } = await import("./runner-WW5OU2YU.js");
81
+ const { runnerCommand } = await import("./runner-D6Z5S3VC.js");
82
82
  await runnerCommand(argv.slice(1));
83
83
  break;
84
84
  }
@@ -3,9 +3,9 @@ import {
3
3
  deviceLogin,
4
4
  loginCommand,
5
5
  refusalSentence
6
- } from "./chunk-F36GGCXC.js";
6
+ } from "./chunk-F4WCO6Z4.js";
7
7
  import "./chunk-AG6SI6I2.js";
8
- import "./chunk-7BREDPJD.js";
8
+ import "./chunk-FW7MMQQV.js";
9
9
  import "./chunk-3DIGCVL4.js";
10
10
  export {
11
11
  deviceLogin,
@@ -33,7 +33,7 @@ import {
33
33
  } from "./chunk-AG6SI6I2.js";
34
34
  import {
35
35
  VERSION
36
- } from "./chunk-7BREDPJD.js";
36
+ } from "./chunk-FW7MMQQV.js";
37
37
  import {
38
38
  getMeshUrl,
39
39
  getToken
@@ -2,10 +2,10 @@
2
2
  import {
3
3
  connectWebhook,
4
4
  runnerCommand
5
- } from "./chunk-M6MHMCV6.js";
6
- import "./chunk-F36GGCXC.js";
5
+ } from "./chunk-TIXA2YXR.js";
6
+ import "./chunk-F4WCO6Z4.js";
7
7
  import "./chunk-AG6SI6I2.js";
8
- import "./chunk-7BREDPJD.js";
8
+ import "./chunk-FW7MMQQV.js";
9
9
  import "./chunk-3DIGCVL4.js";
10
10
  export {
11
11
  connectWebhook,
@@ -7,7 +7,7 @@ import {
7
7
  } from "./chunk-4LFQXBWP.js";
8
8
  import {
9
9
  VERSION
10
- } from "./chunk-7BREDPJD.js";
10
+ } from "./chunk-FW7MMQQV.js";
11
11
  import {
12
12
  getToken
13
13
  } from "./chunk-3DIGCVL4.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloop/runner",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "Make your machine and your agents Cloop runners: device login, the runner daemon, the Cloop MCP server, and Claude Code hooks.",