@cloop/runner 0.3.24 → 0.3.28

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.
Files changed (27) hide show
  1. package/README.md +2 -2
  2. package/dist/{box-OGT2NRPJ.js → box-AKPKKX5S.js} +234 -64
  3. package/dist/{chunk-YEO27QQP.js → chunk-365HFCQQ.js} +1 -1
  4. package/dist/{chunk-VH7XVQFJ.js → chunk-3I6NDELL.js} +1 -1
  5. package/dist/{chunk-NVESLEXA.js → chunk-3S2ECJTO.js} +275 -73
  6. package/dist/{chunk-MHKSBXUD.js → chunk-7GLIYYIB.js} +6 -6
  7. package/dist/{chunk-F4UQ2H5F.js → chunk-EGO3GOXI.js} +1 -1
  8. package/dist/{chunk-6F2ZM5H3.js → chunk-EKLBEP32.js} +2 -1
  9. package/dist/{chunk-PQPWITU3.js → chunk-ER5JS3RP.js} +232 -64
  10. package/dist/{chunk-IJH4O27H.js → chunk-KYGYU5G2.js} +65 -2
  11. package/dist/{chunk-UVB722OW.js → chunk-MVMKRRE2.js} +1 -1
  12. package/dist/{chunk-R3CLO2FB.js → chunk-PKIEWBR7.js} +2 -0
  13. package/dist/{chunk-IXG4H623.js → chunk-W4QJS3GR.js} +5 -5
  14. package/dist/{connect-7DUV7BMO.js → connect-OC5OH33U.js} +9 -8
  15. package/dist/{disconnect-IWGVQ2GZ.js → disconnect-6WIOMOCW.js} +9 -8
  16. package/dist/existing-runner-KN37YN7Y.js +21 -0
  17. package/dist/index.js +23 -23
  18. package/dist/{login-J3N7TYDI.js → login-YB3JV5WY.js} +2 -2
  19. package/dist/{mcp-server-HPMJRI6J.js → mcp-server-MD6X5AWJ.js} +5 -5
  20. package/dist/{read-permissions-SPOKGVLO.js → read-permissions-EGSGI4HL.js} +1 -1
  21. package/dist/{runner-TMR3BBL5.js → runner-VU7TITZM.js} +3 -3
  22. package/dist/{runs-S3QKEWHY.js → runs-LM2JFG3P.js} +2 -2
  23. package/dist/{statusline-UIG25UUX.js → statusline-2DBKYHJA.js} +1 -1
  24. package/dist/{takeover-3U5V2KXY.js → takeover-ANPJB6JG.js} +4 -4
  25. package/dist/{use-I2KUA64A.js → use-JIQY32FQ.js} +10 -9
  26. package/package.json +2 -2
  27. package/dist/existing-runner-4UYED6LY.js +0 -20
package/README.md CHANGED
@@ -12,9 +12,9 @@ cloop install # register the MCP server with Claude Code / others
12
12
 
13
13
  Credentials live in `~/.cloop/credentials.json`. The API origin comes from `CLOOP_ORIGIN`, the stored value, or the staging default.
14
14
 
15
- `npx -y @cloop/runner@latest connect` makes this machine a runner. As its last step, it adds the remote Cloop MCP server to each Claude Code and Codex on the machine, and signs it in with OAuth on a terminal. It runs the usual lines: `claude mcp add -s user --transport http cloop https://app.mycloop.com/api/mcp/mcp` and `codex mcp add cloop --url https://app.mycloop.com/api/mcp/mcp`, then `claude mcp login cloop` and `codex mcp login cloop`. Staging uses the name `cloop-staging` and `https://mcp-staging.mycloop.com/mcp`. When an entry under any name already has the URL, `connect` adds nothing. This step never makes `connect` fail. Details: `docs/runbooks/cloop-local.md`, "Connect", step 5.
15
+ `npx -y @cloop/runner@latest connect` makes this computer a Cloop machine. As its last step, it adds the remote Cloop MCP server to each Claude Code and Codex on the machine, and signs it in with OAuth on a terminal. It runs the usual lines: `claude mcp add -s user --transport http cloop https://app.mycloop.com/api/mcp/mcp` and `codex mcp add cloop --url https://app.mycloop.com/api/mcp/mcp`, then `claude mcp login cloop` and `codex mcp login cloop`. Staging uses the name `cloop-staging` and `https://mcp-staging.mycloop.com/mcp`. When an entry under any name already has the URL, `connect` adds nothing. This step never makes `connect` fail. Details: `docs/runbooks/cloop-local.md`, "Connect", step 5.
16
16
 
17
- To disconnect a runner, use Disconnect in its ⋯ menu on the Threads page.
17
+ To disconnect a machine, use Disconnect in its ⋯ menu on the Threads page.
18
18
 
19
19
  ### Windows
20
20
 
@@ -1,16 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- MeshSocket,
4
- defaultSocketFactory
5
- } from "./chunk-IJH4O27H.js";
6
2
  import {
7
3
  serveTakeovers
8
- } from "./chunk-MHKSBXUD.js";
9
- import "./chunk-F4UQ2H5F.js";
4
+ } from "./chunk-7GLIYYIB.js";
5
+ import "./chunk-EGO3GOXI.js";
10
6
  import {
11
7
  DEFAULT_FALLBACK_MODEL,
12
8
  SUBSCRIPTIONS,
9
+ answerCall,
13
10
  awaitDaemon,
11
+ buildDiag,
12
+ classifyError,
14
13
  claudeDialect,
15
14
  cmdWord,
16
15
  codexDialect,
@@ -27,14 +26,20 @@ import {
27
26
  probeCodex,
28
27
  programFor,
29
28
  psQuote,
30
- runBoxTool,
31
29
  runSteps,
30
+ runnerLog,
32
31
  serviceEnv,
33
32
  stopService,
34
33
  systemServices,
35
34
  unitFor,
36
35
  which
37
- } from "./chunk-PQPWITU3.js";
36
+ } from "./chunk-ER5JS3RP.js";
37
+ import {
38
+ MeshSocket,
39
+ WAKE_TICK_MS,
40
+ defaultSocketFactory,
41
+ wakeWatch
42
+ } from "./chunk-KYGYU5G2.js";
38
43
  import {
39
44
  BoxWatch,
40
45
  hostedThreadsFilePath,
@@ -43,7 +48,7 @@ import {
43
48
  runnerStatePath,
44
49
  threadsFilePath,
45
50
  writeRunnerState
46
- } from "./chunk-6F2ZM5H3.js";
51
+ } from "./chunk-EKLBEP32.js";
47
52
  import {
48
53
  BackgroundReading,
49
54
  BoxToolError,
@@ -59,8 +64,13 @@ import {
59
64
  TOKEN_SCOPE,
60
65
  TOKEN_TTL_MS,
61
66
  addTokens,
67
+ attachedLine,
62
68
  commandFor,
69
+ delivery,
63
70
  failedEnd,
71
+ fetchImages,
72
+ finalWords,
73
+ hasResultBlock,
64
74
  isHosted,
65
75
  isLocal,
66
76
  isT3,
@@ -71,30 +81,32 @@ import {
71
81
  readRunResult,
72
82
  readRunnerConfig,
73
83
  resultPrUrl,
84
+ resultText,
74
85
  runnerDir,
75
86
  runnerEnvironment,
76
87
  runnerPath,
88
+ saveImages,
77
89
  showsOtherThreads,
78
90
  sortedDays,
79
91
  sourceKey,
80
92
  utcWindow,
81
93
  windowsPowerShellEnv,
82
94
  writeBoxConfig
83
- } from "./chunk-NVESLEXA.js";
95
+ } from "./chunk-3S2ECJTO.js";
84
96
  import {
85
97
  getMachine
86
98
  } from "./chunk-NTXQLEMQ.js";
87
99
  import "./chunk-VK6GV757.js";
88
100
  import {
89
101
  olderThan
90
- } from "./chunk-YEO27QQP.js";
91
- import "./chunk-R3CLO2FB.js";
92
- import "./chunk-IXG4H623.js";
93
- import "./chunk-UVB722OW.js";
102
+ } from "./chunk-365HFCQQ.js";
103
+ import "./chunk-PKIEWBR7.js";
104
+ import "./chunk-W4QJS3GR.js";
105
+ import "./chunk-MVMKRRE2.js";
94
106
  import "./chunk-ES5BRAKJ.js";
95
107
  import {
96
108
  VERSION
97
- } from "./chunk-VH7XVQFJ.js";
109
+ } from "./chunk-3I6NDELL.js";
98
110
  import {
99
111
  getMeshUrl,
100
112
  getOrigin,
@@ -329,6 +341,7 @@ function sseRecord(block) {
329
341
 
330
342
  // src/drivers/cloudroom.ts
331
343
  import { createHash } from "crypto";
344
+ import { join as join2 } from "path";
332
345
 
333
346
  // src/drivers/cloudroom-repos.ts
334
347
  import { execFile, spawn } from "child_process";
@@ -542,13 +555,15 @@ function placeFor(a) {
542
555
  branch: `cloop/${run3}`
543
556
  };
544
557
  }
545
- function launchText(prompt, place) {
558
+ function launchText(prompt, place, photos = "") {
546
559
  const where = place.kind === "worktree" ? `
547
560
 
548
561
  This folder is a git worktree of ${place.repository} on its own branch, \`${place.branch}\`, made for this Task. Other Tasks on this repository work in other folders at the same time. Commit here, and push the branch when the work should leave the box.` : place.named ? `
549
562
 
550
563
  The Task names the repository ${place.named}. This folder is empty: clone it here first.` : "";
551
- return `${prompt}${where}
564
+ return `${prompt}${where}${photos ? `
565
+
566
+ ${photos}` : ""}
552
567
 
553
568
  ${RESULT_INSTRUCTION}`;
554
569
  }
@@ -612,6 +627,7 @@ function apply(fold, r) {
612
627
  const turn = turnOf(fold, r.request);
613
628
  if (!turn) return null;
614
629
  if (turn.item !== r.item) {
630
+ if (hasResultBlock(turn.text)) turn.block = turn.text;
615
631
  turn.item = r.item;
616
632
  turn.text = "";
617
633
  }
@@ -623,6 +639,7 @@ function apply(fold, r) {
623
639
  if (!turn) return null;
624
640
  turn.item = r.item;
625
641
  turn.text = r.text;
642
+ if (hasResultBlock(r.text)) turn.block = r.text;
626
643
  return turn;
627
644
  }
628
645
  case "usage_limited": {
@@ -664,9 +681,9 @@ function runEnd(fold, harness) {
664
681
  }
665
682
  if (last.state === "completed" && !last.limited) {
666
683
  const text = last.text.trim();
667
- const result = readRunResult(text).result;
684
+ const result = readRunResult(resultText(text, last.block)).result;
668
685
  const pr = resultPrUrl(text);
669
- const summary = text.replace(/\s+/g, " ").slice(0, RUN_TEXT_MAX);
686
+ const summary = finalWords(text).slice(0, RUN_TEXT_MAX);
670
687
  return {
671
688
  kind: "settled",
672
689
  ...result ? { result } : {},
@@ -736,6 +753,7 @@ var sleep = (ms) => new Promise((resolve) => {
736
753
  const timer = setTimeout(resolve, ms);
737
754
  timer.unref?.();
738
755
  });
756
+ var ATTACHMENTS_ROOT = "/code/.attachments";
739
757
  var CloudroomDriver = class {
740
758
  constructor(deps) {
741
759
  this.deps = deps;
@@ -859,6 +877,11 @@ var CloudroomDriver = class {
859
877
  const thread = `cr_${start}`;
860
878
  const prompt = coreRequestId("run", a.work_id);
861
879
  const place = placeFor(a);
880
+ let photos;
881
+ const photosOnce = async () => {
882
+ photos ??= await this.photos(a, place);
883
+ return photos;
884
+ };
862
885
  const go = async () => {
863
886
  const existing2 = await this.core.session(thread);
864
887
  if (existing2?.receipts[prompt]) return existing2;
@@ -888,7 +911,7 @@ var CloudroomDriver = class {
888
911
  if (this.stopped.has(thread)) throw STOPPED_IN_PREPARATION;
889
912
  await this.core.command(thread, "prompts", {
890
913
  request_id: prompt,
891
- text: launchText(a.prompt, place)
914
+ text: launchText(a.prompt, place, (await photosOnce()).line)
892
915
  });
893
916
  this.preparing.delete(thread);
894
917
  if (this.stopped.has(thread))
@@ -901,13 +924,20 @@ var CloudroomDriver = class {
901
924
  };
902
925
  const answer = (resumed) => {
903
926
  this.log(`launch work=${a.work_id} thread=${thread}${resumed ? " resumed" : ""}`);
904
- return { thread_id: thread, resumed, permission: "full" };
927
+ return {
928
+ thread_id: thread,
929
+ resumed,
930
+ permission: "full",
931
+ harness: this.harness,
932
+ ...photos ? delivery(a.attachments, photos.attached) : {}
933
+ };
905
934
  };
906
935
  if (place.kind === "folder") return answer(Boolean(await go()));
907
936
  const existing = await this.core.session(thread);
908
937
  if (existing?.receipts[prompt]) return answer(true);
909
938
  const again = this.preparing.has(thread);
910
939
  if (!again) {
940
+ if (a.attachments?.length) await photosOnce();
911
941
  const prep = this.repos.locked(place.clone, go).then(() => {
912
942
  this.preparing.delete(thread);
913
943
  });
@@ -1051,6 +1081,28 @@ ${line}` : line;
1051
1081
  this.log(`interrupt thread=${id} was_running=${was_running}`);
1052
1082
  return { ok: true, was_running };
1053
1083
  }
1084
+ /**
1085
+ * The Task's photos, saved where the harness can open them, and the line
1086
+ * that names them. Core takes a prompt as text only, so the files are the
1087
+ * way in. Empty when the Task has none.
1088
+ */
1089
+ async photos(a, place) {
1090
+ if (!a.attachments?.length) return { line: "", attached: 0 };
1091
+ const log3 = (line) => this.log(`${line} work=${a.work_id}`);
1092
+ const { images } = await fetchImages(a.attachments, { log: log3, fetch: this.deps.fetch });
1093
+ const dir = join2(this.deps.attachments ?? ATTACHMENTS_ROOT, place.workspace);
1094
+ const paths = await saveImages(images, dir).catch((err) => {
1095
+ log3(`attachments_unsaved reason=${err.message.slice(0, 120)}`);
1096
+ return [];
1097
+ });
1098
+ this.log(
1099
+ `attachments work=${a.work_id} attached=${paths.length} missed=${a.attachments.length - paths.length}`
1100
+ );
1101
+ return {
1102
+ line: attachedLine(paths.length, a.attachments.length - paths.length, paths),
1103
+ attached: paths.length
1104
+ };
1105
+ }
1054
1106
  /**
1055
1107
  * Read the run's history after the last record seen, then follow its live
1056
1108
  * stream. When the stream ends or fails, core stopped or the connection
@@ -1062,7 +1114,10 @@ ${line}` : line;
1062
1114
  * while a child works or a turn waits, and looks again every
1063
1115
  * CHILDREN_WAIT_MS in case a child ends without a reply.
1064
1116
  */
1065
- watch(id, onEvent) {
1117
+ watch(id, report) {
1118
+ const onEvent = (event) => report(
1119
+ event.kind === "settled" || event.kind === "failed" ? { ...event, harness: this.harness } : event
1120
+ );
1066
1121
  let fold = NEW_FOLD;
1067
1122
  let stopped = false;
1068
1123
  let live = null;
@@ -1241,7 +1296,7 @@ import { spawn as spawn2 } from "child_process";
1241
1296
  import { createReadStream } from "fs";
1242
1297
  import { readdir, realpath, stat } from "fs/promises";
1243
1298
  import { homedir, hostname, tmpdir } from "os";
1244
- import { join as join2 } from "path";
1299
+ import { join as join3 } from "path";
1245
1300
  import { createInterface } from "readline";
1246
1301
  var PROBE_TIMEOUT_MS = 1e4;
1247
1302
  var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -1356,7 +1411,7 @@ async function probeCodexQuota(bin = "codex", timeoutMs = PROBE_TIMEOUT_MS) {
1356
1411
  }
1357
1412
  async function listLogs(dir, depth, match, found) {
1358
1413
  for (const entry of await readdir(dir, { withFileTypes: true })) {
1359
- const path = join2(dir, entry.name);
1414
+ const path = join3(dir, entry.name);
1360
1415
  if (entry.isFile() && match(entry.name)) found.files.push(path);
1361
1416
  else if (entry.isDirectory() && depth > 1)
1362
1417
  await listLogs(path, depth - 1, match, found).catch(() => {
@@ -1502,8 +1557,8 @@ async function scanTokenUsage(opts = {}) {
1502
1557
  const window = utcWindow(opts.now ?? Date.now(), TOKEN_DAYS);
1503
1558
  const sinceMs = Date.parse(`${window.sinceDay}T00:00:00Z`);
1504
1559
  const days = /* @__PURE__ */ new Map();
1505
- const claudeHome = opts.claudeHome ?? (process.env.CLAUDE_CONFIG_DIR || join2(homedir(), ".claude"));
1506
- const codexHome = opts.codexHome ?? (process.env.CODEX_HOME || join2(homedir(), ".codex"));
1560
+ const claudeHome = opts.claudeHome ?? (process.env.CLAUDE_CONFIG_DIR || join3(homedir(), ".claude"));
1561
+ const codexHome = opts.codexHome ?? (process.env.CODEX_HOME || join3(homedir(), ".codex"));
1507
1562
  const claude = claudeReader(window, days);
1508
1563
  const sources = [
1509
1564
  await scanSource(
@@ -1511,7 +1566,7 @@ async function scanTokenUsage(opts = {}) {
1511
1566
  provider: "claude",
1512
1567
  home: claudeHome,
1513
1568
  // projects/<project>/<session>.jsonl and projects/<project>/<session>/subagents/agent-*.jsonl
1514
- roots: [{ dir: join2(claudeHome, "projects"), depth: 4 }],
1569
+ roots: [{ dir: join3(claudeHome, "projects"), depth: 4 }],
1515
1570
  match: (name) => name.endsWith(".jsonl"),
1516
1571
  reader: () => claude.read
1517
1572
  },
@@ -1522,8 +1577,8 @@ async function scanTokenUsage(opts = {}) {
1522
1577
  provider: "codex",
1523
1578
  home: codexHome,
1524
1579
  roots: [
1525
- { dir: join2(codexHome, "sessions"), depth: 4 },
1526
- { dir: join2(codexHome, "archived_sessions"), depth: 1 }
1580
+ { dir: join3(codexHome, "sessions"), depth: 4 },
1581
+ { dir: join3(codexHome, "archived_sessions"), depth: 1 }
1527
1582
  ],
1528
1583
  match: (name) => name.startsWith("rollout-") && name.endsWith(".jsonl"),
1529
1584
  reader: codexReader(window, days)
@@ -1596,21 +1651,21 @@ var LocalUsage = class {
1596
1651
  import { createReadStream as createReadStream2 } from "fs";
1597
1652
  import { readdir as readdir2, stat as stat2 } from "fs/promises";
1598
1653
  import { homedir as homedir2 } from "os";
1599
- import { join as join3 } from "path";
1654
+ import { join as join4 } from "path";
1600
1655
  import { createInterface as createInterface2 } from "readline";
1601
1656
  var seen = /* @__PURE__ */ new Map();
1602
1657
  var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
1603
- async function listOutsideSessions(root = join3(homedir2(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
1658
+ async function listOutsideSessions(root = join4(homedir2(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
1604
1659
  const files = [];
1605
1660
  for (const project of await readdir2(root, { withFileTypes: true }).catch(() => [])) {
1606
1661
  if (!project.isDirectory()) continue;
1607
- for (const entry of await readdir2(join3(root, project.name), { withFileTypes: true }).catch(
1662
+ for (const entry of await readdir2(join4(root, project.name), { withFileTypes: true }).catch(
1608
1663
  () => []
1609
1664
  )) {
1610
1665
  if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
1611
1666
  const id = entry.name.slice(0, -6);
1612
1667
  if (!UUID.test(id) || own.has(id)) continue;
1613
- const path = join3(root, project.name, entry.name);
1668
+ const path = join4(root, project.name, entry.name);
1614
1669
  const info = await stat2(path).catch(() => null);
1615
1670
  if (info && info.mtimeMs >= now - 7 * 864e5)
1616
1671
  files.push({ id, project: project.name.slice(0, 200), file: path, mtime: info.mtimeMs });
@@ -1666,6 +1721,52 @@ async function listOutsideSessions(root = join3(homedir2(), ".claude", "projects
1666
1721
  return results;
1667
1722
  }
1668
1723
 
1724
+ // src/result-outbox.ts
1725
+ var OUTBOX_MAX = 50;
1726
+ var OUTBOX_KEEP_MS = 24 * 36e5;
1727
+ var ResultOutbox = class {
1728
+ constructor(deps) {
1729
+ this.deps = deps;
1730
+ }
1731
+ deps;
1732
+ held = /* @__PURE__ */ new Map();
1733
+ acking = false;
1734
+ get size() {
1735
+ return this.held.size;
1736
+ }
1737
+ send(frame) {
1738
+ this.held.delete(frame.id);
1739
+ this.held.set(frame.id, { frame, at: this.now() });
1740
+ this.trim();
1741
+ this.deps.send(frame);
1742
+ }
1743
+ ack(id) {
1744
+ this.acking = true;
1745
+ this.held.delete(id);
1746
+ }
1747
+ /** Sends every unacked result again, oldest first. Answers how many went. */
1748
+ resend() {
1749
+ this.trim();
1750
+ if (!this.acking) return 0;
1751
+ let sent = 0;
1752
+ for (const { frame } of this.held.values()) if (this.deps.send(frame)) sent++;
1753
+ return sent;
1754
+ }
1755
+ now() {
1756
+ return (this.deps.now ?? Date.now)();
1757
+ }
1758
+ trim() {
1759
+ const oldest = this.now() - OUTBOX_KEEP_MS;
1760
+ let dropped = 0;
1761
+ for (const [id, { at }] of this.held) {
1762
+ if (at >= oldest && this.held.size <= OUTBOX_MAX) break;
1763
+ this.held.delete(id);
1764
+ dropped++;
1765
+ }
1766
+ if (dropped) this.deps.onDropped?.(dropped);
1767
+ }
1768
+ };
1769
+
1669
1770
  // src/setup-share.ts
1670
1771
  import { spawn as spawn3 } from "child_process";
1671
1772
  import {
@@ -1680,7 +1781,7 @@ import {
1680
1781
  symlinkSync
1681
1782
  } from "fs";
1682
1783
  import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
1683
- import { join as join4 } from "path";
1784
+ import { join as join5 } from "path";
1684
1785
  var SKILL_DIRS = [".agents/skills", ".claude/skills", ".codex/skills"];
1685
1786
  var GUIDE_FILES = [".agents/AGENTS.md", ".claude/CLAUDE.md", ".codex/AGENTS.md"];
1686
1787
  var SKILLS_CAP_BYTES = 25 * 1024 * 1024;
@@ -1698,13 +1799,13 @@ function findSetup(home) {
1698
1799
  for (const dir of SKILL_DIRS) {
1699
1800
  let entries;
1700
1801
  try {
1701
- entries = readdirSync(join4(home, dir)).sort();
1802
+ entries = readdirSync(join5(home, dir)).sort();
1702
1803
  } catch {
1703
1804
  continue;
1704
1805
  }
1705
1806
  for (const name of entries) {
1706
- const path = join4(home, dir, name);
1707
- if (names.has(name) || !existsSync2(join4(path, "SKILL.md"))) continue;
1807
+ const path = join5(home, dir, name);
1808
+ if (names.has(name) || !existsSync2(join5(path, "SKILL.md"))) continue;
1708
1809
  const real = realpath2(path);
1709
1810
  if (!real || reals.has(real)) continue;
1710
1811
  names.add(name);
@@ -1712,15 +1813,15 @@ function findSetup(home) {
1712
1813
  skills.push({ name, path: real });
1713
1814
  }
1714
1815
  }
1715
- const guide = GUIDE_FILES.map((file) => realpath2(join4(home, file))).find((p) => p !== null) ?? null;
1816
+ const guide = GUIDE_FILES.map((file) => realpath2(join5(home, file))).find((p) => p !== null) ?? null;
1716
1817
  return { skills, guide };
1717
1818
  }
1718
1819
  function stage(setup) {
1719
- const dir = mkdtempSync(join4(tmpdir2(), "cloop-setup-"));
1720
- mkdirSync2(join4(dir, ".agents", "skills"), { recursive: true });
1820
+ const dir = mkdtempSync(join5(tmpdir2(), "cloop-setup-"));
1821
+ mkdirSync2(join5(dir, ".agents", "skills"), { recursive: true });
1721
1822
  for (const skill of setup.skills)
1722
- symlinkSync(skill.path, join4(dir, ".agents", "skills", skill.name), "junction");
1723
- if (setup.guide) copyFileSync(setup.guide, join4(dir, ".agents", "owner-guide.md"));
1823
+ symlinkSync(skill.path, join5(dir, ".agents", "skills", skill.name), "junction");
1824
+ if (setup.guide) copyFileSync(setup.guide, join5(dir, ".agents", "owner-guide.md"));
1724
1825
  return dir;
1725
1826
  }
1726
1827
  async function packSkills(home = homedir3(), capBytes = SKILLS_CAP_BYTES, tarBin = "tar") {
@@ -1880,10 +1981,10 @@ function readText(path) {
1880
1981
  return "";
1881
1982
  }
1882
1983
  }
1883
- function readRemoteMcp(home = homedir3(), codexHome = process.env.CODEX_HOME || join4(home, ".codex")) {
1984
+ function readRemoteMcp(home = homedir3(), codexHome = process.env.CODEX_HOME || join5(home, ".codex")) {
1884
1985
  return remoteMcp([
1885
- ...claudeRemoteMcp(readText(join4(home, ".claude.json"))),
1886
- ...codexRemoteMcp(readText(join4(codexHome, "config.toml")))
1986
+ ...claudeRemoteMcp(readText(join5(home, ".claude.json"))),
1987
+ ...codexRemoteMcp(readText(join5(codexHome, "config.toml")))
1887
1988
  ]);
1888
1989
  }
1889
1990
  async function sendSkills(tar, deps) {
@@ -1970,7 +2071,7 @@ import {
1970
2071
  writeFileSync
1971
2072
  } from "fs";
1972
2073
  import { homedir as homedir4 } from "os";
1973
- import { dirname, join as join5 } from "path";
2074
+ import { dirname, join as join6 } from "path";
1974
2075
  var REGISTRY_LATEST = "https://registry.npmjs.org/@cloop/runner/latest";
1975
2076
  var FIRST_CHECK_MS = 10 * 6e4;
1976
2077
  var CHECK_EVERY_MS = 6 * 36e5;
@@ -2010,10 +2111,10 @@ function updateDir(env) {
2010
2111
  return runnerPath(env, process.env.CLOOP_UPDATE_DIR, (dir) => dir);
2011
2112
  }
2012
2113
  function updateLogPath() {
2013
- return join5(updateDir(), "update.log");
2114
+ return join6(updateDir(), "update.log");
2014
2115
  }
2015
2116
  function statePath(env) {
2016
- return join5(updateDir(env), "update.json");
2117
+ return join6(updateDir(env), "update.json");
2017
2118
  }
2018
2119
  function readFailed() {
2019
2120
  try {
@@ -2061,7 +2162,7 @@ var adoptWords = (npx, to, kind) => [
2061
2162
  kind
2062
2163
  ];
2063
2164
  function adoptScriptPath() {
2064
- return join5(updateDir(), "adopt.cmd");
2165
+ return join6(updateDir(), "adopt.cmd");
2065
2166
  }
2066
2167
  function adoptScript(npx, to, kind, log3) {
2067
2168
  return [
@@ -2105,16 +2206,28 @@ function fetchVersion(npx, version) {
2105
2206
  );
2106
2207
  });
2107
2208
  }
2108
- function selfUpdate(kind, platform = process.platform) {
2209
+ function selfUpdate(kind, platform = process.platform, onFailed = () => {
2210
+ }) {
2109
2211
  let latest = null;
2110
2212
  let handing = false;
2111
2213
  let lastWhy = null;
2214
+ const state = { checked_at: null, latest: null, error: null };
2215
+ const fail = (error, version) => {
2216
+ state.error = error;
2217
+ onFailed(error, version);
2218
+ };
2112
2219
  const canDetach = platform === "darwin" || platform === "win32" || platform === "linux" && which("systemd-run") !== null;
2113
2220
  const check = async () => {
2221
+ state.checked_at = (/* @__PURE__ */ new Date()).toISOString();
2114
2222
  const read = await readLatest();
2115
- if (!read || read === latest || !olderThan(VERSION, read) || read === readFailed()) return;
2223
+ if (!read) return fail("registry_unreachable");
2224
+ state.latest = read;
2225
+ state.error = null;
2226
+ if (read === latest || !olderThan(VERSION, read) || read === readFailed()) return;
2116
2227
  const npx = findNpx();
2117
- if (npx && await fetchVersion(npx, read)) latest = read;
2228
+ if (!npx) return fail("npx_missing", read);
2229
+ if (await fetchVersion(npx, read)) latest = read;
2230
+ else fail("fetch_failed", read);
2118
2231
  };
2119
2232
  setTimeout(() => {
2120
2233
  void check();
@@ -2125,6 +2238,7 @@ function selfUpdate(kind, platform = process.platform) {
2125
2238
  if (!npx) {
2126
2239
  log(`npx is not on PATH, so ${to} cannot start`);
2127
2240
  recordFailed(to);
2241
+ fail("npx_missing", to);
2128
2242
  return;
2129
2243
  }
2130
2244
  const [command, ...args] = handOverCommand(platform, npx, to, kind);
@@ -2151,6 +2265,7 @@ function selfUpdate(kind, platform = process.platform) {
2151
2265
  handing = false;
2152
2266
  log(`${to} did not take over (${why}); staying on ${VERSION}`);
2153
2267
  recordFailed(to);
2268
+ fail("handover_failed", to);
2154
2269
  };
2155
2270
  child.on("error", (err) => failed(err.message));
2156
2271
  child.on("exit", (code, signal) => {
@@ -2158,6 +2273,7 @@ function selfUpdate(kind, platform = process.platform) {
2158
2273
  });
2159
2274
  };
2160
2275
  return {
2276
+ state: () => ({ ...state }),
2161
2277
  beat({ running, inFlight }) {
2162
2278
  if (handing) return;
2163
2279
  const decision = updateDecision({
@@ -2251,6 +2367,7 @@ async function adopt(from, kind, { services: given, script = process.argv[1] ??
2251
2367
  // src/commands/box.ts
2252
2368
  var BEAT_MS = 6e4;
2253
2369
  var RESEND_MS = 5 * 6e4;
2370
+ var RECENT_CALLS = 20;
2254
2371
  var REPAIR_BEFORE_MS = 2 * 24 * 36e5;
2255
2372
  var EXPIRING_BEFORE_MS = 3 * 24 * 36e5;
2256
2373
  var out = (line) => console.log(line);
@@ -2338,7 +2455,7 @@ async function run2() {
2338
2455
  let token = cfg?.deviceToken ?? getToken();
2339
2456
  if (!token || !cfg) {
2340
2457
  out(
2341
- `${red("\u2717")} ${legacyStagingRunner() ? "This staging runner is still in ~/.cloop from before 0.3.9. Run `cloop connect --staging` to move it to ~/.cloop/staging." : "Not connected. Run `cloop connect` first."}`
2458
+ `${red("\u2717")} ${legacyStagingRunner() ? "This staging machine is still in ~/.cloop from before 0.3.9. Run `cloop connect --staging` to move it to ~/.cloop/staging." : "Not connected. Run `cloop connect` first."}`
2342
2459
  );
2343
2460
  process.exit(1);
2344
2461
  }
@@ -2395,25 +2512,56 @@ async function run2() {
2395
2512
  });
2396
2513
  let inFlight = 0;
2397
2514
  let callsStarted = 0;
2515
+ const startedAt = performance.now();
2516
+ let lastBeatAt = null;
2517
+ const wake = { last: null, unsent: false };
2518
+ const recentCalls = [];
2519
+ const outbox = new ResultOutbox({
2520
+ send: (frame) => socket.send(frame),
2521
+ onDropped: (n) => socket.send(runnerLog("results_dropped", { n }))
2522
+ });
2523
+ const resendResults = () => {
2524
+ const n = outbox.resend();
2525
+ if (!n) return;
2526
+ log2(`resent results n=${n}`);
2527
+ socket.send(runnerLog("result_resent", { n }));
2528
+ };
2398
2529
  const onCall = async (frame) => {
2399
- const started = Date.now();
2400
2530
  inFlight++;
2401
2531
  callsStarted++;
2402
2532
  try {
2403
- const result = await runBoxTool(
2533
+ const outcome = await answerCall(
2404
2534
  {
2405
2535
  driver,
2406
2536
  onLaunch: (workId, threadId) => watch.add(workId, threadId),
2407
2537
  onResume: (threadId) => watch.resume(threadId),
2408
- ...setup ? { setup } : {}
2538
+ ...setup ? { setup } : {},
2539
+ diag: async () => buildDiag({
2540
+ version: VERSION,
2541
+ platform: process.platform,
2542
+ arch: process.arch,
2543
+ uptimeMs: performance.now() - startedAt,
2544
+ lastBeatAt,
2545
+ lastWake: wake.last,
2546
+ harnesses: await driver.status().then(
2547
+ (s) => s.harnesses,
2548
+ () => []
2549
+ ),
2550
+ update: update?.state() ?? { checked_at: null, latest: null, error: null },
2551
+ unacked: outbox.size,
2552
+ clockOffsetMs: socket.clockOffset(),
2553
+ calls: recentCalls
2554
+ })
2409
2555
  },
2410
- frame.tool,
2411
- frame.args
2412
- );
2413
- socket.send({ type: "result", id: frame.id, ...result });
2414
- log2(
2415
- `call tool=${frame.tool} ok=${result.ok} ms=${Date.now() - started}${result.ok ? "" : ` error=${result.error} detail=${result.detail.slice(0, 300)}`}`
2556
+ frame,
2557
+ {
2558
+ send: (f) => f.type === "result" ? outbox.send(f) : socket.send(f),
2559
+ log: log2,
2560
+ offset: () => socket.clockOffset()
2561
+ }
2416
2562
  );
2563
+ recentCalls.push(outcome);
2564
+ if (recentCalls.length > RECENT_CALLS) recentCalls.shift();
2417
2565
  } finally {
2418
2566
  inFlight--;
2419
2567
  }
@@ -2428,6 +2576,7 @@ async function run2() {
2428
2576
  },
2429
2577
  onCall: (frame) => void onCall(frame),
2430
2578
  onAck: (of, ok) => watch.ack(of, ok),
2579
+ onResultAck: (id) => outbox.ack(id),
2431
2580
  onOpen: () => {
2432
2581
  log2(`connected to ${getMeshUrl()}`);
2433
2582
  recordConnected(
@@ -2435,6 +2584,8 @@ async function run2() {
2435
2584
  (state) => writeRunnerState(state, runnerStatePath(void 0, threadsFile))
2436
2585
  );
2437
2586
  watch.flush();
2587
+ resendResults();
2588
+ if (wake.unsent && wake.last) wake.unsent = !socket.send({ type: "wake", ...wake.last });
2438
2589
  },
2439
2590
  onClose: (code) => log2(
2440
2591
  code === REVOKED_CLOSE ? "disconnected by Cloop (revoked), checking" : "disconnected, reconnecting"
@@ -2460,7 +2611,10 @@ async function run2() {
2460
2611
  `connecting to ${getMeshUrl()} as ${sessionKey} (${readCredentials()?.deviceName ?? machine}) driver=${driver.name}`
2461
2612
  );
2462
2613
  watch.start();
2463
- setInterval(() => watch.flush(), RESEND_MS).unref();
2614
+ setInterval(() => {
2615
+ watch.flush();
2616
+ resendResults();
2617
+ }, RESEND_MS).unref();
2464
2618
  const unfollow = driver instanceof CloudroomDriver ? driver.refuseOwnSandboxChildren() : null;
2465
2619
  if (driver instanceof LocalDriver) serveTakeovers(driver, log2);
2466
2620
  const renewT3 = async () => {
@@ -2485,7 +2639,11 @@ async function run2() {
2485
2639
  log2(`T3 session renewal failed: ${err instanceof Error ? err.message : String(err)}`);
2486
2640
  }
2487
2641
  };
2488
- const update = hosted ? null : selfUpdate(driver.name === "t3" ? "workstation" : "local");
2642
+ const update = hosted ? null : selfUpdate(
2643
+ driver.name === "t3" ? "workstation" : "local",
2644
+ process.platform,
2645
+ (error, ver) => socket.send(runnerLog("update_failed", { error, ver }))
2646
+ );
2489
2647
  const beat = async () => {
2490
2648
  await renewT3();
2491
2649
  const callsBefore = callsStarted;
@@ -2507,7 +2665,10 @@ async function run2() {
2507
2665
  );
2508
2666
  } catch (err) {
2509
2667
  log2(`${driver.name} unreachable: ${err instanceof Error ? err.message : String(err)}`);
2668
+ socket.send(runnerLog("driver_unreachable", { error: classifyError(err, driver.name) }));
2510
2669
  }
2670
+ lastBeatAt = (/* @__PURE__ */ new Date()).toISOString();
2671
+ socket.ping();
2511
2672
  socket.sendPresence(
2512
2673
  boxPresence({
2513
2674
  sessionKey,
@@ -2525,6 +2686,15 @@ async function run2() {
2525
2686
  };
2526
2687
  void beat();
2527
2688
  setInterval(() => void beat(), BEAT_MS);
2689
+ const sleptSince = wakeWatch();
2690
+ setInterval(() => {
2691
+ const woke = sleptSince();
2692
+ if (!woke) return;
2693
+ wake.last = woke;
2694
+ log2(`wake slept_ms=${woke.slept_ms}`);
2695
+ wake.unsent = !socket.send({ type: "wake", ...woke });
2696
+ void beat();
2697
+ }, WAKE_TICK_MS).unref();
2528
2698
  const stop = (code = 0) => {
2529
2699
  log2("stopping");
2530
2700
  watch.stop();