gcf-board 0.7.0 → 0.8.2

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.
@@ -11,6 +11,9 @@ import { writeAtomic } from './store.js';
11
11
  const HARD_TURNS = 8;
12
12
  const HARD_OVER = 15;
13
13
 
14
+ /** How often a session that may be stopped (`halt`) looks for the stop. */
15
+ const HALT_POLL_MS = 1000;
16
+
14
17
  /**
15
18
  * Keep what a session's activity told: the last of each, and the model's window from the result.
16
19
  */
@@ -153,14 +156,34 @@ function launchSession(s) {
153
156
  return spawnAgent(command, dir, { ...env, ...adapter.env(dir) }, Boolean(chat));
154
157
  }
155
158
 
159
+ /**
160
+ * The operator's stop of a session that may be stopped (`halt`): `stop` once it comes, without
161
+ * waiting for the session's `close`, which a tool that outlived the kill may hold off by keeping
162
+ * the pipes open. The watch, to clear at the session's end.
163
+ */
164
+ function haltWatch(halt, stop) {
165
+ if (!halt) return undefined;
166
+ const t = setInterval(() => {
167
+ if (halt()) stop();
168
+ }, HALT_POLL_MS);
169
+ t.unref();
170
+
171
+ return t;
172
+ }
173
+
156
174
  /**
157
175
  * A session's timeout that stands still while the session waits for the operator (`pause`);
158
- * `waited()` is how long it stood. After `stop()` nothing starts it again.
176
+ * `waited()` is how long it stood. After `stop()` nothing starts it again. The operator's stop
177
+ * (`halt`) is watched with it.
178
+ * @param {number} ms
179
+ * @param {() => void} onTimeout
180
+ * @param {{halt?: () => boolean, stop: () => void}} onHalt
159
181
  */
160
- function sessionTimeout(ms, onTimeout) {
182
+ function sessionTimeout(ms, onTimeout, onHalt) {
161
183
  /** @type {{left: number, since: number, timer?: NodeJS.Timeout, waited: number,
162
184
  * pausedAt: number | null, stopped: boolean}} */
163
185
  const t = { left: ms, since: Date.now(), waited: 0, pausedAt: null, stopped: false };
186
+ const halting = haltWatch(onHalt.halt, onHalt.stop);
164
187
  const arm = () => {
165
188
  t.since = Date.now();
166
189
  t.timer = setTimeout(onTimeout, t.left);
@@ -186,6 +209,7 @@ function sessionTimeout(ms, onTimeout) {
186
209
  stop: () => {
187
210
  t.stopped = true;
188
211
  clearTimeout(t.timer);
212
+ clearInterval(halting);
189
213
  resume();
190
214
  },
191
215
  waited: () => t.waited,
@@ -208,6 +232,7 @@ function sessionTimeout(ms, onTimeout) {
208
232
  * @property {any} [handoff] `{pct, windowOf(model, live), flag(info)}`
209
233
  * @property {string | null} [quota] the file the last usage-limit state goes to
210
234
  * @property {any} [chat] the chat's options (chat.js `openChat`)
235
+ * @property {() => boolean} [halt] the operator stopped the work: the session ends at once
211
236
  * @property {((events: import('./activity.js').Neutral[]) => void) | null} [observe]
212
237
  */
213
238
 
@@ -233,7 +258,7 @@ function sessionTimeout(ms, onTimeout) {
233
258
  * handedOver: boolean, model?: string, window?: number, result?: string, waited: number}>}
234
259
  */
235
260
  export function runSession(s) {
236
- const { adapter, fd, timeoutMs, id, onSpawn, handoff, quota, chat, observe } = s;
261
+ const { adapter, fd, timeoutMs, id, onSpawn, handoff, quota, chat, observe, halt } = s;
237
262
 
238
263
  return new Promise((resolve) => {
239
264
  const child = launchSession(s);
@@ -259,7 +284,7 @@ export function runSession(s) {
259
284
  stop: stop('handoff'),
260
285
  onFlag: flagged,
261
286
  });
262
- const limit = sessionTimeout(timeoutMs, stop('timeout'));
287
+ const limit = sessionTimeout(timeoutMs, stop('timeout'), { halt, stop: stop('stopped') });
263
288
  /** @type {((tokens: number, model?: string) => void) | null} */
264
289
  let shown = null;
265
290
  if (chat) {
@@ -272,7 +297,8 @@ export function runSession(s) {
272
297
  const a = adapter.parse(line);
273
298
  // The result's window first: the chat's context share of this line is taken of it.
274
299
  absorb(seen, a);
275
- if (talk) talk.see(a.events);
300
+ // A stopped session ended before its pipes: what it still wrote reaches no chat.
301
+ if (talk && open) talk.see(a.events);
276
302
  if (a.quota && quota) keepQuota(quota, a.quota);
277
303
  observe?.(a.events);
278
304
  write(a.lines);
@@ -284,9 +310,10 @@ export function runSession(s) {
284
310
  write([line]);
285
311
  });
286
312
  function end(exit) {
287
- if (!open) return;
288
313
  flushOut();
289
314
  flushErr();
315
+ // Ended already, by an earlier call or by a last line that stopped it.
316
+ if (!open) return;
290
317
  open = false;
291
318
  limit.stop();
292
319
  // A project chat that closed its session says why: `idle`, `handoff`.
@@ -2,7 +2,8 @@
2
2
  // project's folder, run as a job with a chat policy. Its files live in `.gcf-session/chats/<t>/`:
3
3
  // `thread.json` (its sessions), `chat.jsonl` (what the operator reads), `chat-in.jsonl` (what
4
4
  // the operator writes), `att/` (pictures), `context.md` (what the center gives it to read),
5
- // `handoff-<n>.md` (the summaries its sessions handed over by), `spec.json` (how it runs).
5
+ // `handoff-<n>.md` (the summaries its sessions handed over by), `spec.json` (how it runs),
6
+ // `agent.json` (the model and effort the operator picked).
6
7
  import { randomBytes } from 'node:crypto';
7
8
  import {
8
9
  closeSync,
@@ -16,9 +17,12 @@ import {
16
17
  } from 'node:fs';
17
18
  import path from 'node:path';
18
19
  import { createHash } from 'node:crypto';
20
+ import { PICKS } from './adapter/claude.js';
19
21
  import { adapterFor } from './adapter/index.js';
20
22
  import { runJob } from './job.js';
21
- import { alive, killTree } from './proc.js';
23
+ import { postTo, readFrom } from './chat.js';
24
+ import { realClock } from './limit.js';
25
+ import { alive } from './proc.js';
22
26
  import { chatsDir, runsDir, writeAtomic } from './store.js';
23
27
  import { readWindows, windowFor } from './windows.js';
24
28
 
@@ -28,9 +32,15 @@ export const THREAD_ID = /^t[0-9a-f]{8}$/;
28
32
  /** The share of the window a thread hands over at when the domain names none (AD-43). */
29
33
  export const HANDOFF_PCT = 60;
30
34
 
31
- /** How often a live session's thread looks for its stop mark. */
35
+ /** How often a thread waiting for the usage limit looks for its stop mark. */
32
36
  const STOP_POLL_MS = 1000;
33
37
 
38
+ // The limit wait's clock: the operator's stop ends it within a second, not at the next poll.
39
+ const stopClock = {
40
+ now: realClock.now,
41
+ sleep: (ms) => realClock.sleep(Math.min(ms, STOP_POLL_MS)),
42
+ };
43
+
34
44
  /** How long a summary turn may take before it counts as failed (AD-42). */
35
45
  export const SUMMARY_MS = 2 * 60_000;
36
46
 
@@ -82,6 +92,56 @@ function keepTrying(dir, t, rec) {
82
92
  }
83
93
  }
84
94
 
95
+ // A picked model or effort goes into the agent's shell command: one plain word, no flag.
96
+ const PICK_WORD = /^[A-Za-z0-9][\w.-]*$/;
97
+
98
+ // The pick that leaves the choice to the agent.
99
+ const AGENT_DEFAULT = 'default';
100
+
101
+ const pickFile = (td) => path.join(td, 'agent.json');
102
+
103
+ /** A pick's word, or null for the agent's own: none, `default`, or a word that is not plain. */
104
+ const wordOf = (v) =>
105
+ typeof v === 'string' && v !== AGENT_DEFAULT && PICK_WORD.test(v) ? v : null;
106
+
107
+ /** What `agent.json` of folder `td` picks, `{model?, effort?}`; a hand edit's bad word left out. */
108
+ function pickIn(td) {
109
+ try {
110
+ const v = JSON.parse(readFileSync(pickFile(td), 'utf8'));
111
+
112
+ return Object.fromEntries(PICKS.flatMap((k) => (wordOf(v?.[k]) ? [[k, v[k]]] : [])));
113
+ } catch {
114
+ return {};
115
+ }
116
+ }
117
+
118
+ /** The model and effort thread `t`'s sessions run on, `{model?, effort?}`; none: the agent's. */
119
+ export const threadAgent = (dir, t) => pickIn(threadDir(dir, t));
120
+
121
+ /**
122
+ * Pick the model and effort of thread `t` (Board-PRD decision 24): each a plain word, `default`
123
+ * or null the agent's own choice, one left out kept as it is. Its next session takes them (a
124
+ * resume or a fresh agent); the live one keeps its own. Returns the pick kept. A word that is not
125
+ * plain is a RangeError.
126
+ * @param {{model?: string | null, effort?: string | null}} pick
127
+ */
128
+ export function setThreadAgent(dir, t, pick) {
129
+ for (const k of PICKS)
130
+ if (pick[k] && !PICK_WORD.test(pick[k]))
131
+ throw new RangeError(`${k} is one plain word, e.g. opus`);
132
+ const was = threadAgent(dir, t);
133
+ const kept = Object.fromEntries(
134
+ PICKS.flatMap((k) => {
135
+ const v = pick[k] === undefined ? was[k] : wordOf(pick[k]);
136
+
137
+ return v ? [[k, v]] : [];
138
+ }),
139
+ );
140
+ writeAtomic(pickFile(threadDir(dir, t)), `${JSON.stringify(kept)}\n`);
141
+
142
+ return kept;
143
+ }
144
+
85
145
  /** The thread bound to `item`, or null (AD-46). */
86
146
  export function threadOf(dir, item) {
87
147
  try {
@@ -205,18 +265,20 @@ function promptFile(td, spec, summary) {
205
265
 
206
266
  /**
207
267
  * The flags of a thread's session: ask mode with the spec's rules (AD-5), the project's settings,
208
- * the MCP servers (the project's and the center's), and the prompt file at a start or a handoff.
268
+ * the MCP servers (the project's and the center's), the prompt file at a start or a handoff, and
269
+ * the model and effort picked (`pick`).
209
270
  * shortcut: claude's flags written out here; move them into the adapter with a second provider.
210
271
  */
211
- function flagsOf(dir, td, spec, settings) {
272
+ function flagsOf({ dir, td, spec, adapter }, settings) {
212
273
  const mcp = [
213
274
  ...(existsSync(path.join(dir, '.mcp.json')) ? ['.mcp.json'] : []),
214
275
  ...(spec.mcp ?? []),
215
276
  ];
216
277
 
217
- return (kind, summary) =>
278
+ return (kind, summary, pick) =>
218
279
  [
219
280
  '--permission-mode default --setting-sources project,local',
281
+ adapter.pickFlags(pick),
220
282
  `--settings "${settings}"`,
221
283
  ...(mcp.length ? ['--strict-mcp-config', ...mcp.map((f) => `--mcp-config "${f}"`)] : []),
222
284
  kind === 'resume' ? '' : `--append-system-prompt-file "${promptFile(td, spec, summary)}"`,
@@ -241,35 +303,81 @@ export async function runThread(dir, t, spec, opts = {}) {
241
303
  const last = rec.sessions.at(-1) ?? null;
242
304
  const s = {
243
305
  ...{ dir, t, td, rec, spec, adapter, stopped },
244
- flags: flagsOf(dir, td, spec, settingsOf(td, adapter, spec.rules)),
306
+ flags: flagsOf({ dir, td, spec, adapter }, settingsOf(td, adapter, spec.rules)),
307
+ // The model and effort of the session starting now: read afresh for each (agent.json).
308
+ pick: {},
245
309
  learned: readWindows(runsDir(dir)),
246
310
  input: inputOf(dir, t, rec),
247
311
  // The newest summary: a fresh start after a lost resume goes on from it too.
248
312
  summary: rec.sessions.findLast((x) => x.summary)?.summary ?? null,
249
313
  saved: /** @type {string | null} */ (null),
250
314
  started: contextHash(td),
251
- pid: 0,
252
315
  fd: openSync(path.join(td, 'thread.log'), 'a'),
253
316
  };
254
- // A stop ends the live session too, not only a wait between sessions.
255
- const watchStop = setInterval(() => {
256
- if (s.pid && stopped()) killTree(s.pid);
257
- }, STOP_POLL_MS);
258
- watchStop.unref();
317
+ /** @type {any} */
318
+ let ran = null;
259
319
  try {
260
320
  // The last session: resumed, or a fresh one from its summary after a handoff.
261
- const ran = await runJob(jobOf(s, goesOn(last)));
262
-
321
+ ran = await runJob(jobOf(s, goesOn(last)));
263
322
  // The session it resumed is gone: a fresh one takes the operator's message.
264
- return ran.lost && !stopped() ? await runJob(jobOf(s, null)) : ran;
323
+ if (ran.lost && !stopped()) ran = await runJob(jobOf(s, null));
324
+
325
+ return ran;
265
326
  } finally {
266
- clearInterval(watchStop);
327
+ // A stop that came after the session ended by itself closed nothing; one that came after a
328
+ // lost resume kept the fresh session from starting.
329
+ if (ran ? ran.stopped || (ran.lost && stopped()) : stopped()) closed(s);
267
330
  closeSync(s.fd);
268
331
  }
269
332
  }
270
333
 
334
+ /**
335
+ * The operator closed the thread's agent: what they wrote that no session took in is dropped,
336
+ * each message with its error line, and the chat says the agent is closed (AD-52). A message
337
+ * the agent had not yet acknowledged counts as not taken: it may have been lost with it.
338
+ */
339
+ function closed(s) {
340
+ const { rec, td } = s;
341
+ const out = path.join(td, 'chat.jsonl');
342
+ const { lines, next } = readFrom(path.join(td, 'chat-in.jsonl'), Number(rec.in_at) || 0);
343
+ const says = lines.flatMap((l) => {
344
+ try {
345
+ const e = JSON.parse(l);
346
+
347
+ return e?.type === 'say' ? [{ text: String(e.text ?? '').slice(0, 80), id: e.id }] : [];
348
+ } catch {
349
+ return [];
350
+ }
351
+ });
352
+ rec.in_at = next;
353
+ rec.in_read = Math.max(Number(rec.in_read) || 0, next);
354
+ // The record before the word: unwritten, the board would start the thread again with what the
355
+ // operator is told was dropped. A scanner's hold on the file passes in a moment.
356
+ for (let tries = 1; ; tries++)
357
+ try {
358
+ writeThread(s.dir, s.t, rec);
359
+ break;
360
+ } catch (e) {
361
+ if (tries === 3) throw e;
362
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
363
+ }
364
+
365
+ for (const { text, id } of says)
366
+ postTo(out, {
367
+ type: 'error',
368
+ text: `the agent was closed, not sent: ${text}`,
369
+ ...(typeof id === 'string' ? { id } : {}),
370
+ });
371
+ postTo(out, { type: 'closed', dropped: says.length });
372
+ }
373
+
271
374
  const CHANGED = "The thread's context changed since this session began:";
272
375
 
376
+ // The first message of a session the operator closed, resumed (AD-52).
377
+ const CLOSED =
378
+ 'The operator closed your last session: the processes it started (servers, watchers, ' +
379
+ 'background tasks) are stopped.';
380
+
273
381
  // The first message of a session the usage limit cut, after its reset: the operator's last
274
382
  // message got no answer.
275
383
  const AFTER_LIMIT =
@@ -315,7 +423,10 @@ function keep(s, ran, kind) {
315
423
  const { rec, input } = s;
316
424
  rec.sessions.push({
317
425
  ...(ran.session_id ? { session_id: ran.session_id } : {}),
318
- ended: String(ran.code),
426
+ // Stopped as it idled out: what it started is killed all the same, and its resume is told.
427
+ ended: ran.stopped && ran.code === 'idle' ? 'stopped' : String(ran.code),
428
+ // Closed by the operator as it handed over: the fresh session is told too.
429
+ ...(ran.stopped ? { stopped: true } : {}),
319
430
  kind,
320
431
  context: s.started,
321
432
  ...(ran.code === 'handoff' && s.saved ? { summary: s.saved } : {}),
@@ -350,6 +461,19 @@ const handoverOf = (s) => ({
350
461
  },
351
462
  });
352
463
 
464
+ /**
465
+ * What the session's first message starts with: the operator's close of the session before
466
+ * (AD-52), the context that changed since it began; null for nothing.
467
+ */
468
+ function prefixOf(td, prev, changed) {
469
+ const parts = [
470
+ prev?.stopped || prev?.ended === 'stopped' ? CLOSED : null,
471
+ changed ? `${CHANGED}\n\n${readOr(path.join(td, 'context.md'))}` : null,
472
+ ].filter(Boolean);
473
+
474
+ return parts.length ? parts.join('\n\n') : null;
475
+ }
476
+
353
477
  /** The chat of a thread's session of `kind`, after the session `prev`. */
354
478
  function chatOf(s, kind, prev) {
355
479
  const { dir, td, rec, spec } = s;
@@ -374,12 +498,13 @@ function chatOf(s, kind, prev) {
374
498
  saveAlways: (rule) => s.adapter.saveAlways(dir, rule),
375
499
  handover: handoverOf(s),
376
500
  summary: kind === 'handoff' ? s.summary : null,
501
+ pick: s.pick,
377
502
  fresh: kind === 'handoff' || Boolean(rec.unheard),
378
503
  onHeard: () => {
379
504
  rec.unheard = false;
380
505
  keepTrying(dir, s.t, rec);
381
506
  },
382
- prefix: changed ? `${CHANGED}\n\n${readOr(path.join(td, 'context.md'))}` : null,
507
+ prefix: prefixOf(td, prev, changed),
383
508
  onPrefix: () => {
384
509
  s.started = now;
385
510
  },
@@ -401,14 +526,15 @@ function jobOf(s, record) {
401
526
  record,
402
527
  // A thread starts on the operator's message; after the usage limit's wait, on this.
403
528
  prompt: (kind, _caps, rec) => (rec?.ended === 'limit' ? AFTER_LIMIT : null),
404
- flags: (kind) => s.flags(kind, s.summary),
405
- onSpawn: (p) => {
406
- s.pid = p;
407
- },
408
- onIdle: () => {
409
- s.pid = 0;
529
+ // The flags come before the chat of each session (job.js): the chat says what they picked.
530
+ flags: (kind) => {
531
+ s.pick = pickIn(s.td);
532
+
533
+ return s.flags(kind, s.summary, s.pick);
410
534
  },
411
535
  stopped: s.stopped,
536
+ halt: true,
537
+ clock: stopClock,
412
538
  chatFile: path.join(s.td, 'chat.jsonl'),
413
539
  handoff: {
414
540
  pct: Number(spec.handoffPct) > 0 ? Number(spec.handoffPct) : HANDOFF_PCT,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-session",
3
- "version": "0.12.1",
3
+ "version": "0.12.4",
4
4
  "private": true,
5
5
  "description": "The session engine of GCF: one agent session and a run as a chain of them, the chat protocol, the provider adapters. Bundled by gcf-harness-aif-ext and gcf-board, never published.",
6
6
  "type": "module",
@@ -10,14 +10,24 @@ interface At {
10
10
 
11
11
  export type ChatEvent = At &
12
12
  (
13
- | { type: 'session'; kind: 'start' | 'resume' | 'handoff'; v?: number; summary?: string }
13
+ | {
14
+ type: 'session';
15
+ kind: 'start' | 'resume' | 'handoff';
16
+ v?: number;
17
+ summary?: string;
18
+ /** A project chat's: the model and effort it started with; null, the agent's own. */
19
+ model?: string | null;
20
+ effort?: string | null;
21
+ }
14
22
  | {
15
23
  type: 'session_end';
16
- code: number | 'timeout' | 'handoff' | 'idle' | string;
24
+ code: number | 'timeout' | 'handoff' | 'idle' | 'stopped' | string;
17
25
  cost_usd: number | null;
18
26
  limit_resets?: string | null;
19
27
  }
20
28
  | { type: 'limit'; until: string }
29
+ /** A project chat's: the operator closed its agent; `dropped` messages it never took in. */
30
+ | { type: 'closed'; dropped: number }
21
31
  | {
22
32
  type: 'say';
23
33
  by: 'run' | 'operator' | 'timeout' | 'engine';
@@ -33,7 +43,8 @@ export type ChatEvent = At &
33
43
  | { type: 'waiting'; kind: 'card' | 'text' | 'stop' }
34
44
  | { type: 'timeout'; kind: 'card' | 'text' }
35
45
  | { type: 'interrupt' }
36
- | { type: 'error'; text: string }
46
+ /** `id`: the input line of the operator's message it did not send, when it has one. */
47
+ | { type: 'error'; text: string; id?: string }
37
48
  | { type: 'background'; tasks: { id: string; description: string }[] }
38
49
  | {
39
50
  type: 'question';
@@ -139,6 +150,25 @@ export interface ThreadSpec {
139
150
  timeoutMin?: number;
140
151
  }
141
152
 
153
+ /** The model and effort an operator picked, `chats/<t>/agent.json`: none, the agent's own. */
154
+ export interface AgentPick {
155
+ model?: string;
156
+ effort?: string;
157
+ }
158
+
159
+ /** What an agent command offers to pick from (Board-PRD decision 24). */
160
+ export interface AgentPresets {
161
+ model: string[];
162
+ effort: string[];
163
+ }
164
+
165
+ export declare function threadAgent(dir: string, t: string): AgentPick;
166
+ export declare function setThreadAgent(
167
+ dir: string,
168
+ t: string,
169
+ pick: { model?: string | null; effort?: string | null },
170
+ ): AgentPick;
171
+ export declare function presetsOf(agent: string): AgentPresets;
142
172
  export declare function createThread(dir: string, opts?: { item?: string | null }): string;
143
173
  export declare function threadOf(dir: string, item: string): string | null;
144
174
  export declare function threadDir(dir: string, t: string): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-board",
3
- "version": "0.7.0",
3
+ "version": "0.8.2",
4
4
  "description": "A local web board for GCF game projects: shows `gcf board --json` and runs the same ai-factory gcf commands an operator runs in a console",
5
5
  "type": "module",
6
6
  "license": "MIT",