gcf-board 0.28.1 → 0.30.0

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.
@@ -4,8 +4,8 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>GCF board</title>
7
- <script type="module" crossorigin src="/assets/index-UBIHpB-m.js"></script>
8
- <link rel="stylesheet" crossorigin href="/assets/index-BHNTx9zd.css">
7
+ <script type="module" crossorigin src="/assets/index-zKctM0qB.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/index-BhGhi45o.css">
9
9
  </head>
10
10
  <body>
11
11
  <div id="root"></div>
@@ -229,7 +229,7 @@ export const claude = {
229
229
  * What a session runs on when neither it nor the project picks (Board-PRD decision 36): aliases,
230
230
  * never versions, so the machine's or the account's default never decides.
231
231
  */
232
- defaults: { model: 'opus', effort: 'high' },
232
+ defaults: { model: 'opus', effort: 'medium' },
233
233
  /** The flags of a picked model and effort (`{model?, effort?}`, plain words). */
234
234
  pickFlags: (pick) => PICKS.flatMap((k) => (pick?.[k] ? [`--${k} ${pick[k]}`] : [])).join(' '),
235
235
  /** The env a session adds: the guards read the session's own checkout. */
@@ -0,0 +1,137 @@
1
+ // The Codex CLI as a reviewer (Operator-Tasks-Plan t2 d4): its model catalog (`codex debug models`,
2
+ // codex 0.167; it refreshes from the network, `--bundled` does not), the families a review row
3
+ // names (`sol`, `terra`, `luna`, `astra`), the newest listed slug of a family, and the presets a
4
+ // settings screen offers: no list is written into GCF, the catalog says.
5
+ import { spawnSync } from 'node:child_process';
6
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ /** How long a catalog read is kept: the families change with a Codex release, not by the hour. */
10
+ export const CATALOG_MAX_AGE_MS = 6 * 3_600_000;
11
+
12
+ /**
13
+ * `{exe, pre, shell}` of the Codex CLI: GCF_CODEX (a JSON list, a test's fake) or `codex`; the
14
+ * Windows `codex.cmd` needs a shell.
15
+ */
16
+ export function codexCommand() {
17
+ if (process.env.GCF_CODEX) {
18
+ const [exe, ...pre] = JSON.parse(process.env.GCF_CODEX);
19
+
20
+ return { exe, pre, shell: false };
21
+ }
22
+
23
+ return { exe: 'codex', pre: [], shell: process.platform === 'win32' };
24
+ }
25
+
26
+ /** Whether the Codex CLI answers `--version`. */
27
+ export function codexInstalled(cmd = codexCommand()) {
28
+ const r = spawnSync(cmd.exe, [...cmd.pre, '--version'], {
29
+ windowsHide: true,
30
+ encoding: 'utf8',
31
+ shell: cmd.shell,
32
+ timeout: 20_000,
33
+ });
34
+
35
+ return !r.error && r.status === 0;
36
+ }
37
+
38
+ /**
39
+ * The catalog's listed models: `{slug, family, version, priority, efforts}`. Read live, else the
40
+ * bundled one; `cache` (a file) keeps a read for CATALOG_MAX_AGE_MS. Null when Codex gives none.
41
+ * @param {{cache?: string, cmd?: ReturnType<typeof codexCommand>}} [o]
42
+ */
43
+ export function codexModels({ cache, cmd = codexCommand() } = {}) {
44
+ const kept = cache && fresh(cache) ? parse(readFileSync(cache, 'utf8')) : null;
45
+ if (kept) return kept;
46
+ for (const args of [[], ['--bundled']]) {
47
+ const r = spawnSync(cmd.exe, [...cmd.pre, 'debug', 'models', ...args], {
48
+ windowsHide: true,
49
+ encoding: 'utf8',
50
+ shell: cmd.shell,
51
+ timeout: 60_000,
52
+ maxBuffer: 64 << 20,
53
+ });
54
+ const models = r.status === 0 ? parse(r.stdout) : null;
55
+ if (!models) continue;
56
+ if (cache) {
57
+ mkdirSync(path.dirname(cache), { recursive: true });
58
+ writeFileSync(cache, r.stdout);
59
+ }
60
+
61
+ return models;
62
+ }
63
+
64
+ return null;
65
+ }
66
+
67
+ const fresh = (file) =>
68
+ existsSync(file) && Date.now() - statSync(file).mtimeMs < CATALOG_MAX_AGE_MS;
69
+
70
+ /** A slug's family and version: `gpt-6.1-sol` is sol 6.1; a slug of no such form, none. */
71
+ export function familyOf(slug) {
72
+ const m = /^[a-z]+-(\d+(?:\.\d+)*)-([a-z]+)$/.exec(String(slug));
73
+
74
+ return m ? { family: m[2], version: m[1].split('.').map(Number) } : null;
75
+ }
76
+
77
+ /** The listed models of a catalog's JSON (`{models: [...]}`), or null when it is none. */
78
+ function parse(text) {
79
+ try {
80
+ const list = JSON.parse(text)?.models;
81
+ if (!Array.isArray(list)) return null;
82
+
83
+ return list
84
+ .filter((m) => m?.visibility === 'list' && typeof m.slug === 'string')
85
+ .map((m) => ({
86
+ slug: m.slug,
87
+ ...(familyOf(m.slug) ?? { family: m.slug, version: [] }),
88
+ priority: Number(m.priority ?? 0),
89
+ efforts: (m.supported_reasoning_levels ?? []).map((l) => String(l?.effort ?? l)),
90
+ }));
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ const newer = (a, b) => {
97
+ for (let i = 0; i < Math.max(a.length, b.length); i++)
98
+ if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
99
+
100
+ return false;
101
+ };
102
+
103
+ /**
104
+ * The slug a row's model names: a family's newest listed slug, a full slug as it is; null when
105
+ * the catalog lists no such family.
106
+ * @param {ReturnType<typeof parse>} models
107
+ * @param {string} model
108
+ */
109
+ export function slugOf(models, model) {
110
+ if (!models) return familyOf(model) ? model : null;
111
+ if (models.some((m) => m.slug === model)) return model;
112
+ const of = models.filter((m) => m.family === model);
113
+
114
+ return (
115
+ of.reduce(
116
+ (best, m) => (!best || newer(m.version, best.version) ? m : best),
117
+ /** @type {any} */ (null),
118
+ )?.slug ?? null
119
+ );
120
+ }
121
+
122
+ /**
123
+ * What a review row offers for Codex: its families, the catalog's order, each with its newest
124
+ * slug and the efforts it takes.
125
+ * @param {ReturnType<typeof parse>} models
126
+ */
127
+ export function codexPresets(models) {
128
+ const families = [
129
+ ...new Set([...(models ?? [])].sort((a, b) => a.priority - b.priority).map((m) => m.family)),
130
+ ];
131
+
132
+ return families.map((family) => {
133
+ const slug = /** @type {string} */ (slugOf(models, family));
134
+
135
+ return { model: family, slug, efforts: models?.find((m) => m.slug === slug)?.efforts ?? [] };
136
+ });
137
+ }
@@ -70,13 +70,26 @@ function chatState(runs, id, lockFor) {
70
70
 
71
71
  const lines = text.split('\n').filter(Boolean);
72
72
  for (let i = lines.length - 1; i >= 0; i--) {
73
- const type = /"type":"(session|session_end|limit)"/.exec(lines[i])?.[1];
73
+ const type = /"type":"(session|session_end|limit|limit_end)"/.exec(lines[i])?.[1];
74
+ if (type === 'limit_end') return endedWait(lines[i]);
74
75
  if (type) return type;
75
76
  }
76
77
 
77
78
  return null;
78
79
  }
79
80
 
81
+ /**
82
+ * A wait's end (`limit_end`, t1 d2): the clock or a wake starts the session now, which reads the
83
+ * input, as during the wait; a stop or a Hold ends the run.
84
+ */
85
+ function endedWait(line) {
86
+ try {
87
+ return /^(stop|hold)$/.test(JSON.parse(line).by) ? 'session_end' : 'limit';
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+
80
93
  /**
81
94
  * Whether item `id` has a live chat session: a run that lives drives it, and its chat's last
82
95
  * session event is a start, not an end; or the run waits for the limit's reset, and the session
@@ -1095,9 +1095,21 @@ function closeChat(c, code, seen) {
1095
1095
  export function drainChat(logs, id, input) {
1096
1096
  const { lines, next } = readFrom(chatIn(logs, id), input.at);
1097
1097
  input.at = next;
1098
- for (const l of lines)
1098
+ for (const l of lines) {
1099
+ const e = parse(l);
1099
1100
  postTo(chatOut(logs, id), {
1100
1101
  type: 'error',
1101
- text: `the item's session has ended, not sent: ${l.slice(0, 80)}`,
1102
+ // Its id: the page drops that very bubble and offers its text back (t1 d7).
1103
+ ...(e?.id ? { id: e.id } : {}),
1104
+ text: `the item's session has ended, not sent: ${unsent(e, l)}`,
1102
1105
  });
1106
+ }
1107
+ }
1108
+
1109
+ /** An unsent input line in the operator's words: a message's text, else its kind; raw if bad. */
1110
+ function unsent(e, line) {
1111
+ if (!e?.type) return line.slice(0, 80);
1112
+ if (typeof e.text === 'string') return e.text.slice(0, 80);
1113
+
1114
+ return e.type;
1103
1115
  }
@@ -3,12 +3,13 @@
3
3
  // idles out, the operator stops it, or it ends. The center starts it detached, through its relay,
4
4
  // when a message comes in and no session of the thread lives. It prints nothing: what happens is
5
5
  // in the thread's files. A second open of a live thread finds its lock held and leaves at once;
6
- // `.gcf-session/chats/<t>/stop` stops it.
6
+ // `.gcf-session/chats/<t>/stop` stops it; `chats/<t>/wake` ends its usage-limit wait early.
7
7
  import { existsSync, readFileSync, rmSync } from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { claim } from './lock.js';
10
10
  import { stopWithSessions } from './proc.js';
11
11
  import { THREAD_ID, runThread, threadDir } from './thread.js';
12
+ import { usageCommand, wakeWatch } from './wake.js';
12
13
 
13
14
  // The threads this process runs: its own lock does not hold it off a second time.
14
15
  const opened = new Set();
@@ -30,10 +31,14 @@ export async function open(dir, t) {
30
31
  // shortcut: a stop the board writes between the claim and this removal is lost (a window of
31
32
  // milliseconds); the page's "closing…" gives up after 15 s, and the operator closes again.
32
33
  rmSync(stop, { force: true });
34
+ const mark = path.join(td, 'wake');
35
+ rmSync(mark, { force: true });
33
36
  const unhook = stopWithSessions();
34
37
  try {
35
38
  const spec = JSON.parse(readFileSync(path.join(td, 'spec.json'), 'utf8'));
36
- await runThread(dir, t, spec, { stopped: () => existsSync(stop) });
39
+ // The thread has no reserve watch: its wait asks `/usage` itself (t1 d1).
40
+ const wake = wakeWatch({ mark, model: spec.agent, command: usageCommand(spec.agent) });
41
+ await runThread(dir, t, spec, { stopped: () => existsSync(stop), wake });
37
42
 
38
43
  return true;
39
44
  } finally {
@@ -32,6 +32,14 @@ export { addCost, beyond } from './cost.js';
32
32
  export { claim, clearDead, create, dead } from './lock.js';
33
33
  export { WIN, alive, byLine, killTree, sessions, spawnAgent, stopWithSessions } from './proc.js';
34
34
  export { adapterFor, defaultsOf, presetsOf, raw } from './adapter/index.js';
35
+ export {
36
+ codexCommand,
37
+ codexInstalled,
38
+ codexModels,
39
+ codexPresets,
40
+ familyOf,
41
+ slugOf,
42
+ } from './adapter/codex.js';
35
43
  export {
36
44
  NO_SESSION,
37
45
  PICKS,
@@ -60,6 +68,7 @@ export {
60
68
  threadOfEntry,
61
69
  } from './thread.js';
62
70
  export { writeAtomic } from './store.js';
71
+ export { lastWaitEvent, threadWaits, usageCommand, wakeThread, wakeWatch } from './wake.js';
63
72
  export {
64
73
  RESERVE_PCT,
65
74
  USAGE_MAX_AGE_MS,
@@ -67,6 +76,7 @@ export {
67
76
  askUsageOnce,
68
77
  gcfHome,
69
78
  lastReading,
79
+ limitBack,
70
80
  limitsOf,
71
81
  readUsage,
72
82
  reasonOf,
@@ -47,9 +47,12 @@ const AFTER_MS = 10 * 60_000;
47
47
  * @property {(ran: any, kind: string) => void} [onSession] a session ended: its result
48
48
  * @property {(n: number) => void} [onHandoff] the `n`th fresh session is about to start
49
49
  * @property {(ran: any, ask: Ask) => Promise<any>} [afterSession] the turn after a session
50
- * @property {(now: number) => Gate | Promise<Gate>} [beforeSession] the gate before each
51
- * session (Hold-Plan d7): `{go}`, `{wait, until, reserve?}` (a usage-limit reset still ahead,
52
- * AD-19, or the quota's reserve) or `{stop, why}`; a Date is a wait, null a go
50
+ * @property {(now: number, o: {woke: 'operator' | 'usage' | null}) => Gate | Promise<Gate>}
51
+ * [beforeSession] the gate before each session (Hold-Plan d7): `{go}`, `{wait, until,
52
+ * reserve?, pct?}` (a usage-limit reset still ahead, AD-19, or the quota's reserve) or `{stop,
53
+ * why}`; a Date is a wait, null a go. `woke`: the wait before it ended early (t1 d3), so the
54
+ * last quota state is still the cut session's
55
+ * @property {import('./wake.js').Wake} [wake] what ends a limit wait early (t1 d1)
53
56
  * @property {() => string | null} [hold] why the work is to stop now, its sessions handing over
54
57
  * (`hold`, `reserve`): a live session is flagged, a wait ends
55
58
  * @property {(state: any) => void | Promise<void>} [persist] keep the work's record before a
@@ -70,7 +73,8 @@ const AFTER_MS = 10 * 60_000;
70
73
  /** @typedef {(prompt: string, opts?: {timeoutMs?: number}) => Promise<any>} Ask */
71
74
 
72
75
  /**
73
- * @typedef {{go: true} | {wait: true, until: Date, reserve?: boolean} | {stop: true, why: string}
76
+ * @typedef {{go: true} | {wait: true, until: Date, reserve?: boolean, pct?: number, keep?: number}
77
+ * | {stop: true, why: string}
74
78
  * | Date | null | undefined} Gate
75
79
  */
76
80
 
@@ -130,19 +134,73 @@ function first(j, kind, rec) {
130
134
  * a run killed meanwhile resumes the same session; then the chat's `limit {until}`. The wait is
131
135
  * not the job's: the deadline moves by as much. Resolves `reset`, `stopped`, or null when the
132
136
  * job does not wait (the week's window, an unknown reset, too far, the item's third limit).
137
+ * `reserve`: the quota's reserve waits, its window at `pct` (t1 d5).
138
+ * @param {any} j
139
+ * @param {{at: any, weekly: boolean}} reset
140
+ * @param {any} state
141
+ * `keep` is the reserve's own percent: a reading under it wakes the wait (Codex review of t1).
142
+ * @param {{reserve?: boolean, pct?: number, keep?: number}} [o]
133
143
  */
134
- async function limitWait(j, reset, state, { reserve = false } = {}) {
144
+ async function limitWait(j, reset, state, { reserve = false, pct, keep = 0 } = {}) {
135
145
  const { p } = j;
136
146
  const clock = p.clock ?? realClock;
137
147
  if (!counted(j, reset, clock.now(), reserve)) return null;
138
148
  const until = new Date(reset.at.getTime() + MARGIN_MS);
139
- await p.persist?.({ ...state, limit: { ...state.limit, at: reset.at.toISOString() } });
140
- tellWait(p, until);
149
+ // Before the record: a mark written as the last wait ended would end this one (t1 d2).
150
+ // `keep` comes with the reserve's wait only: a limit's wait wakes under 100%.
151
+ p.wake?.begin({ now: clock.now(), until, pct: keep, usage: !j.usageOff });
152
+ const limit = { ...state.limit, at: reset.at.toISOString(), ...(reserve ? { reserve } : {}) };
153
+ await p.persist?.({ ...state, ...inputAt(p), limit });
154
+ tellWait(p, until, reserve ? { reserve, pct } : {});
155
+ const { ok, by } = await sleepTill(j, until, clock);
156
+ if (ok === 'woke') wokeEarly(j, by, reserve ? null : reset, clock.now());
157
+ tellEnd(p, endOf(p, ok, by));
158
+
159
+ return awake(p, ok, state);
160
+ }
161
+
162
+ /** The wait itself: the job's deadline moves by its time. Resolves `waitUntil`'s and the wake. */
163
+ async function sleepTill(j, until, clock) {
164
+ const { p } = j;
141
165
  const t0 = clock.now();
142
- const ok = await waitUntil(until.getTime(), () => Boolean(p.stopped?.() || heldNow(p)), clock);
166
+ let by = null;
167
+ const ok = await waitUntil(
168
+ until.getTime(),
169
+ () => Boolean(p.stopped?.() || heldNow(p)),
170
+ clock,
171
+ () => (by = p.wake?.by(clock.now()) ?? null),
172
+ );
173
+ p.wake?.end();
143
174
  j.deadline += clock.now() - t0;
144
175
 
145
- return awake(p, ok, state);
176
+ return { ok, by };
177
+ }
178
+
179
+ /** What ended a wait (`limit_end.by`): the wake, the clock, the stop or the Hold. */
180
+ const endOf = (p, ok, by) => (ok === 'woke' ? by : ok ? 'clock' : p.stopped?.() ? 'stop' : 'hold');
181
+
182
+ /** Where the operator's unread input starts: a run killed in the wait hands it on (t1 d6). */
183
+ const inputAt = (p) =>
184
+ p.chat && typeof p.chat === 'object' && p.chat.input ? { chat_in_at: p.chat.input.at } : {};
185
+
186
+ /**
187
+ * A wait the operator's mark or `/usage` ended (t1 d3): before the limit's reset it spends no
188
+ * try (`reset` null for the reserve's, which spends none), and the next gate knows the quota
189
+ * state is the cut session's.
190
+ */
191
+ function wokeEarly(j, by, reset, now) {
192
+ j.woke = by;
193
+ if (reset && now < reset.at.getTime()) j.waits--;
194
+ try {
195
+ writeSync(j.p.fd, `[${hhmmss()}] limit: back early (${by})\n`);
196
+ } catch {
197
+ // A log that cannot be written loses its line, not the wake.
198
+ }
199
+ }
200
+
201
+ /** The wait's end in the chat (`limit_end {by}`): the feed drops its wait at once (t1 d2). */
202
+ function tellEnd(p, by) {
203
+ if (p.chat) postTo(p.chatFile ?? chatOut(p.logs, p.id), { type: 'limit_end', by });
146
204
  }
147
205
 
148
206
  /**
@@ -166,13 +224,18 @@ function counted(j, reset, now, reserve) {
166
224
  return true;
167
225
  }
168
226
 
169
- /** The wait, in the chat (`limit {until}`) and the log. */
170
- function tellWait(p, until) {
227
+ /** The wait, in the chat (`limit {until, reserve?, pct?}`: the reserve's, t1 d5) and the log. */
228
+ function tellWait(p, until, more) {
171
229
  if (p.chat)
172
- postTo(p.chatFile ?? chatOut(p.logs, p.id), { type: 'limit', until: until.toISOString() });
230
+ postTo(p.chatFile ?? chatOut(p.logs, p.id), {
231
+ type: 'limit',
232
+ until: until.toISOString(),
233
+ ...more,
234
+ });
173
235
  try {
174
236
  const at = until.toTimeString().slice(0, 5);
175
- writeSync(p.fd, `[${hhmmss()}] limit: waits for the reset, goes on at ${at}\n`);
237
+ const what = more.reserve ? `reserve${more.pct ? ` (quota at ${more.pct}%)` : ''}` : 'limit';
238
+ writeSync(p.fd, `[${hhmmss()}] ${what}: waits for the reset, goes on at ${at}\n`);
176
239
  } catch {
177
240
  // A log that cannot be written loses its line, not the wait.
178
241
  }
@@ -205,12 +268,16 @@ function decisionOf(d) {
205
268
  async function gate(j, kind, rec) {
206
269
  const holding = heldNow(j.p);
207
270
  if (holding) return { held: holding };
208
- const d = decisionOf(await j.p.beforeSession?.((j.p.clock ?? realClock).now()));
271
+ const d = decisionOf(await j.p.beforeSession?.((j.p.clock ?? realClock).now(), { woke: j.woke }));
209
272
  if ('stop' in d && d.stop) return { held: d.why };
210
273
  if (!('wait' in d) || !d.wait) return true;
211
274
  const reserve = Boolean(d.reserve);
212
275
  const reset = { at: d.until, weekly: false };
213
- const waited = await limitWait(j, reset, waitState(j, kind, rec), { reserve });
276
+ const waited = await limitWait(j, reset, waitState(j, kind, rec), {
277
+ reserve,
278
+ pct: d.pct,
279
+ keep: d.keep,
280
+ });
214
281
  if (waited === 'held') return { held: /** @type {string} */ (heldNow(j.p)) };
215
282
  if (waited === 'stopped') return { stopped: true };
216
283
 
@@ -257,6 +324,8 @@ async function session(j, kind, rec) {
257
324
  const env = typeof p.env === 'function' ? await p.env(kind) : p.env;
258
325
  // The after-session turn resumes this session: it runs with its env.
259
326
  j.env = env;
327
+ const woke = j.woke;
328
+ j.woke = null;
260
329
  const ran = await runSession({
261
330
  ...common(p, kind),
262
331
  env,
@@ -271,12 +340,18 @@ async function session(j, kind, rec) {
271
340
  chat: typeof p.chat === 'function' ? p.chat(kind, rec) : p.chat && { ...p.chat, kind },
272
341
  });
273
342
  j.deadline += ran.waited;
343
+ usageMissed(j, woke, ran);
274
344
  const done = await settled(p, ran, watch);
275
345
  p.onSession?.(done, kind);
276
346
 
277
347
  return done;
278
348
  }
279
349
 
350
+ /** A wake by `/usage` that met the limit again: no more such wakes this job (t1 d3). */
351
+ function usageMissed(j, woke, ran) {
352
+ if (woke === 'usage' && ran.limit) j.usageOff = true;
353
+ }
354
+
280
355
  /** After a session: its flag cleared, no session named, its window kept, its watch's result. */
281
356
  async function settled(p, ran, watch) {
282
357
  p.handoff?.clear?.();
@@ -390,6 +465,9 @@ export async function runJob(p) {
390
465
  deadline: Date.now() + p.timeoutMs,
391
466
  waits: 0,
392
467
  reserveWaits: 0,
468
+ // What ended the last wait early, till the next session starts; `/usage` wakes off (t1 d3).
469
+ woke: null,
470
+ usageOff: false,
393
471
  after: Boolean(p.afterSession) && p.adapter.caps.resume,
394
472
  };
395
473
  const kind = firstKind(p);
@@ -8,8 +8,8 @@ export const MARGIN_MS = 60_000;
8
8
  /** Past this the run does not wait: it ends paused, as before. */
9
9
  export const MAX_WAIT_MS = 6 * 3_600_000;
10
10
 
11
- /** How often the wait reads the wall clock and the stop mark. */
12
- export const POLL_MS = 30_000;
11
+ /** How often the wait reads the clock, the stop mark and its wake: a button answers at once. */
12
+ export const POLL_MS = 1_000;
13
13
 
14
14
  /** The waits one item gets in a run: its next limit ends it paused. */
15
15
  export const MAX_WAITS = 2;
@@ -116,15 +116,19 @@ export const waitsFor = (reset, waits, now) =>
116
116
  /** @type {Date} */ (reset.at).getTime() + MARGIN_MS - now <= MAX_WAIT_MS;
117
117
 
118
118
  /**
119
- * Wait until `until` (ms), reading the wall clock and `stopped()` each `POLL_MS`: a PC that
120
- * slept wakes past it. Resolves true at the time, false at a stop.
119
+ * Wait until `until` (ms), reading the wall clock, `stopped()` and `woke()` each `POLL_MS`: a PC
120
+ * that slept wakes past it. Resolves true at the time, false at a stop, `'woke'` when `woke()`
121
+ * said so first (Operator-Tasks-Plan t1 d2); a stop is stronger than a wake.
121
122
  * @param {number} until
122
123
  * @param {() => boolean} stopped
123
124
  * @param {{now: () => number, sleep: (ms: number) => Promise<unknown>}} [clock]
125
+ * @param {() => unknown} [woke]
126
+ * @returns {Promise<boolean | 'woke'>}
124
127
  */
125
- export async function waitUntil(until, stopped, clock = realClock) {
128
+ export async function waitUntil(until, stopped, clock = realClock, woke = () => false) {
126
129
  while (clock.now() < until) {
127
130
  if (stopped()) return false;
131
+ if (woke()) return 'woke';
128
132
  await clock.sleep(Math.min(POLL_MS, until - clock.now()));
129
133
  }
130
134
 
@@ -359,17 +359,17 @@ function flagsOf({ dir, td, spec, adapter }, settings) {
359
359
  * `answerMin`, `handoffPct`, `window`, `skill`, `mainLock`, `yolo` (a file: present, the engine
360
360
  * allows each call with no card, AD-54), `timeoutMin`, `pick` (the project's
361
361
  * model and effort, under the thread's own, over the agent's defaults). `stopped()` says the
362
- * operator stopped it.
363
- * @param {{stopped?: () => boolean}} [opts]
362
+ * operator stopped it; `wake` ends a limit wait early (t1 d1).
363
+ * @param {{stopped?: () => boolean, wake?: import('./wake.js').Wake}} [opts]
364
364
  */
365
365
  export async function runThread(dir, t, spec, opts = {}) {
366
- const { stopped = () => false } = opts;
366
+ const { stopped = () => false, wake } = opts;
367
367
  const td = threadDir(dir, t);
368
368
  const rec = readThread(dir, t);
369
369
  const adapter = adapterFor(spec.agent);
370
370
  const last = rec.sessions.at(-1) ?? null;
371
371
  const s = {
372
- ...{ dir, t, td, rec, spec, adapter, stopped },
372
+ ...{ dir, t, td, rec, spec, adapter, stopped, wake },
373
373
  flags: flagsOf({ dir, td, spec, adapter }, settingsOf(td, adapter, spec.rules)),
374
374
  // The model and effort of the session starting now: read afresh for each (agent.json).
375
375
  pick: {},
@@ -605,6 +605,7 @@ function jobOf(s, record) {
605
605
  return s.flags(kind, s.summary, s.pick);
606
606
  },
607
607
  stopped: s.stopped,
608
+ wake: s.wake,
608
609
  halt: true,
609
610
  clock: stopClock,
610
611
  chatFile: path.join(s.td, 'chat.jsonl'),
@@ -253,7 +253,7 @@ const scopedTo = (limit, model) => {
253
253
  };
254
254
 
255
255
  /**
256
- * @typedef {{go: true} | {wait: true, until: Date, reserve: true}
256
+ * @typedef {{go: true} | {wait: true, until: Date, reserve: true, pct?: number, keep?: number}
257
257
  * | {stop: true, why: string, reserve: {weekly?: boolean, until?: string | null}}} Reserve
258
258
  */
259
259
 
@@ -271,8 +271,9 @@ export const reserveOfReading = (reading, model, pct, now = Date.now()) =>
271
271
 
272
272
  /**
273
273
  * The reserve's gate (Hold-Plan d10) over the limits: the 5-hour window at `100 - pct` or more
274
- * waits for its reset (`{wait, until, reserve}`); the week's, all models or the run's, or a reset
275
- * past the longest wait, stops (`{stop, why: 'reserve', reserve}`); else `{go}`. No limits: go.
274
+ * waits for its reset (`{wait, until, reserve, pct, keep}`: `pct` the window's percent, `keep`
275
+ * the reserve's); the week's, all models or the run's, or a reset past the longest wait, stops
276
+ * (`{stop, why: 'reserve', reserve}`); else `{go}`. No limits: go.
276
277
  * @param {any[] | null | undefined} limits
277
278
  * @param {string | null | undefined} model
278
279
  * @param {number} pct
@@ -295,5 +296,19 @@ export function reserveOf(limits, model, pct, now = Date.now()) {
295
296
  if (!until || Number.isNaN(until.getTime()) || until.getTime() - now > MAX_WAIT_MS)
296
297
  return { stop: true, why: 'reserve', reserve: { until: session.resets_at ?? null } };
297
298
 
298
- return { wait: true, until, reserve: true };
299
+ return { wait: true, until, reserve: true, pct: session.percent, keep: pct };
299
300
  }
301
+
302
+ /**
303
+ * Whether a reading taken since `since` (ms) says the limit is back (Operator-Tasks-Plan t1 d1):
304
+ * not failed, with windows, and under `pct`'s reserve (0: the limit itself). An empty list of
305
+ * windows says nothing.
306
+ * @param {any} reading
307
+ * @param {number} since
308
+ * @param {{model?: string | null, pct?: number, now?: number}} [o]
309
+ */
310
+ export const limitBack = (reading, since, { model = null, pct = 0, now = Date.now() } = {}) =>
311
+ Boolean(reading?.limits?.length) &&
312
+ !reading.failed &&
313
+ Date.parse(reading.at) >= since &&
314
+ 'go' in reserveOf(reading.limits, model, pct, now);