gcf-board 0.22.0 → 0.23.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-Dhh107oY.js"></script>
8
- <link rel="stylesheet" crossorigin href="/assets/index-D7HJ7-ko.css">
7
+ <script type="module" crossorigin src="/assets/index-CmVruskr.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/index-D-qaIlaa.css">
9
9
  </head>
10
10
  <body>
11
11
  <div id="root"></div>
@@ -240,8 +240,26 @@ function waiting(c, kind) {
240
240
  post(c, { type: 'waiting', kind });
241
241
  }
242
242
 
243
+ /**
244
+ * A run's session the operator stopped waits for them with no timeout (Hold-Plan d2): the
245
+ * session's clock stands until they write or the agent goes on by itself.
246
+ */
247
+ function stopWait(c) {
248
+ waiting(c, 'stop');
249
+ if (c.stopWait) return;
250
+ c.stopWait = true;
251
+ c.pause(true);
252
+ }
253
+
254
+ function stopWaitEnds(c) {
255
+ if (!c.stopWait) return;
256
+ c.stopWait = false;
257
+ c.pause(false);
258
+ }
259
+
243
260
  /** The agent's first event after a wait (fix B). */
244
261
  function working(c) {
262
+ stopWaitEnds(c);
245
263
  if (!c.idle) return;
246
264
  c.idle = false;
247
265
  post(c, { type: 'working' });
@@ -459,6 +477,7 @@ function take(c, line, entry = { end: 0, echo: false, done: false }) {
459
477
  /** The operator's message (`m` its place in the input, AD-35). */
460
478
  function heard(c, e, m) {
461
479
  if (typeof e.text !== 'string' || !e.text.trim()) return;
480
+ stopWaitEnds(c);
462
481
  // An open card still waits for its answer: its timeout holds.
463
482
  if (!c.cards.size) stopWaiting(c);
464
483
  c.defaulted = false;
@@ -486,7 +505,7 @@ function interrupted(c) {
486
505
  if (c.wait && !c.cards.size) {
487
506
  stopWaiting(c);
488
507
  if (c.handover) idleWait(c);
489
- else waiting(c, 'stop');
508
+ else stopWait(c);
490
509
  }
491
510
  }
492
511
 
@@ -622,7 +641,7 @@ async function settle(c) {
622
641
  * when its item made its move; else the agent's next turn comes as they end.
623
642
  */
624
643
  async function closeOverTasks(c) {
625
- if (c.handoff().flagged) return c.stdin.end();
644
+ if (c.handoff().flagged || (await c.phaseOver?.())) return c.stdin.end();
626
645
  if (!(await c.done?.())) return;
627
646
  // The operator may have written meanwhile, or the session ended: that comes first.
628
647
  if (c.closed || c.read < c.sent) return;
@@ -639,13 +658,14 @@ function settleTalk(c) {
639
658
 
640
659
  /** A run's session after a turn: closed, or waiting for the operator, then the default. */
641
660
  async function settleRun(c) {
642
- if (c.handoff().flagged) return c.stdin.end();
661
+ // The planning phase is over (Hold-Plan d13): the session waits for nobody, a fresh one goes on.
662
+ if (c.handoff().flagged || (await c.phaseOver?.())) return c.stdin.end();
643
663
  const moved = await c.done?.();
644
664
  // The operator may have written meanwhile, a task started, or the session ended.
645
665
  if (c.closed || c.read < c.sent || c.tasks.length) return;
646
666
  if (moved) return c.stdin.end();
647
667
  // The operator's Stop holds even after a default answer went: they are at the screen.
648
- if (c.stopped) return waiting(c, 'stop');
668
+ if (c.stopped) return stopWait(c);
649
669
  if (c.defaulted) return c.stdin.end();
650
670
  waitFor(c, 'text', () => {
651
671
  c.defaulted = true;
@@ -653,6 +673,19 @@ async function settleRun(c) {
653
673
  });
654
674
  }
655
675
 
676
+ /**
677
+ * The session was held (Hold-Plan d4): its turn ends at the agent's next call, as told; one
678
+ * waiting for the operator (an answer, a card, a Stop) or between turns closes now, its default
679
+ * answer never sent. A turn in work closes at its end (`settleRun`, `closeOverTasks`).
680
+ */
681
+ function held(c, reason) {
682
+ post(c, { type: 'held', reason });
683
+ if (c.closed || (c.inTurn && !c.wait && !c.stopWait)) return;
684
+ stopWaiting(c);
685
+ stopWaitEnds(c);
686
+ c.stdin.end();
687
+ }
688
+
656
689
  /** A turn ended: what it cost the session so far, how full its context is, then what follows. */
657
690
  function turnEnd(c, e) {
658
691
  c.inTurn = false;
@@ -950,6 +983,7 @@ export function openChat(opts) {
950
983
  event: (e) => post(c, e),
951
984
  /** Why the chat closed its session: `idle`, `handoff`, or null. */
952
985
  why: () => c.why,
986
+ held: (reason) => held(c, reason),
953
987
  close: (code, seen = {}) => {
954
988
  clearInterval(poll);
955
989
  closeChat(c, code, seen);
@@ -993,7 +1027,7 @@ function chatState(opts) {
993
1027
  out: io.out,
994
1028
  fresh: o.fresh ?? o.kind === 'handoff',
995
1029
  ...{ sent: 0, read: 0, cards: new Map(), wait: null, defaulted: false, closed: false },
996
- ...{ stopped: false, grace: null, idle: false, inTurn: true, tasks: [] },
1030
+ ...{ stopped: false, stopWait: false, grace: null, idle: false, inTurn: true, tasks: [] },
997
1031
  ...{ proposals: new Map(), calls: new Map(), heard: false, summary: null, wanted: null },
998
1032
  // When each task's last progress reached the chat; the last one it held back since.
999
1033
  taskAt: new Map(),
@@ -60,3 +60,18 @@ export {
60
60
  threadOfEntry,
61
61
  } from './thread.js';
62
62
  export { writeAtomic } from './store.js';
63
+ export {
64
+ RESERVE_PCT,
65
+ USAGE_MAX_AGE_MS,
66
+ accountSettings,
67
+ askUsageOnce,
68
+ gcfHome,
69
+ lastReading,
70
+ limitsOf,
71
+ readUsage,
72
+ reasonOf,
73
+ reserveOf,
74
+ reserveOfReading,
75
+ saveAccountSettings,
76
+ usageFile,
77
+ } from './usage.js';
@@ -30,7 +30,10 @@ const AFTER_MS = 10 * 60_000;
30
30
  * @property {(kind: string, caps: {after: boolean}, rec: any) => string | null} prompt the first
31
31
  * message of a session: `start`, `resume` (of `rec`) or `handoff`; `caps.after` says an
32
32
  * after-session turn follows; null: a chat that starts on the operator's message
33
- * @property {Record<string, string>} [env]
33
+ * @property {Record<string, string> | ((kind: string) => Promise<Record<string, string>>)} [env]
34
+ * the sessions' env, or a function of the session's kind that gives it (Hold-Plan d14)
35
+ * @property {(ran: any) => Promise<object | void>} [afterRun] after each session: what it adds
36
+ * to the session's result (`phaseEnded`: the planning phase ended, a fresh session goes on)
34
37
  * @property {(pid: number) => void} [onSpawn] a session's pid
35
38
  * @property {() => void} [onIdle] between two sessions: no session runs
36
39
  * @property {() => {see: (events: any[]) => void, result: () => object}} [watch] one session's
@@ -44,9 +47,11 @@ const AFTER_MS = 10 * 60_000;
44
47
  * @property {(ran: any, kind: string) => void} [onSession] a session ended: its result
45
48
  * @property {(n: number) => void} [onHandoff] the `n`th fresh session is about to start
46
49
  * @property {(ran: any, ask: Ask) => Promise<any>} [afterSession] the turn after a session
47
- * @property {(now: number) => Date | null | Promise<Date | null>} [beforeSession] the gate
48
- * before each
49
- * session: the usage-limit reset still ahead, which the session waits for (AD-19)
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
53
+ * @property {() => string | null} [hold] why the work is to stop now, its sessions handing over
54
+ * (`hold`, `reserve`): a live session is flagged, a wait ends
50
55
  * @property {(state: any) => void | Promise<void>} [persist] keep the work's record before a
51
56
  * limit wait (AD-32): `state` has the job result's fields (`session_id`, `limit {resets, at}`,
52
57
  * `handoffs`, `handoffPending`, `total`)
@@ -64,6 +69,11 @@ const AFTER_MS = 10 * 60_000;
64
69
 
65
70
  /** @typedef {(prompt: string, opts?: {timeoutMs?: number}) => Promise<any>} Ask */
66
71
 
72
+ /**
73
+ * @typedef {{go: true} | {wait: true, until: Date, reserve?: boolean} | {stop: true, why: string}
74
+ * | Date | null | undefined} Gate
75
+ */
76
+
67
77
  /**
68
78
  * The kind a job's first session is: the fresh start after a handoff, the resume of the session
69
79
  * a run before kept (an agent that can resume), or a start.
@@ -104,7 +114,7 @@ const common = (p, kind = 'after') => ({
104
114
  fd: p.fd,
105
115
  id: p.id,
106
116
  onSpawn: p.onSpawn,
107
- env: p.env,
117
+ env: typeof p.env === 'function' ? undefined : p.env,
108
118
  });
109
119
 
110
120
  /** A work session's first message, and the session it resumes (`rec`'s). */
@@ -121,13 +131,43 @@ function first(j, kind, rec) {
121
131
  * not the job's: the deadline moves by as much. Resolves `reset`, `stopped`, or null when the
122
132
  * job does not wait (the week's window, an unknown reset, too far, the item's third limit).
123
133
  */
124
- async function limitWait(j, reset, state) {
134
+ async function limitWait(j, reset, state, { reserve = false } = {}) {
125
135
  const { p } = j;
126
136
  const clock = p.clock ?? realClock;
127
- if (!waitsFor(reset, j.waits, clock.now())) return null;
128
- j.waits++;
137
+ if (!counted(j, reset, clock.now(), reserve)) return null;
129
138
  const until = new Date(reset.at.getTime() + MARGIN_MS);
130
139
  await p.persist?.({ ...state, limit: { ...state.limit, at: reset.at.toISOString() } });
140
+ tellWait(p, until);
141
+ const t0 = clock.now();
142
+ const ok = await waitUntil(until.getTime(), () => Boolean(p.stopped?.() || heldNow(p)), clock);
143
+ j.deadline += clock.now() - t0;
144
+
145
+ return awake(p, ok, state);
146
+ }
147
+
148
+ /**
149
+ * How a wait ended. Awake: the record names no reset before the session starts (AD-32). A
150
+ * stopped wait keeps its reset: the rerun after it goes on with the session. A Hold during the
151
+ * wait ends the job; its record stays as the wait left it.
152
+ */
153
+ async function awake(p, ok, state) {
154
+ if (!ok) return !p.stopped?.() && heldNow(p) ? 'held' : 'stopped';
155
+ await p.persist?.({ ...state, limit: { resets: null } });
156
+
157
+ return 'reset';
158
+ }
159
+
160
+ /** Whether the job waits for `reset`, counted: the reserve's waits spend none of the limit's. */
161
+ function counted(j, reset, now, reserve) {
162
+ if (!waitsFor(reset, reserve ? 0 : j.waits, now)) return false;
163
+ if (reserve) j.reserveWaits++;
164
+ else j.waits++;
165
+
166
+ return true;
167
+ }
168
+
169
+ /** The wait, in the chat (`limit {until}`) and the log. */
170
+ function tellWait(p, until) {
131
171
  if (p.chat)
132
172
  postTo(p.chatFile ?? chatOut(p.logs, p.id), { type: 'limit', until: until.toISOString() });
133
173
  try {
@@ -136,40 +176,67 @@ async function limitWait(j, reset, state) {
136
176
  } catch {
137
177
  // A log that cannot be written loses its line, not the wait.
138
178
  }
179
+ }
139
180
 
140
- const t0 = clock.now();
141
- const ok = await waitUntil(until.getTime(), () => Boolean(p.stopped?.()), clock);
142
- j.deadline += clock.now() - t0;
143
- // Awake: the record names no reset before the session starts (AD-32). A stopped wait keeps
144
- // its reset: the rerun after it goes on with the session.
145
- if (ok) await p.persist?.({ ...state, limit: { resets: null } });
181
+ /**
182
+ * The operator's Hold of the work, if any: the reserve's flag ends a live session, but before
183
+ * a session the gate decides about the reserve (wait or stop), as during a wait.
184
+ */
185
+ function heldNow(p) {
186
+ const why = p.hold?.();
146
187
 
147
- return ok ? 'reset' : 'stopped';
188
+ return why && why !== 'reserve' ? why : null;
189
+ }
190
+
191
+ /** The policy's gate in its one form: a Date is a wait for it, nothing a go. */
192
+ function decisionOf(d) {
193
+ if (d instanceof Date) return { wait: true, until: d };
194
+ if (!d) return { go: true };
195
+
196
+ return d;
148
197
  }
149
198
 
150
199
  /**
151
- * The gate before a session: a reset the policy says is still ahead is waited for. A stop
152
- * during it ends the job before its session: the kept session stays for the next run.
200
+ * The gate before a session (Hold-Plan d7): the work held stops it; a reset the policy says
201
+ * is still ahead, or the reserve's, is waited for; the policy's stop stops it. A stop during
202
+ * the wait ends the job before its session: the kept session stays for the next run. Resolves
203
+ * true to go, else `{stopped}` or `{held}`.
153
204
  */
154
205
  async function gate(j, kind, rec) {
155
- const ahead = await j.p.beforeSession?.((j.p.clock ?? realClock).now());
156
- if (!ahead) return true;
206
+ const holding = heldNow(j.p);
207
+ if (holding) return { held: holding };
208
+ const d = decisionOf(await j.p.beforeSession?.((j.p.clock ?? realClock).now()));
209
+ if ('stop' in d && d.stop) return { held: d.why };
210
+ if (!('wait' in d) || !d.wait) return true;
211
+ const reserve = Boolean(d.reserve);
212
+ const reset = { at: d.until, weekly: false };
213
+ const waited = await limitWait(j, reset, waitState(j, kind, rec), { reserve });
214
+ if (waited === 'held') return { held: /** @type {string} */ (heldNow(j.p)) };
215
+ if (waited === 'stopped') return { stopped: true };
216
+
217
+ // The reserve too far to wait for stands the work, as its stop.
218
+ return waited === null && reserve ? { held: 'reserve' } : true;
219
+ }
220
+
221
+ /** The record a wait before a session keeps: the session it resumes, if any. */
222
+ function waitState(j, kind, rec) {
157
223
  const resumes = kind === 'resume';
158
- const state = {
224
+
225
+ return {
159
226
  session_id: resumes ? rec?.session_id : undefined,
160
227
  handoffs: j.handoffs,
161
228
  handoffPending: false,
162
229
  total: resumes ? Number(rec?.cost_usd) || undefined : undefined,
163
230
  limit: { resets: null },
164
231
  };
165
-
166
- return (await limitWait(j, { at: ahead, weekly: false }, state)) !== 'stopped';
167
232
  }
168
233
 
169
- /** A session the job did not start: stopped at its gate. */
170
- const notStarted = (kind, rec) => ({
234
+ /** A session the job did not start: stopped at its gate, or held there (`held`). */
235
+ const notStarted = (kind, rec, held) => ({
171
236
  code: 'stopped',
172
- stopped: true,
237
+ notStarted: true,
238
+ stopped: !held,
239
+ ...(held ? { held } : {}),
173
240
  gone: false,
174
241
  handoff: false,
175
242
  handedOver: false,
@@ -183,17 +250,23 @@ const notStarted = (kind, rec) => ({
183
250
  */
184
251
  async function session(j, kind, rec) {
185
252
  const { p } = j;
186
- if (!(await gate(j, kind, rec))) return notStarted(kind, rec);
253
+ const go = await gate(j, kind, rec);
254
+ if (go !== true) return notStarted(kind, rec, go.held);
187
255
  p.handoff?.clear?.();
188
256
  const watch = p.watch?.();
257
+ const env = typeof p.env === 'function' ? await p.env(kind) : p.env;
258
+ // The after-session turn resumes this session: it runs with its env.
259
+ j.env = env;
189
260
  const ran = await runSession({
190
261
  ...common(p, kind),
262
+ env,
191
263
  ...first(j, kind, rec),
192
264
  timeoutMs: Math.max(j.deadline - Date.now(), 1000),
193
265
  handoff: p.handoff,
194
266
  quota: p.quota,
195
267
  observe: watch?.see ?? null,
196
268
  halt: p.halt ? p.stopped : undefined,
269
+ hold: p.hold,
197
270
  // A project chat's options may be the kind's: the summary a fresh session starts from.
198
271
  chat: typeof p.chat === 'function' ? p.chat(kind, rec) : p.chat && { ...p.chat, kind },
199
272
  });
@@ -210,7 +283,9 @@ async function settled(p, ran, watch) {
210
283
  p.onIdle?.();
211
284
  if (p.learned) await learnWindow(p.logs, p.learned, ran);
212
285
 
213
- return { ...ran, ...watch?.result(), stopped: Boolean(p.stopped?.()) };
286
+ const more = await p.afterRun?.(ran);
287
+
288
+ return { ...ran, ...watch?.result(), ...more, stopped: Boolean(p.stopped?.()) };
214
289
  }
215
290
 
216
291
  /**
@@ -219,7 +294,10 @@ async function settled(p, ran, watch) {
219
294
  * next run.
220
295
  */
221
296
  async function goesOn(j, ran) {
222
- const over = ran.handedOver && (ran.code === 0 || ran.code === 'handoff') && !ran.limit;
297
+ // The operator's Hold ends the job: the next run goes on from where it stopped.
298
+ if (ran.held && ran.held !== 'reserve') return false;
299
+ const ended = ran.code === 0 || ran.code === 'handoff';
300
+ const over = (ran.handedOver || free(ran)) && ended && !ran.limit;
223
301
 
224
302
  return over && Date.now() < j.deadline && !ran.stopped && !(await j.p.done?.());
225
303
  }
@@ -238,9 +316,17 @@ function resumeLost(kind, rec, ran) {
238
316
  return false;
239
317
  }
240
318
 
241
- /** Whether a session gets its after-session turn: one to resume, not cut by a limit or a stop. */
319
+ /**
320
+ * Whether a session gets its after-session turn: one to resume, not cut by a limit, a stop or a
321
+ * hold.
322
+ */
242
323
  const asksAfter = (j, ran) =>
243
- j.after && SESSION_ID.test(String(ran.session_id)) && !ran.limit && !ran.stopped && !ran.gone;
324
+ j.after &&
325
+ SESSION_ID.test(String(ran.session_id)) &&
326
+ !ran.limit &&
327
+ !ran.stopped &&
328
+ !ran.held &&
329
+ !ran.gone;
244
330
 
245
331
  /**
246
332
  * The after-session turn: the same agent, resumed, gets the policy's questions (`ask`), the
@@ -255,6 +341,7 @@ async function after(j, ran, base) {
255
341
  const ask = async (prompt, { timeoutMs = AFTER_MS } = {}) => {
256
342
  turn = await runSession({
257
343
  ...common(p),
344
+ env: j.env ?? common(p).env,
258
345
  prompt,
259
346
  resume: ran.session_id,
260
347
  timeoutMs,
@@ -302,6 +389,7 @@ export async function runJob(p) {
302
389
  capped: false,
303
390
  deadline: Date.now() + p.timeoutMs,
304
391
  waits: 0,
392
+ reserveWaits: 0,
305
393
  after: Boolean(p.afterSession) && p.adapter.caps.resume,
306
394
  };
307
395
  const kind = firstKind(p);
@@ -346,10 +434,13 @@ async function noReset(j, kind, rec) {
346
434
  async function overLimit(j, s) {
347
435
  while (s.ran.limit && !s.ran.stopped && !(await j.p.done?.())) {
348
436
  const { reset, handover, state } = limitState(j, s);
349
- if (handover && (await pastCap(j))) return;
437
+ const counts = spends(handover, s.ran);
438
+ if (counts && (await pastCap(j))) return;
350
439
  const waited = await limitWait(j, reset, state);
351
440
  if (waited === 'stopped') s.ran = { ...s.ran, stopped: true };
352
- if (waited !== 'reset' || (handover && (await capped(j)))) return;
441
+ // Held during the wait: the job ends, the limit and its session kept (Hold-Plan d7).
442
+ if (waited === 'held') s.ran = { ...s.ran, held: /** @type {string} */ (heldNow(j.p)) };
443
+ if (waited !== 'reset' || (counts && (await capped(j)))) return;
353
444
  await afterReset(j, s, handover);
354
445
  }
355
446
  }
@@ -368,7 +459,8 @@ function limitState(j, s) {
368
459
  if (reset.at) s.ran.limit = { ...s.ran.limit, at: reset.at.toISOString() };
369
460
  // A project chat's flag only marks the share: it hands over by its summary turn, so the
370
461
  // session it was in goes on after the wait.
371
- const handover = s.ran.handoff && !p.handoff?.soft;
462
+ // A planning session that converged goes on fresh, not resumed: the implementation is its own.
463
+ const handover = (s.ran.handoff && !p.handoff?.soft) || Boolean(s.ran.phaseEnded);
372
464
  const state = {
373
465
  ...s.ran,
374
466
  handoffs: j.handoffs,
@@ -398,6 +490,12 @@ async function afterReset(j, s, handover) {
398
490
  s.base = base;
399
491
  }
400
492
 
493
+ /** A handover the cap counts: the reserve's and the plan phase's spend none (d14, review 5). */
494
+ const spends = (handover, ran) => handover && !free(ran);
495
+
496
+ /** A handoff that is not the context's: the reserve's, or the planning phase's end (d14). */
497
+ const free = (ran) => ran.held === 'reserve' || Boolean(ran.phaseEnded);
498
+
401
499
  /** The sessions of the job, from its first `kind` on. */
402
500
  async function chain(j, kind, rec) {
403
501
  const { p } = j;
@@ -410,7 +508,8 @@ async function chain(j, kind, rec) {
410
508
  let turn = await after(j, s.ran, s.base);
411
509
  s.cost = addCost(s.cost, turn.cost);
412
510
  const values = [turn.value];
413
- while ((await goesOn(j, s.ran)) && !(await capped(j))) {
511
+ // A fresh session after the reserve's wait is no context handoff: it spends none (d14).
512
+ while ((await goesOn(j, s.ran)) && (free(s.ran) || !(await capped(j)))) {
414
513
  p.onHandoff?.(j.handoffs);
415
514
  Object.assign(s, { kind: 'handoff', rec: null, base: 0 });
416
515
  s.ran = await session(j, 'handoff', null);
@@ -47,7 +47,7 @@ function absorb(seen, a) {
47
47
  */
48
48
  function handoffWatch(handoff, windowOf, write, { stop, onFlag, fresh = false }) {
49
49
  /** @type {{flagged: boolean, after: number, context: number, turn?: string, unknown: boolean,
50
- * info?: object, readings: number, under: boolean}} */
50
+ * info?: object, readings: number, under: boolean, held?: string, hardStop?: boolean}} */
51
51
  const w = {
52
52
  ...{ flagged: false, after: 0, context: 0, turn: undefined, unknown: false },
53
53
  ...{ readings: 0, under: false },
@@ -97,6 +97,7 @@ function handoffWatch(handoff, windowOf, write, { stop, onFlag, fresh = false })
97
97
 
98
98
  return {
99
99
  state: w,
100
+ hold: holdOf(w, handoff, write),
100
101
  see(a, model) {
101
102
  if (a.context !== undefined) {
102
103
  w.context = a.context;
@@ -107,10 +108,33 @@ function handoffWatch(handoff, windowOf, write, { stop, onFlag, fresh = false })
107
108
 
108
109
  if (handoff?.pct && (a.context !== undefined || a.compacted))
109
110
  check(model, Boolean(a.compacted));
111
+ heldTooLong(w, write, stop);
110
112
  },
111
113
  };
112
114
  }
113
115
 
116
+ /** A held session's own hard stop (`w` its watch): `check` runs only with a share to watch. */
117
+ function heldTooLong(w, write, stop) {
118
+ if (!w.held || w.hardStop || w.after <= HARD_TURNS) return;
119
+ w.hardStop = true;
120
+ write([`[${clock()}] handoff: the session went on past its ${w.held}, stopped`]);
121
+ stop();
122
+ }
123
+
124
+ /**
125
+ * The operator's Hold or the quota's reserve (Hold-Plan d4) of a watched session (`w`): it hands
126
+ * over at its next call, as at its share, with the reason the guard tells it. Once.
127
+ */
128
+ const holdOf = (w, handoff, write) => (reason) => {
129
+ if (w.held) return false;
130
+ w.held = reason;
131
+ w.flagged = true;
132
+ handoff?.flag?.({ reason });
133
+ write([`[${clock()}] handoff: ${reason}, the session hands over`]);
134
+
135
+ return true;
136
+ };
137
+
114
138
  /**
115
139
  * The last usage-limit state a session's stream gave, with its time; a failed write loses it.
116
140
  * The last writer wins on purpose: it is the latest state (AD-34).
@@ -196,15 +220,32 @@ function haltWatch(halt, stop) {
196
220
  return t;
197
221
  }
198
222
 
223
+ /**
224
+ * The hold of a session (`hold`, Hold-Plan d4): its reason, once it comes, goes to `onHold`. The
225
+ * watch, to clear at the session's end.
226
+ */
227
+ function holdWatch(hold, onHold) {
228
+ if (!hold) return undefined;
229
+ const t = setInterval(() => {
230
+ const reason = hold();
231
+ if (reason) onHold(reason);
232
+ }, HALT_POLL_MS);
233
+ t.unref();
234
+
235
+ return t;
236
+ }
237
+
199
238
  /**
200
239
  * A session's timeout that stands still while the session waits for the operator (`pause`);
201
240
  * `waited()` is how long it stood. After `stop()` nothing starts it again. The operator's stop
202
241
  * (`halt`) is watched with it.
203
242
  * @param {number} ms
204
243
  * @param {() => void} onTimeout
205
- * @param {{halt?: () => boolean, stop: () => void}} onHalt
244
+ * @param {{halt?: () => boolean, stop: () => void, hold?: () => string | null,
245
+ * onHold?: (reason: string) => void}} onHalt the operator's stop, and the hold (`holdWatch`)
206
246
  */
207
247
  function sessionTimeout(ms, onTimeout, onHalt) {
248
+ const holding = holdWatch(onHalt.hold, onHalt.onHold);
208
249
  /** @type {{left: number, since: number, timer?: NodeJS.Timeout, waited: number,
209
250
  * pausedAt: number | null, stopped: boolean}} */
210
251
  const t = { left: ms, since: Date.now(), waited: 0, pausedAt: null, stopped: false };
@@ -235,6 +276,7 @@ function sessionTimeout(ms, onTimeout, onHalt) {
235
276
  t.stopped = true;
236
277
  clearTimeout(t.timer);
237
278
  clearInterval(halting);
279
+ clearInterval(holding);
238
280
  resume();
239
281
  },
240
282
  waited: () => t.waited,
@@ -258,6 +300,8 @@ function sessionTimeout(ms, onTimeout, onHalt) {
258
300
  * @property {string | null} [quota] the file the last usage-limit state goes to
259
301
  * @property {any} [chat] the chat's options (chat.js `openChat`)
260
302
  * @property {() => boolean} [halt] the operator stopped the work: the session ends at once
303
+ * @property {() => string | null} [hold] why the session is to hand over now (`hold`, `reserve`):
304
+ * it is flagged with that reason; a chat waiting for the operator closes at once
261
305
  * @property {((events: import('./activity.js').Neutral[]) => void) | null} [observe]
262
306
  * @property {boolean} [ownReply] the caller reads the reply and logs what it made of it: the log
263
307
  * does not get the reply's text (a lessons turn's JSON)
@@ -282,7 +326,8 @@ function sessionTimeout(ms, onTimeout, onHalt) {
282
326
  * @param {SessionSpec} s
283
327
  * @returns {Promise<{code: number | string, cost?: import('./activity.js').Cost,
284
328
  * session_id?: string, limit?: {resets: string | null}, gone: boolean, handoff: boolean,
285
- * handedOver: boolean, model?: string, window?: number, result?: string, waited: number}>}
329
+ * handedOver: boolean, model?: string, window?: number, result?: string, waited: number,
330
+ * held?: string}>}
286
331
  */
287
332
  export function runSession(s) {
288
333
  const { adapter, fd, timeoutMs, id, onSpawn, handoff, quota, chat, observe, halt, ownReply } = s;
@@ -312,7 +357,9 @@ export function runSession(s) {
312
357
  onFlag: flagged,
313
358
  fresh: !s.resume,
314
359
  });
315
- const limit = sessionTimeout(timeoutMs, stop('timeout'), { halt, stop: stop('stopped') });
360
+ const onHold = (reason) => open && watch.hold(reason) && talk?.held(reason);
361
+ const halts = { halt, hold: s.hold, onHold, stop: stop('stopped') };
362
+ const limit = sessionTimeout(timeoutMs, stop('timeout'), halts);
316
363
  /** @type {((tokens: number, model?: string) => void) | null} */
317
364
  let shown = null;
318
365
  if (chat) {
@@ -348,12 +395,7 @@ export function runSession(s) {
348
395
  const code = talk?.why() ?? exit;
349
396
  if (talk) talk.close(code, seen);
350
397
  sessions.delete(child);
351
- const { flagged, after } = watch.state;
352
- // Told to hand over, and it went on past the flag: it read the guard's instruction, or the
353
- // run stopped it. A flag on its last turn found a session already done.
354
- // A project chat hands over by its summary turn, the operator's button too: unflagged.
355
- const handedOver = code === 'handoff' || (flagged && after > 0);
356
- resolve({ ...seen, code, gone, handoff: flagged, handedOver, waited: limit.waited() });
398
+ resolve(resultOf(seen, watch.state, { code, gone, waited: limit.waited() }));
357
399
  }
358
400
 
359
401
  child.on('error', () => end(-1));
@@ -364,6 +406,18 @@ export function runSession(s) {
364
406
  });
365
407
  }
366
408
 
409
+ /**
410
+ * A session's result. Told to hand over, and it went on past the flag: it read the guard's
411
+ * instruction, or the run stopped it. A flag on its last turn found a session already done. A
412
+ * project chat hands over by its summary turn, the operator's button too: unflagged.
413
+ */
414
+ function resultOf(seen, w, { code, gone, waited }) {
415
+ const handedOver = code === 'handoff' || (w.flagged && w.after > 0);
416
+ const why = w.held ? { held: w.held } : {};
417
+
418
+ return { ...seen, code, gone, handoff: w.flagged, handedOver, waited, ...why };
419
+ }
420
+
367
421
  /** A tool the agent left running may hold its output open: the pipes close soon after it exits. */
368
422
  function letGo(child) {
369
423
  child.on('exit', () =>