gcf-board 0.17.1 → 0.18.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.
@@ -12,13 +12,13 @@ import os from 'node:os';
12
12
  import path from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
14
  import { THREAD_ID, createThread, defaultsOf, listThreads, presetsOf, readThread, setThreadAgent, threadAgent, threadDir, threadOf, threadOfEntry, } from 'gcf-session';
15
- import { runModeOf } from '../shared/board.js';
15
+ import { runModeOf, toolOf } from '../shared/board.js';
16
16
  import { writeAtomic } from './atomic.js';
17
- import { briefError } from './cli.js';
17
+ import { briefError, refusalOf } from './cli.js';
18
18
  import { alive } from './events.js';
19
19
  import { HttpError } from './http-error.js';
20
20
  import { IMAGE_EXT } from './chat.js';
21
- import { homeDir } from './registry.js';
21
+ import { homeDir, yoloFile } from './registry.js';
22
22
  // The source runs the .ts files, the package its build beside this file.
23
23
  const own = (name) => fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? `${name}.ts` : `${name}.js`, import.meta.url));
24
24
  const RELAY = own('relay');
@@ -160,6 +160,7 @@ export function talkSpec(p, board, mcp, start = null) {
160
160
  ...(board.context?.window ? { window: board.context.window } : {}),
161
161
  skill: own?.skill ?? chat.skill,
162
162
  mainLock: path.join(p.path, '.gcf-session', 'runs', '.main-run.lock'),
163
+ yolo: yoloFile(),
163
164
  // The project's model and effort: a thread that picked none runs on them.
164
165
  pick: Object.fromEntries(['model', 'effort'].flatMap((k) => board.agent?.[k] ? [[k, board.agent[k]]] : [])),
165
166
  };
@@ -450,6 +451,28 @@ export function chatCard(file) {
450
451
  cards.set(file, { stamp, card });
451
452
  return card;
452
453
  }
454
+ const ends = new Map();
455
+ /** How the last run in a run's chat file ended (`run_end`), or null; read again only when it changed. */
456
+ export function lastRunEnd(file) {
457
+ let stamp = '';
458
+ try {
459
+ const st = statSync(file);
460
+ stamp = `${st.mtimeMs}:${st.size}`;
461
+ }
462
+ catch {
463
+ return null;
464
+ }
465
+ const kept = ends.get(file);
466
+ if (kept?.stamp === stamp)
467
+ return kept.end;
468
+ const events = chatEvents(file);
469
+ const at = events.findLastIndex((e) => e.type === 'run_end');
470
+ // A session started after it: that run has not ended yet.
471
+ const later = events.slice(at + 1).some((e) => e.type === 'session');
472
+ const end = at < 0 || later ? null : events[at];
473
+ ends.set(file, { stamp, end });
474
+ return end;
475
+ }
453
476
  /** The events of a chat file: a thread's, or a run's `<id>.chat.jsonl`; none without one. */
454
477
  /**
455
478
  * The deny group the last session of a run's chat was refused by, for "Allow <group> and run
@@ -479,6 +502,8 @@ export function chatEvents(file) {
479
502
  }
480
503
  });
481
504
  }
505
+ /** What a record keeps that the list does not show. */
506
+ const INNER = ['existed', 'mark', 'head', 'cmd'];
482
507
  const recordsFile = (td) => path.join(td, 'proposals.json');
483
508
  function readRecords(td) {
484
509
  try {
@@ -491,7 +516,28 @@ function readRecords(td) {
491
516
  // One write of a thread's records at a time: each reads, changes and writes the whole file.
492
517
  const writing = new Map();
493
518
  function setRecord(td, id, rec) {
494
- const next = (writing.get(td) ?? Promise.resolve()).then(() => writeAtomic(recordsFile(td), `${JSON.stringify({ ...readRecords(td), [id]: rec }, null, 2)}\n`));
519
+ const next = (writing.get(td) ?? Promise.resolve()).then(() => {
520
+ const all = readRecords(td);
521
+ // The question an answer was proposed for stays with every later state of it.
522
+ const question = rec.question ?? all[id]?.question;
523
+ const kept = question === undefined ? rec : { ...rec, question };
524
+ return writeAtomic(recordsFile(td), `${JSON.stringify({ ...all, [id]: kept }, null, 2)}\n`);
525
+ });
526
+ writing.set(td, next.catch(() => { }));
527
+ return next;
528
+ }
529
+ /**
530
+ * Write `rec` only while proposal `id` has no record yet, in the same queue as setRecord: a
531
+ * click that wrote `accepting` or `accepted` meanwhile wins. Returns the record that holds.
532
+ */
533
+ function addRecord(td, id, rec) {
534
+ const next = (writing.get(td) ?? Promise.resolve()).then(async () => {
535
+ const all = readRecords(td);
536
+ if (all[id])
537
+ return all[id];
538
+ await writeAtomic(recordsFile(td), `${JSON.stringify({ ...all, [id]: rec }, null, 2)}\n`);
539
+ return rec;
540
+ });
495
541
  writing.set(td, next.catch(() => { }));
496
542
  return next;
497
543
  }
@@ -499,18 +545,26 @@ function setRecord(td, id, rec) {
499
545
  const accepting = new Set();
500
546
  /**
501
547
  * Make proposal `id` of thread `t` by its move (AD-16, AD-33): `accepting` is written first,
502
- * with the item it makes and whether that id was taken already; then `accepted` or `refused`
503
- * with the framework's words. `run` is the move; `ids` the items on the board now. A proposal
504
- * made already is made once: a second click, an edited id too, is refused (409), also when a
505
- * board that stopped mid-move left its record `accepting`.
548
+ * with the item it makes, whether that id was taken already and HEAD before it; then `accepted`
549
+ * or `refused` with the framework's words and its machine refusal. `run` is the move; `ids` the
550
+ * items on the board now. A proposal made already is made once: a second click, an edited id
551
+ * too, is refused (409), also when a board that stopped mid-move left its record `accepting`.
552
+ * `question`: for an answer, the question's text now (null when gone): one that changed since
553
+ * the proposal was first seen is refused (409), its id may hold another question now.
506
554
  */
507
- export async function acceptProposal(p, t, id, move, item, ids, run, mark) {
555
+ export async function acceptProposal(p, t, id, move, item, ids, run, mark, question) {
508
556
  const td = writeDir(p, t);
509
557
  const offered = eventsOf(td).find((e) => e.type === 'proposal' && e.id === id);
510
558
  if (offered?.type !== 'proposal')
511
559
  throw new HttpError(404, `no proposal ${id} in thread ${t}`);
512
- if (offered.move !== move)
560
+ // The engine reads the tool's name back with `-` for `:` (verdict:keep comes back verdict-keep).
561
+ if (toolOf(offered.move) !== toolOf(move))
513
562
  throw new HttpError(400, `proposal ${id} is ${offered.move}, not ${move}`);
563
+ if (question !== undefined) {
564
+ const seen = readRecords(td)[id]?.question;
565
+ if (question === null || (seen !== undefined && seen !== question))
566
+ throw new HttpError(409, 'the question changed since it was proposed: ask the agent again');
567
+ }
514
568
  const key = `${td} ${id}`;
515
569
  if (accepting.has(key))
516
570
  throw new HttpError(409, `proposal ${id} is being made already`);
@@ -520,19 +574,23 @@ export async function acceptProposal(p, t, id, move, item, ids, run, mark) {
520
574
  const made = await settled(td, id, readRecords(td)[id], async () => ids, true);
521
575
  if (made?.state === 'accepted')
522
576
  throw new HttpError(409, `proposal ${id} is made already: ${made.item ?? ''}`);
577
+ const head = git(projectOf(td), 'rev-parse', 'HEAD');
523
578
  await setRecord(td, id, {
524
579
  state: 'accepting',
525
580
  item,
526
581
  existed: ids.has(item),
527
582
  ...(mark ? { mark } : {}),
583
+ ...(head ? { head, cmd: move } : {}),
584
+ ...(question ? { question } : {}),
528
585
  at: now(),
529
586
  });
530
587
  const r = await run();
588
+ const refusal = r.ok ? undefined : refusalOf(r.err);
531
589
  await setRecord(td, id, {
532
- // The card shows the core's refusal, not node's stack around it.
590
+ // The card shows the core's refusal, not node's stack around it, and what it can fix.
533
591
  ...(r.ok
534
592
  ? { state: 'accepted', item }
535
- : { state: 'refused', error: briefError(r.err || r.out) }),
593
+ : { state: 'refused', error: briefError(r.err || r.out), ...(refusal && { refusal }) }),
536
594
  at: now(),
537
595
  });
538
596
  return r;
@@ -542,6 +600,25 @@ export async function acceptProposal(p, t, id, move, item, ids, run, mark) {
542
600
  }
543
601
  }
544
602
  const now = () => new Date().toISOString();
603
+ /** The project of a thread's folder: `<project>/.gcf-session/chats/<thread>`. */
604
+ const projectOf = (td) => path.resolve(td, '..', '..', '..');
605
+ /**
606
+ * Whether a commit after `head` made move `cmd` on `item`: its `GCF-Move` trailer, and the item
607
+ * in its `GCF-Items` (an answer names its question in the subject, `gcf(answer): <q-id>`).
608
+ */
609
+ function movedSince(projectDir, head, cmd, item) {
610
+ const log = git(projectDir, 'log', '--format=%s%x1f%b%x1e', `${head}..HEAD`);
611
+ return log.split('\x1e').some((c) => {
612
+ const [subject = '', body = ''] = c.trim().split('\x1f');
613
+ if (!body.split('\n').some((l) => l.trim() === `GCF-Move: ${cmd}`))
614
+ return false;
615
+ // A move with no target (inbox add) names nothing of its own: another one's commit is not it.
616
+ if (!item)
617
+ return false;
618
+ const items = /^GCF-Items: (.*)$/m.exec(body)?.[1].split(', ') ?? [];
619
+ return items.includes(item) || subject === `gcf(answer): ${item}`;
620
+ });
621
+ }
545
622
  /**
546
623
  * A proposal's record, an `accepting` one a board that stopped meanwhile left (AD-33) settled by
547
624
  * the board read (`ids()`, the items on it): its item there and not before, it was made.
@@ -561,11 +638,15 @@ async function settled(td, id, rec, ids, mine = false) {
561
638
  const latest = readRecords(td)[id];
562
639
  if (latest?.state !== 'accepting' || (!mine && accepting.has(`${td} ${id}`)))
563
640
  return latest;
564
- // The project of a thread's folder: `<project>/.gcf-session/chats/<thread>`.
565
- const projectDir = path.resolve(td, '..', '..', '..');
641
+ const projectDir = projectOf(td);
566
642
  const ours = !rec.mark ||
567
643
  git(projectDir, 'log', '-1', '--format=%H', `--grep=^GCF-Proposal: ${rec.mark}$`) !== '';
568
- const made = !rec.existed && Boolean(rec.item) && board.has(rec.item ?? '') && ours;
644
+ // A new item: there now and not before, by its own commit. A move on what is already there
645
+ // (an item, a question): its commit since the HEAD the record kept, by the trailers.
646
+ const made = (!rec.existed && Boolean(rec.item) && board.has(rec.item ?? '') && ours) ||
647
+ (!rec.mark &&
648
+ Boolean(rec.head && rec.cmd) &&
649
+ movedSince(projectDir, rec.head ?? '', rec.cmd ?? '', rec.item ?? ''));
569
650
  const next = made
570
651
  ? { state: 'accepted', item: rec.item, at: now() }
571
652
  : { state: 'refused', error: 'the board stopped while it was made: try again', at: now() };
@@ -575,17 +656,28 @@ async function settled(td, id, rec, ids, mine = false) {
575
656
  /**
576
657
  * Thread `td`'s proposals in the order offered, each with its record. One left `accepting` by
577
658
  * a board that stopped meanwhile (AD-33) is settled by the board read (`ids()`, the items on
578
- * it): its item there and not before, it was made.
659
+ * it). An answer seen for the first time keeps its question's text (`questionOf`): the id may
660
+ * hold another question later.
579
661
  */
580
- async function proposalsOf(td, events, ids) {
662
+ async function proposalsOf(td, events, ids, questionOf, writable = () => td) {
581
663
  const records = readRecords(td);
582
664
  const out = [];
583
665
  for (const e of events) {
584
666
  if (e.type !== 'proposal')
585
667
  continue;
586
- const rec = await settled(td, e.id, records[e.id], ids);
668
+ let rec = await settled(td, e.id, records[e.id], ids);
669
+ const target = typeof e.fields?.id === 'string' ? e.fields.id : '';
670
+ if (!rec && questionOf && target) {
671
+ const question = await questionOf(e.move, target).catch(() => undefined);
672
+ // A folder through a link takes no write (writeDir): no snapshot then.
673
+ if (typeof question === 'string')
674
+ rec = await Promise.resolve()
675
+ .then(() => addRecord(writable(), e.id, { state: 'offered', question }))
676
+ .catch(() => undefined);
677
+ }
587
678
  const shown = { ...(rec ?? { state: 'offered' }) };
588
- delete shown.existed;
679
+ for (const k of INNER)
680
+ delete shown[k];
589
681
  out.push({ id: e.id, move: e.move, ...shown });
590
682
  }
591
683
  return out;
@@ -651,7 +743,7 @@ function sayOf(td) {
651
743
  /** Whether the operator sent thread `t` a message yet. */
652
744
  export const talkSaid = (p, t) => sayOf(dirOf(p, t)) !== null;
653
745
  /** What the list shows of thread `th` (Board-PRD §5.13). */
654
- async function talkOf(p, th, ids) {
746
+ async function talkOf(p, th, ids, questionOf) {
655
747
  const td = threadDir(p.path, th.id);
656
748
  const events = eventsOf(td);
657
749
  const first = sayOf(td);
@@ -677,19 +769,20 @@ async function talkOf(p, th, ids) {
677
769
  card,
678
770
  // A thread whose engine died during the wait waits for nothing.
679
771
  limit_until: live ? limitIn(events) : null,
680
- proposals: await proposalsOf(td, events, ids),
772
+ proposals: await proposalsOf(td, events, ids, questionOf, () => writeDir(p, th.id)),
681
773
  };
682
774
  }
683
775
  /**
684
776
  * The project's threads, newest first; with `item`, its bound one only. `ids()` reads the
685
- * board's items when a proposal needs settling.
777
+ * board's items when a proposal needs settling; `questionOf` the question an answer proposal
778
+ * answers, when it is first seen.
686
779
  */
687
- export async function listTalks(p, ids, item) {
780
+ export async function listTalks(p, ids, item, questionOf) {
688
781
  const threads = listThreads(p.path).filter((th) => !item || th.item === item);
689
782
  // One board read at most, and only when a proposal needs it.
690
783
  let read = null;
691
784
  const once = () => (read ??= ids());
692
- return Promise.all(threads.map((th) => talkOf(p, th, once)));
785
+ return Promise.all(threads.map((th) => talkOf(p, th, once, questionOf)));
693
786
  }
694
787
  /** Where a thread's input is read to, and how far it is written. */
695
788
  function unread(td) {
@@ -0,0 +1,101 @@
1
+ // The account's usage limits, asked of Claude's `/usage` (Board-PRD decision 39): what the top
2
+ // bar shows over the last limit a run reported. The command is free (no model call) and answers
3
+ // in a second or two; it still starts a claude process, so it is asked only while a page is open.
4
+ import { exec } from 'node:child_process';
5
+ import os from 'node:os';
6
+ import { broadcast, watched } from './events.js';
7
+ /** How often an open page's bar is read again, and how long one ask may take. */
8
+ export const USAGE_EVERY_MS = 5 * 60_000;
9
+ const ASK_TIMEOUT_MS = 30_000;
10
+ // No user or local settings, no MCP, no saved session: the user's hooks and plugins do not run
11
+ // for a reading, and the operator's session list gets no entry per ask. The cwd is the temp
12
+ // folder, whose project settings are no one's.
13
+ const FLAGS = '-p "/usage" --output-format stream-json --verbose --no-session-persistence ' +
14
+ '--setting-sources project --strict-mcp-config';
15
+ let command = null;
16
+ let last = null;
17
+ let asking = null;
18
+ let askedAt = 0;
19
+ // An ask still going when the board is configured again writes nothing into the new setup.
20
+ let generation = 0;
21
+ /** Ask with `agent` (claude, or a stand-in in the tests); null asks nothing, as in the tests. */
22
+ export function configureUsage(agent) {
23
+ generation += 1;
24
+ command = agent;
25
+ last = null;
26
+ asking = null;
27
+ askedAt = 0;
28
+ }
29
+ /** The last reading, with the last ask's failure when the ask after it failed; null before any. */
30
+ export const lastUsage = () => last;
31
+ const isLimit = (l) => typeof l === 'object' &&
32
+ l !== null &&
33
+ typeof l.kind === 'string' &&
34
+ typeof l.percent === 'number';
35
+ /**
36
+ * The limits of `/usage`'s stream-json answer: its assistant event's
37
+ * `usage_report.rate_limits.limits`; null when no line carries them (an API-key account has no
38
+ * plan limits, an older claude no report).
39
+ */
40
+ export function limitsOf(out) {
41
+ for (const line of out.split(/\r?\n/)) {
42
+ let e;
43
+ try {
44
+ e = JSON.parse(line);
45
+ }
46
+ catch {
47
+ continue;
48
+ }
49
+ const limits = e?.usage_report?.rate_limits?.limits;
50
+ if (Array.isArray(limits))
51
+ return limits.filter(isLimit);
52
+ }
53
+ return null;
54
+ }
55
+ /**
56
+ * Why an ask failed: the last two lines of its stderr (cmd's "not recognized" spans two), a
57
+ * timeout, or the error itself.
58
+ */
59
+ export function reasonOf(e, err) {
60
+ if (!e)
61
+ return 'claude answered /usage without the plan limits (an API key has none)';
62
+ const tail = err.trim();
63
+ if (tail)
64
+ return tail.split(/\r?\n/).slice(-2).join(' ').slice(0, 300);
65
+ return e.killed ? `no answer in ${ASK_TIMEOUT_MS / 1000} s` : e.message.slice(0, 300);
66
+ }
67
+ /**
68
+ * Ask `/usage` now, once at a time: a second ask while one goes waits for it. A reading tells
69
+ * every page (`quota`); a failed ask keeps the last reading and says why beside it.
70
+ */
71
+ export function askUsage() {
72
+ if (!command)
73
+ return Promise.resolve();
74
+ if (asking)
75
+ return asking;
76
+ askedAt = Date.now();
77
+ const mine = generation;
78
+ // shortcut: a timeout kills the shell, not a claude it started on Windows; one stuck claude
79
+ // then lingers until it ends itself. Kill the tree (gcf-session's killTree) if that is seen.
80
+ asking = new Promise((resolve) => {
81
+ exec(`${command} ${FLAGS}`, { cwd: os.tmpdir(), timeout: ASK_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 << 20 }, (e, out, err) => {
82
+ if (mine !== generation)
83
+ return resolve();
84
+ const limits = limitsOf(out);
85
+ const at = new Date().toISOString();
86
+ if (limits)
87
+ last = { at, limits };
88
+ else
89
+ last = { ...(last ?? { at: null, limits: [] }), failed: { at, error: reasonOf(e, err) } };
90
+ asking = null;
91
+ broadcast({ type: 'quota' });
92
+ resolve();
93
+ });
94
+ });
95
+ return asking;
96
+ }
97
+ /** Ask when a page is open and the last ask is older than `everyMs`. */
98
+ export function askIfDue(everyMs = USAGE_EVERY_MS, now = Date.now()) {
99
+ if (command && watched() && now - askedAt >= everyMs)
100
+ void askUsage();
101
+ }
@@ -19,3 +19,20 @@ export function runModeOf(board, id, asked) {
19
19
  const own = board.items.find((i) => i.id === id)?.run_mode;
20
20
  return own === 'main' || own === 'worktree' ? own : board.run_mode;
21
21
  }
22
+ /**
23
+ * The tool of a proposed move: `propose_<key>`, `-` and `:` as `_` (AD-12). The session engine
24
+ * reads the name back with `_` as `-`, so `verdict:keep` comes back `verdict-keep`: moveOfTool
25
+ * finds the domain's key again.
26
+ */
27
+ export const toolOf = (key) => `propose_${key.replace(/[-:]/g, '_')}`;
28
+ /**
29
+ * The domain's move key a proposal's `move` names: the key itself, else the one whose tool it
30
+ * is (a proposable move first); null when none is.
31
+ */
32
+ export function moveOfTool(moves, raw) {
33
+ if (!raw)
34
+ return null;
35
+ const tool = toolOf(raw);
36
+ const keys = Object.keys(moves).filter((k) => toolOf(k) === tool);
37
+ return keys.find((k) => moves[k].propose) ?? (Object.hasOwn(moves, raw) ? raw : keys[0]) ?? null;
38
+ }