gcf-board 0.7.0 → 0.8.1

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.
@@ -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,77 @@ 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' ? [String(e.text ?? '').slice(0, 80)] : [];
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 of says)
366
+ postTo(out, { type: 'error', text: `the agent was closed, not sent: ${text}` });
367
+ postTo(out, { type: 'closed', dropped: says.length });
368
+ }
369
+
271
370
  const CHANGED = "The thread's context changed since this session began:";
272
371
 
372
+ // The first message of a session the operator closed, resumed (AD-52).
373
+ const CLOSED =
374
+ 'The operator closed your last session: the processes it started (servers, watchers, ' +
375
+ 'background tasks) are stopped.';
376
+
273
377
  // The first message of a session the usage limit cut, after its reset: the operator's last
274
378
  // message got no answer.
275
379
  const AFTER_LIMIT =
@@ -315,7 +419,10 @@ function keep(s, ran, kind) {
315
419
  const { rec, input } = s;
316
420
  rec.sessions.push({
317
421
  ...(ran.session_id ? { session_id: ran.session_id } : {}),
318
- ended: String(ran.code),
422
+ // Stopped as it idled out: what it started is killed all the same, and its resume is told.
423
+ ended: ran.stopped && ran.code === 'idle' ? 'stopped' : String(ran.code),
424
+ // Closed by the operator as it handed over: the fresh session is told too.
425
+ ...(ran.stopped ? { stopped: true } : {}),
319
426
  kind,
320
427
  context: s.started,
321
428
  ...(ran.code === 'handoff' && s.saved ? { summary: s.saved } : {}),
@@ -350,6 +457,19 @@ const handoverOf = (s) => ({
350
457
  },
351
458
  });
352
459
 
460
+ /**
461
+ * What the session's first message starts with: the operator's close of the session before
462
+ * (AD-52), the context that changed since it began; null for nothing.
463
+ */
464
+ function prefixOf(td, prev, changed) {
465
+ const parts = [
466
+ prev?.stopped || prev?.ended === 'stopped' ? CLOSED : null,
467
+ changed ? `${CHANGED}\n\n${readOr(path.join(td, 'context.md'))}` : null,
468
+ ].filter(Boolean);
469
+
470
+ return parts.length ? parts.join('\n\n') : null;
471
+ }
472
+
353
473
  /** The chat of a thread's session of `kind`, after the session `prev`. */
354
474
  function chatOf(s, kind, prev) {
355
475
  const { dir, td, rec, spec } = s;
@@ -374,12 +494,13 @@ function chatOf(s, kind, prev) {
374
494
  saveAlways: (rule) => s.adapter.saveAlways(dir, rule),
375
495
  handover: handoverOf(s),
376
496
  summary: kind === 'handoff' ? s.summary : null,
497
+ pick: s.pick,
377
498
  fresh: kind === 'handoff' || Boolean(rec.unheard),
378
499
  onHeard: () => {
379
500
  rec.unheard = false;
380
501
  keepTrying(dir, s.t, rec);
381
502
  },
382
- prefix: changed ? `${CHANGED}\n\n${readOr(path.join(td, 'context.md'))}` : null,
503
+ prefix: prefixOf(td, prev, changed),
383
504
  onPrefix: () => {
384
505
  s.started = now;
385
506
  },
@@ -401,14 +522,15 @@ function jobOf(s, record) {
401
522
  record,
402
523
  // A thread starts on the operator's message; after the usage limit's wait, on this.
403
524
  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;
525
+ // The flags come before the chat of each session (job.js): the chat says what they picked.
526
+ flags: (kind) => {
527
+ s.pick = pickIn(s.td);
528
+
529
+ return s.flags(kind, s.summary, s.pick);
410
530
  },
411
531
  stopped: s.stopped,
532
+ halt: true,
533
+ clock: stopClock,
412
534
  chatFile: path.join(s.td, 'chat.jsonl'),
413
535
  handoff: {
414
536
  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.3",
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';
@@ -139,6 +149,25 @@ export interface ThreadSpec {
139
149
  timeoutMin?: number;
140
150
  }
141
151
 
152
+ /** The model and effort an operator picked, `chats/<t>/agent.json`: none, the agent's own. */
153
+ export interface AgentPick {
154
+ model?: string;
155
+ effort?: string;
156
+ }
157
+
158
+ /** What an agent command offers to pick from (Board-PRD decision 24). */
159
+ export interface AgentPresets {
160
+ model: string[];
161
+ effort: string[];
162
+ }
163
+
164
+ export declare function threadAgent(dir: string, t: string): AgentPick;
165
+ export declare function setThreadAgent(
166
+ dir: string,
167
+ t: string,
168
+ pick: { model?: string | null; effort?: string | null },
169
+ ): AgentPick;
170
+ export declare function presetsOf(agent: string): AgentPresets;
142
171
  export declare function createThread(dir: string, opts?: { item?: string | null }): string;
143
172
  export declare function threadOf(dir: string, item: string): string | null;
144
173
  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.1",
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",