@cloop/runner 0.3.31 → 0.3.35

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.
@@ -239,6 +239,199 @@ function stamp(now) {
239
239
  return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":");
240
240
  }
241
241
 
242
+ // src/outside-sessions.ts
243
+ import { createReadStream } from "fs";
244
+ import { readFile, readdir, stat } from "fs/promises";
245
+ import { homedir as homedir2 } from "os";
246
+ import { dirname as dirname3, join as join4 } from "path";
247
+ import { createInterface } from "readline";
248
+ var seen = /* @__PURE__ */ new Map();
249
+ var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
250
+ async function listOutsideSessions(root = join4(homedir2(), ".claude", "projects"), own = /* @__PURE__ */ new Set(), now = Date.now()) {
251
+ const files = [];
252
+ for (const project of await readdir(root, { withFileTypes: true }).catch(() => [])) {
253
+ if (!project.isDirectory()) continue;
254
+ for (const entry of await readdir(join4(root, project.name), { withFileTypes: true }).catch(
255
+ () => []
256
+ )) {
257
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
258
+ const id = entry.name.slice(0, -6);
259
+ if (!UUID.test(id) || own.has(id)) continue;
260
+ const path = join4(root, project.name, entry.name);
261
+ const info = await stat(path).catch(() => null);
262
+ if (info && info.mtimeMs >= now - 7 * 864e5)
263
+ files.push({ id, project: project.name.slice(0, 200), file: path, mtime: info.mtimeMs });
264
+ }
265
+ }
266
+ const results = [];
267
+ const newest = files.sort((a, b) => b.mtime - a.mtime).slice(0, 20);
268
+ for (const path of seen.keys()) if (!newest.some((file) => file.file === path)) seen.delete(path);
269
+ for (const file of newest) {
270
+ const { title, cwd } = await claudeMeta(file.file, file.mtime);
271
+ results.push({
272
+ id: file.id,
273
+ project: file.project,
274
+ updatedAt: new Date(file.mtime).toISOString(),
275
+ status: "idle",
276
+ ...cwd ? { cwd } : {},
277
+ ...title ? { title } : {}
278
+ });
279
+ }
280
+ return results;
281
+ }
282
+ async function claudeMeta(file, mtime) {
283
+ const known = seen.get(file);
284
+ if (known?.mtime === mtime) return known;
285
+ let title;
286
+ let cwd;
287
+ const stream = createReadStream(file, { encoding: "utf8" });
288
+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
289
+ try {
290
+ for await (const line of lines) {
291
+ if (!cwd && line.includes('"cwd"')) {
292
+ try {
293
+ const record = JSON.parse(line);
294
+ if (typeof record.cwd === "string" && record.cwd.startsWith("/") && record.cwd.length <= 500)
295
+ cwd = record.cwd;
296
+ } catch {
297
+ }
298
+ }
299
+ if (!/^\s*\{\s*"type"\s*:\s*"(?:summary|custom-title|title)"/.test(line)) continue;
300
+ try {
301
+ const record = JSON.parse(line);
302
+ const value = record.type === "summary" ? record.summary : record.type === "custom-title" ? record.customTitle : record.title;
303
+ if (typeof value === "string" && value.trim()) title = value.trim().slice(0, 120);
304
+ } catch {
305
+ }
306
+ }
307
+ } finally {
308
+ lines.close();
309
+ stream.destroy();
310
+ }
311
+ const meta = { mtime, ...title ? { title } : {}, ...cwd ? { cwd } : {} };
312
+ seen.set(file, meta);
313
+ return meta;
314
+ }
315
+ function sessionRoots(home = homedir2()) {
316
+ return { claude: join4(home, ".claude", "projects"), codex: join4(home, ".codex", "sessions") };
317
+ }
318
+ async function findSession(id, roots, harnesses) {
319
+ if (!UUID.test(id)) return null;
320
+ if (harnesses.includes("claude-code")) {
321
+ for (const project of await readdir(roots.claude, { withFileTypes: true }).catch(() => [])) {
322
+ if (!project.isDirectory()) continue;
323
+ const file = join4(roots.claude, project.name, `${id}.jsonl`);
324
+ const info = await stat(file).catch(() => null);
325
+ if (!info?.isFile()) continue;
326
+ const meta = await claudeMeta(file, info.mtimeMs);
327
+ return {
328
+ harness: "claude-code",
329
+ id,
330
+ cwd: meta.cwd ?? null,
331
+ ...meta.title ? { title: meta.title } : {},
332
+ mtime: info.mtimeMs
333
+ };
334
+ }
335
+ }
336
+ if (harnesses.includes("codex")) {
337
+ const file = (await codexFiles(roots.codex)).find((f) => f.id === id);
338
+ if (file) {
339
+ const meta = await codexMeta(file.file, file.mtime);
340
+ if (meta?.id === id) {
341
+ const title = (await codexTitles(roots.codex)).get(id);
342
+ return {
343
+ harness: "codex",
344
+ id,
345
+ cwd: meta.cwd,
346
+ ...title ? { title } : {},
347
+ mtime: file.mtime
348
+ };
349
+ }
350
+ }
351
+ }
352
+ return null;
353
+ }
354
+ async function listCodexSessions(root, own = /* @__PURE__ */ new Set(), now = Date.now()) {
355
+ const files = (await codexFiles(root, now - 7 * 864e5)).filter((f) => !own.has(f.id)).slice(0, 20);
356
+ const titles = files.length ? await codexTitles(root) : /* @__PURE__ */ new Map();
357
+ const results = [];
358
+ for (const file of files) {
359
+ const meta = await codexMeta(file.file, file.mtime);
360
+ if (meta?.id !== file.id) continue;
361
+ const title = titles.get(file.id);
362
+ results.push({
363
+ id: file.id,
364
+ updatedAt: new Date(file.mtime).toISOString(),
365
+ status: "idle",
366
+ ...meta.cwd ? { cwd: meta.cwd } : {},
367
+ ...title ? { title } : {}
368
+ });
369
+ }
370
+ return results;
371
+ }
372
+ var ROLLOUT = /^rollout-.+-([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.jsonl$/i;
373
+ async function codexFiles(root, since = 0) {
374
+ const out = [];
375
+ const names = async (dir) => (await readdir(dir, { withFileTypes: true }).catch(() => [])).filter((d) => d.isDirectory() && /^\d+$/.test(d.name)).map((d) => d.name).sort().reverse();
376
+ for (const year of await names(root))
377
+ for (const month of await names(join4(root, year)))
378
+ for (const day of await names(join4(root, year, month))) {
379
+ const dir = join4(root, year, month, day);
380
+ for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
381
+ const id = entry.isFile() ? ROLLOUT.exec(entry.name)?.[1] : void 0;
382
+ if (!id) continue;
383
+ const file = join4(dir, entry.name);
384
+ const info = await stat(file).catch(() => null);
385
+ if (info && info.mtimeMs >= since) out.push({ id, file, mtime: info.mtimeMs });
386
+ }
387
+ }
388
+ return out.sort((a, b) => b.mtime - a.mtime);
389
+ }
390
+ var codexSeen = /* @__PURE__ */ new Map();
391
+ async function codexMeta(file, mtime) {
392
+ const known = codexSeen.get(file);
393
+ if (known?.mtime === mtime) return known.meta;
394
+ const stream = createReadStream(file, { encoding: "utf8" });
395
+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
396
+ let meta = null;
397
+ try {
398
+ for await (const line of lines) {
399
+ try {
400
+ const record = JSON.parse(line);
401
+ const payload = record?.type === "session_meta" ? record.payload : null;
402
+ if (typeof payload?.id === "string") {
403
+ const cwd = payload.cwd;
404
+ meta = {
405
+ id: payload.id,
406
+ cwd: typeof cwd === "string" && cwd.startsWith("/") && cwd.length <= 500 ? cwd : null
407
+ };
408
+ }
409
+ } catch {
410
+ }
411
+ break;
412
+ }
413
+ } finally {
414
+ lines.close();
415
+ stream.destroy();
416
+ }
417
+ if (codexSeen.size > 200) codexSeen.clear();
418
+ codexSeen.set(file, { mtime, meta });
419
+ return meta;
420
+ }
421
+ async function codexTitles(root) {
422
+ const titles = /* @__PURE__ */ new Map();
423
+ const text3 = await readFile(join4(dirname3(root), "session_index.jsonl"), "utf8").catch(() => "");
424
+ for (const line of text3.split("\n")) {
425
+ try {
426
+ const record = JSON.parse(line);
427
+ if (typeof record?.id === "string" && typeof record.thread_name === "string" && record.thread_name.trim())
428
+ titles.set(record.id, record.thread_name.trim().slice(0, 120));
429
+ } catch {
430
+ }
431
+ }
432
+ return titles;
433
+ }
434
+
242
435
  // src/spawn-command.ts
243
436
  import { execFileSync } from "child_process";
244
437
  function commandFor(bin, args, platform = process.platform, comspec = process.env.ComSpec) {
@@ -297,7 +490,7 @@ function windowsPowerShellEnv(env = process.env) {
297
490
  // src/t3-bin.ts
298
491
  import { execFileSync as execFileSync2 } from "child_process";
299
492
  import { existsSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
300
- import { join as join4 } from "path";
493
+ import { join as join5 } from "path";
301
494
  var CLEAN_ENV = () => ({
302
495
  HOME: process.env.HOME,
303
496
  USER: process.env.USER,
@@ -307,7 +500,7 @@ function defaultT3BinSources(home, stored) {
307
500
  return {
308
501
  env: process.env,
309
502
  home,
310
- appDirs: process.platform === "darwin" ? ["/Applications", join4(home, "Applications")] : [],
503
+ appDirs: process.platform === "darwin" ? ["/Applications", join5(home, "Applications")] : [],
311
504
  onPath: () => whichAll("t3"),
312
505
  ...stored ? { stored } : {}
313
506
  };
@@ -328,9 +521,9 @@ function bundleBinaries(appDir) {
328
521
  return [];
329
522
  }
330
523
  return bundles.flatMap((bundle) => {
331
- const root = join4(appDir, bundle);
524
+ const root = join5(appDir, bundle);
332
525
  try {
333
- return readdirSync2(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join4(root, rel)).filter(isExecutable);
526
+ return readdirSync2(root, { recursive: true }).filter((rel) => rel === "t3" || rel.endsWith("/t3")).map((rel) => join5(root, rel)).filter(isExecutable);
334
527
  } catch {
335
528
  return [];
336
529
  }
@@ -339,8 +532,8 @@ function bundleBinaries(appDir) {
339
532
  function t3Candidates(serverVersion, sources) {
340
533
  const ordered = [
341
534
  sources.env.T3_BIN,
342
- join4(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
343
- join4(sources.env.T3CODE_HOME || join4(sources.home, ".t3"), "bin", "t3"),
535
+ join5(sources.home, ".t3", "runtime", "versions", serverVersion, "t3"),
536
+ join5(sources.env.T3CODE_HOME || join5(sources.home, ".t3"), "bin", "t3"),
344
537
  ...sources.appDirs.flatMap(bundleBinaries),
345
538
  ...sources.onPath(),
346
539
  sources.stored
@@ -562,7 +755,7 @@ function parseFrames(data) {
562
755
  import { execFile, execFileSync as execFileSync3 } from "child_process";
563
756
  import { randomUUID } from "crypto";
564
757
  import { existsSync as existsSync2 } from "fs";
565
- import { join as join6 } from "path";
758
+ import { join as join7 } from "path";
566
759
 
567
760
  // ../clo0p-app/contracts/run-result.ts
568
761
  var WIZARD_STEPS_MAX = 6;
@@ -706,10 +899,6 @@ function droppedLine(dropped, run2) {
706
899
  return dropped.outputs || dropped.checks ? `result_items_dropped run=${run2} outputs=${dropped.outputs} checks=${dropped.checks}` : null;
707
900
  }
708
901
 
709
- // src/drivers/attachments.ts
710
- import { mkdir, writeFile } from "fs/promises";
711
- import { join as join5 } from "path";
712
-
713
902
  // ../clo0p-app/contracts/work-spec.ts
714
903
  var IMAGE_TYPES = {
715
904
  "image/jpeg": "jpg",
@@ -722,8 +911,14 @@ function isImageType(type) {
722
911
  }
723
912
  var IMAGE_MAX_BYTES = 10 * 1024 * 1024;
724
913
  var ATTACHMENTS_MAX = 8;
914
+ function repoName(repository) {
915
+ const name = repository?.trim().toLowerCase().split("/").filter(Boolean).at(-1);
916
+ return name || null;
917
+ }
725
918
 
726
919
  // src/drivers/attachments.ts
920
+ import { mkdir, writeFile } from "fs/promises";
921
+ import { join as join6 } from "path";
727
922
  var FETCH_BUDGET_MS = 1e4;
728
923
  function parseAttachments(value) {
729
924
  if (!Array.isArray(value)) return void 0;
@@ -782,7 +977,7 @@ async function saveImages(images, dir) {
782
977
  await mkdir(dir, { recursive: true, mode: 448 });
783
978
  return Promise.all(
784
979
  images.map(async (image) => {
785
- const path = join5(dir, image.name);
980
+ const path = join6(dir, image.name);
786
981
  await writeFile(path, image.data, { mode: 384 });
787
982
  return path;
788
983
  })
@@ -1203,6 +1398,7 @@ function isChild(t) {
1203
1398
  }
1204
1399
  var SESSIONS_TTL_MS = 5 * 6e4;
1205
1400
  var STATUS_TTL_MS = 3e4;
1401
+ var REPOS_TTL_MS = 10 * 6e4;
1206
1402
  var TERMINAL_RUN = /* @__PURE__ */ new Set(["completed", "interrupted", "failed", "cancelled", "rolled_back"]);
1207
1403
  var STOPPED_IN_T3 = "You stopped this in T3.";
1208
1404
  var IDLE_SETTLE_MS = 20 * 6e4;
@@ -1266,6 +1462,8 @@ function steerableRun(p) {
1266
1462
  }
1267
1463
  var STEER_WAIT_MS = 8e3;
1268
1464
  var STEER_POLL_MS = 500;
1465
+ var ASKS_READ_MAX = 8;
1466
+ var START_WAIT_MS = 5e3;
1269
1467
  function outcomeOf(p) {
1270
1468
  const run2 = latestRun(p.runs ?? []);
1271
1469
  const status = run2?.status ?? "pending";
@@ -1343,20 +1541,23 @@ function providerHarness(instanceId, cfg) {
1343
1541
  const id = p?.driver ?? instanceId;
1344
1542
  return { harness: PROVIDER_HARNESS[id] ?? id };
1345
1543
  }
1544
+ function projectNames(p) {
1545
+ const names = [p.title, p.workspaceRoot.split("/").at(-1), p.repositoryIdentity?.displayName];
1546
+ return [...new Set(names.filter((name) => Boolean(name)))];
1547
+ }
1548
+ function isRepository(p) {
1549
+ return Boolean(p.repositoryIdentity) || existsSync2(join7(p.workspaceRoot, ".git"));
1550
+ }
1346
1551
  function pickProject(projects, repository) {
1347
1552
  if (!repository) {
1348
- const repos = projects.filter(
1349
- (p) => p.repositoryIdentity || existsSync2(join6(p.workspaceRoot, ".git"))
1350
- );
1553
+ const repos = projects.filter(isRepository);
1351
1554
  const pool = repos.length > 0 ? repos : projects;
1352
1555
  const only = pool.length === 1 ? pool[0] : void 0;
1353
1556
  if (only) return only;
1354
1557
  throw new BoxToolError("no_project");
1355
1558
  }
1356
- const want = repository.toLowerCase();
1357
- const found = projects.find(
1358
- (p) => p.title.toLowerCase() === want || p.workspaceRoot.split("/").at(-1)?.toLowerCase() === want || p.repositoryIdentity?.displayName?.toLowerCase() === want
1359
- );
1559
+ const want = repoName(repository);
1560
+ const found = projects.find((p) => projectNames(p).some((name) => repoName(name) === want));
1360
1561
  if (!found) throw new BoxToolError("no_project");
1361
1562
  return found;
1362
1563
  }
@@ -1470,6 +1671,16 @@ var T3Driver = class {
1470
1671
  }
1471
1672
  return cache.value ? Promise.resolve(cache.value) : cache.refreshing;
1472
1673
  }
1674
+ reposRead = null;
1675
+ /** The checkouts' projects, by every name `pickProject` matches. */
1676
+ async checkouts() {
1677
+ if (this.reposRead && this.now() - this.reposRead.at < REPOS_TTL_MS)
1678
+ return this.reposRead.names;
1679
+ const [, shell] = await this.readT3State();
1680
+ const names = [...new Set((shell.projects ?? []).filter(isRepository).flatMap(projectNames))];
1681
+ if (names.length) this.reposRead = { names, at: this.now() };
1682
+ return names;
1683
+ }
1473
1684
  async status() {
1474
1685
  const [cfg, shell] = await this.readT3State();
1475
1686
  const sessions = this.listSessions();
@@ -1543,14 +1754,48 @@ var T3Driver = class {
1543
1754
  const shell = await this.t3.http("/api/orchestration/shell", SHELL_HEADERS);
1544
1755
  const all = (shell.threads ?? []).filter((t) => !isChild(t));
1545
1756
  const threads = scope === "all" ? all : all.filter(isUnsettled);
1757
+ const listed = orderThreads(threads, limit);
1758
+ const asks = await this.asksOf(listed);
1546
1759
  return {
1547
1760
  scope,
1548
1761
  unsettled: all.filter(isUnsettled).length,
1549
1762
  settled: all.length - all.filter(isUnsettled).length,
1550
1763
  running: threads.filter((t) => t.status === "running").length,
1551
- threads: orderThreads(threads, limit).map(threadView)
1764
+ threads: listed.map((t) => {
1765
+ const view = threadView(t);
1766
+ const waiting = asks.get(t.id);
1767
+ return waiting?.length ? { ...view, asks: waiting } : view;
1768
+ })
1552
1769
  };
1553
1770
  }
1771
+ /**
1772
+ * The questions each listed thread waits on, in the words the owner reads.
1773
+ * The shell names a thread's pending request but not its words, so the
1774
+ * projection is read only for a thread the shell says waits, or, from a T3
1775
+ * that names none, for a running one. A run that ended waits on nothing.
1776
+ */
1777
+ async asksOf(threads) {
1778
+ const waiting = threads.filter(
1779
+ (t) => !TERMINAL_RUN.has(t.status) && (t.pendingRuntimeRequest === void 0 ? t.status === "running" : Boolean(t.pendingRuntimeRequest))
1780
+ ).slice(0, ASKS_READ_MAX);
1781
+ const read = await Promise.all(
1782
+ waiting.map(async (t) => {
1783
+ try {
1784
+ const pending = pendingQuestions(await this.readProjection(t.id));
1785
+ return [
1786
+ t.id,
1787
+ pending.map((q) => ({ question_id: q.request_id, question: questionText(q) }))
1788
+ ];
1789
+ } catch (err) {
1790
+ this.log(
1791
+ `asks read failed thread=${t.id}: ${err instanceof Error ? err.message : String(err)}`
1792
+ );
1793
+ return [t.id, []];
1794
+ }
1795
+ })
1796
+ );
1797
+ return new Map(read);
1798
+ }
1554
1799
  /**
1555
1800
  * `work_id` is T3's `commandId`, so a second launch of the same work returns
1556
1801
  * the same thread with `resumed: true` and runs nothing twice. The worktree
@@ -1601,7 +1846,10 @@ var T3Driver = class {
1601
1846
  type: "worktree",
1602
1847
  baseRef: this.baseRefFor(project.workspaceRoot)
1603
1848
  },
1849
+ // Stored images belong to the thread their ids name, so the thread takes that id.
1850
+ ...photos2.attachments.length ? { threadId: a.work_id } : {},
1604
1851
  initialMessage: {
1852
+ ...photos2.attachments.length ? { messageId: a.work_id } : {},
1605
1853
  text: [a.prompt, photos2.line, RESULT_INSTRUCTION].filter(Boolean).join("\n\n"),
1606
1854
  attachments: photos2.attachments
1607
1855
  }
@@ -1626,27 +1874,35 @@ var T3Driver = class {
1626
1874
  resumed: launched.resumed,
1627
1875
  permission,
1628
1876
  ...providerHarness(modelSelection.instanceId, cfg),
1877
+ repository: project.repositoryIdentity?.displayName ?? project.workspaceRoot.split("/").at(-1) ?? project.title,
1629
1878
  // A resumed thread kept its first message: these photos did not go in.
1630
1879
  ...launched.resumed ? {} : delivery(a.attachments, photos2.attachments.length)
1631
1880
  };
1632
1881
  }
1633
- /** The Task's photos as T3 image attachments, which T3 shows in the thread and hands its harness. */
1882
+ /**
1883
+ * The Task's photos, stored in T3 as image attachments, which T3 shows in the
1884
+ * thread and hands its harness. The work_id is the thread and message id, so a
1885
+ * retried launch stores the same bytes under the same ids.
1886
+ */
1634
1887
  async photos(a) {
1635
1888
  if (!a.attachments?.length) return { attachments: [], line: "" };
1636
1889
  const { images, missed } = await fetchImages(a.attachments, {
1637
1890
  log: (line) => this.log(`${line} work=${a.work_id}`)
1638
1891
  });
1639
1892
  this.log(`attachments work=${a.work_id} attached=${images.length} missed=${missed}`);
1640
- return {
1893
+ if (!images.length) return { attachments: [], line: attachedLine(0, missed) };
1894
+ const stored = await this.t3.rpc("assets.persistChatAttachments", {
1895
+ threadId: a.work_id,
1896
+ messageId: a.work_id,
1641
1897
  attachments: images.map((image) => ({
1642
1898
  type: "image",
1643
1899
  name: image.name,
1644
- mimeType: image.type,
1900
+ mimeType: image.type.toLowerCase(),
1645
1901
  sizeBytes: image.data.length,
1646
- dataUrl: `data:${image.type};base64,${image.data.toString("base64")}`
1647
- })),
1648
- line: attachedLine(images.length, missed)
1649
- };
1902
+ dataUrl: `data:${image.type.toLowerCase()};base64,${image.data.toString("base64")}`
1903
+ }))
1904
+ });
1905
+ return { attachments: stored.attachments, line: attachedLine(images.length, missed) };
1650
1906
  }
1651
1907
  /**
1652
1908
  * Say something to a thread. While the thread waits on a question, only
@@ -1698,6 +1954,7 @@ var T3Driver = class {
1698
1954
  const active = activeRun(p.runs ?? []);
1699
1955
  if (!active && !a.resume && this.deps.watched?.({ thread_id: a.thread_id })?.settled)
1700
1956
  throw new BoxToolError("already_finished");
1957
+ const before = latestRun(p.runs ?? [])?.id;
1701
1958
  const receipt = await this.dispatch({
1702
1959
  type: "message.dispatch",
1703
1960
  commandId: a.command_id,
@@ -1709,8 +1966,17 @@ var T3Driver = class {
1709
1966
  createdBy: "user",
1710
1967
  creationSource: "mcp"
1711
1968
  });
1969
+ if (!active && (a.resume || a.work_id)) await this.untilNewRun(a.thread_id, before);
1712
1970
  return { sequence: receipt.sequence, delivered: steer ? "steer" : active ? "queue" : "start" };
1713
1971
  }
1972
+ async untilNewRun(threadId, before) {
1973
+ for (let waited = 0; waited < START_WAIT_MS; waited += STEER_POLL_MS) {
1974
+ const latest = latestRun((await this.readProjection(threadId)).runs ?? []);
1975
+ if (latest && latest.id !== before) return;
1976
+ await sleep(STEER_POLL_MS);
1977
+ }
1978
+ this.log(`new turn not seen thread=${threadId} after ${START_WAIT_MS} ms; watching on`);
1979
+ }
1714
1980
  /**
1715
1981
  * Stop the running turn. A thread with nothing running answers
1716
1982
  * `was_running: false`, and so does a run that ended while the interrupt
@@ -2181,8 +2447,8 @@ ${RESULT_INSTRUCTION}`
2181
2447
  import { execFile as execFile2, execFileSync as execFileSync4, spawn } from "child_process";
2182
2448
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync2 } from "fs";
2183
2449
  import { hostname } from "os";
2184
- import { basename, dirname as dirname3, join as join7 } from "path";
2185
- import { createInterface } from "readline";
2450
+ import { basename, dirname as dirname4, join as join8 } from "path";
2451
+ import { createInterface as createInterface2 } from "readline";
2186
2452
 
2187
2453
  // src/drivers/harness-check.ts
2188
2454
  var HARNESS_STALE_MS = 5 * 6e4;
@@ -2231,6 +2497,7 @@ var STOPPED = { kind: "failed", summary: STOPPED_SUMMARY };
2231
2497
  function takeoverSummary(machine) {
2232
2498
  return `You took this over on ${machine}.`;
2233
2499
  }
2500
+ var ADOPT_QUIET_MS = 2 * 6e4;
2234
2501
  var CONTINUE_PROMPT = "Continue the work from where you stopped. If it is already done, say so in one sentence.";
2235
2502
  var SHARED_BRANCHES = /* @__PURE__ */ new Set(["staging", "main", "master", "HEAD"]);
2236
2503
  var COMMANDS_KEPT = 50;
@@ -2261,16 +2528,16 @@ function failedEnd(harness, run2) {
2261
2528
  return { summary: `${lead}${quoted}"`, ...error };
2262
2529
  }
2263
2530
  function localRunsFilePath(env) {
2264
- return runnerPath(env, process.env.CLOOP_LOCAL_RUNS_FILE, (dir) => join7(dir, "local-runs.json"));
2531
+ return runnerPath(env, process.env.CLOOP_LOCAL_RUNS_FILE, (dir) => join8(dir, "local-runs.json"));
2265
2532
  }
2266
2533
  function pickRepo(repos, repository) {
2267
2534
  if (!repository) {
2268
2535
  if (repos.length === 1 && repos[0]) return repos[0];
2269
2536
  throw new BoxToolError("no_project");
2270
2537
  }
2271
- const want = repository.toLowerCase().split("/").at(-1) ?? "";
2538
+ const want = repoName(repository);
2272
2539
  const found = repos.find(
2273
- (r) => r.label.toLowerCase() === want || basename(r.path).toLowerCase() === want
2540
+ (r) => repoName(r.label) === want || repoName(basename(r.path)) === want
2274
2541
  );
2275
2542
  if (!found) throw new BoxToolError("no_project");
2276
2543
  return found;
@@ -2389,6 +2656,10 @@ var LocalDriver = class {
2389
2656
  warmHarnesses() {
2390
2657
  void this.harnessCheck.refresh().then(() => this.status()).catch((err) => this.log(`usage warm failed: ${err?.message}`));
2391
2658
  }
2659
+ /** Its repository folders, by label and folder name, the names `pickRepo` matches. */
2660
+ async checkouts() {
2661
+ return [...new Set(this.deps.repos.flatMap((r) => [r.label, basename(r.path)]))];
2662
+ }
2392
2663
  async status() {
2393
2664
  const { harnesses, checkedAt, probing } = await this.harnessCheck.read();
2394
2665
  const all = [...this.runs.values()];
@@ -2420,22 +2691,95 @@ var LocalDriver = class {
2420
2691
  }) {
2421
2692
  const all = [...this.runs.values()];
2422
2693
  const unsettled = all.filter((r) => !r.end);
2423
- const shown = (scope === "all" ? all : unsettled).map((r) => ({
2424
- id: r.work_id,
2425
- title: r.title,
2426
- status: this.statusOf(r),
2427
- branch: null,
2428
- source: "cloop",
2429
- cloop: true,
2430
- settled: Boolean(r.end),
2431
- updatedAt: r.end?.at ?? r.started_at
2432
- }));
2694
+ const shown = (scope === "all" ? all : unsettled).map((r) => {
2695
+ const asks = this.lives.get(r.work_id)?.asks ?? [];
2696
+ return {
2697
+ id: r.work_id,
2698
+ title: r.title,
2699
+ status: this.statusOf(r),
2700
+ branch: null,
2701
+ source: r.adopted ? this.dialectOf(r).name : "cloop",
2702
+ cloop: !r.adopted,
2703
+ settled: Boolean(r.end),
2704
+ updatedAt: r.end?.at ?? r.started_at,
2705
+ ...asks.length ? { asks: asks.map((a) => ({ question_id: a.request_id, question: a.summary })) } : {}
2706
+ };
2707
+ });
2433
2708
  return {
2434
2709
  scope,
2435
2710
  unsettled: unsettled.length,
2436
2711
  settled: all.length - unsettled.length,
2437
2712
  running: shown.filter((t) => t.status === "running").length,
2438
- threads: orderThreads(shown, limit)
2713
+ threads: orderThreads([...shown, ...await this.ownSessions()], limit)
2714
+ };
2715
+ }
2716
+ /**
2717
+ * The owner's own Claude Code and Codex sessions on this machine, the ones
2718
+ * Cloop did not start, so a thread id from this list can be steered. Each
2719
+ * is idle: a send resumes it.
2720
+ */
2721
+ async ownSessions() {
2722
+ const known = new Set(
2723
+ [...this.runs.values()].flatMap((r) => [r.work_id, ...r.session_id ? [r.session_id] : []])
2724
+ );
2725
+ const roots = this.deps.sessions ?? sessionRoots();
2726
+ const harnesses = this.sessionHarnesses();
2727
+ const [claude, codex] = await Promise.all([
2728
+ harnesses.includes("claude-code") ? listOutsideSessions(roots.claude, known) : [],
2729
+ harnesses.includes("codex") ? listCodexSessions(roots.codex, known) : []
2730
+ ]);
2731
+ const view = (source) => (t) => ({
2732
+ id: t.id,
2733
+ title: t.title ?? t.project ?? "Untitled session",
2734
+ status: t.status,
2735
+ branch: null,
2736
+ source,
2737
+ cloop: false,
2738
+ settled: false,
2739
+ updatedAt: t.updatedAt
2740
+ });
2741
+ return [...claude.map(view("claude-code")), ...codex.map(view("codex"))];
2742
+ }
2743
+ sessionHarnesses() {
2744
+ return [this.deps.dialect, this.deps.fallbackHarness].flatMap(
2745
+ (d) => d && (d.name === "claude-code" || d.name === "codex") ? [d.name] : []
2746
+ );
2747
+ }
2748
+ /**
2749
+ * A session the owner started outside Cloop, as a run, the first time Cloop
2750
+ * sends it something. It keeps its own harness and folder, and a send
2751
+ * resumes it there. Not registered here: the send that takes it does that.
2752
+ */
2753
+ async adopt(id) {
2754
+ const found = await findSession(
2755
+ id,
2756
+ this.deps.sessions ?? sessionRoots(),
2757
+ this.sessionHarnesses()
2758
+ );
2759
+ if (!found) throw new BoxToolError("bad_args");
2760
+ if (!found.cwd) throw new BoxToolError("no_project");
2761
+ const age = this.now() - found.mtime;
2762
+ if (age < ADOPT_QUIET_MS) {
2763
+ this.log(`adopt refused work=${id} reason=thread_busy age_ms=${Math.round(age)}`);
2764
+ throw new BoxToolError("thread_busy");
2765
+ }
2766
+ this.refuseBusy(found.cwd);
2767
+ const head = await this.repo.head(found.cwd).catch(() => null);
2768
+ const raced = this.runs.get(id);
2769
+ if (raced) return raced;
2770
+ this.log(`adopt work=${id} harness=${found.harness}`);
2771
+ return {
2772
+ work_id: id,
2773
+ session_id: id,
2774
+ repo: found.cwd,
2775
+ title: found.title ?? "Your session",
2776
+ // A move to the other harness would leave the owner's session behind.
2777
+ harness_named: true,
2778
+ ...found.harness !== this.deps.dialect.name ? { harness: found.harness } : {},
2779
+ adopted: true,
2780
+ pid: null,
2781
+ started_at: new Date(this.now()).toISOString(),
2782
+ head_at_launch: head
2439
2783
  };
2440
2784
  }
2441
2785
  async readThread(id) {
@@ -2504,13 +2848,14 @@ ${photos2.line}` : a.prompt,
2504
2848
  permission: record.used_permission,
2505
2849
  takeover: true,
2506
2850
  harness: dialect.name,
2851
+ repository: basename(repo.path),
2507
2852
  ...delivery(a.attachments, photos2.paths.length)
2508
2853
  };
2509
2854
  }
2510
2855
  async send(a) {
2511
- const r = this.record(a.thread_id);
2512
- const seen = r.commands?.find(([id]) => id === a.command_id);
2513
- if (seen) return { delivered: seen[1] };
2856
+ const r = this.runs.get(a.thread_id) ?? await this.adopt(a.thread_id);
2857
+ const seen2 = r.commands?.find(([id]) => id === a.command_id);
2858
+ if (seen2) return { delivered: seen2[1] };
2514
2859
  const live = this.lives.get(r.work_id);
2515
2860
  const ask = live?.asks[0];
2516
2861
  if (a.answer && (!ask || ask.request_id !== a.question_id)) {
@@ -2546,6 +2891,7 @@ ${photos2.line}` : a.prompt,
2546
2891
  r.end = void 0;
2547
2892
  r.last_text = void 0;
2548
2893
  }
2894
+ this.runs.set(r.work_id, r);
2549
2895
  this.spawnRun(r, a.text, true);
2550
2896
  this.remember(r, a.command_id, "start");
2551
2897
  return { delivered: "start" };
@@ -2681,7 +3027,7 @@ ${a.text}` : a.text;
2681
3027
  const { images, missed } = await fetchImages(a.attachments, { log });
2682
3028
  const paths = await saveImages(
2683
3029
  images,
2684
- join7(dirname3(this.file), "attachments", a.work_id)
3030
+ join8(dirname4(this.file), "attachments", a.work_id)
2685
3031
  ).catch((err) => {
2686
3032
  log(`attachments_unsaved reason=${err.message.slice(0, 120)}`);
2687
3033
  return [];
@@ -2752,7 +3098,7 @@ ${RESULT_INSTRUCTION}`, images));
2752
3098
  child.stderr?.on("data", (chunk) => {
2753
3099
  live.stderr = (live.stderr + chunk.toString("utf-8")).slice(-2e3);
2754
3100
  });
2755
- const lines = createInterface({ input: child.stdout });
3101
+ const lines = createInterface2({ input: child.stdout });
2756
3102
  lines.on("line", (line) => {
2757
3103
  for (const item of dialect.parse(line, r)) this.onItem(r, live, item);
2758
3104
  });
@@ -3020,7 +3366,7 @@ ${RESULT_INSTRUCTION}`, images));
3020
3366
  return readRunRecords(this.file).filter((r) => !(r.end && Date.parse(r.end.at) < cutoff));
3021
3367
  }
3022
3368
  save() {
3023
- mkdirSync3(dirname3(this.file), { recursive: true, mode: 448 });
3369
+ mkdirSync3(dirname4(this.file), { recursive: true, mode: 448 });
3024
3370
  const tmp = `${this.file}.tmp`;
3025
3371
  writeFileSync2(tmp, `${JSON.stringify([...this.runs.values()], null, 2)}
3026
3372
  `, { mode: 384 });
@@ -3070,16 +3416,17 @@ export {
3070
3416
  otherThreadsChoice,
3071
3417
  readRunnerConfig,
3072
3418
  writeBoxConfig,
3419
+ IMAGE_TYPES,
3073
3420
  runLogDir,
3074
3421
  runLogPath,
3075
3422
  redactSecrets,
3076
3423
  STOPPED_SUMMARY,
3077
3424
  isEndLogLine,
3425
+ listOutsideSessions,
3078
3426
  commandFor,
3079
3427
  quoteWindowsArg,
3080
3428
  windowsExecutable,
3081
3429
  windowsPowerShellEnv,
3082
- IMAGE_TYPES,
3083
3430
  parseAttachments,
3084
3431
  fetchImages,
3085
3432
  delivery,