gcf-board 0.28.0 → 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.
Files changed (33) hide show
  1. package/README.md +3 -3
  2. package/dist/server/aif-entry.js +76 -0
  3. package/dist/server/app.js +60 -6
  4. package/dist/server/chat.js +61 -1
  5. package/dist/server/cli.js +23 -4
  6. package/dist/server/desktop.js +1 -0
  7. package/dist/server/moves.js +3 -2
  8. package/dist/server/reviewPresets.js +35 -0
  9. package/dist/server/runs.js +6 -3
  10. package/dist/server/talks.js +29 -11
  11. package/dist/shared/board.js +45 -0
  12. package/dist/web/assets/index-BhGhi45o.css +1 -0
  13. package/dist/web/assets/index-zKctM0qB.js +123 -0
  14. package/dist/web/index.html +2 -2
  15. package/node_modules/gcf-session/lib/adapter/claude.js +1 -1
  16. package/node_modules/gcf-session/lib/adapter/codex.js +137 -0
  17. package/node_modules/gcf-session/lib/chat-input.js +14 -1
  18. package/node_modules/gcf-session/lib/chat.js +36 -18
  19. package/node_modules/gcf-session/lib/cli.js +7 -2
  20. package/node_modules/gcf-session/lib/index.js +10 -0
  21. package/node_modules/gcf-session/lib/job.js +93 -15
  22. package/node_modules/gcf-session/lib/limit.js +9 -5
  23. package/node_modules/gcf-session/lib/proc.js +5 -1
  24. package/node_modules/gcf-session/lib/session.js +39 -19
  25. package/node_modules/gcf-session/lib/store.js +14 -9
  26. package/node_modules/gcf-session/lib/thread.js +14 -7
  27. package/node_modules/gcf-session/lib/usage.js +23 -5
  28. package/node_modules/gcf-session/lib/wake.js +141 -0
  29. package/node_modules/gcf-session/package.json +1 -1
  30. package/node_modules/gcf-session/types/index.d.ts +52 -2
  31. package/package.json +1 -1
  32. package/dist/web/assets/index-BCfiz95-.css +0 -1
  33. package/dist/web/assets/index-CcsKtA2D.js +0 -119
@@ -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-CcsKtA2D.js"></script>
8
- <link rel="stylesheet" crossorigin href="/assets/index-BCfiz95-.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
@@ -901,22 +901,7 @@ const SEEN = {
901
901
  };
902
902
 
903
903
  if (!taskGate(c, e, Date.now(), later)) return;
904
- const prompt = e.phase === 'start' ? e.prompt : null;
905
- post(c, {
906
- type: 'task',
907
- phase: e.phase,
908
- id: e.id,
909
- ...(e.kind ? { kind: e.kind } : {}),
910
- ...(e.agent ? { agent: e.agent } : {}),
911
- ...(e.description ? { description: cut(e.description, WHY_MAX) } : {}),
912
- ...(e.doing ? { doing: cut(e.doing, WHY_MAX) } : {}),
913
- ...(prompt ? { prompt: cut(prompt, TASK_PROMPT_MAX) } : {}),
914
- ...(e.calls !== null ? { calls: e.calls } : {}),
915
- ...(e.ms !== null ? { ms: e.ms } : {}),
916
- ...(e.status ? { status: e.status } : {}),
917
- ...(e.summary ? { summary: cut(e.summary, TASK_SUMMARY_MAX) } : {}),
918
- ...(e.background ? { background: true } : {}),
919
- });
904
+ post(c, taskCard(e));
920
905
  },
921
906
  // While they run, no answer is waited for; claude starts a turn itself as they end. Their end
922
907
  // with no new turn after the grace settles the session, so it is not held for good.
@@ -928,6 +913,27 @@ const SEEN = {
928
913
  },
929
914
  };
930
915
 
916
+ /** The chat's `task` event of a task event `e`: only the fields it has. */
917
+ function taskCard(e) {
918
+ const prompt = e.phase === 'start' ? e.prompt : null;
919
+
920
+ return {
921
+ type: 'task',
922
+ phase: e.phase,
923
+ id: e.id,
924
+ ...(e.kind ? { kind: e.kind } : {}),
925
+ ...(e.agent ? { agent: e.agent } : {}),
926
+ ...(e.description ? { description: cut(e.description, WHY_MAX) } : {}),
927
+ ...(e.doing ? { doing: cut(e.doing, WHY_MAX) } : {}),
928
+ ...(prompt ? { prompt: cut(prompt, TASK_PROMPT_MAX) } : {}),
929
+ ...(e.calls !== null ? { calls: e.calls } : {}),
930
+ ...(e.ms !== null ? { ms: e.ms } : {}),
931
+ ...(e.status ? { status: e.status } : {}),
932
+ ...(e.summary ? { summary: cut(e.summary, TASK_SUMMARY_MAX) } : {}),
933
+ ...(e.background ? { background: true } : {}),
934
+ };
935
+ }
936
+
931
937
  // The events that say a new turn has begun: the messages it echoes count themselves.
932
938
  const TURN = new Set(['said', 'read', 'tool_call', 'tool_result']);
933
939
 
@@ -1089,9 +1095,21 @@ function closeChat(c, code, seen) {
1089
1095
  export function drainChat(logs, id, input) {
1090
1096
  const { lines, next } = readFrom(chatIn(logs, id), input.at);
1091
1097
  input.at = next;
1092
- for (const l of lines)
1098
+ for (const l of lines) {
1099
+ const e = parse(l);
1093
1100
  postTo(chatOut(logs, id), {
1094
1101
  type: 'error',
1095
- 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)}`,
1096
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;
1097
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
 
@@ -21,7 +21,11 @@ export function alive(pid) {
21
21
  * group (`detached`), and the group gets the signal.
22
22
  */
23
23
  export function killTree(pid) {
24
- if (WIN) spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
24
+ if (WIN)
25
+ spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], {
26
+ windowsHide: true,
27
+ stdio: 'ignore',
28
+ });
25
29
  else {
26
30
  try {
27
31
  process.kill(-pid, 'SIGKILL');
@@ -70,29 +70,25 @@ function handoffWatch(handoff, windowOf, write, { stop, onFlag, fresh = false })
70
70
  onFlag(info);
71
71
  };
72
72
 
73
+ const pastFlag = (share) => {
74
+ if (w.flagged && (w.after > HARD_TURNS || share >= handoff.pct + HARD_OVER)) {
75
+ write([`[${clock()}] handoff: the session went on past its flag, stopped`]);
76
+ stop();
77
+ }
78
+ };
79
+
73
80
  const check = (model, compacted) => {
74
81
  const win = windowOf(model);
75
82
  const pct = win ? Math.round((100 * w.context) / win) : null;
76
83
  // No share is under every threshold: a session of an unknown window hands over at a compaction.
77
84
  const share = pct ?? 0;
78
85
  if (pct === null && !compacted) unknownOnce(model);
79
- // A run's fresh session starts from the same prompt; a project chat's, from a summary.
80
- const under = fresh && !handoff.soft && w.readings === 1 && share >= handoff.pct;
81
- if (under && !compacted && !w.under) {
82
- w.under = true;
83
- write([
84
- `[${clock()}] handoff: off, the session starts at ${pct}% of the window, over ` +
85
- `context_handoff_pct ${handoff.pct}: a fresh session would start there too; raise it`,
86
- ]);
87
- }
86
+ underOnce(w, handoff, write, { fresh, pct, share, compacted });
88
87
 
89
88
  if (!w.flagged && (compacted || (share >= handoff.pct && !w.under))) flag(win, pct, compacted);
90
89
  // A project chat hands over by its summary turn, which goes on past the flag (AD-42).
91
90
  if (handoff.soft) return;
92
- if (w.flagged && (w.after > HARD_TURNS || share >= handoff.pct + HARD_OVER)) {
93
- write([`[${clock()}] handoff: the session went on past its flag, stopped`]);
94
- stop();
95
- }
91
+ pastFlag(share);
96
92
  };
97
93
 
98
94
  return {
@@ -113,6 +109,34 @@ function handoffWatch(handoff, windowOf, write, { stop, onFlag, fresh = false })
113
109
  };
114
110
  }
115
111
 
112
+ /** The chat of a session with `chat` options (`runSession`), and its context line `shown`. */
113
+ function openSessionChat(s, child, { watch, limit, windowOf, seen }) {
114
+ const parts = { ...sessionOf(child, watch, limit, windowOf), limited: () => !!seen.limit };
115
+ const talk = openChat({
116
+ ...s.chat,
117
+ ...parts,
118
+ id: s.id,
119
+ prompt: s.prompt,
120
+ encode: s.adapter.encode,
121
+ });
122
+ const shown = contextWatch((e) => talk?.event(e), windowOf);
123
+
124
+ return { talk, shown };
125
+ }
126
+
127
+ /** The note, once, of a fresh session at its first reading over the share (`w` its watch). */
128
+ function underOnce(w, handoff, write, { fresh, pct, share, compacted }) {
129
+ // A run's fresh session starts from the same prompt; a project chat's, from a summary.
130
+ const under = fresh && !handoff.soft && w.readings === 1 && share >= handoff.pct;
131
+ if (under && !compacted && !w.under) {
132
+ w.under = true;
133
+ write([
134
+ `[${clock()}] handoff: off, the session starts at ${pct}% of the window, over ` +
135
+ `context_handoff_pct ${handoff.pct}: a fresh session would start there too; raise it`,
136
+ ]);
137
+ }
138
+ }
139
+
116
140
  /** A held session's own hard stop (`w` its watch): `check` runs only with a share to watch. */
117
141
  function heldTooLong(w, write, stop) {
118
142
  if (!w.held || w.hardStop || w.after <= HARD_TURNS) return;
@@ -330,7 +354,7 @@ function sessionTimeout(ms, onTimeout, onHalt) {
330
354
  * held?: string}>}
331
355
  */
332
356
  export function runSession(s) {
333
- const { adapter, fd, timeoutMs, id, onSpawn, handoff, quota, chat, observe, halt, ownReply } = s;
357
+ const { adapter, fd, timeoutMs, onSpawn, handoff, quota, chat, observe, halt, ownReply } = s;
334
358
 
335
359
  return new Promise((resolve) => {
336
360
  const child = launchSession(s);
@@ -362,11 +386,7 @@ export function runSession(s) {
362
386
  const limit = sessionTimeout(timeoutMs, stop('timeout'), halts);
363
387
  /** @type {((tokens: number, model?: string) => void) | null} */
364
388
  let shown = null;
365
- if (chat) {
366
- const parts = { ...sessionOf(child, watch, limit, windowOf), limited: () => !!seen.limit };
367
- talk = openChat({ ...chat, ...parts, id, prompt: s.prompt, encode: adapter.encode });
368
- shown = contextWatch((e) => talk?.event(e), windowOf);
369
- }
389
+ if (chat) ({ talk, shown } = openSessionChat(s, child, { watch, limit, windowOf, seen }));
370
390
 
371
391
  const flushOut = byLine(child.stdout, (line) => {
372
392
  const a = adapter.parse(line);