gcf-board 0.5.1 → 0.7.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 (42) hide show
  1. package/README.md +14 -12
  2. package/dist/server/app.js +166 -20
  3. package/dist/server/chat.js +42 -1
  4. package/dist/server/files.js +5 -2
  5. package/dist/server/mcp.js +28 -0
  6. package/dist/server/moves.js +11 -0
  7. package/dist/server/propose.js +96 -0
  8. package/dist/server/runs.js +28 -120
  9. package/dist/server/talks.js +553 -0
  10. package/dist/web/assets/golos-text-cyrillic-ext-wght-normal-hICkpzq7.woff2 +0 -0
  11. package/dist/web/assets/golos-text-cyrillic-wght-normal-mKek_fSS.woff2 +0 -0
  12. package/dist/web/assets/golos-text-latin-ext-wght-normal-B-I5lbAQ.woff2 +0 -0
  13. package/dist/web/assets/golos-text-latin-wght-normal-BS5oQT7X.woff2 +0 -0
  14. package/dist/web/assets/index-B3u-VrJK.css +1 -0
  15. package/dist/web/assets/index-BB3i2FaE.js +39 -0
  16. package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  17. package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  18. package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  19. package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  20. package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  21. package/dist/web/index.html +2 -2
  22. package/node_modules/gcf-session/lib/activity.js +371 -0
  23. package/node_modules/gcf-session/lib/adapter/claude.js +226 -0
  24. package/node_modules/gcf-session/lib/adapter/index.js +33 -0
  25. package/node_modules/gcf-session/lib/chat-input.js +260 -0
  26. package/node_modules/gcf-session/lib/chat.js +834 -0
  27. package/node_modules/gcf-session/lib/cli.js +52 -0
  28. package/node_modules/gcf-session/lib/cost.js +29 -0
  29. package/node_modules/gcf-session/lib/index.js +58 -0
  30. package/node_modules/gcf-session/lib/job.js +437 -0
  31. package/node_modules/gcf-session/lib/limit.js +132 -0
  32. package/node_modules/gcf-session/lib/lock.js +81 -0
  33. package/node_modules/gcf-session/lib/proc.js +93 -0
  34. package/node_modules/gcf-session/lib/session.js +320 -0
  35. package/node_modules/gcf-session/lib/store.js +28 -0
  36. package/node_modules/gcf-session/lib/thread.js +423 -0
  37. package/node_modules/gcf-session/lib/windows.js +46 -0
  38. package/node_modules/gcf-session/package.json +23 -0
  39. package/node_modules/gcf-session/types/index.d.ts +152 -0
  40. package/package.json +12 -3
  41. package/dist/web/assets/index-BYAEKw51.css +0 -1
  42. package/dist/web/assets/index-DpzFCrLV.js +0 -36
@@ -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,437 @@
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
+ await noReset(j, kind, rec);
309
+ try {
310
+ return await chain(j, kind, rec);
311
+ } finally {
312
+ // What the operator wrote after the last session ended reached no one: they hear so.
313
+ // A project chat's later input starts its next session: none is drained.
314
+ if (p.chat && typeof p.chat !== 'function') drainChat(p.logs, p.id, p.chat.input);
315
+ }
316
+ }
317
+
318
+ /**
319
+ * A record a stopped wait left paused: limit names its reset: a run started on it (the
320
+ * operator's Run, before the reset or after) names none while it works (AD-32), so no board
321
+ * reads it as waiting for the limit.
322
+ */
323
+ async function noReset(j, kind, rec) {
324
+ if (!rec?.resets) return;
325
+ // As the gate's: a session the run does not resume is named by none, so a handoff stays one.
326
+ const resumes = kind === 'resume';
327
+ await j.p.persist?.({
328
+ session_id: resumes ? rec.session_id : undefined,
329
+ handoffs: j.handoffs,
330
+ handoffPending: false,
331
+ total: resumes ? Number(rec.cost_usd) || undefined : undefined,
332
+ limit: { resets: null },
333
+ });
334
+ }
335
+
336
+ /**
337
+ * A session the usage limit cut (`s.ran`): the job waits for the reset, then goes on with it
338
+ * resumed; with a fresh one when it was told to hand over (a handoff, counted), or when it has
339
+ * no session to resume. No wait leaves it as it ended: paused. A stop during the wait keeps
340
+ * the limit and its reset (PRD §3.2): the item is paused: limit, and a rerun resumes the
341
+ * session; the stop is the operator's, so it pauses no queue.
342
+ */
343
+ async function overLimit(j, s) {
344
+ while (s.ran.limit && !s.ran.stopped && !(await j.p.done?.())) {
345
+ const { reset, handover, state } = limitState(j, s);
346
+ if (handover && (await pastCap(j))) return;
347
+ const waited = await limitWait(j, reset, state);
348
+ if (waited === 'stopped') s.ran = { ...s.ran, stopped: true };
349
+ if (waited !== 'reset' || (handover && (await capped(j)))) return;
350
+ await afterReset(j, s, handover);
351
+ }
352
+ }
353
+
354
+ /** A handoff past the cap: it does not wait for the reset to find that out. */
355
+ const pastCap = async (j) => j.handoffs >= (j.p.maxHandoffs ?? Infinity) && capped(j);
356
+
357
+ /**
358
+ * The reset of the limit that cut `s.ran`, whether the session was told to hand over, and the
359
+ * record to keep while the job waits.
360
+ */
361
+ function limitState(j, s) {
362
+ const { p } = j;
363
+ const now = new Date((p.clock ?? realClock).now());
364
+ const reset = resetOf(s.ran.quota, s.ran.limit.resets, now);
365
+ if (reset.at) s.ran.limit = { ...s.ran.limit, at: reset.at.toISOString() };
366
+ // A project chat's flag only marks the share: it hands over by its summary turn, so the
367
+ // session it was in goes on after the wait.
368
+ const handover = s.ran.handoff && !p.handoff?.soft;
369
+ const state = {
370
+ ...s.ran,
371
+ handoffs: j.handoffs,
372
+ handoffPending: handover,
373
+ total: s.ran.cost?.cost_usd ?? s.base,
374
+ };
375
+
376
+ return { reset, handover, state };
377
+ }
378
+
379
+ /** The session after the reset: the cut one resumed, or a fresh one after a handoff. */
380
+ async function afterReset(j, s, handover) {
381
+ const { p } = j;
382
+ const id = String(s.ran.session_id);
383
+ const resumes = !handover && p.adapter.caps.resume && SESSION_ID.test(id);
384
+ if (handover) p.onHandoff?.(j.handoffs);
385
+ // The session it resumes reports its whole total: its own dollars count from the cut.
386
+ const base = resumes ? (s.ran.cost?.cost_usd ?? s.base) : 0;
387
+ s.kind = resumes ? 'resume' : handover ? 'handoff' : s.kind;
388
+ s.rec = resumes ? { session_id: s.ran.session_id, ended: 'limit' } : s.rec;
389
+ s.ran = await session(j, s.kind, s.rec);
390
+ // A resume that died before it named its session is still that session; one the agent no
391
+ // longer has is lost: the next start is fresh.
392
+ if (resumeLost(s.kind, s.rec, s.ran)) s.lost = true;
393
+ s.sessions.push(s.ran);
394
+ s.cost = addCost(s.cost, beyond(s.ran.cost, base));
395
+ s.base = base;
396
+ }
397
+
398
+ /** The sessions of the job, from its first `kind` on. */
399
+ async function chain(j, kind, rec) {
400
+ const { p } = j;
401
+ const ran = await session(j, kind, rec);
402
+ const lost = resumeLost(kind, rec, ran);
403
+ // The dollars the first session counts from; a fresh one after a handoff from none.
404
+ const base = reachedBefore(kind, rec);
405
+ const s = { ran, kind, rec, base, cost: beyond(ran.cost, base), sessions: [ran], lost };
406
+ await overLimit(j, s);
407
+ let turn = await after(j, s.ran, s.base);
408
+ s.cost = addCost(s.cost, turn.cost);
409
+ const values = [turn.value];
410
+ while ((await goesOn(j, s.ran)) && !(await capped(j))) {
411
+ p.onHandoff?.(j.handoffs);
412
+ Object.assign(s, { kind: 'handoff', rec: null, base: 0 });
413
+ s.ran = await session(j, 'handoff', null);
414
+ s.sessions.push(s.ran);
415
+ s.cost = addCost(s.cost, s.ran.cost);
416
+ await overLimit(j, s);
417
+ turn = await after(j, s.ran, s.base);
418
+ s.cost = addCost(s.cost, turn.cost);
419
+ values.push(turn.value);
420
+ }
421
+
422
+ const { sessions, cost, ran: last } = s;
423
+
424
+ return {
425
+ ...last,
426
+ cost,
427
+ total: turn.total ?? last.cost?.cost_usd ?? s.base,
428
+ handoffs: j.handoffs,
429
+ handoffLimit: j.capped,
430
+ // Told to hand over, and no fresh session took it (a limit with no wait, a stop, the
431
+ // deadline): the rerun starts fresh, it does not resume the full one.
432
+ handoffPending: last.handoff && !j.capped,
433
+ lost: s.lost,
434
+ sessions,
435
+ after: values,
436
+ };
437
+ }