gcf-board 0.28.0 → 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.
Files changed (33) hide show
  1. package/README.md +3 -3
  2. package/dist/server/aif-entry.js +76 -0
  3. package/dist/server/app.js +60 -6
  4. package/dist/server/chat.js +61 -1
  5. package/dist/server/cli.js +23 -4
  6. package/dist/server/desktop.js +1 -0
  7. package/dist/server/moves.js +3 -2
  8. package/dist/server/reviewPresets.js +35 -0
  9. package/dist/server/runs.js +6 -3
  10. package/dist/server/talks.js +29 -11
  11. package/dist/shared/board.js +45 -0
  12. package/dist/web/assets/index-BhGhi45o.css +1 -0
  13. package/dist/web/assets/index-zKctM0qB.js +123 -0
  14. package/dist/web/index.html +2 -2
  15. package/node_modules/gcf-session/lib/adapter/claude.js +1 -1
  16. package/node_modules/gcf-session/lib/adapter/codex.js +137 -0
  17. package/node_modules/gcf-session/lib/chat-input.js +14 -1
  18. package/node_modules/gcf-session/lib/chat.js +36 -18
  19. package/node_modules/gcf-session/lib/cli.js +7 -2
  20. package/node_modules/gcf-session/lib/index.js +10 -0
  21. package/node_modules/gcf-session/lib/job.js +93 -15
  22. package/node_modules/gcf-session/lib/limit.js +9 -5
  23. package/node_modules/gcf-session/lib/proc.js +5 -1
  24. package/node_modules/gcf-session/lib/session.js +39 -19
  25. package/node_modules/gcf-session/lib/store.js +14 -9
  26. package/node_modules/gcf-session/lib/thread.js +14 -7
  27. package/node_modules/gcf-session/lib/usage.js +23 -5
  28. package/node_modules/gcf-session/lib/wake.js +141 -0
  29. package/node_modules/gcf-session/package.json +1 -1
  30. package/node_modules/gcf-session/types/index.d.ts +52 -2
  31. package/package.json +1 -1
  32. package/dist/web/assets/index-BCfiz95-.css +0 -1
  33. package/dist/web/assets/index-CcsKtA2D.js +0 -119
package/README.md CHANGED
@@ -44,7 +44,7 @@ The board knows no domain by name: the project's board read gives its columns, m
44
44
 
45
45
  - **Command**: **waiting for me**, what only the operator moves on (Board-PRD §1.3), by group, each a grid of tiles (board 0.16.0, the designer's final round): failed run reports and a paused queue (its tile opens Runs), a card waiting in a chat (its tile opens the chat), the decisions, the items to play and judge, to decide, to unblock (the columns the domain marks `human`), and a `paused: limit` item to resume. Beside it **Live**: the runs going on with their plan progress, **Follow** and **Stop**, the console runs and sessions, **Run next**, the queue, the run reports, and what the board did by itself.
46
46
  - **Board**: columns ready, running, blocked, awaiting-verdict, awaiting-decision, unplayed, parked. A card shows the type, the gate, the plan progress (`2/5`), the severity, `verified`, the model, **needs N** and **needed by N**. A running card shows when its run log was last written (`active 12 s ago`), and `quiet 6 min` when the log has been silent for 5 minutes or more. A run's end report gives each item's cost when the agent reported it. Pointing at a card (or focusing it from the keyboard) lights up the cards it needs and the cards that need it, each saying how, and dims the rest. The toolbar (board 0.9.0, core 0.13.0) searches ids and titles, keeps **waiting for me**, filters by the fields the domain marks `filter` (GCF: type, gate, severity, system, milestone; several values at once, each a chip to take off) and lays the board out in lanes by a field it marks `group` (system, parent, milestone): an item with two systems stands in both lanes, one with none in **none**, a parent lane is named by the feature's title. The mouse drags the board sideways from its empty space; the wheel over a column with no scroll of its own pans it.
47
- - **An item** (a window over the screen, dragged by its head; a page on a phone; board 0.14.0): its **Status** (why it is blocked or waits, its fields, its dependencies; it opens there when it is blocked or waits), its file (the front matter folded, a `key:` body by sections), its plan and its run log as it grows, its **Lessons**, and the moves the core offers for it (`items[].moves`, Methodology §4.1): run, verdict, decide, block, unblock, drop, close, submit, depends. Each move's form comes from the core; the core still checks the rest itself, and the board shows its answer. **Dependencies**: what it needs that has not ended in history (an item with its column, a design unit with its TBDs or the questions that block it, a graveyard line, an unknown id) and the items that need it, each a link; **Edit…** opens the picker of the board's items and design units (search by id and title, or type an id), and Save sends the `depends` move's adds and removes. **History** (core 0.13.0): its moves newest first, when, which, who (a run, your session, you; unknown on a commit older than the framework's marks), the commit and its subject; then its runs, as on the Runs screen. **Related**: its feature's other children, and the graveyard lines tagged with its system ("did we kill this before?"). An item that ended opens from **Ended** with its History.
47
+ - **An item** (a window over the screen, dragged by its head; a page on a phone; board 0.14.0): its **Status** (why it is blocked or waits, its fields, its dependencies; it opens there when it is blocked or waits, unless you last clicked another tab: the next item opens on that one; a tuned item lists its tune notes there), its file (the front matter folded, a `key:` body by sections), its plan and its run log as it grows, its **Lessons**, and the moves the core offers for it (`items[].moves`, Methodology §4.1): run, verdict, decide, block, unblock, drop, close, submit, depends. Each move's form comes from the core; the core still checks the rest itself, and the board shows its answer. **Dependencies**: what it needs that has not ended in history (an item with its column, a design unit with its TBDs or the questions that block it, a graveyard line, an unknown id) and the items that need it, each a link; **Edit…** opens the picker of the board's items and design units (search by id and title, or type an id), and Save sends the `depends` move's adds and removes. **History** (core 0.13.0): its moves newest first, when, which, who (a run, your session, you; unknown on a commit older than the framework's marks), the commit and its subject; then its runs, as on the Runs screen. **Related**: its feature's other children, and the graveyard lines tagged with its system ("did we kill this before?"). An item that ended opens from **Ended** with its History.
48
48
  - **Runs** (harness 0.13.0): what runs now with the run's model and effort, its last log lines, **Whole log** and **Stop**; the queue with what each item will run on; the past runs of the harness's run log, newest first, 50 at a time: start, end, mode, cost, and per item its result word, the reason word for word, cost, tokens, turns, handoffs, a broken step and what it ran on. **log** opens the part of the item's log that run wrote, **chat** that run's chat. Every start the operator asks for (Run selected, Run next, a drop on running, this screen) asks first with a model and effort picker for that run only (**default: each item's own**); the drawer's Run is one click. An older harness shows the active runs only, and the dialog has no pickers. The API: `GET /api/p/<project>/runs/past?limit=` (`gcf-harness runs --json`; 404 without a harness that keeps them), `GET …/item/<id>/history` (`{id, moves, runs}`), `GET …/log/<id>?from=&to=` (a past run's part, once: `{text, cut}`, at most its last 2 MB; without `from` and `to` the log as it grows), `POST …/run` with `model` and `effort`, `POST …/inbox/<entry>/draft` (`{thread, created}`).
49
49
  - **Log** (board 0.20.1, gcf-session 0.18.1): a subagent's lines say so (`subagent:`, `subagent tool:`, `subagent tool error:`), drawn as the main agent's kinds; the pulse's current action names a subagent's call as one.
50
50
  - **Play** (board 0.24.0, core 0.26.0): a card waiting for play shows its build (one per code, `Same build as` when shared), **Play** per target of `play:` that builds first when there is none, **Stop** and **Change** (find again with agent, edit, build again), on its run's end card, in its window and on Playtest; **Set up** opens a chat thread whose agent finds the commands, **by hand** opens the form; **Play main** and **Build main** play the checkout as it is; a verdict stops the card's player and removes a build no other card holds.
@@ -74,7 +74,7 @@ The board knows no domain by name: the project's board read gives its columns, m
74
74
  - **An item's chat** (its drawer's **Chat** tab; harness 0.11.1, core 0.11.1): every run the board starts keeps its agent sessions open; the project's `chat:` settings (Settings: `chat.ask`, `chat.answer_timeout_min`) say what the agent asks and how long a question waits. The tab shows the run's chat, then the item's own thread of the project chat: the talk, question cards (picks, several questions, **Submit**), the run's milestones, its sessions, the limit wait, the context share. A message goes where the server puts it: the live run (its limit wait too), else the item's thread, and the line under the box says where it went. `GET /api/p/<project>/chat/<id>` follows the item's chat from its start, in raw chunks of JSON lines (the page splits them). `POST` there sends `{type: 'say', text, images?, attach?}`, `{type: 'interrupt'}` or `{type: 'answer', request_id, answers}` through `gcf-harness chat`; with no live run a message goes to the item's thread (answer `{talk}`), else a message with no session to read it gets 409, bad input 400. `attach` (`[{kind: item | unit | file, ref}]`) goes into the message's text as a line the agent reads; a file picked on the operator's machine (`{kind: file, ref: <name>, data: <base64>}`, the composer's 📎) is written into `.gcf-session/uploads/` and goes as `file <its absolute path>`; a move's `file` field (`attach`) takes `{name, data}` the same way, its copy removed after the command; a design unit (the composer's **+ unit**, from the board read's `units`) goes as `unit <id> (<file>)`. `GET /api/p/<project>/chat/<id>/att/<file>` serves a chat picture; **attach to item…** under a picture gives it to an item (`gcf item attach`).
75
75
  - **Functional base A** (board 0.10.0, core and harness 0.14.0; docs/Base-A-Plan.md): Settings has `session_timeout_min` and the project's `agent.model` / `agent.effort`; the drawer shows the project's model on an item without its own, "(project)". The drawer's Run is off with the run gate's reason when the gate refuses the item now, and the start dialog marks each refused item and runs the rest (`GET /api/p/<project>/gate?ids=` runs `gcf-harness gate --each`). An item's attachments and an inbox entry's pictures are links (`GET /api/p/<project>/attachment?path=`: only `gcf/work/<id>/attachments/` and `gcf/inbox/in-<hex>/attachments/`, no `..`, no link on the way, a picture shown, any other file a download, `nosniff` and `default-src 'none'`), and a picture or link in File or Plan that points there loads through it. A permission card for one MCP tool offers Always, saying it allows every call of the tool with any arguments.
76
76
  - **Model and effort** (board 0.8.0, core 0.12.3; a closed select since board 0.15.0, Board-PRD decision 33): pickers in the New item form, in the drawer (**change** beside the model and effort, and **model / effort** under **More**), in a thread's composer and in Settings (`agent.model` / `agent.effort`). Each is one select: Default first — "Default (Opus)" / "Default (High)", or "Default - project setting (Sonnet)" when the project sets one, and "Default - each item's own" in the run dialog; Default sends `default` — then the agent's presets by name (Fable, Opus, xHigh). Nothing set anywhere runs on Opus / High (decision 36). A thread's composer has no Default row: it shows what holds, and **↺ project** takes the thread's own pick off (board 0.16.2). No own word; a value set from the console that the presets lack shows as its own row, so a form sent unchanged keeps it. An item's next run takes them; a thread's next session does (`chats/<t>/agent.json`), and its line in the chat says so.
77
- - **Project chat** (the **Chat** screen; core 0.12): threads of an agent in the project's folder, listed newest first and filtered by their item; a new thread is made when its first message is sent. Each thread is run by the bundled session engine (`gcf-session`) through the same detached relay as runs. It asks a card before each edit, git command and framework move (**allow once**, **always** — saved in `.claude/settings.local.json`; the card says saved only when it was — or **deny**); a new item it proposes through the board's MCP server `gcf` (tool `propose_item_new`, asked with no card: the proposal card is the question), the proposal card shows every field it proposed, and the operator's **Create** makes it with `POST /move` (`proposal: {talk, id}`), **Edit…** first in the new-item form. A proposed item has no id: the server asks `gcf item new --dry-run` for it, records it, then creates the item with it, so a board that stops halfway does not make it twice. An inbox entry the agent proposed is filed with origin `agent`: the server adds `--origin=agent`, never from the request. With core 0.16 (board 0.12.0, Board-PRD decision 27) it also proposes a move on an item or an inbox entry already there — `block`, `drop`, `depends`, and the inbox's `add` (with its category), sort, Later and erase (sort and Later with core 0.18, board 0.15.0) — naming it in `id`: the card shows the item's id, title and status now (or the entry's first line), warns when the item does not take the move now or is not on the board, its button is the move's name (a drop or an erase asks first), and **Edit…** opens that move's form. A thread's list entry names the card that waits in it and its limit wait (`card`, `limit_until`); a running item names the card of its run's chat (`chat_card`). A long talk hands over to a fresh agent from a summary; an idle agent closes after `chat.answer_timeout_min` (0 means 15) and the next message resumes it. Each item has at most one thread: a message to an item with no live run goes there. `GET /api/p/<project>/talks[?item=]` lists the threads with their proposals' states; `POST` there makes one (`{item?}`); `GET /api/p/<project>/talk/<t>` follows a thread's events; `POST` there sends `say`, `interrupt`, `answer`, `allow`, `deny` or `handoff`; `POST …/talk/<t>/stop` is the composer's **close agent** (board 0.8.1): the thread's agent ends with everything it started, or its limit wait does, and what it had not taken in is dropped with a "not sent" line; the next message resumes the talk; `GET …/talk/<t>/att/<file>` serves its pictures. The files live in `.gcf-session/chats/` (docs/Chat-Plan.md §3).
77
+ - **Project chat** (the **Chat** screen; core 0.12): threads of an agent in the project's folder, listed by their last message and filtered by their item; **Reply** on an agent message sends your words with it quoted; a new thread is made when its first message is sent. Each thread is run by the bundled session engine (`gcf-session`) through the same detached relay as runs. It asks a card before each edit, git command and framework move (**allow once**, **always** — saved in `.claude/settings.local.json`; the card says saved only when it was — or **deny**); a new item it proposes through the board's MCP server `gcf` (tool `propose_item_new`, asked with no card: the proposal card is the question), the proposal card shows every field it proposed, and the operator's **Create** makes it with `POST /move` (`proposal: {talk, id}`), **Edit…** first in the new-item form. A proposed item has no id: the server asks `gcf item new --dry-run` for it, records it, then creates the item with it, so a board that stops halfway does not make it twice. An inbox entry the agent proposed is filed with origin `agent`: the server adds `--origin=agent`, never from the request. With core 0.16 (board 0.12.0, Board-PRD decision 27) it also proposes a move on an item or an inbox entry already there — `block`, `drop`, `depends`, and the inbox's `add` (with its category), sort, Later and erase (sort and Later with core 0.18, board 0.15.0) — naming it in `id`: the card shows the item's id, title and status now (or the entry's first line), warns when the item does not take the move now or is not on the board, its button is the move's name (a drop or an erase asks first), and **Edit…** opens that move's form. A thread's list entry names the card that waits in it and its limit wait (`card`, `limit_until`); a running item names the card of its run's chat (`chat_card`). A long talk hands over to a fresh agent from a summary; an idle agent closes after `chat.answer_timeout_min` (0 means 15) and the next message resumes it. Each item has at most one thread: a message to an item with no live run goes there. `GET /api/p/<project>/talks[?item=]` lists the threads with their proposals' states; `POST` there makes one (`{item?}`); `GET /api/p/<project>/talk/<t>` follows a thread's events; `POST` there sends `say`, `interrupt`, `answer`, `allow`, `deny` or `handoff`; `POST …/talk/<t>/stop` is the composer's **close agent** (board 0.8.1): the thread's agent ends with everything it started, or its limit wait does, and what it had not taken in is dropped with a "not sent" line; the next message resumes the talk; `GET …/talk/<t>/att/<file>` serves its pictures. The files live in `.gcf-session/chats/` (docs/Chat-Plan.md §3).
78
78
  - **Inbox** (categories since board 0.15.0, core 0.18.0; Board-PRD decision 32): add an entry (Ctrl+Enter adds, Enter breaks the line; a category of the ones you may file, Note by default, and a detail), **Sort…** it into another category, put it away to **Later** and take it **Back**, erase it, or turn it into an item (its first line the title, the rest the note). Each entry shows its category and detail, its origin, its lines and date. Search the entries, filter them by category (or "in Later") and by detail. Since board 0.16.0 each group is a panel of tiles, Needs you first; a tile opens the record in the detail window (the item window's frame); the filter takes a category, its details, the origin, an item and the text; on the Inbox `j` / `k` move between tiles, Enter opens, `s` sorts, `l` puts Later or Back, `e` erases. The decisions and the agent's assumptions are records of their own categories there too. **Draft with agent** opens a project chat thread bound to the entry and sends "Draft an item from inbox entry <id>:" with its text; a second click opens the same thread. The first proposal's **Create** takes the entry (it is erased); a later one makes an item with no entry. Off while the usage limit holds.
79
79
  - **Design**: where a game starts and its design changes. The steps from an empty project to the first work (the design, the pillars, the open questions, a ready unit), each with what does it: **Import GDD** (a markdown file), **Review GDD first**, **Create with agent**, **Draft with agent** for the glossary, **Pillars interview**, **Name with agent** for pillars without a name; each opens a project chat thread that follows its own skill and writes the design files without a card. **Record design** commits what a thread wrote, and **Discard draft…** takes an agent's unrecorded draft back (`gcf design discard`); a form save of the drafted part takes the draft along. The pillars, the vision, the glossary, a subsystem's purpose and each unit open in a form whose fields come from the core; a save goes through the core's checks, a refusal says why. A pillar is edited by its name, its id read-only (a changed name renames the id after the save); Retire. **Add unit** asks a subsystem, a type and a title, no id, and opens the new unit. A subsystem's purpose has **Draft with agent**. A unit's Drop, the design questions with their answer box, the designer's Export and Import. Until the first work, while steps are left, Command says how many and opens Design.
80
80
  - **Keys**: `/` search, `i` a new inbox entry, `n` a new item, `j` / `k` between cards, Enter opens one, `r` runs the focused card (it asks), `1`–`7` a column, `?` Help, `g` then a letter goes to a screen (`g c` Command, `g b` Board, `g t` Chat, `g i` Inbox, `g d` Design, `g r` Runs, `g p` Playtest, `g e` Ended, `g a` Agent, `g m` Metrics, `g s` Settings; the nav's icons say theirs), Esc closes a dialog, Help, the item's or the detail window; none while a field has the focus. Board 0.16.0: the nav is a rail of icons, the project switcher sits at the header's left.
@@ -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;
@@ -667,7 +693,7 @@ export function createApp(o) {
667
693
  },
668
694
  ],
669
695
  [
670
- // The project chat's threads (AD-46: `?item=` its bound one), newest first.
696
+ // The project chat's threads (AD-46: `?item=` its bound one), the last used first.
671
697
  'GET',
672
698
  /^\/api\/p\/([^/]+)\/talks$/,
673
699
  async (_req, res, m, url) => {
@@ -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,3 +1,8 @@
1
+ // What the operator writes into an item's chat (docs/Chat-Plan.md): its shape checked here, at
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';
5
+ import { replyBlock } from '../shared/board.js';
1
6
  import { HttpError } from './http-error.js';
2
7
  import { saveUpload } from './upload.js';
3
8
  /** A chat message may carry images: a body up to 10 MB. */
@@ -93,6 +98,18 @@ export async function withUploads(root, body) {
93
98
  /** Whether a body attaches a design unit: its route reads the board's units for it. */
94
99
  export const attachesUnit = (body) => Array.isArray(body.attach) &&
95
100
  body.attach.some((a) => a?.kind === 'unit');
101
+ /** A request's `reply_to` (Board-Use-Plan d1): the agent message's `at` and its text; null for none. */
102
+ function replyTo(r) {
103
+ if (r === undefined || r === null)
104
+ return null;
105
+ const { at, text } = r;
106
+ if (typeof at !== 'string' ||
107
+ !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z$/.test(at) ||
108
+ typeof text !== 'string')
109
+ throw bad("reply_to is {at: <the agent message's ISO time>, text: <its text>}");
110
+ // The body's own limit bounds it; only its first REPLY_QUOTE_MAX characters are quoted.
111
+ return { at, text };
112
+ }
96
113
  /**
97
114
  * The line a request writes into the chat input: a message, a stop of the step, an answer.
98
115
  * `units`: the design units an attachment may name.
@@ -101,7 +118,18 @@ export function chatInput(body, units) {
101
118
  if (body.type === 'interrupt')
102
119
  return { type: 'interrupt' };
103
120
  if (body.type === 'say') {
104
- const text = typeof body.text === 'string' ? body.text + attachLine(body.attach, units) : body.text;
121
+ const attach = typeof body.text === 'string' ? attachLine(body.attach, units) : '';
122
+ const reply = replyTo(body.reply_to);
123
+ if (reply && !(typeof body.text === 'string' && body.text.trim()))
124
+ throw bad('a reply carries your own words: the quote alone says nothing');
125
+ // The quote gives way to the operator's words and the attachments: it is cut, not refused.
126
+ const text = typeof body.text === 'string'
127
+ ? body.text +
128
+ (reply
129
+ ? replyBlock(reply.at, reply.text, TEXT_MAX - body.text.length - attach.length)
130
+ : '') +
131
+ attach
132
+ : body.text;
105
133
  if (typeof text !== 'string' || !text.trim() || text.length > TEXT_MAX)
106
134
  throw bad(`a message is text, up to ${TEXT_MAX} characters`);
107
135
  const list = images(body.images);
@@ -133,3 +161,35 @@ export function talkInput(body, units) {
133
161
  return { type: 'deny', request_id: id };
134
162
  return { type: 'allow', request_id: id, always: body.always === true };
135
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
@@ -31,7 +45,7 @@ export function aiFactoryEntry() {
31
45
  function globalRoots() {
32
46
  const roots = [];
33
47
  try {
34
- roots.push(execSync('npm root -g', { encoding: 'utf8', stdio: 'pipe' }).trim());
48
+ roots.push(execSync('npm root -g', { windowsHide: true, encoding: 'utf8', stdio: 'pipe' }).trim());
35
49
  }
36
50
  catch {
37
51
  // No npm on PATH: the folders beside this node still hold the global packages.
@@ -110,10 +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], {
130
+ windowsHide: true,
115
131
  cwd,
116
- env,
132
+ env: { ...env, ...start.env },
117
133
  shell: false,
118
134
  stdio: ['pipe', 'pipe', 'pipe'],
119
135
  });
@@ -132,7 +148,10 @@ export function runCli(entry, cwd, args, timeoutMs = 120_000, input) {
132
148
  err += `\nstopped after ${timeoutMs / 1000} s`;
133
149
  // On Windows a kill stops node alone: a build it started (Unity) would go on.
134
150
  if (process.platform === 'win32' && child.pid)
135
- spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
151
+ spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
152
+ windowsHide: true,
153
+ stdio: 'ignore',
154
+ });
136
155
  else
137
156
  child.kill();
138
157
  // A grandchild holding the pipes keeps close from firing: the answer does not wait for it.
@@ -72,6 +72,7 @@ export function createShortcut(main, port) {
72
72
  const plan = shortcutPlan(process.platform, process.execPath, main, port);
73
73
  if ('powershell' in plan) {
74
74
  const r = spawnSync('powershell', ['-NoProfile', '-Command', plan.powershell], {
75
+ windowsHide: true,
75
76
  encoding: 'utf8',
76
77
  });
77
78
  if (r.error)
@@ -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';
@@ -173,7 +173,7 @@ export function talkSpec(p, board, mcp, start = null) {
173
173
  };
174
174
  }
175
175
  /** A command's output in the project, or empty. */
176
- const git = (cwd, ...args) => spawnSync('git', args, { cwd, encoding: 'utf8' }).stdout?.trim() ?? '';
176
+ const git = (cwd, ...args) => spawnSync('git', args, { windowsHide: true, cwd, encoding: 'utf8' }).stdout?.trim() ?? '';
177
177
  // The most lines of a log or of commits a thread's context gives: it goes into every session.
178
178
  const CONTEXT_LINES = 30;
179
179
  /** The last lines of a csv log (no header, Harness-PRD §11) whose fields include the id. */
@@ -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. */
@@ -841,6 +856,8 @@ async function talkOf(p, th, ids, questionOf) {
841
856
  start: th.start?.id ?? null,
842
857
  created_at: th.created_at,
843
858
  last_at: events.at(-1)?.at ?? null,
859
+ // A close, a limit or a session's end is no use of it (Board-Use-Plan d4).
860
+ used_at: events.findLast((e) => e.type === 'say' || e.type === 'agent')?.at ?? th.created_at,
844
861
  cost_usd: Math.round(cost * 100) / 100,
845
862
  model: pick.model ?? null,
846
863
  effort: pick.effort ?? null,
@@ -854,7 +871,7 @@ async function talkOf(p, th, ids, questionOf) {
854
871
  };
855
872
  }
856
873
  /**
857
- * The project's threads, newest first; with `item`, its bound one only. `ids()` reads the
874
+ * The project's threads, the last used first (`used_at`); with `item`, its bound one only. `ids()` reads the
858
875
  * board's items when a proposal needs settling; `questionOf` the question an answer proposal
859
876
  * answers, when it is first seen.
860
877
  */
@@ -863,7 +880,8 @@ export async function listTalks(p, ids, item, questionOf) {
863
880
  // One board read at most, and only when a proposal needs it.
864
881
  let read = null;
865
882
  const once = () => (read ??= ids());
866
- return Promise.all(threads.map((th) => talkOf(p, th, once, questionOf)));
883
+ const talks = await Promise.all(threads.map((th) => talkOf(p, th, once, questionOf)));
884
+ return talks.sort((a, b) => b.used_at.localeCompare(a.used_at));
867
885
  }
868
886
  /** Where a thread's input is read to, and how far it is written. */
869
887
  function unread(td) {