gcf-board 0.18.7 → 0.19.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.
@@ -11,7 +11,7 @@ import { lstat, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/pr
11
11
  import { pipeline } from 'node:stream/promises';
12
12
  import os from 'node:os';
13
13
  import path from 'node:path';
14
- import { BOARD_SCHEMA, runModeOf, toolOf, } from '../shared/board.js';
14
+ import { BOARD_SCHEMA, gatePath, runModeOf, toolOf, } from '../shared/board.js';
15
15
  import { admit, cookieName, fromPage, hostAllowed, tokenInUrl } from './auth.js';
16
16
  import { upgrade } from './ws.js';
17
17
  import { briefError, refusalOf, runCli } from './cli.js';
@@ -844,11 +844,8 @@ export function createApp(o) {
844
844
  if (!Array.isArray(paths) ||
845
845
  !paths.length ||
846
846
  paths.length > most ||
847
- paths.some((x) => typeof x !== 'string' ||
848
- !x.startsWith('gcf/') ||
849
- /[\\\r\n]/.test(x) ||
850
- x.split('/').includes('..')))
851
- throw new HttpError(400, `paths: 1 to ${most} paths under gcf/, with /`);
847
+ paths.some((x) => !gatePath(x)))
848
+ throw new HttpError(400, `paths: 1 to ${most} paths under gcf/ or GLOSSARY.md, with /`);
852
849
  const r = await cli(p, [
853
850
  'gcf',
854
851
  'edits',
@@ -3,6 +3,7 @@
3
3
  import { execSync, spawn, spawnSync } from 'node:child_process';
4
4
  import { existsSync, readFileSync } from 'node:fs';
5
5
  import path from 'node:path';
6
+ import { gatePath } from '../shared/board.js';
6
7
  /**
7
8
  * The JS entry of the `ai-factory` CLI: GCF_BOARD_AIF, or the bin of the global package. The
8
9
  * global one is found through `npm root -g`, a fixed command line: the shell Windows needs for
@@ -74,7 +75,7 @@ export function refusalOf(err) {
74
75
  const { code, paths, left } = (data ?? {});
75
76
  if (!Array.isArray(paths))
76
77
  return undefined;
77
- const safe = (a) => (Array.isArray(a) ? a : []).filter((x) => typeof x === 'string' && x.startsWith('gcf/') && !x.split('/').includes('..'));
78
+ const safe = (a) => (Array.isArray(a) ? a : []).filter(gatePath);
78
79
  if (code === 'clean')
79
80
  return { code, paths: safe(paths), left: safe(left) };
80
81
  if (code !== 'dirty')
@@ -1,7 +1,7 @@
1
1
  // The account's usage limits, asked of Claude's `/usage` (Board-PRD decision 39): what the top
2
2
  // bar shows over the last limit a run reported. The command is free (no model call) and answers
3
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';
4
+ import { spawn, spawnSync } from 'node:child_process';
5
5
  import os from 'node:os';
6
6
  import { broadcast, watched } from './events.js';
7
7
  /** How often an open page's bar is read again, and how long one ask may take. */
@@ -13,15 +13,20 @@ const ASK_TIMEOUT_MS = 30_000;
13
13
  const FLAGS = '-p "/usage" --output-format stream-json --verbose --no-session-persistence ' +
14
14
  '--setting-sources project --strict-mcp-config';
15
15
  let command = null;
16
+ let askTimeout = ASK_TIMEOUT_MS;
16
17
  let last = null;
17
18
  let asking = null;
18
19
  let askedAt = 0;
19
20
  // An ask still going when the board is configured again writes nothing into the new setup.
20
21
  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) {
22
+ /**
23
+ * Ask with `agent` (claude, or a stand-in in the tests); null asks nothing, as in the tests.
24
+ * `timeoutMs` is the tests' own, shorter wait.
25
+ */
26
+ export function configureUsage(agent, timeoutMs = ASK_TIMEOUT_MS) {
23
27
  generation += 1;
24
28
  command = agent;
29
+ askTimeout = timeoutMs;
25
30
  last = null;
26
31
  asking = null;
27
32
  askedAt = 0;
@@ -53,16 +58,19 @@ export function limitsOf(out) {
53
58
  return null;
54
59
  }
55
60
  /**
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.
61
+ * Why an ask failed: a timeout, else the last two lines of its stderr (cmd's "not recognized"
62
+ * spans two), else the error itself.
58
63
  */
59
64
  export function reasonOf(e, err) {
60
65
  if (!e)
61
66
  return 'claude answered /usage without the plan limits (an API key has none)';
67
+ // A stuck ask is told by its timeout, not by a warning it printed before it hung.
68
+ if (e.killed)
69
+ return `no answer in ${askTimeout / 1000} s`;
62
70
  const tail = err.trim();
63
71
  if (tail)
64
72
  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);
73
+ return e.message.slice(0, 300);
66
74
  }
67
75
  /**
68
76
  * Ask `/usage` now, once at a time: a second ask while one goes waits for it. A reading tells
@@ -75,22 +83,65 @@ export function askUsage() {
75
83
  return asking;
76
84
  askedAt = Date.now();
77
85
  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
86
  asking = new Promise((resolve) => {
81
- exec(`${command} ${FLAGS}`, { cwd: os.tmpdir(), timeout: ASK_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 << 20 }, (e, out, err) => {
87
+ let late = false;
88
+ let out = '';
89
+ let err = '';
90
+ const windows = process.platform === 'win32';
91
+ // Off Windows the shell leads a group of its own: a timeout signals the group, so a claude
92
+ // the shell forked ends with it.
93
+ const child = spawn(`${command} ${FLAGS}`, {
94
+ shell: true,
95
+ cwd: os.tmpdir(),
96
+ windowsHide: true,
97
+ detached: !windows,
98
+ });
99
+ // The answer is a few KB; a runaway one keeps its last 4 MB. Text, so a character split
100
+ // between two chunks comes whole.
101
+ const keep = (s, d) => (s + d).slice(-(4 << 20));
102
+ child.stdout.setEncoding('utf8').on('data', (d) => (out = keep(out, d)));
103
+ child.stderr.setEncoding('utf8').on('data', (d) => (err = keep(err, d)));
104
+ let ended = false;
105
+ // A spawn error is followed by a close: the first one tells.
106
+ const done = (e) => {
107
+ if (ended)
108
+ return;
109
+ ended = true;
110
+ clearTimeout(timer);
82
111
  if (mine !== generation)
83
112
  return resolve();
84
113
  const limits = limitsOf(out);
85
114
  const at = new Date().toISOString();
115
+ const why = e && late ? Object.assign(e, { killed: true }) : e;
86
116
  if (limits)
87
117
  last = { at, limits };
88
118
  else
89
- last = { ...(last ?? { at: null, limits: [] }), failed: { at, error: reasonOf(e, err) } };
119
+ last = { ...(last ?? { at: null, limits: [] }), failed: { at, error: reasonOf(why, err) } };
90
120
  asking = null;
91
121
  broadcast({ type: 'quota' });
92
122
  resolve();
93
- });
123
+ };
124
+ child.on('error', done);
125
+ child.on('close', (code, signal) => done(code === 0 ? null : new Error(`${command} /usage ended with ${code ?? signal}`)));
126
+ // Not the shell alone: on Windows a killed shell leaves the claude under it running.
127
+ const timer = setTimeout(() => {
128
+ late = true;
129
+ if (!child.pid)
130
+ return;
131
+ if (windows)
132
+ spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
133
+ else
134
+ try {
135
+ process.kill(-child.pid, 'SIGKILL');
136
+ }
137
+ catch {
138
+ // The group ended on its own meanwhile.
139
+ }
140
+ // A process outside the tree that holds the pipes would hold the ask for good: the board
141
+ // would read no quota until its restart.
142
+ child.stdout.destroy();
143
+ child.stderr.destroy();
144
+ }, askTimeout).unref();
94
145
  });
95
146
  return asking;
96
147
  }
@@ -37,6 +37,14 @@ export function leftOf(r, named) {
37
37
  * reads the name back with `_` as `-`, so `verdict:keep` comes back `verdict-keep`: moveOfTool
38
38
  * finds the domain's key again.
39
39
  */
40
+ /**
41
+ * A path the core's gate covers (GATE_SCOPE), as a refusal names it: one under gcf/, or the
42
+ * project's GLOSSARY.md at the root (core 0.21). With `/`, no `..`, no backslash or newline.
43
+ */
44
+ export const gatePath = (x) => typeof x === 'string' &&
45
+ (x === 'GLOSSARY.md' || x.startsWith('gcf/')) &&
46
+ !/[\\\r\n]/.test(x) &&
47
+ !x.split('/').includes('..');
40
48
  export const toolOf = (key) => `propose_${key.replace(/[-:]/g, '_')}`;
41
49
  /**
42
50
  * The domain's move key a proposal's `move` names: the key itself, else the one whose tool it