gcf-board 0.5.1 → 0.6.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.
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ // `node cli.js open <project> <thread>`: run a project chat thread (thread.js) until its session
3
+ // idles out, the operator stops it, or it ends. The center starts it detached, through its relay,
4
+ // when a message comes in and no session of the thread lives. It prints nothing: what happens is
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.
7
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
8
+ import path from 'node:path';
9
+ import { claim } from './lock.js';
10
+ import { stopWithSessions } from './proc.js';
11
+ import { THREAD_ID, runThread, threadDir } from './thread.js';
12
+
13
+ // The threads this process runs: its own lock does not hold it off a second time.
14
+ const opened = new Set();
15
+
16
+ /** Open thread `t` of `dir` with its `spec.json`; resolves when it ends, at once when it lives. */
17
+ export async function open(dir, t) {
18
+ if (!THREAD_ID.test(t)) throw new Error(`${t} is not a thread id`);
19
+ const td = threadDir(dir, t);
20
+ if (opened.has(td)) return false;
21
+ opened.add(td);
22
+ const release = await claim(path.join(td, 'open.lock'));
23
+ if (!release) {
24
+ opened.delete(td);
25
+
26
+ return false;
27
+ }
28
+
29
+ const stop = path.join(td, 'stop');
30
+ rmSync(stop, { force: true });
31
+ const unhook = stopWithSessions();
32
+ try {
33
+ const spec = JSON.parse(readFileSync(path.join(td, 'spec.json'), 'utf8'));
34
+ await runThread(dir, t, spec, { stopped: () => existsSync(stop) });
35
+
36
+ return true;
37
+ } finally {
38
+ unhook();
39
+ opened.delete(td);
40
+ await release();
41
+ }
42
+ }
43
+
44
+ const entry = process.argv[1]?.replaceAll('\\', '/');
45
+ if (entry?.endsWith('gcf-session/lib/cli.js') || entry?.endsWith('/cli.js')) {
46
+ const [cmd, dir, t] = process.argv.slice(2);
47
+ if (cmd !== 'open' || !dir || !t) process.exitCode = 2;
48
+ else
49
+ open(path.resolve(dir), t).catch(() => {
50
+ process.exitCode = 1;
51
+ });
52
+ }
@@ -0,0 +1,29 @@
1
+ // What sessions spent, as claude reports it at each `result`.
2
+
3
+ /** Two costs as one: what an item's sessions spent together. */
4
+ export function addCost(a, b) {
5
+ if (!a || !b) return a ?? b;
6
+ const t = (k) => a.tokens[k] + b.tokens[k];
7
+
8
+ return {
9
+ cost_usd: a.cost_usd + b.cost_usd,
10
+ tokens: {
11
+ input: t('input'),
12
+ output: t('output'),
13
+ cache_read: t('cache_read'),
14
+ cache_creation: t('cache_creation'),
15
+ },
16
+ turns: a.turns + b.turns,
17
+ duration_ms: a.duration_ms + b.duration_ms,
18
+ };
19
+ }
20
+
21
+ /**
22
+ * What a resumed session spent itself: claude reports the dollars of the whole session, the
23
+ * turns before the resume included (seen live, 2026-10-16), the tokens of this call only.
24
+ */
25
+ export function beyond(cost, before) {
26
+ if (!cost || !before) return cost;
27
+
28
+ return { ...cost, cost_usd: Math.max(0, cost.cost_usd - before) };
29
+ }
@@ -0,0 +1,58 @@
1
+ // gcf-session, the session engine (docs/Session-Engine.md): the mechanics of agent sessions,
2
+ // with no GCF policy in it. The harness and the board bundle it.
3
+ export { activity, clock, count } from './activity.js';
4
+ export {
5
+ ASK_NONE,
6
+ CHAT_FLAGS,
7
+ CHAT_TIMEOUT_MIN,
8
+ EVENTS_V,
9
+ DEFAULT_ANSWER,
10
+ IMAGE_TYPES,
11
+ READ_GRACE_MS,
12
+ chatIn,
13
+ chatOut,
14
+ defaultAnswers,
15
+ drainChat,
16
+ openChat,
17
+ postTo,
18
+ readFrom,
19
+ sizeOf,
20
+ } from './chat.js';
21
+ export {
22
+ ChatRefusal,
23
+ IMAGES_MAX,
24
+ IMAGE_MAX,
25
+ REQUEST_ID,
26
+ TEXT_MAX,
27
+ chatInput,
28
+ liveSession,
29
+ readText,
30
+ } from './chat-input.js';
31
+ export { addCost, beyond } from './cost.js';
32
+ export { claim, clearDead, create, dead } from './lock.js';
33
+ export { WIN, alive, byLine, killTree, sessions, spawnAgent, stopWithSessions } from './proc.js';
34
+ export { adapterFor, raw } from './adapter/index.js';
35
+ export {
36
+ NO_SESSION,
37
+ claude,
38
+ encode,
39
+ hookCall,
40
+ permissions,
41
+ saveAlways,
42
+ trustedFlags,
43
+ } from './adapter/claude.js';
44
+ export { SESSION_ID, runJob } from './job.js';
45
+ export { runSession } from './session.js';
46
+ export { MARGIN_MS, resetAhead, resetAt, resetOf } from './limit.js';
47
+ export { learnWindow, readWindows, windowFor, windowsOf } from './windows.js';
48
+ export {
49
+ THREAD_ID,
50
+ answerMsOf,
51
+ createThread,
52
+ listThreads,
53
+ readThread,
54
+ runThread,
55
+ threadDir,
56
+ threadOf,
57
+ } from './thread.js';
58
+ export { writeAtomic } from './store.js';
@@ -0,0 +1,417 @@
1
+ // A job (`runJob`): the chain of agent sessions one piece of work takes (docs/Session-Engine.md
2
+ // AD-18). The first starts, or resumes the session a run before it kept; while one hands over
3
+ // as told, a fresh one goes on, up to `maxHandoffs`; after each, its after-session turn. The
4
+ // mechanics are here; what the work is and when it is done, the policy says.
5
+ import { writeSync } from 'node:fs';
6
+ import { clock as hhmmss } from './activity.js';
7
+ import { addCost, beyond } from './cost.js';
8
+ import { chatOut, drainChat, postTo } from './chat.js';
9
+ import { MARGIN_MS, realClock, resetOf, waitUntil, waitsFor } from './limit.js';
10
+ import { learnWindow } from './windows.js';
11
+ import { runSession } from './session.js';
12
+
13
+ // A session id goes into the agent's shell command: a UUID, nothing else.
14
+ export const SESSION_ID = /^[0-9a-f-]{36}$/i;
15
+
16
+ // An after-session turn is one reply: past this it is stopped, and the work's result stands.
17
+ const AFTER_MS = 10 * 60_000;
18
+
19
+ /**
20
+ * @typedef {object} Policy What the work is, for the engine.
21
+ * @property {any} adapter the provider adapter of `agent`
22
+ * @property {string} agent the agent command
23
+ * @property {string} dir where the sessions work
24
+ * @property {string} id the work's id: the name of its chat files
25
+ * @property {string} logs the folder of its chat files and windows
26
+ * @property {number} fd the session log
27
+ * @property {number} timeoutMs one deadline for all the sessions, waits for the operator aside
28
+ * @property {any} [record] the session a run before kept: `{session_id?, ended, handoffs?,
29
+ * counted?, cost_usd?}`
30
+ * @property {(kind: string, caps: {after: boolean}, rec: any) => string | null} prompt the first
31
+ * message of a session: `start`, `resume` (of `rec`) or `handoff`; `caps.after` says an
32
+ * after-session turn follows; null: a chat that starts on the operator's message
33
+ * @property {Record<string, string>} [env]
34
+ * @property {(pid: number) => void} [onSpawn] a session's pid
35
+ * @property {() => void} [onIdle] between two sessions: no session runs
36
+ * @property {() => {see: (events: any[]) => void, result: () => object}} [watch] one session's
37
+ * watch of its neutral events; its result rides on the session
38
+ * @property {() => boolean | Promise<boolean>} [done] the work made its move
39
+ * @property {() => boolean} [stopped] the operator stopped the work
40
+ * @property {any} [handoff] `{pct, windowOf(model, live), flag(info), clear()}`
41
+ * @property {number} [maxHandoffs] fresh sessions in a row; the next handoff is the cap
42
+ * @property {() => Promise<void>} [onCap] the cap is reached
43
+ * @property {(ran: any, kind: string) => void} [onSession] a session ended: its result
44
+ * @property {(n: number) => void} [onHandoff] the `n`th fresh session is about to start
45
+ * @property {(ran: any, ask: Ask) => Promise<any>} [afterSession] the turn after a session
46
+ * @property {(now: number) => Date | null | Promise<Date | null>} [beforeSession] the gate
47
+ * before each
48
+ * session: the usage-limit reset still ahead, which the session waits for (AD-19)
49
+ * @property {(state: any) => void | Promise<void>} [persist] keep the work's record before a
50
+ * limit wait (AD-32): `state` has the job result's fields (`session_id`, `limit {resets, at}`,
51
+ * `handoffs`, `handoffPending`, `total`)
52
+ * @property {{now: () => number, sleep: (ms: number) => Promise<unknown>}} [clock] the limit
53
+ * wait's clock
54
+ * @property {any} [chat] the chat's options (chat.js `openChat`), the same for each session,
55
+ * or a function of the session's kind and record that gives them
56
+ * @property {string | ((kind: string) => string)} [flags] the flags of each session, or of
57
+ * its kind
58
+ * @property {string | null} [quota] the file of the last usage-limit state
59
+ * @property {string} [chatFile] the chat file a limit wait is told in, when it is not
60
+ * `<logs>/<id>.chat.jsonl`
61
+ * @property {Record<string, number>} [learned] the windows learned, kept in `logs`
62
+ */
63
+
64
+ /** @typedef {(prompt: string, opts?: {timeoutMs?: number}) => Promise<any>} Ask */
65
+
66
+ /**
67
+ * The kind a job's first session is: the fresh start after a handoff, the resume of the session
68
+ * a run before kept (an agent that can resume), or a start.
69
+ */
70
+ const firstKind = (p) =>
71
+ p.record?.ended === 'handoff'
72
+ ? 'handoff'
73
+ : p.record && p.adapter.caps.resume && SESSION_ID.test(String(p.record.session_id))
74
+ ? 'resume'
75
+ : 'start';
76
+
77
+ /**
78
+ * Count the job's next handoff, or say the cap is reached. The cap counts each handoff once,
79
+ * the one a kept record still owes a session included.
80
+ */
81
+ async function capped(j) {
82
+ if (j.handoffs < (j.p.maxHandoffs ?? Infinity)) {
83
+ j.handoffs++;
84
+
85
+ return false;
86
+ }
87
+
88
+ j.capped = true;
89
+ await j.p.onCap?.();
90
+
91
+ return true;
92
+ }
93
+
94
+ /**
95
+ * What every session of the job runs with, its after-session turns included. `flags` may be
96
+ * the session kind's (a project chat gives its prompt files at a start and after a handoff).
97
+ */
98
+ const common = (p, kind = 'after') => ({
99
+ adapter: p.adapter,
100
+ agent: p.agent,
101
+ dir: p.dir,
102
+ flags: typeof p.flags === 'function' ? p.flags(kind) : p.flags,
103
+ fd: p.fd,
104
+ id: p.id,
105
+ onSpawn: p.onSpawn,
106
+ env: p.env,
107
+ });
108
+
109
+ /** A work session's first message, and the session it resumes (`rec`'s). */
110
+ function first(j, kind, rec) {
111
+ // The id goes into the agent's shell command: a UUID, nothing else.
112
+ const r = kind === 'resume' && SESSION_ID.test(String(rec?.session_id)) ? rec : null;
113
+
114
+ return { prompt: j.p.prompt(kind, { after: j.after }, r), resume: r?.session_id ?? null };
115
+ }
116
+
117
+ /**
118
+ * Wait for the usage limit's reset (AD-19), when the job may: the record first (`persist`), so
119
+ * a run killed meanwhile resumes the same session; then the chat's `limit {until}`. The wait is
120
+ * not the job's: the deadline moves by as much. Resolves `reset`, `stopped`, or null when the
121
+ * job does not wait (the week's window, an unknown reset, too far, the item's third limit).
122
+ */
123
+ async function limitWait(j, reset, state) {
124
+ const { p } = j;
125
+ const clock = p.clock ?? realClock;
126
+ if (!waitsFor(reset, j.waits, clock.now())) return null;
127
+ j.waits++;
128
+ const until = new Date(reset.at.getTime() + MARGIN_MS);
129
+ await p.persist?.({ ...state, limit: { ...state.limit, at: reset.at.toISOString() } });
130
+ if (p.chat)
131
+ postTo(p.chatFile ?? chatOut(p.logs, p.id), { type: 'limit', until: until.toISOString() });
132
+ try {
133
+ const at = until.toTimeString().slice(0, 5);
134
+ writeSync(p.fd, `[${hhmmss()}] limit: waits for the reset, goes on at ${at}\n`);
135
+ } catch {
136
+ // A log that cannot be written loses its line, not the wait.
137
+ }
138
+
139
+ const t0 = clock.now();
140
+ const ok = await waitUntil(until.getTime(), () => Boolean(p.stopped?.()), clock);
141
+ j.deadline += clock.now() - t0;
142
+ // Awake: the record names no reset before the session starts (AD-32). A stopped wait keeps
143
+ // its reset: the rerun after it goes on with the session.
144
+ if (ok) await p.persist?.({ ...state, limit: { resets: null } });
145
+
146
+ return ok ? 'reset' : 'stopped';
147
+ }
148
+
149
+ /**
150
+ * The gate before a session: a reset the policy says is still ahead is waited for. A stop
151
+ * during it ends the job before its session: the kept session stays for the next run.
152
+ */
153
+ async function gate(j, kind, rec) {
154
+ const ahead = await j.p.beforeSession?.((j.p.clock ?? realClock).now());
155
+ if (!ahead) return true;
156
+ const resumes = kind === 'resume';
157
+ const state = {
158
+ session_id: resumes ? rec?.session_id : undefined,
159
+ handoffs: j.handoffs,
160
+ handoffPending: false,
161
+ total: resumes ? Number(rec?.cost_usd) || undefined : undefined,
162
+ limit: { resets: null },
163
+ };
164
+
165
+ return (await limitWait(j, { at: ahead, weekly: false }, state)) !== 'stopped';
166
+ }
167
+
168
+ /** A session the job did not start: stopped at its gate. */
169
+ const notStarted = (kind, rec) => ({
170
+ code: 'stopped',
171
+ stopped: true,
172
+ gone: false,
173
+ handoff: false,
174
+ handedOver: false,
175
+ waited: 0,
176
+ ...(kind === 'resume' && rec?.session_id ? { session_id: rec.session_id } : {}),
177
+ });
178
+
179
+ /**
180
+ * One session of the job: its gate, its kind, the deadline left, its watch, its chat. The time
181
+ * it waited for the operator is not the job's: the deadline moves by as much.
182
+ */
183
+ async function session(j, kind, rec) {
184
+ const { p } = j;
185
+ if (!(await gate(j, kind, rec))) return notStarted(kind, rec);
186
+ p.handoff?.clear?.();
187
+ const watch = p.watch?.();
188
+ const ran = await runSession({
189
+ ...common(p, kind),
190
+ ...first(j, kind, rec),
191
+ timeoutMs: Math.max(j.deadline - Date.now(), 1000),
192
+ handoff: p.handoff,
193
+ quota: p.quota,
194
+ observe: watch?.see ?? null,
195
+ // A project chat's options may be the kind's: the summary a fresh session starts from.
196
+ chat: typeof p.chat === 'function' ? p.chat(kind, rec) : p.chat && { ...p.chat, kind },
197
+ });
198
+ j.deadline += ran.waited;
199
+ const done = await settled(p, ran, watch);
200
+ p.onSession?.(done, kind);
201
+
202
+ return done;
203
+ }
204
+
205
+ /** After a session: its flag cleared, no session named, its window kept, its watch's result. */
206
+ async function settled(p, ran, watch) {
207
+ p.handoff?.clear?.();
208
+ p.onIdle?.();
209
+ if (p.learned) await learnWindow(p.logs, p.learned, ran);
210
+
211
+ return { ...ran, ...watch?.result(), stopped: Boolean(p.stopped?.()) };
212
+ }
213
+
214
+ /**
215
+ * Only a session that handed over as told goes on: one that saw its flag and ended its reply,
216
+ * or that the job stopped past it. A stop, a limit or the deadline leaves the handoff to the
217
+ * next run.
218
+ */
219
+ async function goesOn(j, ran) {
220
+ const over = ran.handedOver && (ran.code === 0 || ran.code === 'handoff') && !ran.limit;
221
+
222
+ return over && Date.now() < j.deadline && !ran.stopped && !(await j.p.done?.());
223
+ }
224
+
225
+ /**
226
+ * Whether the session the record kept is gone: a resume the agent answered with "no such
227
+ * session", so the next run starts fresh rather than fail on it again. Any other early end (a
228
+ * stop, a crash, no network) keeps it for the next try, and the resumed session's id stands in
229
+ * for one its own run did not report. A fresh session after a handoff has none to borrow.
230
+ */
231
+ function resumeLost(kind, rec, ran) {
232
+ if (kind !== 'resume') return false;
233
+ if (ran.gone) return true;
234
+ ran.session_id ??= rec.session_id;
235
+
236
+ return false;
237
+ }
238
+
239
+ /** Whether a session gets its after-session turn: one to resume, not cut by a limit or a stop. */
240
+ const asksAfter = (j, ran) =>
241
+ j.after && SESSION_ID.test(String(ran.session_id)) && !ran.limit && !ran.stopped && !ran.gone;
242
+
243
+ /**
244
+ * The after-session turn: the same agent, resumed, gets the policy's questions (`ask`), the
245
+ * policy reads its answer. Its own cost counts from what the session reached (`base`); a turn
246
+ * cut by the limit does not wait. A stop during it holds for the session after it too.
247
+ */
248
+ async function after(j, ran, base) {
249
+ const { p } = j;
250
+ if (!asksAfter(j, ran)) return { value: undefined, cost: undefined, total: undefined };
251
+ /** @type {any} */
252
+ let turn = null;
253
+ const ask = async (prompt, { timeoutMs = AFTER_MS } = {}) => {
254
+ turn = await runSession({
255
+ ...common(p),
256
+ prompt,
257
+ resume: ran.session_id,
258
+ timeoutMs,
259
+ // One reply, past the work: no handoff watch, no quota, no chat.
260
+ handoff: null,
261
+ quota: null,
262
+ chat: null,
263
+ });
264
+ p.onIdle?.();
265
+
266
+ return turn;
267
+ };
268
+
269
+ try {
270
+ const value = await p.afterSession?.(ran, ask);
271
+ if (!turn) return { value, cost: undefined, total: undefined };
272
+ const t = /** @type {any} */ (turn);
273
+
274
+ return { value, cost: beyond(t.cost, ran.cost?.cost_usd ?? base), total: t.cost?.cost_usd };
275
+ } finally {
276
+ ran.stopped ||= Boolean(p.stopped?.());
277
+ }
278
+ }
279
+
280
+ /**
281
+ * What a resumed session's earlier runs spent: its dollars count from there. A kept record is
282
+ * resumed unless its session handed over.
283
+ */
284
+ const reachedBefore = (kind, rec) => (kind === 'resume' ? Number(rec?.cost_usd) || 0 : 0);
285
+
286
+ /**
287
+ * Run the job of `p` (`Policy`). Returns the last session's result with: `cost`, what the
288
+ * sessions and their after-session turns spent; `total`, what the last session reached (a rerun
289
+ * that resumes it counts from there); `handoffs`; `handoffLimit` (the cap); `handoffPending`
290
+ * (told to hand over, no fresh session took it: the next run does); `lost` (the kept session
291
+ * is gone); `sessions`, each session's result; `after`, each after-session turn's value.
292
+ * @param {Policy} p
293
+ */
294
+ export async function runJob(p) {
295
+ const rec = p.record ?? null;
296
+ const j = {
297
+ p,
298
+ handoffs: Number(rec?.handoffs) || 0,
299
+ capped: false,
300
+ deadline: Date.now() + p.timeoutMs,
301
+ waits: 0,
302
+ after: Boolean(p.afterSession) && p.adapter.caps.resume,
303
+ };
304
+ const kind = firstKind(p);
305
+ // A record whose handoff its own run already counted (`counted`) owes none.
306
+ if (kind === 'handoff' && !rec.counted && (await capped(j)))
307
+ return { code: 0, handoffs: j.handoffs, handoffLimit: true, handoffPending: false };
308
+ try {
309
+ return await chain(j, kind, rec);
310
+ } finally {
311
+ // What the operator wrote after the last session ended reached no one: they hear so.
312
+ // A project chat's later input starts its next session: none is drained.
313
+ if (p.chat && typeof p.chat !== 'function') drainChat(p.logs, p.id, p.chat.input);
314
+ }
315
+ }
316
+
317
+ /**
318
+ * A session the usage limit cut (`s.ran`): the job waits for the reset, then goes on with it
319
+ * resumed; with a fresh one when it was told to hand over (a handoff, counted), or when it has
320
+ * no session to resume. No wait leaves it as it ended: paused. A stop during the wait leaves
321
+ * the session to the next run, not paused by the limit.
322
+ */
323
+ async function overLimit(j, s) {
324
+ while (s.ran.limit && !s.ran.stopped && !(await j.p.done?.())) {
325
+ const { reset, handover, state } = limitState(j, s);
326
+ if (handover && (await pastCap(j))) return;
327
+ const waited = await limitWait(j, reset, state);
328
+ if (waited === 'stopped') s.ran = { ...s.ran, limit: undefined, stopped: true };
329
+ if (waited !== 'reset' || (handover && (await capped(j)))) return;
330
+ await afterReset(j, s, handover);
331
+ }
332
+ }
333
+
334
+ /** A handoff past the cap: it does not wait for the reset to find that out. */
335
+ const pastCap = async (j) => j.handoffs >= (j.p.maxHandoffs ?? Infinity) && capped(j);
336
+
337
+ /**
338
+ * The reset of the limit that cut `s.ran`, whether the session was told to hand over, and the
339
+ * record to keep while the job waits.
340
+ */
341
+ function limitState(j, s) {
342
+ const { p } = j;
343
+ const now = new Date((p.clock ?? realClock).now());
344
+ const reset = resetOf(s.ran.quota, s.ran.limit.resets, now);
345
+ if (reset.at) s.ran.limit = { ...s.ran.limit, at: reset.at.toISOString() };
346
+ // A project chat's flag only marks the share: it hands over by its summary turn, so the
347
+ // session it was in goes on after the wait.
348
+ const handover = s.ran.handoff && !p.handoff?.soft;
349
+ const state = {
350
+ ...s.ran,
351
+ handoffs: j.handoffs,
352
+ handoffPending: handover,
353
+ total: s.ran.cost?.cost_usd ?? s.base,
354
+ };
355
+
356
+ return { reset, handover, state };
357
+ }
358
+
359
+ /** The session after the reset: the cut one resumed, or a fresh one after a handoff. */
360
+ async function afterReset(j, s, handover) {
361
+ const { p } = j;
362
+ const id = String(s.ran.session_id);
363
+ const resumes = !handover && p.adapter.caps.resume && SESSION_ID.test(id);
364
+ if (handover) p.onHandoff?.(j.handoffs);
365
+ // The session it resumes reports its whole total: its own dollars count from the cut.
366
+ const base = resumes ? (s.ran.cost?.cost_usd ?? s.base) : 0;
367
+ s.kind = resumes ? 'resume' : handover ? 'handoff' : s.kind;
368
+ s.rec = resumes ? { session_id: s.ran.session_id, ended: 'limit' } : s.rec;
369
+ s.ran = await session(j, s.kind, s.rec);
370
+ // A resume that died before it named its session is still that session; one the agent no
371
+ // longer has is lost: the next start is fresh.
372
+ if (resumeLost(s.kind, s.rec, s.ran)) s.lost = true;
373
+ s.sessions.push(s.ran);
374
+ s.cost = addCost(s.cost, beyond(s.ran.cost, base));
375
+ s.base = base;
376
+ }
377
+
378
+ /** The sessions of the job, from its first `kind` on. */
379
+ async function chain(j, kind, rec) {
380
+ const { p } = j;
381
+ const ran = await session(j, kind, rec);
382
+ const lost = resumeLost(kind, rec, ran);
383
+ // The dollars the first session counts from; a fresh one after a handoff from none.
384
+ const base = reachedBefore(kind, rec);
385
+ const s = { ran, kind, rec, base, cost: beyond(ran.cost, base), sessions: [ran], lost };
386
+ await overLimit(j, s);
387
+ let turn = await after(j, s.ran, s.base);
388
+ s.cost = addCost(s.cost, turn.cost);
389
+ const values = [turn.value];
390
+ while ((await goesOn(j, s.ran)) && !(await capped(j))) {
391
+ p.onHandoff?.(j.handoffs);
392
+ Object.assign(s, { kind: 'handoff', rec: null, base: 0 });
393
+ s.ran = await session(j, 'handoff', null);
394
+ s.sessions.push(s.ran);
395
+ s.cost = addCost(s.cost, s.ran.cost);
396
+ await overLimit(j, s);
397
+ turn = await after(j, s.ran, s.base);
398
+ s.cost = addCost(s.cost, turn.cost);
399
+ values.push(turn.value);
400
+ }
401
+
402
+ const { sessions, cost, ran: last } = s;
403
+
404
+ return {
405
+ ...last,
406
+ cost,
407
+ total: turn.total ?? last.cost?.cost_usd ?? s.base,
408
+ handoffs: j.handoffs,
409
+ handoffLimit: j.capped,
410
+ // Told to hand over, and no fresh session took it (a limit with no wait, a stop, the
411
+ // deadline): the rerun starts fresh, it does not resume the full one.
412
+ handoffPending: last.handoff && !j.capped,
413
+ lost: s.lost,
414
+ sessions,
415
+ after: values,
416
+ };
417
+ }
@@ -0,0 +1,132 @@
1
+ // The usage-limit wait (docs/Session-Engine.md AD-19): when the limit resets, whether a run waits
2
+ // for it, and the wait itself, which a stop ends and a sleeping PC does not fool.
3
+ import { readFileSync } from 'node:fs';
4
+
5
+ /** The wait ends this long after the reset: a resume right at it may meet the limit still. */
6
+ export const MARGIN_MS = 60_000;
7
+
8
+ /** Past this the run does not wait: it ends paused, as before. */
9
+ export const MAX_WAIT_MS = 6 * 3_600_000;
10
+
11
+ /** How often the wait reads the wall clock and the stop mark. */
12
+ export const POLL_MS = 30_000;
13
+
14
+ /** The waits one item gets in a run: its next limit ends it paused. */
15
+ export const MAX_WAITS = 2;
16
+
17
+ /** The real clock; a test gives its own. */
18
+ export const realClock = {
19
+ now: () => Date.now(),
20
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
21
+ };
22
+
23
+ /**
24
+ * The time a usage limit resets, as Claude names it (`3am`, `3:30pm`, `15:00`, with or without
25
+ * `(Europe/Berlin)`): its next occurrence after `now`; null when the text is no such time.
26
+ * @param {string} text
27
+ * @param {Date} [now]
28
+ */
29
+ export function resetAt(text, now = new Date()) {
30
+ // shortcut: the time is read on this machine's clock and the zone it names is ignored: the
31
+ // run goes where the operator's claude does; convert through Intl if a zone ever differs.
32
+ const m = /^\s*(\d{1,2})(?::(\d{2}))?\s*([ap]m)?\s*(\(.*\))?\s*$/i.exec(text);
33
+ if (!m || (!m[2] && !m[3])) return null;
34
+ const hour = hourOf(Number(m[1]), m[3]);
35
+ const minute = Number(m[2] ?? 0);
36
+ if (hour === null || hour > 23 || minute > 59) return null;
37
+ const at = new Date(now);
38
+ at.setHours(hour, minute, 0, 0);
39
+ if (at <= now) at.setDate(at.getDate() + 1);
40
+
41
+ return at;
42
+ }
43
+
44
+ /** The 24-hour hour of `hour` with its `am`/`pm`, if any; null for a 12-hour one out of 1–12. */
45
+ function hourOf(hour, ampm) {
46
+ if (!ampm) return hour;
47
+ if (hour < 1 || hour > 12) return null;
48
+
49
+ return (hour % 12) + (ampm.toLowerCase() === 'pm' ? 12 : 0);
50
+ }
51
+
52
+ const weeklyType = (type) => /seven_day/.test(String(type ?? ''));
53
+
54
+ /** A reset in epoch seconds, while it is ahead of `now`: one behind it is a stale state. */
55
+ const ahead = (s, now) => (Number(s) * 1000 > now.getTime() ? new Date(Number(s) * 1000) : null);
56
+
57
+ /**
58
+ * When the limit that stopped a session resets, by the first source that says (AD-19): the
59
+ * latest reset of the account's windows that are used up, the reset of a rejected state, the
60
+ * time in the limit's text. `weekly` says the week's window is the one used up: no run waits
61
+ * for that. `quota` is the stream's `rate_limit_info`, `text` the limit message's time.
62
+ * @param {any} quota
63
+ * @param {string | null | undefined} text
64
+ * @param {Date} [now]
65
+ * @returns {{at: Date | null, weekly: boolean}}
66
+ */
67
+ export function resetOf(quota, text, now = new Date()) {
68
+ const windows = Object.entries(quota?.unifiedWindows ?? {}).filter(
69
+ ([, w]) => Number(w?.utilization) >= 1 && ahead(w.resetsAt, now),
70
+ );
71
+ if (windows.length) {
72
+ const at = new Date(Math.max(...windows.map(([, w]) => Number(w.resetsAt) * 1000)));
73
+
74
+ return { at, weekly: windows.some(([type]) => weeklyType(type)) };
75
+ }
76
+
77
+ if (quota?.status === 'rejected' && ahead(quota.resetsAt, now))
78
+ return { at: ahead(quota.resetsAt, now), weekly: weeklyType(quota.rateLimitType) };
79
+
80
+ // shortcut: a weekly limit known by its text alone is not told apart; its reset is mostly a
81
+ // date, not a time, so it ends paused anyway. Read the message's wording once it is known.
82
+ return { at: text ? resetAt(text, now) : null, weekly: false };
83
+ }
84
+
85
+ /**
86
+ * The reset the account's last usage-limit state still waits for (`runs/quota.json`), when it
87
+ * is ahead: a run started now would meet the limit. Null when the state allows, or is unknown.
88
+ * @param {string | null | undefined} file
89
+ * @param {number} now
90
+ */
91
+ export function resetAhead(file, now) {
92
+ if (!file) return null;
93
+ try {
94
+ const { info } = JSON.parse(readFileSync(file, 'utf8'));
95
+ const used = Object.values(info?.unifiedWindows ?? {}).some((w) => Number(w?.utilization) >= 1);
96
+ if (!used && info?.status !== 'rejected') return null;
97
+ const { at, weekly } = resetOf(info, null, new Date(now));
98
+
99
+ return at && !weekly ? at : null;
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Whether a run waits for a reset at `at`, its `waits` so far counted: not for the week's
107
+ * window, an unknown reset, one past `MAX_WAIT_MS`, or a third limit of the item.
108
+ * @param {{at: Date | null, weekly: boolean}} reset
109
+ * @param {number} waits
110
+ * @param {number} now
111
+ */
112
+ export const waitsFor = (reset, waits, now) =>
113
+ Boolean(reset.at) &&
114
+ !reset.weekly &&
115
+ waits < MAX_WAITS &&
116
+ /** @type {Date} */ (reset.at).getTime() + MARGIN_MS - now <= MAX_WAIT_MS;
117
+
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.
121
+ * @param {number} until
122
+ * @param {() => boolean} stopped
123
+ * @param {{now: () => number, sleep: (ms: number) => Promise<unknown>}} [clock]
124
+ */
125
+ export async function waitUntil(until, stopped, clock = realClock) {
126
+ while (clock.now() < until) {
127
+ if (stopped()) return false;
128
+ await clock.sleep(Math.min(POLL_MS, until - clock.now()));
129
+ }
130
+
131
+ return !stopped();
132
+ }