@cloop/runner 0.3.68 → 0.3.69

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 (30) hide show
  1. package/dist/{box-YFGM56QY.js → box-UOJ6ET2B.js} +156 -511
  2. package/dist/{chunk-7LPSTDZE.js → chunk-4JTIWZHB.js} +1 -1
  3. package/dist/{chunk-BVPS6DCH.js → chunk-57E5WOOP.js} +574 -1673
  4. package/dist/{chunk-TCNIRZLU.js → chunk-CLOYOD2X.js} +10 -6
  5. package/dist/{chunk-6LYMSWSB.js → chunk-DN6TQALA.js} +265 -1961
  6. package/dist/{chunk-HWNRORIZ.js → chunk-DTUNRKBC.js} +1 -1
  7. package/dist/chunk-EEG5JOZ7.js +939 -0
  8. package/dist/chunk-GAEZIKCK.js +626 -0
  9. package/dist/chunk-HIBAH65V.js +1178 -0
  10. package/dist/{chunk-7ZL3Z3IO.js → chunk-JI5FWLDU.js} +6 -6
  11. package/dist/chunk-JJWSPBM4.js +40 -0
  12. package/dist/{chunk-L7D3ANPW.js → chunk-KIYCULVE.js} +4 -2
  13. package/dist/{chunk-34VZ5LZI.js → chunk-SJAGZNFF.js} +3 -83
  14. package/dist/chunk-TPKYD3JF.js +43 -0
  15. package/dist/chunk-WCKW2Z2G.js +459 -0
  16. package/dist/chunk-ZHQSGJCE.js +85 -0
  17. package/dist/{connect-D2SXLADA.js → connect-HVOAYXWM.js} +11 -47
  18. package/dist/disconnect-DQ6WSDR7.js +163 -0
  19. package/dist/existing-runner-BSSRQFFP.js +15 -0
  20. package/dist/index.js +14 -14
  21. package/dist/{login-VNDFCJD4.js → login-4HWP4PF4.js} +3 -2
  22. package/dist/{mcp-server-XPHCDBFR.js → mcp-server-DTJVCFRG.js} +10 -10
  23. package/dist/{runner-A3HFZ727.js → runner-4XWS2RJL.js} +4 -3
  24. package/dist/{runs-DOFU45TW.js → runs-TWUGWGNU.js} +4 -2
  25. package/dist/{statusline-VA2DSWVT.js → statusline-C2FH3YQ4.js} +1 -1
  26. package/dist/{takeover-U2EHJ5GW.js → takeover-5QSP6YAG.js} +6 -4
  27. package/dist/{use-7D5GQFGB.js → use-U3E55XBK.js} +20 -13
  28. package/package.json +1 -1
  29. package/dist/disconnect-7SJKPYIN.js +0 -30
  30. package/dist/existing-runner-XT3HLIPM.js +0 -20
@@ -1,54 +1,67 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- serveTakeovers
4
- } from "./chunk-7ZL3Z3IO.js";
5
- import "./chunk-TCNIRZLU.js";
3
+ AGENTS,
4
+ LOCAL_AGENTS,
5
+ LocalUsage,
6
+ SUBSCRIPTIONS,
7
+ answerCall,
8
+ classifyError,
9
+ configuredBin,
10
+ connectCommand,
11
+ localAgent,
12
+ mintSession,
13
+ quotaProbes
14
+ } from "./chunk-57E5WOOP.js";
6
15
  import {
7
16
  CAPTURE_TICK_MS,
8
- DEFAULT_FALLBACK_MODEL,
9
17
  HOST_ID_MAX,
10
- SUBSCRIPTIONS,
11
18
  TITLE_MAX,
12
19
  ThreadCapture,
13
- answerCall,
20
+ captureCursorPath
21
+ } from "./chunk-EEG5JOZ7.js";
22
+ import "./chunk-JJWSPBM4.js";
23
+ import {
24
+ serveTakeovers
25
+ } from "./chunk-JI5FWLDU.js";
26
+ import "./chunk-CLOYOD2X.js";
27
+ import {
28
+ LocalDriver,
29
+ failedEnd,
30
+ listOutsideSessions
31
+ } from "./chunk-HIBAH65V.js";
32
+ import {
33
+ STOPPED_SUMMARY,
34
+ T3Client,
35
+ T3Driver,
36
+ attachedLine,
37
+ delivery,
38
+ fetchImages,
39
+ orderThreads,
40
+ saveImages
41
+ } from "./chunk-DN6TQALA.js";
42
+ import {
43
+ olderThan
44
+ } from "./chunk-365HFCQQ.js";
45
+ import {
46
+ pinExistingRunner
47
+ } from "./chunk-TPKYD3JF.js";
48
+ import {
14
49
  awaitDaemon,
15
- captureCursorPath,
16
- classifyError,
17
- claudeDialect,
18
- claudeHome,
19
50
  cmdWord,
20
- codexDialect,
21
- codexHome,
22
- codexModels,
23
- connectCommand,
24
51
  findNpx,
25
52
  installedService,
26
53
  isRelease,
54
+ legacyNotConnectedLine,
27
55
  legacyStagingRunner,
28
- mintSession,
29
56
  moveLegacyStagingRunner,
30
- moveRunnerFiles,
31
- pinExistingRunner,
32
- probeClaude,
33
- probeClaudePermissions,
34
- probeCodex,
57
+ moveLegacyStagingRunnerBack,
35
58
  programFor,
36
59
  psQuote,
37
60
  runSteps,
38
61
  serviceEnv,
39
- stopService,
40
62
  systemServices,
41
- unitFor,
42
- which
43
- } from "./chunk-BVPS6DCH.js";
44
- import {
45
- MeshSocket,
46
- WAKE_TICK_MS,
47
- buildDiag,
48
- defaultSocketFactory,
49
- runnerLog,
50
- wakeWatch
51
- } from "./chunk-AZQGERT7.js";
63
+ unitFor
64
+ } from "./chunk-WCKW2Z2G.js";
52
65
  import {
53
66
  BoxWatch,
54
67
  hostedThreadsFilePath,
@@ -58,42 +71,25 @@ import {
58
71
  runnerStatePath,
59
72
  threadsFilePath,
60
73
  writeRunnerState
61
- } from "./chunk-7LPSTDZE.js";
74
+ } from "./chunk-4JTIWZHB.js";
62
75
  import {
63
- BackgroundReading,
64
76
  BoxToolError,
65
77
  CLAUDE_AUTH_LOCKED,
66
78
  HARNESS_LIMIT,
67
- HARNESS_STALE_MS,
68
79
  IDLE_SETTLE_MS,
69
- LocalDriver,
70
80
  MACHINE_RESULT_INSTRUCTION,
71
81
  RUN_TEXT_MAX,
72
- STOPPED_SUMMARY,
73
- T3Client,
74
- T3Driver,
75
- TOKEN_DAYS,
76
- TOKEN_SCOPE,
77
- TOKEN_TTL_MS,
78
- addTokens,
79
- attachedLine,
80
82
  commandFor,
81
- delivery,
82
- failedEnd,
83
- fetchImages,
84
83
  finalWords,
85
84
  hasResultBlock,
86
85
  holdsForNextTurn,
87
86
  isHosted,
88
87
  isLocal,
88
+ isLocalDriver,
89
89
  isT3,
90
- listOutsideSessions,
91
90
  nextModel,
92
91
  nextProgress,
93
- orderThreads,
94
92
  ownHarnessFirst,
95
- quotaFromClaude,
96
- quotaFromCodex,
97
93
  readRunResult,
98
94
  readRunnerConfig,
99
95
  refusedModel,
@@ -104,27 +100,30 @@ import {
104
100
  runnerDir,
105
101
  runnerEnvironment,
106
102
  runnerPath,
107
- saveImages,
108
103
  showsOtherThreads,
109
- sortedDays,
110
- sourceKey,
111
- utcWindow,
104
+ which,
112
105
  windowsPowerShellEnv,
113
106
  writeBoxConfig
114
- } from "./chunk-6LYMSWSB.js";
115
- import "./chunk-VK6GV757.js";
107
+ } from "./chunk-GAEZIKCK.js";
116
108
  import {
117
- olderThan
118
- } from "./chunk-365HFCQQ.js";
109
+ MeshSocket,
110
+ WAKE_TICK_MS,
111
+ buildDiag,
112
+ defaultSocketFactory,
113
+ runnerLog,
114
+ wakeWatch
115
+ } from "./chunk-AZQGERT7.js";
116
+ import "./chunk-VK6GV757.js";
119
117
  import "./chunk-PKIEWBR7.js";
120
- import "./chunk-L7D3ANPW.js";
121
- import "./chunk-34VZ5LZI.js";
118
+ import "./chunk-KIYCULVE.js";
119
+ import "./chunk-SJAGZNFF.js";
120
+ import "./chunk-ZHQSGJCE.js";
122
121
  import {
123
122
  getMachine
124
123
  } from "./chunk-SBYSVZ7J.js";
125
124
  import {
126
125
  VERSION
127
- } from "./chunk-HWNRORIZ.js";
126
+ } from "./chunk-DTUNRKBC.js";
128
127
  import {
129
128
  getMeshUrl,
130
129
  getOrigin,
@@ -135,7 +134,7 @@ import {
135
134
 
136
135
  // src/commands/box.ts
137
136
  import { homedir as homedir3 } from "os";
138
- import { dirname as dirname3, join as join6 } from "path";
137
+ import { dirname as dirname3, join as join5 } from "path";
139
138
 
140
139
  // src/cloudroom-core.ts
141
140
  var CoreError = class extends Error {
@@ -1935,369 +1934,6 @@ ${asked}` : AUTH_LOCK_CONTINUE;
1935
1934
  }
1936
1935
  };
1937
1936
 
1938
- // src/drivers/local-usage.ts
1939
- import { spawn as spawn2 } from "child_process";
1940
- import { createReadStream } from "fs";
1941
- import { readdir, realpath, stat } from "fs/promises";
1942
- import { hostname, tmpdir } from "os";
1943
- import { join as join3 } from "path";
1944
- import { createInterface } from "readline";
1945
- var PROBE_TIMEOUT_MS = 1e4;
1946
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1947
- var count = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
1948
- var parse = (line) => {
1949
- try {
1950
- return JSON.parse(line);
1951
- } catch {
1952
- return void 0;
1953
- }
1954
- };
1955
- function askHarness(bin, args, requests, answer, timeoutMs = PROBE_TIMEOUT_MS) {
1956
- const command = commandFor(bin, args);
1957
- return new Promise((resolve, reject) => {
1958
- const child = spawn2(command.file, command.args, {
1959
- cwd: tmpdir(),
1960
- stdio: ["pipe", "pipe", "ignore"],
1961
- env: process.env,
1962
- windowsHide: true,
1963
- ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
1964
- });
1965
- let settled = false;
1966
- const finish = (err, value) => {
1967
- if (settled) return;
1968
- settled = true;
1969
- clearTimeout(timer);
1970
- child.stdin?.end();
1971
- child.kill();
1972
- setTimeout(() => {
1973
- if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
1974
- }, 2e3).unref();
1975
- if (err) reject(err);
1976
- else resolve(value);
1977
- };
1978
- const timer = setTimeout(
1979
- () => finish(new Error(`no answer in ${timeoutMs / 1e3} s`)),
1980
- timeoutMs
1981
- );
1982
- child.on("error", (err) => finish(err));
1983
- child.on("close", () => finish(new Error("it exited before it answered")));
1984
- child.stdin?.on("error", () => {
1985
- });
1986
- createInterface({ input: child.stdout }).on("line", (line) => {
1987
- const msg = parse(line);
1988
- const value = isObject(msg) ? answer(msg) : void 0;
1989
- if (value !== void 0) finish(null, value);
1990
- });
1991
- child.stdin?.write(requests.map((r) => `${JSON.stringify(r)}
1992
- `).join(""));
1993
- });
1994
- }
1995
- var reason = (err) => err?.message ?? "the probe failed";
1996
- async function probeClaudeQuota(bin = "claude", timeoutMs = PROBE_TIMEOUT_MS) {
1997
- const args = [
1998
- "--print",
1999
- "--verbose",
2000
- "--output-format",
2001
- "stream-json",
2002
- "--input-format",
2003
- "stream-json",
2004
- "--settings",
2005
- JSON.stringify({ disableAllHooks: true }),
2006
- "--strict-mcp-config",
2007
- "--no-session-persistence",
2008
- "--disable-slash-commands"
2009
- ];
2010
- const request = (id, request2) => ({
2011
- type: "control_request",
2012
- request_id: id,
2013
- request: request2
2014
- });
2015
- try {
2016
- const response = await askHarness(
2017
- bin,
2018
- args,
2019
- [
2020
- request("cloop-init", { subtype: "initialize" }),
2021
- request("cloop-usage", { subtype: "get_usage", skip_behaviors: true })
2022
- ],
2023
- (msg) => {
2024
- const r = msg.type === "control_response" ? msg.response : void 0;
2025
- return isObject(r) && r.request_id === "cloop-usage" ? r : void 0;
2026
- },
2027
- timeoutMs
2028
- );
2029
- return quotaFromClaude(response, (/* @__PURE__ */ new Date()).toISOString());
2030
- } catch (err) {
2031
- return quotaFromClaude({ subtype: "error", error: reason(err) }, (/* @__PURE__ */ new Date()).toISOString());
2032
- }
2033
- }
2034
- async function probeCodexQuota(bin = "codex", timeoutMs = PROBE_TIMEOUT_MS) {
2035
- try {
2036
- const answer = await askHarness(
2037
- bin,
2038
- ["app-server"],
2039
- [
2040
- {
2041
- id: 1,
2042
- method: "initialize",
2043
- params: { clientInfo: { name: "cloop-runner", version: VERSION } }
2044
- },
2045
- { method: "initialized" },
2046
- { id: 2, method: "account/rateLimits/read" }
2047
- ],
2048
- (msg) => msg.id === 2 ? msg : void 0,
2049
- timeoutMs
2050
- );
2051
- return quotaFromCodex(answer, (/* @__PURE__ */ new Date()).toISOString());
2052
- } catch (err) {
2053
- return quotaFromCodex({ error: { message: reason(err) } }, (/* @__PURE__ */ new Date()).toISOString());
2054
- }
2055
- }
2056
- async function listLogs(dir, depth, match, found) {
2057
- for (const entry of await readdir(dir, { withFileTypes: true })) {
2058
- const path = join3(dir, entry.name);
2059
- if (entry.isFile() && match(entry.name)) found.files.push(path);
2060
- else if (entry.isDirectory() && depth > 1)
2061
- await listLogs(path, depth - 1, match, found).catch(() => {
2062
- found.skipped++;
2063
- });
2064
- }
2065
- }
2066
- async function readLines(file, read) {
2067
- let malformed = 0;
2068
- let lastBad = false;
2069
- const lines = createInterface({
2070
- input: createReadStream(file, "utf-8"),
2071
- crlfDelay: Number.POSITIVE_INFINITY
2072
- });
2073
- for await (const line of lines) {
2074
- lastBad = !read(line);
2075
- if (lastBad) malformed++;
2076
- }
2077
- return lastBad ? malformed - 1 : malformed;
2078
- }
2079
- function dayOf(v) {
2080
- const ms = typeof v === "string" ? Date.parse(v) : Number.NaN;
2081
- return Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 10) : null;
2082
- }
2083
- var inWindow = (day, w) => day >= w.sinceDay && day <= w.untilDay;
2084
- function claudeReader(window, days) {
2085
- const calls = /* @__PURE__ */ new Map();
2086
- return {
2087
- read: (line) => {
2088
- if (!line.includes('"assistant"')) return true;
2089
- const d = parse(line);
2090
- if (d === void 0) return false;
2091
- if (!isObject(d) || d.type !== "assistant") return true;
2092
- const m = d.message;
2093
- const u = isObject(m) ? m.usage : void 0;
2094
- if (!isObject(m) || !isObject(u) || m.model === "<synthetic>") return true;
2095
- const day = dayOf(d.timestamp);
2096
- if (!day) return false;
2097
- if (!inWindow(day, window)) return true;
2098
- const details = isObject(u.output_tokens_details) ? u.output_tokens_details : {};
2099
- const call = {
2100
- day,
2101
- uncached: count(u.input_tokens),
2102
- cached: count(u.cache_read_input_tokens),
2103
- creation: count(u.cache_creation_input_tokens),
2104
- output: count(u.output_tokens),
2105
- reasoning: count(details.thinking_tokens),
2106
- records: 1
2107
- };
2108
- if (typeof m.id !== "string") addTokens(days, day, "claude", call);
2109
- else {
2110
- const key = `${m.id} ${String(d.requestId ?? "")}`;
2111
- const seen = calls.get(key);
2112
- if (!seen || call.output >= seen.output) calls.set(key, call);
2113
- }
2114
- return true;
2115
- },
2116
- finish: () => {
2117
- for (const call of calls.values()) addTokens(days, call.day, "claude", call);
2118
- }
2119
- };
2120
- }
2121
- function codexReader(window, days) {
2122
- return () => {
2123
- let prev = { input: 0, cached: 0, write: 0, output: 0, reasoning: 0 };
2124
- return (line) => {
2125
- if (!line.includes('"token_count"')) return true;
2126
- const d = parse(line);
2127
- if (d === void 0) return false;
2128
- const p = isObject(d) ? d.payload : void 0;
2129
- if (!isObject(p) || p.type !== "token_count") return true;
2130
- if (p.info === null || p.info === void 0) return true;
2131
- const t = isObject(p.info) ? p.info.total_token_usage : void 0;
2132
- const day = isObject(d) ? dayOf(d.timestamp) : null;
2133
- if (!isObject(t) || !day) return false;
2134
- const cur = {
2135
- input: count(t.input_tokens),
2136
- cached: count(t.cached_input_tokens),
2137
- write: count(t.cache_write_input_tokens),
2138
- output: count(t.output_tokens),
2139
- reasoning: count(t.reasoning_output_tokens)
2140
- };
2141
- if (cur.input + cur.output <= prev.input + prev.output) return true;
2142
- const rise = (k) => Math.max(0, cur[k] - prev[k]);
2143
- if (inWindow(day, window))
2144
- addTokens(days, day, "codex", {
2145
- uncached: Math.max(0, rise("input") - rise("cached") - rise("write")),
2146
- cached: rise("cached"),
2147
- creation: rise("write"),
2148
- output: rise("output"),
2149
- reasoning: rise("reasoning"),
2150
- records: 1
2151
- });
2152
- prev = cur;
2153
- return true;
2154
- };
2155
- };
2156
- }
2157
- async function scanSource(source, sinceMs) {
2158
- const key = sourceKey([
2159
- hostname(),
2160
- source.provider,
2161
- await realpath(source.home).catch(() => source.home)
2162
- ]);
2163
- const base = { source_key: key, provider: source.provider };
2164
- const found = { files: [], skipped: 0 };
2165
- for (const [i, root] of source.roots.entries()) {
2166
- try {
2167
- await listLogs(root.dir, root.depth, source.match, found);
2168
- } catch (err) {
2169
- const code = err.code;
2170
- if (i > 0 && code === "ENOENT") continue;
2171
- const empty = { scanned_files: 0, skipped_files: 0, malformed_records: 0 };
2172
- return code === "ENOENT" ? { ...base, status: "missing", ...empty } : {
2173
- ...base,
2174
- status: "failed",
2175
- ...empty,
2176
- message: `The log folder could not be read (${code ?? "error"}).`
2177
- };
2178
- }
2179
- }
2180
- let scanned = 0;
2181
- let skipped = found.skipped;
2182
- let malformed = 0;
2183
- for (const file of found.files) {
2184
- try {
2185
- if ((await stat(file)).mtimeMs < sinceMs) continue;
2186
- malformed += await readLines(file, source.reader());
2187
- scanned++;
2188
- } catch {
2189
- skipped++;
2190
- }
2191
- }
2192
- return {
2193
- ...base,
2194
- status: skipped || malformed ? "partial" : "ok",
2195
- scanned_files: scanned,
2196
- skipped_files: skipped,
2197
- malformed_records: malformed
2198
- };
2199
- }
2200
- async function scanTokenUsage(opts = {}) {
2201
- const window = utcWindow(opts.now ?? Date.now(), TOKEN_DAYS);
2202
- const sinceMs = Date.parse(`${window.sinceDay}T00:00:00Z`);
2203
- const days = /* @__PURE__ */ new Map();
2204
- const claudeHome2 = opts.claudeHome ?? claudeHome();
2205
- const codexHome2 = opts.codexHome ?? codexHome();
2206
- const claude = claudeReader(window, days);
2207
- const sources = [
2208
- await scanSource(
2209
- {
2210
- provider: "claude",
2211
- home: claudeHome2,
2212
- // projects/<project>/<session>.jsonl and projects/<project>/<session>/subagents/agent-*.jsonl
2213
- roots: [{ dir: join3(claudeHome2, "projects"), depth: 4 }],
2214
- match: (name) => name.endsWith(".jsonl"),
2215
- reader: () => claude.read
2216
- },
2217
- sinceMs
2218
- ),
2219
- await scanSource(
2220
- {
2221
- provider: "codex",
2222
- home: codexHome2,
2223
- roots: [
2224
- { dir: join3(codexHome2, "sessions"), depth: 4 },
2225
- { dir: join3(codexHome2, "archived_sessions"), depth: 1 }
2226
- ],
2227
- match: (name) => name.startsWith("rollout-") && name.endsWith(".jsonl"),
2228
- reader: codexReader(window, days)
2229
- },
2230
- sinceMs
2231
- )
2232
- ];
2233
- claude.finish();
2234
- const partial = sources.some((s) => s.status === "partial" || s.status === "failed");
2235
- return {
2236
- status: partial ? "partial" : "ok",
2237
- scope: TOKEN_SCOPE,
2238
- window: { since_day: window.sinceDay, until_day: window.untilDay, time_zone: "UTC" },
2239
- read_at: (/* @__PURE__ */ new Date()).toISOString(),
2240
- by_day: sortedDays(days),
2241
- sources
2242
- };
2243
- }
2244
- var LocalUsage = class {
2245
- constructor(deps) {
2246
- this.deps = deps;
2247
- this.tokens = new BackgroundReading({
2248
- ttlMs: TOKEN_TTL_MS,
2249
- read: () => this.scan(),
2250
- now: deps.now
2251
- });
2252
- }
2253
- deps;
2254
- quotas = /* @__PURE__ */ new Map();
2255
- tokens;
2256
- /** The quota of a signed-in harness, probed at most once per harness check period. */
2257
- quota(harness) {
2258
- const probe = this.deps.probes[harness];
2259
- if (!probe) return { status: "not_reported" };
2260
- let reading = this.quotas.get(harness);
2261
- if (!reading) {
2262
- reading = new BackgroundReading({
2263
- ttlMs: HARNESS_STALE_MS,
2264
- read: async () => {
2265
- const q = await probe();
2266
- if (q.status === "probe_failed")
2267
- this.deps.log?.(`quota probe failed harness=${harness}: ${q.message ?? ""}`);
2268
- return q;
2269
- },
2270
- now: this.deps.now
2271
- });
2272
- this.quotas.set(harness, reading);
2273
- }
2274
- return reading.get();
2275
- }
2276
- /** Each report with its quota. A signed-out harness has no account to ask. */
2277
- withQuota(harnesses) {
2278
- return harnesses.map((h) => ({
2279
- ...h,
2280
- quota: h.signedIn ? this.quota(h.id) : { status: "not_reported" }
2281
- }));
2282
- }
2283
- /** Token counts from the last log scan, rescanned at most every TOKEN_TTL_MS. */
2284
- tokenUsage() {
2285
- return this.tokens.get();
2286
- }
2287
- async scan() {
2288
- const now = this.deps.now ?? Date.now;
2289
- const started = now();
2290
- try {
2291
- const usage = await (this.deps.scan ?? scanTokenUsage)();
2292
- this.deps.log?.(`token scan took ${now() - started} ms status=${usage.status}`);
2293
- return usage;
2294
- } catch (err) {
2295
- this.deps.log?.(`token scan failed: ${err?.message}`);
2296
- return { status: "unavailable", reason: "The agent logs could not be read" };
2297
- }
2298
- }
2299
- };
2300
-
2301
1937
  // src/last-known.ts
2302
1938
  function lastKnown(read, initial, { ms, what, onFail }) {
2303
1939
  let last = initial;
@@ -2371,7 +2007,7 @@ var ResultOutbox = class {
2371
2007
  };
2372
2008
 
2373
2009
  // src/setup-share.ts
2374
- import { spawn as spawn3 } from "child_process";
2010
+ import { spawn as spawn2 } from "child_process";
2375
2011
  import {
2376
2012
  copyFileSync,
2377
2013
  existsSync as existsSync2,
@@ -2383,12 +2019,21 @@ import {
2383
2019
  rmSync as rmSync3,
2384
2020
  symlinkSync
2385
2021
  } from "fs";
2386
- import { homedir, tmpdir as tmpdir2 } from "os";
2387
- import { join as join4 } from "path";
2022
+ import { homedir, tmpdir } from "os";
2023
+ import { join as join3 } from "path";
2024
+
2025
+ // ../clo0p-app/contracts/box-mcp.ts
2026
+ var BOX_MCP_NAME_MAX = 40;
2027
+ var BOX_MCP_NAME = new RegExp(`^[a-z0-9][a-z0-9-]{0,${BOX_MCP_NAME_MAX - 1}}$`);
2028
+ var BOX_MCP_MAX_SERVERS = 20;
2029
+ var BOX_BROWSER_MCP = "playwright";
2030
+ var BOX_CLOOP_MCP = "cloop";
2031
+ var BOX_SKILLS_CAP_BYTES = 25 * 1024 * 1024;
2032
+
2033
+ // src/setup-share.ts
2388
2034
  var SKILL_DIRS = [".agents/skills", ".claude/skills", ".codex/skills"];
2389
2035
  var GUIDE_FILES = [".agents/AGENTS.md", ".claude/CLAUDE.md", ".codex/AGENTS.md"];
2390
- var SKILLS_CAP_BYTES = 25 * 1024 * 1024;
2391
- function realpath2(path) {
2036
+ function realpath(path) {
2392
2037
  try {
2393
2038
  return realpathSync(path);
2394
2039
  } catch {
@@ -2402,32 +2047,32 @@ function findSetup(home) {
2402
2047
  for (const dir of SKILL_DIRS) {
2403
2048
  let entries;
2404
2049
  try {
2405
- entries = readdirSync(join4(home, dir)).sort();
2050
+ entries = readdirSync(join3(home, dir)).sort();
2406
2051
  } catch {
2407
2052
  continue;
2408
2053
  }
2409
2054
  for (const name of entries) {
2410
- const path = join4(home, dir, name);
2411
- if (names.has(name) || !existsSync2(join4(path, "SKILL.md"))) continue;
2412
- const real = realpath2(path);
2055
+ const path = join3(home, dir, name);
2056
+ if (names.has(name) || !existsSync2(join3(path, "SKILL.md"))) continue;
2057
+ const real = realpath(path);
2413
2058
  if (!real || reals.has(real)) continue;
2414
2059
  names.add(name);
2415
2060
  reals.add(real);
2416
2061
  skills.push({ name, path: real });
2417
2062
  }
2418
2063
  }
2419
- const guide = GUIDE_FILES.map((file) => realpath2(join4(home, file))).find((p) => p !== null) ?? null;
2064
+ const guide = GUIDE_FILES.map((file) => realpath(join3(home, file))).find((p) => p !== null) ?? null;
2420
2065
  return { skills, guide };
2421
2066
  }
2422
2067
  function stage(setup) {
2423
- const dir = mkdtempSync(join4(tmpdir2(), "cloop-setup-"));
2424
- mkdirSync3(join4(dir, ".agents", "skills"), { recursive: true });
2068
+ const dir = mkdtempSync(join3(tmpdir(), "cloop-setup-"));
2069
+ mkdirSync3(join3(dir, ".agents", "skills"), { recursive: true });
2425
2070
  for (const skill of setup.skills)
2426
- symlinkSync(skill.path, join4(dir, ".agents", "skills", skill.name), "junction");
2427
- if (setup.guide) copyFileSync(setup.guide, join4(dir, ".agents", "owner-guide.md"));
2071
+ symlinkSync(skill.path, join3(dir, ".agents", "skills", skill.name), "junction");
2072
+ if (setup.guide) copyFileSync(setup.guide, join3(dir, ".agents", "owner-guide.md"));
2428
2073
  return dir;
2429
2074
  }
2430
- async function packSkills(home = homedir(), capBytes = SKILLS_CAP_BYTES, tarBin = "tar") {
2075
+ async function packSkills(home = homedir(), capBytes = BOX_SKILLS_CAP_BYTES, tarBin = "tar") {
2431
2076
  const setup = findSetup(home);
2432
2077
  if (setup.skills.length === 0 && !setup.guide) return { ok: false, reason: "no_skills" };
2433
2078
  let dir;
@@ -2437,7 +2082,7 @@ async function packSkills(home = homedir(), capBytes = SKILLS_CAP_BYTES, tarBin
2437
2082
  return { ok: false, reason: "tar_failed" };
2438
2083
  }
2439
2084
  const packed = await new Promise((resolve) => {
2440
- const child = spawn3(
2085
+ const child = spawn2(
2441
2086
  tarBin,
2442
2087
  [
2443
2088
  "-c",
@@ -2484,10 +2129,9 @@ async function packSkills(home = homedir(), capBytes = SKILLS_CAP_BYTES, tarBin
2484
2129
  rmSync3(dir, { recursive: true, force: true });
2485
2130
  return packed;
2486
2131
  }
2487
- var RESERVED_MCP = /* @__PURE__ */ new Set(["cloop", "playwright"]);
2488
- var MAX_REMOTE_MCP = 20;
2132
+ var RESERVED_MCP = /* @__PURE__ */ new Set([BOX_CLOOP_MCP, BOX_BROWSER_MCP]);
2489
2133
  function mcpName(raw) {
2490
- const name = raw.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/-{2,}/g, "-").replace(/^-+/, "").slice(0, 40).replace(/-+$/, "");
2134
+ const name = raw.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/-{2,}/g, "-").replace(/^-+/, "").slice(0, BOX_MCP_NAME_MAX).replace(/-+$/, "");
2491
2135
  return name && !RESERVED_MCP.has(name) ? name : null;
2492
2136
  }
2493
2137
  function urlCarriesSecret(url) {
@@ -2575,7 +2219,7 @@ function remoteMcp(found) {
2575
2219
  if (seen) seen.keyed ||= entry.keyed;
2576
2220
  else byUrl.set(url, { name, url, keyed: entry.keyed });
2577
2221
  }
2578
- return [...byUrl.values()].slice(0, MAX_REMOTE_MCP);
2222
+ return [...byUrl.values()].slice(0, BOX_MCP_MAX_SERVERS);
2579
2223
  }
2580
2224
  function readText(path) {
2581
2225
  try {
@@ -2584,10 +2228,10 @@ function readText(path) {
2584
2228
  return "";
2585
2229
  }
2586
2230
  }
2587
- function readRemoteMcp(home = homedir(), codexHome2 = process.env.CODEX_HOME || join4(home, ".codex")) {
2231
+ function readRemoteMcp(home = homedir(), codexHome = process.env.CODEX_HOME || join3(home, ".codex")) {
2588
2232
  return remoteMcp([
2589
- ...claudeRemoteMcp(readText(join4(home, ".claude.json"))),
2590
- ...codexRemoteMcp(readText(join4(codexHome2, "config.toml")))
2233
+ ...claudeRemoteMcp(readText(join3(home, ".claude.json"))),
2234
+ ...codexRemoteMcp(readText(join3(codexHome, "config.toml")))
2591
2235
  ]);
2592
2236
  }
2593
2237
  async function sendSkills(tar, deps) {
@@ -2674,16 +2318,39 @@ function isSettled(t) {
2674
2318
  if (t.settledOverride === "unsettled") return false;
2675
2319
  return typeof t.settledAt === "string";
2676
2320
  }
2321
+ var ACTIVE_RUN = /* @__PURE__ */ new Set(["preparing", "queued", "starting", "running", "waiting"]);
2322
+ function awaitsBackground(tasks) {
2323
+ if (!Array.isArray(tasks)) return false;
2324
+ return tasks.some(
2325
+ (task) => Boolean(
2326
+ task && (task.awaited === true || task.kind === "subagent" || task.kind === "background_task")
2327
+ )
2328
+ );
2329
+ }
2330
+ function hostState(t) {
2331
+ if (t.pendingRuntimeRequest) return "your_turn";
2332
+ const status = t.activityRunStatus ?? t.status;
2333
+ if (status === "failed") return void 0;
2334
+ if (status === "running" && t.blockedOnThreadWait === true) return "waiting";
2335
+ if (awaitsBackground(t.pendingBackgroundTasks)) return "waiting";
2336
+ if (typeof status === "string" && ACTIVE_RUN.has(status)) return "working";
2337
+ return void 0;
2338
+ }
2339
+ function carriesState(t) {
2340
+ return Array.isArray(t.pendingBackgroundTasks) && typeof t.blockedOnThreadWait === "boolean";
2341
+ }
2677
2342
  function facts(t) {
2678
2343
  const parent = t.lineage?.parentThreadId;
2679
2344
  const title = typeof t.title === "string" ? t.title.trim() : "";
2345
+ const state = hostState(t);
2680
2346
  return {
2681
2347
  host: "t3",
2682
2348
  threadId: t.id.slice(0, HOST_ID_MAX),
2683
2349
  ...t.createdBy === "agent" && typeof parent === "string" && parent ? { parentId: parent.slice(0, HOST_ID_MAX) } : {},
2684
2350
  ...title ? { title: title.slice(0, TITLE_MAX) } : {},
2685
2351
  delegated: t.createdBy === "agent",
2686
- settled: isSettled(t)
2352
+ settled: isSettled(t),
2353
+ ...state ? { state } : {}
2687
2354
  };
2688
2355
  }
2689
2356
  function harnessKey(t) {
@@ -2732,6 +2399,8 @@ var T3Threads = class {
2732
2399
  );
2733
2400
  const known = /* @__PURE__ */ new Map();
2734
2401
  for (const t of threads) known.set(t.id, facts(t));
2402
+ if (threads.length > 0 && !threads.some(carriesState))
2403
+ this.log(`[runner-threads:t3] t3_state_fields_missing threads=${threads.length}`);
2735
2404
  const knownThreads = new Set(this.threadOf.values());
2736
2405
  for (const id of knownThreads) {
2737
2406
  const prior = this.facts.get(id);
@@ -2754,25 +2423,17 @@ var T3Threads = class {
2754
2423
  for (const id of ids) this.threadOf.set(id, thread.id);
2755
2424
  }
2756
2425
  } catch (err) {
2757
- const reason2 = err instanceof Error ? err.message : String(err);
2758
- this.log(`[runner-threads:t3] t3_read_failed reason=${reason2.slice(0, 120)}`);
2426
+ const reason = err instanceof Error ? err.message : String(err);
2427
+ this.log(`[runner-threads:t3] t3_read_failed reason=${reason.slice(0, 120)}`);
2759
2428
  }
2760
2429
  }
2761
2430
  };
2762
2431
 
2763
2432
  // src/update.ts
2764
- import { execFile as execFile2, spawn as spawn4 } from "child_process";
2765
- import {
2766
- closeSync,
2767
- mkdirSync as mkdirSync4,
2768
- openSync,
2769
- readFileSync as readFileSync3,
2770
- renameSync as renameSync3,
2771
- rmSync as rmSync4,
2772
- writeFileSync as writeFileSync2
2773
- } from "fs";
2433
+ import { execFile as execFile2, spawn as spawn3 } from "child_process";
2434
+ import { closeSync, mkdirSync as mkdirSync4, openSync, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync2 } from "fs";
2774
2435
  import { homedir as homedir2 } from "os";
2775
- import { dirname as dirname2, join as join5 } from "path";
2436
+ import { dirname as dirname2, join as join4 } from "path";
2776
2437
  var REGISTRY_LATEST = "https://registry.npmjs.org/@cloop/runner/latest";
2777
2438
  var FIRST_CHECK_MS = 10 * 6e4;
2778
2439
  var CHECK_EVERY_MS = 6 * 36e5;
@@ -2814,10 +2475,10 @@ function updateDir(env) {
2814
2475
  return runnerPath(env, process.env.CLOOP_UPDATE_DIR, (dir) => dir);
2815
2476
  }
2816
2477
  function updateLogPath() {
2817
- return join5(updateDir(), "update.log");
2478
+ return join4(updateDir(), "update.log");
2818
2479
  }
2819
2480
  function statePath(env) {
2820
- return join5(updateDir(env), "update.json");
2481
+ return join4(updateDir(env), "update.json");
2821
2482
  }
2822
2483
  function readFailed() {
2823
2484
  try {
@@ -2865,7 +2526,7 @@ var adoptWords = (npx, to, kind) => [
2865
2526
  kind
2866
2527
  ];
2867
2528
  function adoptScriptPath() {
2868
- return join5(updateDir(), "adopt.cmd");
2529
+ return join4(updateDir(), "adopt.cmd");
2869
2530
  }
2870
2531
  function adoptScript(npx, to, kind, log3) {
2871
2532
  return [
@@ -2935,7 +2596,10 @@ function selfUpdate(kind, platform = process.platform, onFailed = () => {
2935
2596
  }
2936
2597
  state.latest = read;
2937
2598
  state.error = null;
2938
- if (read === latest || !olderThan(VERSION, read)) return true;
2599
+ if (read === latest || !olderThan(VERSION, read)) {
2600
+ latest = read;
2601
+ return true;
2602
+ }
2939
2603
  if (read === readFailed()) {
2940
2604
  latest = read;
2941
2605
  return true;
@@ -2983,7 +2647,7 @@ function selfUpdate(kind, platform = process.platform, onFailed = () => {
2983
2647
  }
2984
2648
  handing = true;
2985
2649
  log(`handing over ${VERSION} -> ${to}; its log is ${updateLogPath()}`);
2986
- const child = spawn4(
2650
+ const child = spawn3(
2987
2651
  command,
2988
2652
  args,
2989
2653
  platform === "win32" ? { stdio: "ignore", windowsHide: true, env: windowsPowerShellEnv() } : { detached: true, stdio: ["ignore", fd, fd] }
@@ -3083,12 +2747,7 @@ async function adopt(from, kind, { services: given, script = process.argv[1] ??
3083
2747
  }
3084
2748
  log(`adopt ${from} -> ${VERSION} failed: ${why}; putting ${from} back`);
3085
2749
  try {
3086
- if (legacy) {
3087
- const added = installedService({ ...where, environment });
3088
- if (!await stopService(added, run3)) throw new Error(`${added.path} did not stop`);
3089
- rmSync4(added.path, { force: true });
3090
- moveRunnerFiles(runnerDir(environment), runnerDir(was));
3091
- }
2750
+ if (legacy) await moveLegacyStagingRunnerBack({ ...where, environment }, run3);
3092
2751
  recordFailed(VERSION, was);
3093
2752
  writeFileSync2(back.path, old);
3094
2753
  await runSteps(back.start, run3);
@@ -3151,33 +2810,20 @@ function boxPresence(beat) {
3151
2810
  };
3152
2811
  }
3153
2812
  async function machineHarnesses(cfg) {
3154
- const [claude, codex] = await Promise.all([
3155
- probeClaude(cfg.driver === "claude-code" ? cfg.bin : void 0),
3156
- probeCodex(cfg.driver === "codex" ? cfg.bin : void 0)
3157
- ]);
3158
- return ownHarnessFirst([claude, codex], cfg.driver);
2813
+ const reports = await Promise.all(
2814
+ LOCAL_AGENTS.map((agent) => agent.probe(configuredBin(cfg, agent)))
2815
+ );
2816
+ return ownHarnessFirst(reports, cfg.driver);
3159
2817
  }
3160
2818
  async function localDriver(cfg, name) {
3161
- const bin = cfg.driver === name ? cfg.bin : void 0;
3162
- const claude = async (at) => claudeDialect(
3163
- at,
3164
- cfg.fallbackModels ?? DEFAULT_FALLBACK_MODEL,
3165
- cfg.askEverything,
3166
- await probeClaudePermissions(at)
3167
- );
2819
+ const agent = AGENTS[name];
3168
2820
  const driver = new LocalDriver({
3169
- dialect: name === "claude-code" ? await claude(bin) : codexDialect(bin),
3170
- fallbackHarness: name === "claude-code" ? codexDialect() : await claude(),
2821
+ dialect: await agent.dialect(cfg, configuredBin(cfg, agent)),
2822
+ fallbackHarness: await AGENTS[agent.handsOverTo].dialect(cfg),
3171
2823
  repos: cfg.repos,
3172
2824
  label: cfg.label,
3173
2825
  harnesses: () => machineHarnesses(cfg),
3174
- usage: new LocalUsage({
3175
- probes: {
3176
- "claude-code": () => probeClaudeQuota(cfg.driver === "claude-code" ? cfg.bin : void 0),
3177
- codex: () => probeCodexQuota(cfg.driver === "codex" ? cfg.bin : void 0)
3178
- },
3179
- log: log2
3180
- }),
2826
+ usage: new LocalUsage({ probes: quotaProbes(cfg), log: log2 }),
3181
2827
  log: log2
3182
2828
  });
3183
2829
  driver.warmHarnesses();
@@ -3195,9 +2841,7 @@ async function run2() {
3195
2841
  if (cfg && isHosted(cfg)) pinRunnerEnvironment(cfg.origin);
3196
2842
  let token = cfg?.deviceToken ?? getToken();
3197
2843
  if (!token || !cfg) {
3198
- out(
3199
- `${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."}`
3200
- );
2844
+ out(`${red("\u2717")} ${legacyNotConnectedLine() ?? "Not connected. Run `cloop connect` first."}`);
3201
2845
  process.exit(1);
3202
2846
  }
3203
2847
  if (!cfg.deviceToken) {
@@ -3225,29 +2869,27 @@ async function run2() {
3225
2869
  out(`${red("\u2717")} Another \`cloop box run\` is running (pid ${lock.heldBy}). Stop it first.`);
3226
2870
  process.exit(1);
3227
2871
  }
2872
+ const hostedModels = hosted ? localAgent(hosted.harness)?.models : void 0;
3228
2873
  const driver = hosted ? new CloudroomDriver({
3229
2874
  core: new CoreClient(hosted.coreUrl, hosted.coreToken),
3230
2875
  harness: hosted.harness,
3231
2876
  label: hosted.label,
3232
2877
  // The box's harnesses sign in as the agent this daemon runs as, so its probes read the owner's account.
3233
- usage: new LocalUsage({
3234
- probes: { "claude-code": () => probeClaudeQuota(), codex: () => probeCodexQuota() },
3235
- log: log2
3236
- }),
2878
+ usage: new LocalUsage({ probes: quotaProbes(), log: log2 }),
3237
2879
  // The same account's catalog, for a run the account refuses its model.
3238
- ...hosted.harness === "codex" ? { models: () => codexModels() } : {},
2880
+ ...hostedModels ? { models: () => hostedModels() } : {},
3239
2881
  // Beside the daemon's threads: the model a Task named, a run's move off a refused one, refusals and the last list.
3240
2882
  runModels: fileRunModels(hostedRunModelsPath(hosted.harness)),
3241
2883
  log: log2,
3242
2884
  // A held run's lease keeps the box awake until the hold is due to settle.
3243
- awakeDir: join6(homedir3(), ".cloop", "awake"),
2885
+ awakeDir: join5(homedir3(), ".cloop", "awake"),
3244
2886
  // Called only once calls arrive, so the socket below exists by then.
3245
2887
  followUpLost: ({ work, n, error }) => socket.send(runnerLog("followup_lost", { work, n, tool: "thread.send", error })),
3246
2888
  // Watches start after the socket too: a held run's steps, for the hold monitor.
3247
2889
  holdLog: (code, work, ms) => socket.send(runnerLog(code, { work, ms })),
3248
2890
  // A Claude Code run that carries on past the OAuth refresh lock, or fails on it after its last try.
3249
2891
  authLockLog: (code, work, n, ms) => socket.send(runnerLog(code, { work, n, ms }))
3250
- }) : local && (name === "claude-code" || name === "codex") ? await localDriver(local, name) : new T3Driver({
2892
+ }) : local && isLocalDriver(name) ? await localDriver(local, name) : new T3Driver({
3251
2893
  client: () => t3.client,
3252
2894
  t3Bin: isT3(cfg) ? cfg.t3Bin : null,
3253
2895
  scope: () => cfg && isT3(cfg) ? cfg.scope : void 0,
@@ -3262,7 +2904,7 @@ async function run2() {
3262
2904
  deviceToken: () => token,
3263
2905
  log: log2,
3264
2906
  dir: runnerDir(),
3265
- awakeDir: hosted ? join6(homedir3(), ".cloop", "awake") : null
2907
+ awakeDir: hosted ? join5(homedir3(), ".cloop", "awake") : null
3266
2908
  });
3267
2909
  const previews = outputs.connector;
3268
2910
  void previews.resume();
@@ -3422,7 +3064,7 @@ async function run2() {
3422
3064
  const readDriver = lastKnown(
3423
3065
  async () => {
3424
3066
  const shown = showsOtherThreads(readRunnerConfig());
3425
- const own = shown && driver.name === "claude-code";
3067
+ const own = shown && localAgent(driver.name)?.ownSessions === true;
3426
3068
  const listed = await driver.listThreads({
3427
3069
  scope: own ? "all" : "unsettled",
3428
3070
  limit: own ? 200 : 1
@@ -3540,18 +3182,21 @@ async function run2() {
3540
3182
  });
3541
3183
  }
3542
3184
  function hostedRunModelsPath(harness) {
3543
- return join6(dirname3(hostedThreadsFilePath(harness)), "run-models.json");
3185
+ return join5(dirname3(hostedThreadsFilePath(harness)), "run-models.json");
3544
3186
  }
3545
3187
  var MODEL_WAIT_MS = 8e3;
3546
3188
  async function modelCommand(argv, deps = {}) {
3547
3189
  const harness = flag(argv, "--harness");
3548
3190
  const err = deps.err ?? ((line) => console.error(line));
3549
- if (harness !== "codex") {
3550
- err("Usage: cloop box model --harness codex");
3191
+ const models = localAgent(harness)?.models;
3192
+ if (!harness || !models) {
3193
+ err(
3194
+ `Usage: cloop box model --harness ${LOCAL_AGENTS.filter((agent) => agent.models).map((agent) => agent.id).join("|")}`
3195
+ );
3551
3196
  return 1;
3552
3197
  }
3553
3198
  const pick = await boxModel({
3554
- models: deps.models ?? (() => codexModels()),
3199
+ models: deps.models ?? (() => models()),
3555
3200
  store: fileRunModels(deps.file ?? hostedRunModelsPath(harness)),
3556
3201
  now: deps.now ?? Date.now(),
3557
3202
  waitMs: MODEL_WAIT_MS