gcf-board 0.28.1 → 0.30.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.
package/README.md CHANGED
@@ -108,7 +108,7 @@ Do not put the port on a network. Remote and phone access is planned for v2, beh
108
108
  - `~/.gcf/board-token`: the token.
109
109
  - `~/.gcf/runs/`: the record of each run in flight, which a board started again finds; a board's start drops the ended runs of projects no longer on it.
110
110
  - `~/.gcf/themes/`: the theme files.
111
- - `GCF_BOARD_HOME` moves them all; `GCF_BOARD_AIF` points at another `ai-factory` entry script; `GCF_SESSION_AGENT` puts another agent command in place of `claude` in project chats (tests).
111
+ - `GCF_BOARD_HOME` moves them all; `GCF_BOARD_AIF` points at another `ai-factory` entry script; `GCF_BOARD_THIN=0` makes the board start that script itself for every framework command (by default it starts `server/aif-entry`, which loads only the project's extension commands, by `ai-factory`'s own loader and as it registers them, and hands anything else to `ai-factory`: a board read costs about a third less); `GCF_SESSION_AGENT` puts another agent command in place of `claude` in project chats (tests).
112
112
 
113
113
  ## Roadmap (v2)
114
114
 
@@ -0,0 +1,76 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // The board's way into the framework's commands: the project's extension commands as
10
+ // ai-factory registers them (dist/cli/index.js loadExtensionCommands), by ai-factory's own
11
+ // loader (dist/core: loadConfig, loadAllExtensions) and on its own commander, without its own
12
+ // commands. Its start read 63 % of the time in those: a board read cost 681 ms, through here
13
+ // ~480 (2026-11-12). The real ai-factory (GCF_AIF_REAL) gets anything that is not an extension
14
+ // command as the first argument, and every call when its loader cannot be loaded: slower, never
15
+ // other. `node aif-entry <ai-factory args…>`.
16
+ import { spawnSync } from 'node:child_process';
17
+ import { createRequire } from 'node:module';
18
+ import path from 'node:path';
19
+ import { pathToFileURL } from 'node:url';
20
+ if (!process.env.GCF_AIF_REAL)
21
+ throw new Error('GCF_AIF_REAL names no ai-factory: the board sets it');
22
+ const REAL = path.resolve(process.env.GCF_AIF_REAL);
23
+ const args = process.argv.slice(2);
24
+ // ai-factory imports no extension module for these (dist/cli/index.js): neither does the entry.
25
+ const UNLOADED = ['commands', 'worktree-check', 'completion-hook'];
26
+ const url = (...p) => pathToFileURL(path.join(...p)).href;
27
+ /** Its own process, as the board would start it: its argv and its exit stay the real one's. */
28
+ function real() {
29
+ const r = spawnSync(process.execPath, [REAL, ...args], { stdio: 'inherit', windowsHide: true });
30
+ process.exitCode = r.status ?? 1;
31
+ }
32
+ /**
33
+ * The program with the project's extension commands, as ai-factory builds it, when the call is
34
+ * one of them (the command first: an option before it, `--version gcf`, is ai-factory's own);
35
+ * null for anything ai-factory would answer other than its extension does: not an extension
36
+ * command, a name ai-factory loads no module for, a module or manifest that does not load (it
37
+ * warns, and a call to the command it lacks fails), no loader beside the bin.
38
+ */
39
+ async function programOf(cwd) {
40
+ if (UNLOADED.includes(args[0] ?? ''))
41
+ return null;
42
+ // The bin is bin/ai-factory.js: its loader beside it, in dist/core.
43
+ const core = path.join(path.dirname(REAL), '..', 'dist', 'core');
44
+ try {
45
+ const { loadConfig, getCurrentVersion } = await import(__rewriteRelativeImportExtension(url(core, 'config.js')));
46
+ const { loadAllExtensions } = await import(__rewriteRelativeImportExtension(url(core, 'extensions.js')));
47
+ const config = await loadConfig(cwd);
48
+ if (!config?.extensions?.length)
49
+ return null;
50
+ const names = config.extensions.map((e) => e.name);
51
+ const exts = await loadAllExtensions(cwd, names);
52
+ if (!exts.some((e) => e.manifest.commands?.some((c) => c.name === args[0])))
53
+ return null;
54
+ const { Command } = await import(__rewriteRelativeImportExtension(pathToFileURL(createRequire(REAL).resolve('commander')).href));
55
+ const program = new Command().name('ai-factory').version(getCurrentVersion());
56
+ for (const { dir, manifest } of exts)
57
+ for (const cmd of manifest.commands ?? []) {
58
+ const mod = await import(__rewriteRelativeImportExtension(url(dir, cmd.module)));
59
+ if (typeof mod.register === 'function')
60
+ mod.register(program);
61
+ }
62
+ const has = (c) => c.name() === args[0] || c.aliases().includes(args[0]);
63
+ return program.commands.some(has) ? program : null;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ // shortcut: an extension command named like one of ai-factory's own (`extension`) runs the
70
+ // extension's here, ai-factory's own there (it refuses the second); no list of its own names
71
+ // without loading them. The board calls only `gcf` and the harness's command.
72
+ const program = await programOf(process.cwd());
73
+ if (program)
74
+ program.parse();
75
+ else
76
+ real();
@@ -16,7 +16,8 @@ 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';
18
18
  import { broadcast, planRev, SESSION_TTL_MIN, subscribe, watchChanges, watchProject, } from './events.js';
19
- import { attachesUnit, CHAT_BODY_MAX, chatInput, IMAGE_EXT, talkInput, withUploads, } from './chat.js';
19
+ import { attachesUnit, CHAT_BODY_MAX, chatInput, IMAGE_EXT, pendingInput, talkInput, withUploads, } from './chat.js';
20
+ import { reviewPresets } from './reviewPresets.js';
20
21
  import { attachmentOf, follow, followLog, logPart, readShown, shownShape } from './files.js';
21
22
  import { HttpError } from './http-error.js';
22
23
  import { isCenterMove, moveArgs, moveInput, runIds } from './moves.js';
@@ -25,7 +26,7 @@ import { addProject, homeDir, listProjects, projectOf, removeProject, yoloFile,
25
26
  import { allThemes } from './themes.js';
26
27
  import { askIfDue, askUsage, configureUsage, lastUsage } from './usage.js';
27
28
  import { activeRuns, adoptRuns, busyCheck, keepProjects, sweepRuns, closeReport, forgetProject, resumeQueue, holdProject, retryWaiting, runsOf, setAutopilot, startRun, allowOf, whileAllowing, unqueue, ticketState, watchTickets, } from './runs.js';
28
- import { acceptProposal, agentDefaults, agentPresets, chatCard, deniedRuleIn, lastDeniedOf, lastRunEnd, chatOf, entryTalk, listTalks, openTalk, pickTalk, prepareTalk, startDesign, startTalk, stopTalk, talkEntry, talkId, talkLive, talkSaid, talkWaits, watchTalks, writeTalk, } from './talks.js';
29
+ import { acceptProposal, agentDefaults, agentPresets, chatCard, deniedRuleIn, lastDeniedOf, lastRunEnd, chatOf, entryTalk, listTalks, openTalk, pickTalk, prepareTalk, startDesign, startTalk, stopTalk, wakeTalk, talkEntry, talkId, talkLive, talkSaid, talkWaits, watchTalks, writeTalk, } from './talks.js';
29
30
  import { accountSettings, saveAccountSettings, threadDir, threadOfEntry } from 'gcf-session';
30
31
  const send = (res, status, body) => {
31
32
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
@@ -126,6 +127,16 @@ function jsonOf(r, what) {
126
127
  throw new HttpError(502, `ai-factory ${what} gave no report: ${(r.err || r.out).trim()}`);
127
128
  }
128
129
  }
130
+ /** The id `gcf-harness chat say --json` printed, if any (t1 d7). */
131
+ function sentId(out) {
132
+ try {
133
+ const { id } = JSON.parse(out.trim().split('\n').at(-1) ?? '');
134
+ return typeof id === 'string' ? { id } : {};
135
+ }
136
+ catch {
137
+ return {};
138
+ }
139
+ }
129
140
  /** The ids a board read knows: its items, accepted and killed ones too. */
130
141
  const idsOf = (b) => new Set([
131
142
  ...b.items.map((i) => i.id),
@@ -478,6 +489,9 @@ export function createApp(o) {
478
489
  usage: lastUsage(),
479
490
  presets: agentPresets(),
480
491
  defaults: agentDefaults(),
492
+ // What a review row offers, and which review CLIs answer (Operator-Tasks-Plan t2 d5).
493
+ review_presets: reviewPresets().presets,
494
+ providers: reviewPresets().providers,
481
495
  head: await headOf(p.path),
482
496
  };
483
497
  const board = await boardOf(p);
@@ -549,6 +563,14 @@ export function createApp(o) {
549
563
  followLog((await projectOf(m[1])).path, m[2], res, 'chat.jsonl');
550
564
  },
551
565
  ],
566
+ [
567
+ // The operator's messages a run waiting for the limit has not read yet (t1 d6).
568
+ 'GET',
569
+ /^\/api\/p\/([^/]+)\/chat\/([a-z0-9][a-z0-9-]*)\/pending$/,
570
+ async (_req, res, m) => {
571
+ send(res, 200, { lines: pendingInput((await projectOf(m[1])).path, m[2]) });
572
+ },
573
+ ],
552
574
  [
553
575
  // A picture of an item's chat (`<id>.att/`, where `gcf-harness chat` put it); never through
554
576
  // a link. "Attach to item" gives it to the item with the domain's `attach` move.
@@ -641,16 +663,20 @@ export function createApp(o) {
641
663
  writeFileSync(file, Buffer.from(im.data, 'base64'));
642
664
  return ['--image', file];
643
665
  });
644
- args = [...chat, 'say', '--text-file', '-', ...images.flat()];
666
+ // `--json`: the line's id, by which the page knows its bubble (t1 d7).
667
+ args = [...chat, 'say', '--json', '--text-file', '-', ...images.flat()];
645
668
  input = line.text;
646
669
  }
647
670
  else if (line.type === 'answer') {
648
671
  args = [...chat, 'answer', line.request_id, '--answers-file', '-'];
649
672
  input = JSON.stringify(line.answers);
650
673
  }
651
- const r = await runCli(o.entry, p.path, args, undefined, input);
674
+ let r = await runCli(o.entry, p.path, args, undefined, input);
675
+ // A harness before 0.30.0 has no `say --json`: the line goes without its id.
676
+ if (!r.ok && /unknown option '--json'/.test(r.err))
677
+ r = await runCli(o.entry, p.path, args.filter((a) => a !== '--json'), undefined, input);
652
678
  if (r.ok)
653
- return send(res, 202, { ok: true });
679
+ return send(res, 202, { ok: true, ...sentId(r.out) });
654
680
  // No live run session: a message goes to the item's thread of the project chat (AD-49).
655
681
  // An item the board read knows: a stale or mistyped id gets no thread.
656
682
  const t = r.code === 3 && line.type === 'say' && !liveOnly ? await toThread(p, m[2], line) : null;
@@ -744,6 +770,20 @@ export function createApp(o) {
744
770
  send(res, 202, { ok: true });
745
771
  },
746
772
  ],
773
+ [
774
+ // The limit was reset early: a thread's wait goes on now (Operator-Tasks-Plan t1 d4).
775
+ 'POST',
776
+ /^\/api\/p\/([^/]+)\/talk\/([^/]+)\/wake$/,
777
+ async (_req, res, m) => {
778
+ const p = await projectOf(m[1]);
779
+ const t = talkId(m[2]);
780
+ if (!existsSync(threadDir(p.path, t)))
781
+ throw new HttpError(404, `no thread ${t}`);
782
+ if (!wakeTalk(p, t))
783
+ throw new HttpError(409, `thread ${t} waits for nothing`);
784
+ send(res, 202, { ok: true });
785
+ },
786
+ ],
747
787
  [
748
788
  // The model and effort of a thread's next sessions (Board-PRD decision 24).
749
789
  'POST',
@@ -1286,6 +1326,20 @@ export function createApp(o) {
1286
1326
  send(res, 200, { ok: r.ok, out: r.out.trim(), err: briefError(r.err) });
1287
1327
  },
1288
1328
  ],
1329
+ [
1330
+ // The limit was reset early (Operator-Tasks-Plan t1 d4): a card's wait goes on now, or,
1331
+ // with `all`, every wait of the project: the limit is one for the account.
1332
+ 'POST',
1333
+ /^\/api\/p\/([^/]+)\/wake$/,
1334
+ async (req, res, m) => {
1335
+ const p = await projectOf(m[1]);
1336
+ const body = await bodyOf(req);
1337
+ const target = body.all === true ? ['--all'] : runIds({ ids: [body.id] });
1338
+ const r = await cli(p, [await harnessOf(p), 'wake', ...target]);
1339
+ broadcast({ type: 'board', project: p.name });
1340
+ send(res, 200, { ok: r.ok, out: r.out.trim(), err: briefError(r.err) });
1341
+ },
1342
+ ],
1289
1343
  [
1290
1344
  // The operator's Hold of a card (Hold-Plan d6, d20): its session hands over at the next
1291
1345
  // call, its work waits ready; the harness keeps the mark, so a restart keeps the hold.
@@ -1,5 +1,7 @@
1
1
  // What the operator writes into an item's chat (docs/Chat-Plan.md): its shape checked here, at
2
2
  // the board's edge; `gcf-harness chat` checks the rest and writes it for the session.
3
+ import { readFileSync } from 'node:fs';
4
+ import path from 'node:path';
3
5
  import { replyBlock } from '../shared/board.js';
4
6
  import { HttpError } from './http-error.js';
5
7
  import { saveUpload } from './upload.js';
@@ -159,3 +161,35 @@ export function talkInput(body, units) {
159
161
  return { type: 'deny', request_id: id };
160
162
  return { type: 'allow', request_id: id, always: body.always === true };
161
163
  }
164
+ /**
165
+ * The operator's messages a waiting run has not read (Operator-Tasks-Plan t1 d6): the lines of
166
+ * `<id>.chat-in.jsonl` past the offset its limit wait kept in `<id>.agent.json`. None while no
167
+ * wait names a reset, or the record keeps no offset.
168
+ */
169
+ export function pendingInput(root, id) {
170
+ const runs = path.join(root, '.gcf-session', 'runs');
171
+ try {
172
+ const rec = JSON.parse(readFileSync(path.join(runs, `${id}.agent.json`), 'utf8'));
173
+ if (!rec.resets || !Number.isInteger(rec.chat_in_at))
174
+ return [];
175
+ const bytes = readFileSync(path.join(runs, `${id}.chat-in.jsonl`));
176
+ return bytes
177
+ .subarray(rec.chat_in_at)
178
+ .toString('utf8')
179
+ .split('\n')
180
+ .flatMap((l) => {
181
+ try {
182
+ const e = JSON.parse(l);
183
+ return e?.type === 'say' && typeof e.id === 'string' && typeof e.text === 'string'
184
+ ? [{ id: e.id, text: e.text }]
185
+ : [];
186
+ }
187
+ catch {
188
+ return [];
189
+ }
190
+ });
191
+ }
192
+ catch {
193
+ return [];
194
+ }
195
+ }
@@ -3,7 +3,21 @@
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 { fileURLToPath } from 'node:url';
6
7
  import { gatePath } from '../shared/board.js';
8
+ const HERE = fileURLToPath(import.meta.url);
9
+ // Beside this file, as it runs: aif-entry.ts from the sources, aif-entry.js from dist.
10
+ const THIN = path.join(path.dirname(HERE), `aif-entry${path.extname(HERE)}`);
11
+ /**
12
+ * The script a framework command starts from and the env it adds: aif-entry, which loads the
13
+ * project's extension commands by ai-factory's own loader without its own commands, over `entry`
14
+ * (GCF_AIF_REAL); `entry` itself when GCF_BOARD_THIN=0.
15
+ */
16
+ export function startOf(entry) {
17
+ if (process.env.GCF_BOARD_THIN === '0')
18
+ return { script: entry, env: {} };
19
+ return { script: THIN, env: { GCF_AIF_REAL: entry } };
20
+ }
7
21
  /**
8
22
  * The JS entry of the `ai-factory` CLI: GCF_BOARD_AIF, or the bin of the global package. The
9
23
  * global one is found through `npm root -g`, a fixed command line: the shell Windows needs for
@@ -110,11 +124,12 @@ export function runCli(entry, cwd, args, timeoutMs = 120_000, input) {
110
124
  // run would otherwise pass as the owner of that session's mark (Methodology §4), and its
111
125
  // commits as the session's or the run's moves (`GCF-By`).
112
126
  const { CLAUDE_CODE_SESSION_ID: _, GCF_RUN_OWNER: __, GCF_MOVE_BY: ___, GCF_RUN_ITEM: ____, ...env } = process.env;
127
+ const start = startOf(entry);
113
128
  return new Promise((resolve) => {
114
- const child = spawn(process.execPath, [entry, ...args], {
129
+ const child = spawn(process.execPath, [start.script, ...args], {
115
130
  windowsHide: true,
116
131
  cwd,
117
- env,
132
+ env: { ...env, ...start.env },
118
133
  shell: false,
119
134
  stdio: ['pipe', 'pipe', 'pipe'],
120
135
  });
@@ -81,8 +81,9 @@ const MOVES = {
81
81
  const args = Object.entries(pairs).map(([key, v]) => {
82
82
  if (!/^[a-z_]+(\.[a-z_]+)?$/.test(key))
83
83
  throw new HttpError(400, 'key must be a config key');
84
- if (typeof v !== 'string' || /[\r\n]/.test(v))
85
- throw new HttpError(400, 'a value is one line of text');
84
+ // A list (`no_diff`) goes as its lines: Settings saves every key at once (t3 d6).
85
+ if (typeof v !== 'string')
86
+ throw new HttpError(400, 'a value is text');
86
87
  return `--pair=${key}=${v}`;
87
88
  });
88
89
  if (!args.length)
@@ -0,0 +1,35 @@
1
+ // What a review row of Settings offers (Operator-Tasks-Plan t2 d5): Claude's aliases and efforts
2
+ // (its adapter's presets), Codex's families from its catalog (gcf-session adapter/codex.js), and
3
+ // whether each CLI answers. The probes spawn processes: kept for an hour, read once at need.
4
+ import { spawnSync } from 'node:child_process';
5
+ import path from 'node:path';
6
+ import { codexInstalled, codexModels, codexPresets, presetsOf } from 'gcf-session';
7
+ import { homeDir } from './registry.js';
8
+ const KEEP_MS = 3_600_000;
9
+ let kept = null;
10
+ const claudeInstalled = () => {
11
+ const r = spawnSync('claude', ['--version'], {
12
+ windowsHide: true,
13
+ encoding: 'utf8',
14
+ shell: process.platform === 'win32',
15
+ timeout: 20_000,
16
+ });
17
+ return !r.error && r.status === 0;
18
+ };
19
+ /**
20
+ * The presets and the providers. A test's stand-in agent (GCF_SESSION_AGENT) probes nothing:
21
+ * Claude is there, Codex only as GCF_CODEX names it.
22
+ */
23
+ export function reviewPresets() {
24
+ if (kept && Date.now() - kept.at < KEEP_MS)
25
+ return kept;
26
+ const stand = Boolean(process.env.GCF_SESSION_AGENT);
27
+ const codex = stand && !process.env.GCF_CODEX ? false : codexInstalled();
28
+ const models = codex ? codexModels({ cache: path.join(homeDir(), 'codex-models.json') }) : null;
29
+ kept = {
30
+ at: Date.now(),
31
+ presets: { claude: presetsOf('claude'), codex: codexPresets(models) },
32
+ providers: { claude: stand || claudeInstalled(), codex },
33
+ };
34
+ return kept;
35
+ }
@@ -12,7 +12,7 @@ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unl
12
12
  import path from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
14
  import { writeAtomicSync } from './atomic.js';
15
- import { briefError, runCli } from './cli.js';
15
+ import { briefError, runCli, startOf } from './cli.js';
16
16
  import { alive, broadcast } from './events.js';
17
17
  import { HttpError } from './http-error.js';
18
18
  import { homeDir } from './registry.js';
@@ -626,9 +626,11 @@ function spawnRun(q, mode) {
626
626
  active.add(run);
627
627
  // The board says where it goes: it queued it by that mode (an item's own, the run's pick). A
628
628
  // card session works the main checkout too, with no item yet.
629
+ // The run's core calls go through the script it starts from (process.argv[1]): the same one.
630
+ const start = startOf(entry);
629
631
  const args = q.kind === 'card'
630
- ? [entry, harness, 'card', ...ids, '--json', ...(q.waitLimit ? ['--wait-limit'] : [])]
631
- : [entry, harness, 'run', ...ids, '--json', '--mode', mode];
632
+ ? [start.script, harness, 'card', ...ids, '--json', ...(q.waitLimit ? ['--wait-limit'] : [])]
633
+ : [start.script, harness, 'run', ...ids, '--json', '--mode', mode];
632
634
  // A card session takes none of a run's flags: `gcf-harness card` knows --agent, --json and,
633
635
  // for the autopilot, --wait-limit (Hold-Plan d11).
634
636
  if (q.kind !== 'card') {
@@ -652,6 +654,7 @@ function spawnRun(q, mode) {
652
654
  const rid = randomUUID();
653
655
  const relay = spawn(process.execPath, [RELAY, recordOf(rid), endOf(rid), ...args], {
654
656
  cwd: p.path,
657
+ env: { ...process.env, ...start.env },
655
658
  detached: true,
656
659
  stdio: 'ignore',
657
660
  windowsHide: true,
@@ -11,7 +11,7 @@ import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync,
11
11
  import os from 'node:os';
12
12
  import path from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { THREAD_ID, createThread, defaultsOf, listThreads, presetsOf, readThread, setThreadAgent, threadAgent, threadDir, threadOf, threadOfEntry, } from 'gcf-session';
14
+ import { THREAD_ID, createThread, defaultsOf, listThreads, presetsOf, readThread, setThreadAgent, threadAgent, threadDir, threadOf, threadOfEntry, threadWaits, } from 'gcf-session';
15
15
  import { runModeOf, toolOf } from '../shared/board.js';
16
16
  import { writeAtomic } from './atomic.js';
17
17
  import { briefError, refusalOf } from './cli.js';
@@ -319,8 +319,9 @@ export async function prepareTalk(p, board, t) {
319
319
  * the operator's close after it.
320
320
  */
321
321
  export function talkWaits(p, t) {
322
- const last = eventsOf(dirOf(p, t)).findLast((e) => ['session', 'session_end', 'limit', 'closed'].includes(e.type));
323
- return last?.type === 'limit';
322
+ const last = eventsOf(dirOf(p, t)).findLast((e) => ['session', 'session_end', 'limit', 'limit_end', 'closed'].includes(e.type));
323
+ // A wait that ended by the clock or a wake: its session starts now and reads the input (t1 d2).
324
+ return last?.type === 'limit' || (last?.type === 'limit_end' && !/^(stop|hold)$/.test(last.by));
324
325
  }
325
326
  /** Whether a session of thread `t` lives: its `open` holds the thread's lock. */
326
327
  export function talkLive(p, t) {
@@ -483,10 +484,24 @@ export function writeTalk(p, t, input) {
483
484
  * engine's stop mark. A mark the engine never reads (it ended meanwhile) goes at its next open.
484
485
  */
485
486
  export function stopTalk(p, t) {
486
- const stop = path.join(writeDir(p, t), 'stop');
487
- if (existsSync(stop) && lstatSync(stop).isSymbolicLink())
488
- throw new HttpError(400, `${t}'s stop mark goes through a link: refused`);
489
- writeFileSync(stop, '');
487
+ markTalk(p, t, 'stop');
488
+ }
489
+ /**
490
+ * Wake thread `t`'s limit wait (Operator-Tasks-Plan t1 d4): the engine's wake mark, only while
491
+ * the wait lives. Returns whether it waited.
492
+ */
493
+ export function wakeTalk(p, t) {
494
+ if (!threadWaits(p.path, t))
495
+ return false;
496
+ markTalk(p, t, 'wake');
497
+ return true;
498
+ }
499
+ /** Write thread `t`'s `stop` or `wake` mark; one through a link is refused. */
500
+ function markTalk(p, t, kind) {
501
+ const mark = path.join(writeDir(p, t), kind);
502
+ if (existsSync(mark) && lstatSync(mark).isSymbolicLink())
503
+ throw new HttpError(400, `${t}'s ${kind} mark goes through a link: refused`);
504
+ writeFileSync(mark, '');
490
505
  }
491
506
  /** A thread's chat events; a line that is not one is skipped. */
492
507
  function eventsOf(td) {
@@ -796,7 +811,7 @@ export function cardIn(events) {
796
811
  }
797
812
  /** When a thread's agent wakes after the usage limit: its last session event is the wait. */
798
813
  export function limitIn(events) {
799
- const last = events.findLast((e) => e.type === 'limit' || e.type === 'session' || e.type === 'closed');
814
+ const last = events.findLast((e) => ['limit', 'limit_end', 'session', 'closed'].includes(e.type));
800
815
  return last?.type === 'limit' ? last.until : null;
801
816
  }
802
817
  /** The text of the operator's first message to a thread, as written; null before one. */