@cloop/runner 0.3.42 → 0.3.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  serveTakeovers
4
- } from "./chunk-TSUDGSA2.js";
5
- import "./chunk-3N4X2TK2.js";
4
+ } from "./chunk-PUDWLT5C.js";
5
+ import "./chunk-KG2RA3FJ.js";
6
6
  import {
7
7
  CAPTURE_TICK_MS,
8
8
  DEFAULT_FALLBACK_MODEL,
@@ -19,6 +19,7 @@ import {
19
19
  cmdWord,
20
20
  codexDialect,
21
21
  codexHome,
22
+ codexModels,
22
23
  connectCommand,
23
24
  findNpx,
24
25
  installedService,
@@ -38,7 +39,7 @@ import {
38
39
  systemServices,
39
40
  unitFor,
40
41
  which
41
- } from "./chunk-JW5GATBV.js";
42
+ } from "./chunk-HHNLRNOM.js";
42
43
  import {
43
44
  MeshSocket,
44
45
  WAKE_TICK_MS,
@@ -56,7 +57,7 @@ import {
56
57
  runnerStatePath,
57
58
  threadsFilePath,
58
59
  writeRunnerState
59
- } from "./chunk-PN5CQQVG.js";
60
+ } from "./chunk-UXMDNJ3O.js";
60
61
  import {
61
62
  BackgroundReading,
62
63
  BoxToolError,
@@ -83,12 +84,16 @@ import {
83
84
  isLocal,
84
85
  isT3,
85
86
  listOutsideSessions,
87
+ nextModel,
86
88
  nextProgress,
87
89
  orderThreads,
88
90
  quotaFromClaude,
89
91
  quotaFromCodex,
90
92
  readRunResult,
91
93
  readRunnerConfig,
94
+ refusedModel,
95
+ refusedModelLine,
96
+ refusedRecently,
92
97
  resultPrUrl,
93
98
  resultText,
94
99
  runnerDir,
@@ -101,20 +106,20 @@ import {
101
106
  utcWindow,
102
107
  windowsPowerShellEnv,
103
108
  writeBoxConfig
104
- } from "./chunk-NP5VVHLS.js";
109
+ } from "./chunk-RRRV64ZB.js";
105
110
  import "./chunk-VK6GV757.js";
106
111
  import {
107
112
  olderThan
108
113
  } from "./chunk-365HFCQQ.js";
109
114
  import "./chunk-PKIEWBR7.js";
110
- import "./chunk-OXFFDL26.js";
111
- import "./chunk-QOYGTYFE.js";
115
+ import "./chunk-L763FCD7.js";
116
+ import "./chunk-EPWLBMCR.js";
112
117
  import {
113
118
  getMachine
114
119
  } from "./chunk-SBYSVZ7J.js";
115
120
  import {
116
121
  VERSION
117
- } from "./chunk-7B53CL3W.js";
122
+ } from "./chunk-AAHVP23O.js";
118
123
  import {
119
124
  getMeshUrl,
120
125
  getOrigin,
@@ -125,7 +130,7 @@ import {
125
130
 
126
131
  // src/commands/box.ts
127
132
  import { homedir as homedir3 } from "os";
128
- import { join as join6 } from "path";
133
+ import { dirname as dirname3, join as join6 } from "path";
129
134
 
130
135
  // src/cloudroom-core.ts
131
136
  var CoreError = class extends Error {
@@ -353,7 +358,8 @@ function sseRecord(block) {
353
358
 
354
359
  // src/drivers/cloudroom.ts
355
360
  import { createHash } from "crypto";
356
- import { join as join2 } from "path";
361
+ import { chmodSync, mkdirSync as mkdirSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
362
+ import { basename, dirname, join as join2 } from "path";
357
363
 
358
364
  // src/drivers/cloudroom-repos.ts
359
365
  import { execFile, spawn } from "child_process";
@@ -536,6 +542,11 @@ function coreRequestId(kind, id) {
536
542
  return REQUEST_ID.test(plain) ? plain : `${kind}-${createHash("sha256").update(id).digest("hex").slice(0, 40)}`;
537
543
  }
538
544
  var CLOOP_SESSION_PREFIX = "cr_cloop-";
545
+ var MOVES_MAX = 16;
546
+ function movedSessionId(thread, n) {
547
+ const id = `${thread.replace(/^cr_/, "")}-m${n}`;
548
+ return `cr_${REQUEST_ID.test(id) ? id : coreRequestId("cloop", id)}`;
549
+ }
539
550
  function ownerName(repository) {
540
551
  const path = repository.trim().replace(/^(https?:\/\/|git@)github\.com[/:]/i, "").replace(/\.git$/i, "").replace(/\/+$/, "");
541
552
  return /^[\w-][\w.-]*\/[\w-][\w.-]*$/.test(path) ? path : null;
@@ -765,11 +776,91 @@ var sleep = (ms) => new Promise((resolve) => {
765
776
  const timer = setTimeout(resolve, ms);
766
777
  timer.unref?.();
767
778
  });
779
+ function pickModel(fresh, kept, skipped) {
780
+ if (fresh?.length)
781
+ return { model: nextModel(fresh, skipped), source: "fresh", catalog: fresh.length };
782
+ if (kept?.models.length)
783
+ return { model: nextModel(kept.models, skipped), source: "stale", catalog: kept.models.length };
784
+ return { model: null, source: "none", catalog: 0 };
785
+ }
786
+ async function within(value, ms) {
787
+ let timer;
788
+ const late = new Promise((resolve) => {
789
+ timer = setTimeout(() => resolve(null), ms);
790
+ });
791
+ return Promise.race([value, late]).finally(() => clearTimeout(timer));
792
+ }
793
+ async function boxModel(o) {
794
+ const kept = o.store.load();
795
+ const fresh = await within(
796
+ o.models().catch(() => []),
797
+ o.waitMs
798
+ );
799
+ const skipped = refusedRecently(kept.refused, o.now);
800
+ return { ...pickModel(fresh, kept.catalog, skipped), skipped };
801
+ }
802
+ var RUN_MODEL_KEEP_MS = 7 * 24 * 36e5;
803
+ function fileRunModels(file) {
804
+ return {
805
+ load() {
806
+ let raw;
807
+ try {
808
+ raw = JSON.parse(readFileSync(file, "utf-8"));
809
+ } catch {
810
+ return { runs: [], refused: [] };
811
+ }
812
+ const kept = Array.isArray(raw) ? { runs: raw } : raw ?? {};
813
+ const list = (v) => Array.isArray(v) ? v : [];
814
+ return {
815
+ runs: list(kept.runs).filter(
816
+ (r) => typeof r?.thread === "string"
817
+ ),
818
+ refused: list(kept.refused).filter(
819
+ (r) => typeof r?.model === "string" && typeof r?.at === "string"
820
+ ),
821
+ ...kept.catalog && typeof kept.catalog.at === "string" && Array.isArray(kept.catalog.models) ? {
822
+ catalog: {
823
+ at: kept.catalog.at,
824
+ models: kept.catalog.models.filter(
825
+ (m) => typeof m === "string"
826
+ )
827
+ }
828
+ } : {}
829
+ };
830
+ },
831
+ save(models) {
832
+ mkdirSync2(dirname(file), { recursive: true, mode: 448 });
833
+ const tmp = `${file}.tmp`;
834
+ writeFileSync(tmp, `${JSON.stringify(models, null, 2)}
835
+ `, { mode: 384 });
836
+ chmodSync(tmp, 384);
837
+ renameSync2(tmp, file);
838
+ }
839
+ };
840
+ }
841
+ function opened(end, line) {
842
+ const told = (text = "") => text ? `${line}${end.kind === "failed" ? " " : "\n\n"}${text}`.slice(0, RUN_TEXT_MAX) : line;
843
+ return {
844
+ ...end,
845
+ summary: told(end.summary),
846
+ ...end.result ? { result: { ...end.result, summary: told(end.result.summary) } } : {}
847
+ };
848
+ }
768
849
  var ATTACHMENTS_ROOT = "/code/.attachments";
850
+ var CATALOG_MS = 6e4;
851
+ var PICK_WAIT_MS = 5e3;
769
852
  var CloudroomDriver = class {
770
853
  constructor(deps) {
771
854
  this.deps = deps;
772
855
  this.repos = deps.repos ?? new Repos();
856
+ const kept = deps.runModels?.load() ?? { runs: [], refused: [] };
857
+ const cutoff = this.now() - RUN_MODEL_KEEP_MS;
858
+ this.runModels = new Map(
859
+ kept.runs.filter((r) => !(r.ended_at && Date.parse(r.ended_at) < cutoff)).map((r) => [r.thread, r])
860
+ );
861
+ const live = new Set(refusedRecently(kept.refused, this.now()));
862
+ this.refusals = kept.refused.filter((r) => live.has(r.model));
863
+ this.kept = kept.catalog;
773
864
  }
774
865
  deps;
775
866
  name = "cloudroom";
@@ -777,8 +868,86 @@ var CloudroomDriver = class {
777
868
  repos;
778
869
  /** Repository runs still being prepared after launch answered, by thread. A failed one stays, for watch to report. */
779
870
  preparing = /* @__PURE__ */ new Map();
780
- /** Runs stopped while still being prepared. */
871
+ /** Runs stopped while still being prepared, or while moving off a refused model. */
781
872
  stopped = /* @__PURE__ */ new Set();
873
+ /** Runs' model facts, by thread, as the store keeps them. */
874
+ runModels;
875
+ /** The models the box's account refused, one entry per model, newest refusal. */
876
+ refusals;
877
+ /** The account's last list of models, kept for a launch whose list now is slow or empty. */
878
+ kept;
879
+ /** Runs looking for the next model, by thread. */
880
+ moving = /* @__PURE__ */ new Set();
881
+ /** The account's models, best first, while CATALOG_MS lasts. */
882
+ catalog = null;
883
+ /** The run's last move off a refused model, if it moved. */
884
+ movedOf(thread) {
885
+ const r = this.runModels.get(thread);
886
+ return r?.session && r.refused && r.switched ? { session: r.session, refused: r.refused, switched: r.switched } : void 0;
887
+ }
888
+ /** Changes the run's model facts and writes them. */
889
+ keep(thread, change) {
890
+ this.runModels.set(thread, { ...this.runModels.get(thread), ...change, thread });
891
+ this.save(`thread=${thread}`);
892
+ }
893
+ /** The account refused `model`: launches and moves skip it for MODEL_REFUSAL_MS. */
894
+ remember(model) {
895
+ const at = new Date(this.now()).toISOString();
896
+ this.refusals = [...this.refusals.filter((r) => r.model !== model), { model, at }];
897
+ this.save(`refused=${model}`);
898
+ }
899
+ /** A write that fails is logged: the run goes on. */
900
+ save(what) {
901
+ try {
902
+ this.deps.runModels?.save({
903
+ runs: [...this.runModels.values()],
904
+ refused: this.refusals,
905
+ ...this.kept ? { catalog: this.kept } : {}
906
+ });
907
+ } catch (err) {
908
+ this.log(`run models not saved ${what}: ${err instanceof Error ? err.message : String(err)}`);
909
+ }
910
+ }
911
+ /**
912
+ * The account's models, best first. A list that came back empty is not
913
+ * reused, so the next launch asks again. A list that names models is kept
914
+ * in the store, for a launch whose own list is slow or empty.
915
+ */
916
+ listModels() {
917
+ const lister = this.deps.models;
918
+ if (!lister) return Promise.resolve([]);
919
+ const now = this.now();
920
+ if (this.catalog && now - this.catalog.at < CATALOG_MS) return this.catalog.models;
921
+ const entry = { at: now, models: lister().catch(() => []) };
922
+ this.catalog = entry;
923
+ void entry.models.then((models) => {
924
+ if (!models.length) {
925
+ if (this.catalog === entry) this.catalog = null;
926
+ return;
927
+ }
928
+ this.kept = { models, at: new Date(this.now()).toISOString() };
929
+ this.save(`catalog=${models.length}`);
930
+ });
931
+ return entry.models;
932
+ }
933
+ /**
934
+ * The model a run whose Task named none starts on: the best the account
935
+ * lists that it has not refused within MODEL_REFUSAL_MS, so no model is
936
+ * fixed in the box. A list that is slow or empty gives way to the last
937
+ * one the account gave (pickModel). Only a box that never had a list
938
+ * leaves the model to core's default, which the box sets by the same rule
939
+ * at each start (`cloop box model`).
940
+ */
941
+ async pick(work) {
942
+ if (!this.deps.models) return void 0;
943
+ const fresh = await within(this.listModels(), this.deps.pickWaitMs ?? PICK_WAIT_MS);
944
+ const skipped = refusedRecently(this.refusals, this.now());
945
+ const { model, source, catalog } = pickModel(fresh, this.kept, skipped);
946
+ this.log(
947
+ `model work=${work} picked=${model ?? "default"} catalog=${source === "stale" ? `stale:${catalog}` : catalog} skipped=${skipped.join(",") || "none"}`
948
+ );
949
+ return model ?? void 0;
950
+ }
782
951
  get core() {
783
952
  return this.deps.core;
784
953
  }
@@ -791,6 +960,10 @@ var CloudroomDriver = class {
791
960
  log(line) {
792
961
  this.deps.log?.(line);
793
962
  }
963
+ /** The session that carries the thread's run now: the thread's own, or the last one a move off a refused model started. */
964
+ carrier(thread) {
965
+ return this.movedOf(thread)?.session ?? thread;
966
+ }
794
967
  async status() {
795
968
  const [harnesses, sessions] = await Promise.all([this.core.capabilities(), this.sessions()]);
796
969
  const running = sessions.filter(busy);
@@ -863,10 +1036,13 @@ var CloudroomDriver = class {
863
1036
  threads: shown
864
1037
  };
865
1038
  }
866
- async readThread(id) {
1039
+ async readThread(thread) {
1040
+ const id = this.carrier(thread);
867
1041
  const session = await this.session(id);
868
1042
  const fold = await this.history(id);
869
- const end = runEnd(fold, this.harness);
1043
+ const found = runEnd(fold, this.harness);
1044
+ const switched = found?.error === "interrupted" ? null : this.movedOf(thread)?.switched;
1045
+ const end = found && switched ? opened(found, switched) : found;
870
1046
  const last = fold.turns.filter((t) => !t.cancelled).at(-1);
871
1047
  return {
872
1048
  status: end ? end.kind === "settled" ? "completed" : end.error === "interrupted" ? "interrupted" : "failed" : busy(session) ? "running" : session.state,
@@ -891,6 +1067,8 @@ var CloudroomDriver = class {
891
1067
  const start = coreRequestId("cloop", a.work_id);
892
1068
  const thread = `cr_${start}`;
893
1069
  const prompt = coreRequestId("run", a.work_id);
1070
+ if (a.model && this.runModels.get(thread)?.named !== a.model)
1071
+ this.keep(thread, { named: a.model });
894
1072
  const place = placeFor(a);
895
1073
  let photos;
896
1074
  const photosOnce = async () => {
@@ -903,11 +1081,12 @@ var CloudroomDriver = class {
903
1081
  if (place.kind === "worktree") await this.repos.ensureClone(place);
904
1082
  if (this.stopped.has(thread)) throw STOPPED_IN_PREPARATION;
905
1083
  if (!existing2) {
1084
+ const model = a.model ?? await this.pick(a.work_id);
906
1085
  try {
907
1086
  await this.core.start({
908
1087
  request_id: start,
909
1088
  harness: this.harness,
910
- ...a.model ? { model: a.model } : {},
1089
+ ...model ? { model } : {},
911
1090
  workspace: place.workspace,
912
1091
  workspace_name: place.workspace_name
913
1092
  });
@@ -973,7 +1152,8 @@ var CloudroomDriver = class {
973
1152
  * removed when it ended clean, is made again before the text goes in.
974
1153
  */
975
1154
  async send(a) {
976
- const s = await this.session(a.thread_id);
1155
+ const id = this.carrier(a.thread_id);
1156
+ const s = await this.session(id);
977
1157
  if (a.answer) return { delivered: "question_changed", question: null, question_id: null };
978
1158
  const steer = coreRequestId("steer", a.command_id);
979
1159
  const queue = coreRequestId("send", a.command_id);
@@ -984,7 +1164,7 @@ var CloudroomDriver = class {
984
1164
  const deliver = async () => {
985
1165
  if (a.mode === "steer" && s.steer && s.current_request) {
986
1166
  try {
987
- await this.core.command(a.thread_id, "steer", {
1167
+ await this.core.command(id, "steer", {
988
1168
  request_id: steer,
989
1169
  target_request_id: s.current_request,
990
1170
  text: a.text
@@ -992,10 +1172,10 @@ var CloudroomDriver = class {
992
1172
  return { delivered: "steer" };
993
1173
  } catch (err) {
994
1174
  if (!(err instanceof CoreError && err.status === 409)) throw err;
995
- this.log(`steer missed its turn thread=${a.thread_id}; queued instead`);
1175
+ this.log(`steer missed its turn thread=${id}; queued instead`);
996
1176
  }
997
1177
  }
998
- await this.core.command(a.thread_id, "prompts", { request_id: queue, text: a.text });
1178
+ await this.core.command(id, "prompts", { request_id: queue, text: a.text });
999
1179
  return { delivered: running ? "queue" : "start" };
1000
1180
  };
1001
1181
  const tree = worktreeOf(s.workspace);
@@ -1065,7 +1245,12 @@ ${line}` : line;
1065
1245
  this.log(`interrupt thread=${id} during preparation`);
1066
1246
  return { ok: true, was_running: true };
1067
1247
  }
1068
- return this.stopRun(id, commandId);
1248
+ if (this.moving.has(id) && !this.stopped.has(id)) {
1249
+ this.stopped.add(id);
1250
+ this.log(`interrupt thread=${id} while moving model`);
1251
+ return { ok: true, was_running: true };
1252
+ }
1253
+ return this.stopRun(this.carrier(id), commandId);
1069
1254
  }
1070
1255
  async stopRun(id, commandId) {
1071
1256
  const s = await this.session(id);
@@ -1130,11 +1315,19 @@ ${line}` : line;
1130
1315
  * comes back to the run as a new turn. So an end other than a Stop waits
1131
1316
  * while a child works or a turn waits, and looks again every
1132
1317
  * CHILDREN_WAIT_MS in case a child ends without a reply.
1318
+ *
1319
+ * A run the account refused its model moves to a new session (moveModel)
1320
+ * and the watch follows that one under the same thread, from the run's
1321
+ * kept facts after a restart too.
1133
1322
  */
1134
1323
  watch(id, report) {
1135
- const onEvent = (event) => report(
1136
- event.kind === "settled" || event.kind === "failed" ? { ...event, harness: this.harness } : event
1137
- );
1324
+ const onEvent = (event) => {
1325
+ const ends = event.kind === "settled" || event.kind === "failed";
1326
+ if (ends && this.runModels.has(id))
1327
+ this.keep(id, { ended_at: new Date(this.now()).toISOString() });
1328
+ report(ends ? { ...event, harness: this.harness } : event);
1329
+ };
1330
+ let session = this.carrier(id);
1138
1331
  let fold = NEW_FOLD;
1139
1332
  let stopped = false;
1140
1333
  let live = null;
@@ -1144,7 +1337,23 @@ ${line}` : line;
1144
1337
  live?.abort();
1145
1338
  };
1146
1339
  const end = async (event) => {
1147
- if (event.error !== "interrupted" && await this.working(id)) {
1340
+ const refused = event.kind === "failed" && !event.error ? refusedModel(event.summary) : null;
1341
+ if (refused) {
1342
+ const move = await this.moveModel(id, session, refused);
1343
+ if (stopped) return;
1344
+ if (move === "stopped") {
1345
+ stop();
1346
+ onEvent({ kind: "failed", summary: STOPPED_SUMMARY, error: "interrupted" });
1347
+ return;
1348
+ }
1349
+ if (move) {
1350
+ session = move.session;
1351
+ fold = NEW_FOLD;
1352
+ live?.abort();
1353
+ return;
1354
+ }
1355
+ }
1356
+ if (event.error !== "interrupted" && await this.working(session)) {
1148
1357
  if (stopped) return;
1149
1358
  fold = { ...fold, ended: false };
1150
1359
  const wait = ++waits;
@@ -1157,10 +1366,12 @@ ${line}` : line;
1157
1366
  }
1158
1367
  if (stopped) return;
1159
1368
  stop();
1160
- onEvent(await this.tidy(id, event));
1369
+ const told = await this.tidy(session, event);
1370
+ const switched = told.error === "interrupted" ? null : this.movedOf(id)?.switched;
1371
+ onEvent(switched ? opened(told, switched) : told);
1161
1372
  };
1162
- const take = (records) => {
1163
- if (stopped || !records.length) return;
1373
+ const take = (from, records) => {
1374
+ if (stopped || from !== session || !records.length) return;
1164
1375
  const next = foldRecords(fold, records, {
1165
1376
  harness: this.harness,
1166
1377
  now: this.now(),
@@ -1186,26 +1397,29 @@ ${line}` : line;
1186
1397
  }
1187
1398
  let wait = this.deps.retryMs ?? RETRY_MIN_MS;
1188
1399
  while (!stopped) {
1400
+ const from = session;
1189
1401
  try {
1190
1402
  const missed = [];
1191
1403
  for (let after = fold.after; ; ) {
1192
- const page = await this.core.events(id, after);
1404
+ const page = await this.core.events(from, after);
1193
1405
  missed.push(...page);
1194
1406
  if (page.length < EVENTS_PAGE) break;
1195
1407
  after = page.at(-1)?.sequence ?? after;
1196
1408
  }
1197
- take(missed);
1409
+ take(from, missed);
1198
1410
  if (stopped) return;
1411
+ if (from !== session) continue;
1199
1412
  if (fold.start?.state === "completed" && !fold.turns.length && !this.preparing.has(id)) {
1200
1413
  stop();
1201
1414
  onEvent({ kind: "failed", summary: UNSENT_SUMMARY });
1202
1415
  return;
1203
1416
  }
1204
1417
  live = new AbortController();
1205
- await this.core.stream(id, fold.after, (r) => take([r]), live.signal);
1418
+ await this.core.stream(from, fold.after, (r) => take(from, [r]), live.signal);
1206
1419
  wait = this.deps.retryMs ?? RETRY_MIN_MS;
1207
1420
  } catch (err) {
1208
1421
  if (stopped) return;
1422
+ if (from !== session) continue;
1209
1423
  if (err instanceof CoreError && err.status === 404) {
1210
1424
  stop();
1211
1425
  onEvent({ kind: "failed", summary: GONE_SUMMARY });
@@ -1215,6 +1429,7 @@ ${line}` : line;
1215
1429
  `follow failed thread=${id}: ${err instanceof Error ? err.message : String(err)}; again in ${wait} ms`
1216
1430
  );
1217
1431
  }
1432
+ if (from !== session) continue;
1218
1433
  await sleep(wait);
1219
1434
  wait = Math.min(wait * 2, RETRY_MAX_MS);
1220
1435
  }
@@ -1222,6 +1437,78 @@ ${line}` : line;
1222
1437
  void follow();
1223
1438
  return stop;
1224
1439
  }
1440
+ /**
1441
+ * A model the account cannot use refuses the run before it does any work,
1442
+ * as a ChatGPT account without a paid plan refuses the model the box pins
1443
+ * (4 Nov 2026). The run starts again in a new session in the same folder,
1444
+ * with the same prompt, on the next model the account lists, best first,
1445
+ * until one takes it or the list runs out. It does not when the Task named
1446
+ * its model. Both facts are kept (RunModel), so they hold after a restart.
1447
+ * The new session and its prompt have ids made from the thread and the
1448
+ * move's number, so a move made again, by a runner that stopped before it
1449
+ * kept it, finds them in core and starts nothing twice. Null: the run
1450
+ * ends as it is. `stopped`: a Stop came while it looked.
1451
+ */
1452
+ async moveModel(thread, from, refused) {
1453
+ const prior = this.movedOf(thread);
1454
+ if (!this.deps.models) return null;
1455
+ this.remember(refused);
1456
+ if (this.runModels.get(thread)?.named && !prior) return null;
1457
+ const tried = [...prior?.refused ?? [], refused];
1458
+ if (tried.length > MOVES_MAX) return null;
1459
+ this.moving.add(thread);
1460
+ let move;
1461
+ try {
1462
+ const listed = await this.listModels();
1463
+ const skipped = [...tried, ...refusedRecently(this.refusals, this.now())];
1464
+ const { model: next, source, catalog } = pickModel(listed, this.kept, skipped);
1465
+ if (this.stopped.delete(thread)) return "stopped";
1466
+ if (!next) {
1467
+ this.log(
1468
+ `model thread=${thread} refused=${refused} next=none catalog=${source === "stale" ? `stale:${catalog}` : catalog}`
1469
+ );
1470
+ return null;
1471
+ }
1472
+ const was = await this.session(from);
1473
+ const text = Object.values(was.prompts)[0];
1474
+ if (!text || !was.workspace) return null;
1475
+ const session = movedSessionId(thread, tried.length);
1476
+ const request = session.slice("cr_".length);
1477
+ const prompt = coreRequestId("run", request);
1478
+ const existing = await this.core.session(session);
1479
+ if (!existing)
1480
+ await this.core.start({
1481
+ request_id: request,
1482
+ harness: this.harness,
1483
+ model: next,
1484
+ workspace: was.workspace,
1485
+ workspace_name: basename(was.workspace_path ?? was.workspace)
1486
+ });
1487
+ if (!existing?.receipts[prompt])
1488
+ await this.core.command(session, "prompts", { request_id: prompt, text });
1489
+ move = {
1490
+ session,
1491
+ refused: tried,
1492
+ switched: refusedModelLine(harnessFacts(this.harness).name, tried[0] ?? refused, next)
1493
+ };
1494
+ this.keep(thread, { ...move, ended_at: void 0 });
1495
+ this.log(`model thread=${thread} refused=${refused} next=${next} session=${session}`);
1496
+ } catch (err) {
1497
+ this.log(
1498
+ `model move failed thread=${thread}: ${err instanceof Error ? err.message : String(err)}`
1499
+ );
1500
+ return null;
1501
+ } finally {
1502
+ this.moving.delete(thread);
1503
+ }
1504
+ if (this.stopped.delete(thread))
1505
+ await this.stopRun(move.session, `moved-${move.session}`).catch(
1506
+ (err) => this.log(
1507
+ `interrupt after model move failed thread=${thread}: ${err instanceof Error ? err.message : String(err)}`
1508
+ )
1509
+ );
1510
+ return move;
1511
+ }
1225
1512
  /**
1226
1513
  * Refuse at once every child spawned without `--shared-sandbox`. Core
1227
1514
  * would run it here after 15 s anyway; the refusal makes the agent add
@@ -1748,9 +2035,9 @@ import { spawn as spawn3 } from "child_process";
1748
2035
  import {
1749
2036
  copyFileSync,
1750
2037
  existsSync as existsSync2,
1751
- mkdirSync as mkdirSync2,
2038
+ mkdirSync as mkdirSync3,
1752
2039
  mkdtempSync,
1753
- readFileSync,
2040
+ readFileSync as readFileSync2,
1754
2041
  readdirSync,
1755
2042
  realpathSync,
1756
2043
  rmSync as rmSync2,
@@ -1794,7 +2081,7 @@ function findSetup(home) {
1794
2081
  }
1795
2082
  function stage(setup) {
1796
2083
  const dir = mkdtempSync(join4(tmpdir2(), "cloop-setup-"));
1797
- mkdirSync2(join4(dir, ".agents", "skills"), { recursive: true });
2084
+ mkdirSync3(join4(dir, ".agents", "skills"), { recursive: true });
1798
2085
  for (const skill of setup.skills)
1799
2086
  symlinkSync(skill.path, join4(dir, ".agents", "skills", skill.name), "junction");
1800
2087
  if (setup.guide) copyFileSync(setup.guide, join4(dir, ".agents", "owner-guide.md"));
@@ -1952,7 +2239,7 @@ function remoteMcp(found) {
1952
2239
  }
1953
2240
  function readText(path) {
1954
2241
  try {
1955
- return readFileSync(path, "utf8");
2242
+ return readFileSync2(path, "utf8");
1956
2243
  } catch {
1957
2244
  return "";
1958
2245
  }
@@ -2137,15 +2424,15 @@ var T3Threads = class {
2137
2424
  import { execFile as execFile2, spawn as spawn4 } from "child_process";
2138
2425
  import {
2139
2426
  closeSync,
2140
- mkdirSync as mkdirSync3,
2427
+ mkdirSync as mkdirSync4,
2141
2428
  openSync,
2142
- readFileSync as readFileSync2,
2143
- renameSync as renameSync2,
2429
+ readFileSync as readFileSync3,
2430
+ renameSync as renameSync3,
2144
2431
  rmSync as rmSync3,
2145
- writeFileSync
2432
+ writeFileSync as writeFileSync2
2146
2433
  } from "fs";
2147
2434
  import { homedir as homedir2 } from "os";
2148
- import { dirname, join as join5 } from "path";
2435
+ import { dirname as dirname2, join as join5 } from "path";
2149
2436
  var REGISTRY_LATEST = "https://registry.npmjs.org/@cloop/runner/latest";
2150
2437
  var FIRST_CHECK_MS = 10 * 6e4;
2151
2438
  var CHECK_EVERY_MS = 6 * 36e5;
@@ -2192,7 +2479,7 @@ function statePath(env) {
2192
2479
  }
2193
2480
  function readFailed() {
2194
2481
  try {
2195
- const failed = JSON.parse(readFileSync2(statePath(), "utf-8")).failed;
2482
+ const failed = JSON.parse(readFileSync3(statePath(), "utf-8")).failed;
2196
2483
  return typeof failed === "string" ? failed : null;
2197
2484
  } catch {
2198
2485
  return null;
@@ -2200,11 +2487,11 @@ function readFailed() {
2200
2487
  }
2201
2488
  function recordFailed(version, env) {
2202
2489
  try {
2203
- mkdirSync3(updateDir(env), { recursive: true, mode: 448 });
2490
+ mkdirSync4(updateDir(env), { recursive: true, mode: 448 });
2204
2491
  const temp = `${statePath(env)}.${process.pid}.tmp`;
2205
- writeFileSync(temp, `${JSON.stringify({ failed: version })}
2492
+ writeFileSync2(temp, `${JSON.stringify({ failed: version })}
2206
2493
  `, { mode: 384 });
2207
- renameSync2(temp, statePath(env));
2494
+ renameSync3(temp, statePath(env));
2208
2495
  } catch (err) {
2209
2496
  log(`could not record ${version} as failed: ${err.code ?? err}`);
2210
2497
  }
@@ -2257,7 +2544,7 @@ function servicePath(kind, platform) {
2257
2544
  }
2258
2545
  function readText2(path) {
2259
2546
  try {
2260
- return readFileSync2(path, "utf-8");
2547
+ return readFileSync3(path, "utf-8");
2261
2548
  } catch {
2262
2549
  return null;
2263
2550
  }
@@ -2318,9 +2605,9 @@ function selfUpdate(kind, platform = process.platform, onFailed = () => {
2318
2605
  const [command, ...args] = handOverCommand(platform, npx, to, kind);
2319
2606
  let fd;
2320
2607
  try {
2321
- mkdirSync3(updateDir(), { recursive: true, mode: 448 });
2608
+ mkdirSync4(updateDir(), { recursive: true, mode: 448 });
2322
2609
  if (platform === "win32")
2323
- writeFileSync(adoptScriptPath(), adoptScript(npx, to, kind, updateLogPath()));
2610
+ writeFileSync2(adoptScriptPath(), adoptScript(npx, to, kind, updateLogPath()));
2324
2611
  fd = openSync(updateLogPath(), "a");
2325
2612
  } catch (err) {
2326
2613
  log(`could not open ${updateLogPath()}: ${err.code ?? err}`);
@@ -2406,8 +2693,8 @@ async function adopt(from, kind, { services: given, script = process.argv[1] ??
2406
2693
  let why;
2407
2694
  try {
2408
2695
  if (legacy) await moveLegacyStagingRunner(services);
2409
- mkdirSync3(dirname(unit.path), { recursive: true });
2410
- writeFileSync(unit.path, unit.contents);
2696
+ mkdirSync4(dirname2(unit.path), { recursive: true });
2697
+ writeFileSync2(unit.path, unit.contents);
2411
2698
  await runSteps(unit.start, run3);
2412
2699
  if (await services.awaitUp(since)) {
2413
2700
  log(`adopt ${from} -> ${VERSION}: up`);
@@ -2426,7 +2713,7 @@ async function adopt(from, kind, { services: given, script = process.argv[1] ??
2426
2713
  moveRunnerFiles(runnerDir(environment), runnerDir(was));
2427
2714
  }
2428
2715
  recordFailed(VERSION, was);
2429
- writeFileSync(back.path, old);
2716
+ writeFileSync2(back.path, old);
2430
2717
  await runSteps(back.start, run3);
2431
2718
  } catch (err) {
2432
2719
  log(
@@ -2569,6 +2856,10 @@ async function run2() {
2569
2856
  probes: { "claude-code": () => probeClaudeQuota(), codex: () => probeCodexQuota() },
2570
2857
  log: log2
2571
2858
  }),
2859
+ // The same account's catalog, for a run the account refuses its model.
2860
+ ...hosted.harness === "codex" ? { models: () => codexModels() } : {},
2861
+ // Beside the daemon's threads: the model a Task named, a run's move off a refused one, refusals and the last list.
2862
+ runModels: fileRunModels(hostedRunModelsPath(hosted.harness)),
2572
2863
  log: log2
2573
2864
  }) : local && (name === "claude-code" || name === "codex") ? await localDriver(local, name) : new T3Driver({
2574
2865
  client: () => t3.client,
@@ -2849,6 +3140,30 @@ async function run2() {
2849
3140
  await new Promise(() => {
2850
3141
  });
2851
3142
  }
3143
+ function hostedRunModelsPath(harness) {
3144
+ return join6(dirname3(hostedThreadsFilePath(harness)), "run-models.json");
3145
+ }
3146
+ var MODEL_WAIT_MS = 8e3;
3147
+ async function modelCommand(argv, deps = {}) {
3148
+ const harness = flag(argv, "--harness");
3149
+ const err = deps.err ?? ((line) => console.error(line));
3150
+ if (harness !== "codex") {
3151
+ err("Usage: cloop box model --harness codex");
3152
+ return 1;
3153
+ }
3154
+ const pick = await boxModel({
3155
+ models: deps.models ?? (() => codexModels()),
3156
+ store: fileRunModels(deps.file ?? hostedRunModelsPath(harness)),
3157
+ now: deps.now ?? Date.now(),
3158
+ waitMs: MODEL_WAIT_MS
3159
+ });
3160
+ err(
3161
+ `[cloop-box:model] harness=${harness} picked=${pick.model ?? "none"} source=${pick.source} catalog=${pick.catalog} skipped=${pick.skipped.join(",") || "none"}`
3162
+ );
3163
+ if (pick.model) (deps.out ?? ((line) => process.stdout.write(`${line}
3164
+ `)))(pick.model);
3165
+ return 0;
3166
+ }
2852
3167
  function flag(argv, name) {
2853
3168
  const i = argv.indexOf(name);
2854
3169
  return i >= 0 ? argv[i + 1] : void 0;
@@ -2873,9 +3188,12 @@ async function boxCommand(argv) {
2873
3188
  process.exit(await adopt(from, kind));
2874
3189
  break;
2875
3190
  }
3191
+ case "model":
3192
+ pinExistingRunner();
3193
+ process.exit(await modelCommand(argv.slice(1)));
2876
3194
  default:
2877
3195
  console.error(
2878
- "Usage: cloop box connect [--t3-url <url>] [--t3-bin <path>] [--no-service] | cloop box run"
3196
+ "Usage: cloop box connect [--t3-url <url>] [--t3-bin <path>] [--no-service] | cloop box run | cloop box model --harness codex"
2879
3197
  );
2880
3198
  process.exit(1);
2881
3199
  }
@@ -2885,8 +3203,10 @@ export {
2885
3203
  awaitNewDeviceToken,
2886
3204
  boxCommand,
2887
3205
  boxPresence,
3206
+ hostedRunModelsPath,
2888
3207
  localDriver,
2889
3208
  machineHarnesses,
3209
+ modelCommand,
2890
3210
  recordConnected,
2891
3211
  run2 as run,
2892
3212
  t3Presence