gcf-board 0.5.1 → 0.7.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 (42) hide show
  1. package/README.md +14 -12
  2. package/dist/server/app.js +166 -20
  3. package/dist/server/chat.js +42 -1
  4. package/dist/server/files.js +5 -2
  5. package/dist/server/mcp.js +28 -0
  6. package/dist/server/moves.js +11 -0
  7. package/dist/server/propose.js +96 -0
  8. package/dist/server/runs.js +28 -120
  9. package/dist/server/talks.js +553 -0
  10. package/dist/web/assets/golos-text-cyrillic-ext-wght-normal-hICkpzq7.woff2 +0 -0
  11. package/dist/web/assets/golos-text-cyrillic-wght-normal-mKek_fSS.woff2 +0 -0
  12. package/dist/web/assets/golos-text-latin-ext-wght-normal-B-I5lbAQ.woff2 +0 -0
  13. package/dist/web/assets/golos-text-latin-wght-normal-BS5oQT7X.woff2 +0 -0
  14. package/dist/web/assets/index-B3u-VrJK.css +1 -0
  15. package/dist/web/assets/index-BB3i2FaE.js +39 -0
  16. package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  17. package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  18. package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  19. package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  20. package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  21. package/dist/web/index.html +2 -2
  22. package/node_modules/gcf-session/lib/activity.js +371 -0
  23. package/node_modules/gcf-session/lib/adapter/claude.js +226 -0
  24. package/node_modules/gcf-session/lib/adapter/index.js +33 -0
  25. package/node_modules/gcf-session/lib/chat-input.js +260 -0
  26. package/node_modules/gcf-session/lib/chat.js +834 -0
  27. package/node_modules/gcf-session/lib/cli.js +52 -0
  28. package/node_modules/gcf-session/lib/cost.js +29 -0
  29. package/node_modules/gcf-session/lib/index.js +58 -0
  30. package/node_modules/gcf-session/lib/job.js +437 -0
  31. package/node_modules/gcf-session/lib/limit.js +132 -0
  32. package/node_modules/gcf-session/lib/lock.js +81 -0
  33. package/node_modules/gcf-session/lib/proc.js +93 -0
  34. package/node_modules/gcf-session/lib/session.js +320 -0
  35. package/node_modules/gcf-session/lib/store.js +28 -0
  36. package/node_modules/gcf-session/lib/thread.js +423 -0
  37. package/node_modules/gcf-session/lib/windows.js +46 -0
  38. package/node_modules/gcf-session/package.json +23 -0
  39. package/node_modules/gcf-session/types/index.d.ts +152 -0
  40. package/package.json +12 -3
  41. package/dist/web/assets/index-BYAEKw51.css +0 -1
  42. package/dist/web/assets/index-DpzFCrLV.js +0 -36
package/README.md CHANGED
@@ -6,7 +6,8 @@ A local web board for game projects on [GCF](../gcf-aif-ext): the items by statu
6
6
 
7
7
  - Node.js ≥ 22.18
8
8
  - [`ai-factory`](https://www.npmjs.com/package/ai-factory) installed globally, and in each project [`gcf-aif-ext`](../gcf-aif-ext) ≥ 0.10 (`gcf board --json` with `schema: 3`: the columns, the moves, the item's fields, the blocks and the Help terms come from it as data)
9
- - for runs: [`gcf-harness-aif-ext`](../gcf-harness-aif-ext) ≥ 0.11 (every board run opens its chat: `--chat`, `--chat-timeout`, `gcf-harness chat`) and Claude Code (`claude -p`)
9
+ - for runs: [`gcf-harness-aif-ext`](../gcf-harness-aif-ext) ≥ 0.11 (every board run opens its chat: `--chat`, `gcf-harness chat`; it waits the project's answer time) and Claude Code (`claude -p`); ≥ 0.12 to wait for the usage limit's reset and for queued runs (`--wait-limit`)
10
+ - for the project chat: `gcf-aif-ext` ≥ 0.12 (`domain.chat`, `agent.rules`) and Claude Code
10
11
  - gcf-board 0.2 needs `gcf-aif-ext` ≥ 0.7 (priority, questions, session marks, `run_mode`)
11
12
 
12
13
  ## Run
@@ -30,8 +31,9 @@ It puts **GCF Board** on the desktop (Windows: a shortcut whose server console s
30
31
 
31
32
  ## What it does
32
33
 
33
- The board knows no domain by name: the project's board read gives its columns, moves with their forms, item fields, blocks and Help terms (`domain`, Board-PRD decision 16). For a GCF project:
34
+ The board knows no domain by name: the project's board read gives its columns, moves with their forms, item fields, blocks and Help terms (`domain`, Board-PRD decision 16). The page follows design B (`docs/design/mockup`): a left nav with the project switcher (add a project, take one off the board), the screens **Command**, **Board**, **Chat**, **Inbox**, **Playtest**, **Ended**, **Agent**, **Settings** and **Metrics** (a domain without a block has no screen for it, a project without a harness no Metrics), and a header with the phase, the runs, the limit wait, the quota, WIP, the release, **waiting for me**, **+ item** and **?**. The project and the screen are in the URL hash. On a phone a bottom bar holds Command, Board, Chat, Inbox and More. When the server is gone, the page says so and reconnects by itself. For a GCF project:
34
35
 
36
+ - **Command**: **waiting for me**, what only the operator moves on (Board-PRD §1.3), by group: failed run reports and a paused queue, a card waiting in a chat (a permission is answered right there, **Always** naming the rule it saves), D1 questions, 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.
35
37
  - **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. 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.
36
38
  - **An item**: its file, its plan and its run log as it grows, its fields, 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.
37
39
  - **Drag**:
@@ -44,16 +46,18 @@ The board knows no domain by name: the project's board read gives its columns, m
44
46
  - `run_mode: worktree`: one worktree and one agent session per item, all at once, then the integrator;
45
47
  - `run_mode: main`: one item at a time in the project folder. A run asked for meanwhile waits in the board's **queue**; **remove from queue** takes it out.
46
48
 
47
- A run asks first: it spends the subscription. **Stop** on a running item ends its session; the item stays ready and its work is kept. A queued main run that the next one would repeat (the harness did not start, or another run works the checkout) pauses the queue: the header shows **queue paused — resume**; fix the cause, then resume. A card marked **interrupted** had a run that stopped (a timeout, a stop, a crash, the usage limit): **resume** continues its agent session with all its context, **start fresh** drops it. After the usage limit the card reads **paused: limit** and the board resumes it by itself at the reset time; the header shows **resumes HH:MM** with **cancel**, and a queue the limit paused resumes only by that clock until the operator cancels it; a pause after a failure keeps its **resume** button. When a run ends, a report card lists each item's result and stays until closed, across page reloads. **What the board did by itself** lists its automatic acts with their times: a usage limit, a context handoff, the queue paused or started, a resume run or cancelled. A run confirmation names what each interrupted item picks up. The header shows the usage limit as the last run read it, from the newest `.gcf-session/runs/quota.json` of the board's projects: `quota 19% left · resets 03:00`, the window with the least left, every window in its tooltip; `quota ?` before any reading, or once every window has reset since. The queue, the reports and that list live in the board's memory: a board restart forgets them. A run itself outlives the board: closing it or Ctrl+C in its console leaves the run going, and the board started again shows it running, then its report (a run in flight keeps its record in `~/.gcf/runs/`).
49
+ A run asks first: it spends the subscription. **Stop** on a running item ends its session; the item stays ready and its work is kept. **Stop** during the wait for the usage limit's reset leaves the item **paused: limit** with its reset, and the queue goes on. A queued main run that the next one would repeat (the harness did not start, or another run works the checkout) pauses the queue: the header shows **queue paused — resume**; fix the cause, then resume. A card marked **interrupted** had a run that stopped (a timeout, a stop, a crash, the usage limit): **resume** continues its agent session with all its context, **start fresh** drops it. After the usage limit the run itself waits for the reset and goes on in the same session (harness 0.12): the card reads **limit: resumes HH:MM**, and **Stop** ends the wait. A run that could not wait (the week's limit, an unknown reset) ends **paused: limit** and pauses the main queue; **resume** on the header goes on after the reset. When a run ends, a report card lists each item's result and stays until closed, across page reloads. **What the board did by itself** lists its automatic acts with their times: a usage limit, a context handoff, the queue paused, resumed or started. A run confirmation names what each interrupted item picks up. The header shows the usage limit as the last run read it, from the newest `.gcf-session/runs/quota.json` of the board's projects: `quota 19% left · resets 03:00`, the window with the least left, every window in its tooltip; `quota ?` before any reading, or once every window has reset since. The queue, the reports and that list live in the board's memory: a board restart forgets them. A run itself outlives the board: closing it or Ctrl+C in its console leaves the run going, and the board started again shows it running, then its report (a run in flight keeps its record in `~/.gcf/runs/`).
48
50
  - **Who runs it** (core 0.7.13): a running card tells a console run and **your session** (a `gcf claim` mark) from the board's own run; a session offers **release mark** instead of **stop**. A ready card whose dependencies are not built yet shows **waits for <dep>**; the drawer shows when an item began to wait (`since_at`).
49
51
  - **Run next N independent**: the framework's gate picks the ready items that can run together now, by priority, and the board runs them after asking.
50
52
  - **Priority**: drop a ready card on another to put it before; the column's ranks are committed (`gcf prioritize`).
51
53
  - **Questions**: each D1 shows its question and proposed answer; **Answer** writes yours into its record (`gcf question answer`), and the next agent on its units puts it in place.
52
54
  - **New item**: `gcf item new … --commit`, its form from the core: a bug asks its severity, a release its version and channel. The item's `model` and `effort` go to its run.
53
55
  - **Help** (**?**): the domain's terms, columns, moves and field values with what each means, and the words of runs, under one filter.
54
- - **Settings**: the keys of `gcf/config.yml` and the agents' language (`language.ui`, `language.artifacts` of `.ai-factory/config.yaml`), each a `gcf config set` commit.
55
- - **Chat** (data only, the page waits for its design; harness 0.11.1, core 0.11.1): every run the board starts keeps its agent sessions open; the project's `chat:` settings (Settings tab: `chat.ask`, `chat.answer_timeout_min`) say what the agent asks and how long a question waits. `GET /api/p/<project>/chat/<id>` follows the item's chat from its start, in raw chunks of JSON lines (the page splits them): the talk, the questions, the run's milestones, its sessions and context share. `POST` there sends `{type: 'say', text, images?}`, `{type: 'interrupt'}` or `{type: 'answer', request_id, answers}` through `gcf-harness chat`: a message with no live session to read it gets 409, bad input 400. Until the chat screen ships, a board run waits for no answer (`--chat-timeout 0`). `GET /api/p/<project>/chat/<id>/att/<file>` serves a chat picture; the item move **attach** (`gcf item attach`) gives a file to the item.
56
- - **Inbox**: add, erase, or turn an entry into an item. Open questions are listed there too.
56
+ - **Settings**: the keys of `gcf/config.yml` and the agents' language (`language.ui`, `language.artifacts` of `.ai-factory/config.yaml`), by the core's groups, each a `gcf config set` commit.
57
+ - **Agent**: the deny groups to tick, the rules the ticked groups add, the operator's own deny rules (add, remove) and the allow rules of `agent.allow`, apart; the context limits, read only.
58
+ - **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 | file, ref}]`) goes into the message's text as a line the agent reads. `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`).
59
+ - **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 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`; `GET …/talk/<t>/att/<file>` serves its pictures. The files live in `.gcf-session/chats/` (docs/Chat-Plan.md §3).
60
+ - **Inbox**: add an entry (Enter adds, Shift+Enter breaks the line; its source and tags), tag it, erase it, or turn it into an item (its first line the title, the rest the note); search the entries, filter them by tag and by lesson kind. The D1 questions and the agent's D2 assumptions are listed there too.
57
61
  - **Lessons** (core 0.7.10, harness 0.9.2): what got in an agent's way, asked at the end of each session, lands in the inbox with its kind (`tool`, `rules`, `framework`, `template`, `other`) and its item. The inbox filters them; a card shows `N lessons`, and the drawer lists the item's lessons with the inbox's buttons. A run's report line ends with `, N lessons`, and with `— code written outside aif-implement` when a session skipped that skill.
58
62
  - **Playtest**: `gcf playtest session` with the checklist grouped by subsystem; keep, tune or kill each item from the list. **Build** runs `dod.build`. A note goes to the inbox as `--source playtest`.
59
63
  - **Ended**: history (accepted) and graveyard (killed, dropped, won't-fix).
@@ -72,6 +76,7 @@ The board starts agents that write code and commit: whoever can talk to it runs
72
76
  - A change must come from the board's own page (`Origin`). This blocks another site in the same browser.
73
77
  - Commands run without a shell: the operator's text reaches `ai-factory` as one argument, never as a command line.
74
78
  - The API shows only item files, plans and run logs inside a project.
79
+ - A project chat's agent may not read the board's folder (`~/.gcf`, the token's): not by read, search or a shell command that names it. A command that spells the path another way still could; a separate secret for a card's answer comes with remote access.
75
80
 
76
81
  Do not put the port on a network. Remote and phone access is planned for v2, behind its own authentication.
77
82
 
@@ -79,15 +84,12 @@ Do not put the port on a network. Remote and phone access is planned for v2, beh
79
84
 
80
85
  - `~/.gcf/projects.json`: the projects on the board, `{projects: [{name, path}]}`.
81
86
  - `~/.gcf/board-token`: the token.
82
- - `GCF_BOARD_HOME` moves both; `GCF_BOARD_AIF` points at another `ai-factory` entry script.
87
+ - `~/.gcf/runs/`: the record of each run in flight, which a board started again finds.
88
+ - `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).
83
89
 
84
90
  ## Roadmap (v2)
85
91
 
86
- - **Chat with Claude in a project**:
87
- - `claude -p --output-format stream-json`;
88
- - a choice of model and effort;
89
- - permission prompts answered from the board through a `PermissionRequest` hook;
90
- - resume a session.
92
+ - **The chat**: a choice of model and effort for a thread; a design unit picked by name as a message's attachment (today a project path).
91
93
  - **Phone and remote access**: Tailscale or Claude Remote Control, with their own authentication; push notifications when an item blocks or waits for a verdict.
92
94
 
93
95
  ## Develop
@@ -1,23 +1,26 @@
1
1
  // The board's HTTP server: the page, and an API that is a thin layer over `ai-factory gcf`.
2
2
  // Reads: projects, the board, a shown file, a run log, the playtest session, the run metrics
3
- // (`ai-factory <harness> metrics`, the domain's harness). Writes: a project on the board, a
4
- // move, a run. Every write is a command of the framework.
3
+ // (`ai-factory <harness> metrics`, the domain's harness), the project chat's threads. Writes: a
4
+ // project on the board, a move, a run, a project chat message. Every write of the project is a
5
+ // command of the framework; a project chat's agent asks the operator for each one (talks.ts).
5
6
  import { randomBytes } from 'node:crypto';
6
7
  import { createServer } from 'node:http';
7
8
  import { existsSync, statSync, writeFileSync } from 'node:fs';
8
9
  import { lstat, mkdtemp, readFile, rm } from 'node:fs/promises';
9
10
  import os from 'node:os';
10
11
  import path from 'node:path';
11
- import { BOARD_SCHEMA } from '../shared/board.js';
12
+ import { BOARD_SCHEMA, } from '../shared/board.js';
12
13
  import { admit, cookieName, hostAllowed, tokenInUrl } from './auth.js';
13
14
  import { briefError, runCli } from './cli.js';
14
15
  import { broadcast, planRev, subscribe, watchProject } from './events.js';
15
- import { CHAT_BODY_MAX, chatInput, IMAGE_EXT } from './chat.js';
16
- import { followLog, readShown, shownShape } from './files.js';
16
+ import { CHAT_BODY_MAX, chatInput, IMAGE_EXT, talkInput } from './chat.js';
17
+ import { follow, followLog, readShown, shownShape } from './files.js';
17
18
  import { HttpError } from './http-error.js';
18
- import { isCenterMove, moveArgs, runIds } from './moves.js';
19
+ import { isCenterMove, moveArgs, moveInput, runIds } from './moves.js';
19
20
  import { addProject, listProjects, projectOf, removeProject } from './registry.js';
20
- import { adoptRuns, cancelResume, closeReport, forgetProject, resumeQueue, runsOf, startRun, unqueue, } from './runs.js';
21
+ import { adoptRuns, closeReport, forgetProject, resumeQueue, runsOf, startRun, unqueue, } from './runs.js';
22
+ import { acceptProposal, chatCard, chatOf, listTalks, openTalk, prepareTalk, startTalk, talkId, talkLive, talkWaits, watchTalks, writeTalk, } from './talks.js';
23
+ import { threadDir } from 'gcf-session';
21
24
  const send = (res, status, body) => {
22
25
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
23
26
  res.end(JSON.stringify(body));
@@ -52,6 +55,13 @@ function jsonOf(r, what) {
52
55
  throw new HttpError(502, `ai-factory ${what} gave no report: ${(r.err || r.out).trim()}`);
53
56
  }
54
57
  }
58
+ /** The ids a board read knows: its items, accepted and killed ones too. */
59
+ const idsOf = (b) => new Set([
60
+ ...b.items.map((i) => i.id),
61
+ ...(b.history ?? []).map((h) => h.id),
62
+ ...(b.graveyard ?? []).map((g) => g.id),
63
+ ]);
64
+ const SLUG = /^[a-z0-9][a-z0-9-]*$/;
55
65
  /** The ISO time a file was last written, or null when it is not there. */
56
66
  const activeAt = (file) => {
57
67
  try {
@@ -115,12 +125,16 @@ export function createApp(o) {
115
125
  return;
116
126
  for (const p of projects)
117
127
  if (!watchers.has(p.name)) {
118
- watchers.set(p.name, watchProject(p));
128
+ const stops = [
129
+ watchProject(p),
130
+ watchTalks(p, () => broadcast({ type: 'talks', project: p.name }), async (t) => prepareTalk(p, await boardOf(p), t)),
131
+ ];
132
+ watchers.set(p.name, () => stops.forEach((stop) => stop()));
119
133
  // The runs a board before this one started go on: show them, and their ends.
120
134
  adoptRuns(o.entry, p);
121
135
  }
122
136
  };
123
- const cli = (p, args, timeout) => runCli(o.entry, p.path, args, timeout);
137
+ const cli = (p, args, timeout, input) => runCli(o.entry, p.path, args, timeout, input);
124
138
  // The last domain each project's board read gave: an item move is built from its form.
125
139
  const domains = new Map();
126
140
  /**
@@ -149,6 +163,38 @@ export function createApp(o) {
149
163
  domains.set(p.name, board.domain);
150
164
  return board;
151
165
  };
166
+ /**
167
+ * The operator's input into thread `t`. A message or a fresh agent starts the thread's engine
168
+ * when no session of it lives, with what it runs by written fresh from the board read (`board`,
169
+ * or one read now); the rest needs a live session (409).
170
+ */
171
+ const sendTalk = async (p, t, input, board) => {
172
+ const live = talkLive(p, t);
173
+ if (!live && input.type !== 'say' && input.type !== 'handoff')
174
+ throw new HttpError(409, `thread ${t} has no live agent: nothing sent`);
175
+ // Nothing runs while it waits for the limit: a stop would cut the turn after the reset.
176
+ if (live && input.type !== 'say' && talkWaits(p, t))
177
+ throw new HttpError(409, `thread ${t} waits for the usage limit: only a message waits`);
178
+ if (!live)
179
+ await prepareTalk(p, board ?? (await boardOf(p)), t);
180
+ const line = writeTalk(p, t, input);
181
+ if (!live)
182
+ startTalk(p, t);
183
+ broadcast({ type: 'talks', project: p.name });
184
+ return line;
185
+ };
186
+ /**
187
+ * A message to item `item`'s thread of the project chat (AD-49), when the project has one and
188
+ * the board read knows the item: the thread's id, else null.
189
+ */
190
+ const toThread = async (p, item, line) => {
191
+ const board = await boardOf(p).catch(() => null);
192
+ if (!board?.domain.chat || !board.agent?.rules || !idsOf(board).has(item))
193
+ return null;
194
+ const t = openTalk(p, item).id;
195
+ await sendTalk(p, t, line, board);
196
+ return t;
197
+ };
152
198
  const routes = [
153
199
  ['GET', /^\/api\/events$/, async (_req, res) => subscribe(res)],
154
200
  ['GET', /^\/api\/projects$/, async (_req, res) => send(res, 200, await listProjects())],
@@ -197,6 +243,11 @@ export function createApp(o) {
197
243
  for (const i of board.items) {
198
244
  if (i.running)
199
245
  i.active_at = i.log ? activeAt(path.join(p.path, i.log)) : null;
246
+ // A card waits in its run's chat: it is in "waiting for me" (Board-PRD §1.3).
247
+ if (i.running) {
248
+ const chat = path.join(p.path, '.gcf-session', 'runs', `${i.id}.chat.jsonl`);
249
+ i.chat_card = chatCard(chat);
250
+ }
200
251
  if (i.running_kind === 'run')
201
252
  i.running_kind = mine.has(i.id) ? 'board' : 'console';
202
253
  }
@@ -260,7 +311,18 @@ export function createApp(o) {
260
311
  async (req, res, m) => {
261
312
  const p = await projectOf(m[1]);
262
313
  const line = chatInput(await bodyOf(req, CHAT_BODY_MAX));
263
- const chat = [await harnessOf(p), 'chat', m[2]];
314
+ let harness;
315
+ try {
316
+ harness = await harnessOf(p);
317
+ }
318
+ catch (e) {
319
+ // No harness, so no run: a message goes to the item's thread all the same.
320
+ const t = line.type === 'say' ? await toThread(p, m[2], line) : null;
321
+ if (t)
322
+ return send(res, 202, { ok: true, talk: t });
323
+ throw e;
324
+ }
325
+ const chat = [harness, 'chat', m[2]];
264
326
  const tmp = await mkdtemp(path.join(os.tmpdir(), 'gcf-board-chat-'));
265
327
  try {
266
328
  let args = [...chat, 'interrupt'];
@@ -281,6 +343,11 @@ export function createApp(o) {
281
343
  const r = await runCli(o.entry, p.path, args, undefined, input);
282
344
  if (r.ok)
283
345
  return send(res, 202, { ok: true });
346
+ // No live run session: a message goes to the item's thread of the project chat (AD-49).
347
+ // An item the board read knows: a stale or mistyped id gets no thread.
348
+ const t = r.code === 3 && line.type === 'say' ? await toThread(p, m[2], line) : null;
349
+ if (t)
350
+ return send(res, 202, { ok: true, talk: t });
284
351
  const why = briefError(r.err || r.out).replace(/^[\w-]+ chat: /, '');
285
352
  if (/unknown command 'chat'/.test(why))
286
353
  throw new HttpError(400, 'the chat needs gcf-harness-aif-ext 0.11.0 or later');
@@ -291,6 +358,77 @@ export function createApp(o) {
291
358
  }
292
359
  },
293
360
  ],
361
+ [
362
+ // The project chat's threads (AD-46: `?item=` its bound one), newest first.
363
+ 'GET',
364
+ /^\/api\/p\/([^/]+)\/talks$/,
365
+ async (_req, res, m, url) => {
366
+ const p = await projectOf(m[1]);
367
+ const item = url.searchParams.get('item') ?? undefined;
368
+ const talks = await listTalks(p, async () => idsOf(await boardOf(p)), item);
369
+ send(res, 200, { talks });
370
+ },
371
+ ],
372
+ [
373
+ // A new thread, or the item's one (AD-46): the same thread for two calls.
374
+ 'POST',
375
+ /^\/api\/p\/([^/]+)\/talks$/,
376
+ async (req, res, m) => {
377
+ const p = await projectOf(m[1]);
378
+ const { item = null } = await bodyOf(req);
379
+ if (item !== null && (typeof item !== 'string' || !SLUG.test(item)))
380
+ throw new HttpError(400, 'item must be an item id');
381
+ const board = await boardOf(p);
382
+ chatOf(board);
383
+ if (item && !idsOf(board).has(item))
384
+ throw new HttpError(404, `no item ${item}`);
385
+ const { id, created } = openTalk(p, item);
386
+ await prepareTalk(p, board, id);
387
+ broadcast({ type: 'talks', project: p.name });
388
+ send(res, created ? 201 : 200, { id, created });
389
+ },
390
+ ],
391
+ [
392
+ // A thread's chat as it grows, from its start: one event a line.
393
+ 'GET',
394
+ /^\/api\/p\/([^/]+)\/talk\/([^/]+)$/,
395
+ async (_req, res, m) => {
396
+ const p = await projectOf(m[1]);
397
+ follow(p.path, path.join(threadDir(p.path, talkId(m[2])), 'chat.jsonl'), res, true);
398
+ },
399
+ ],
400
+ [
401
+ // The operator writes into a thread: a message starts its agent when none lives.
402
+ 'POST',
403
+ /^\/api\/p\/([^/]+)\/talk\/([^/]+)$/,
404
+ async (req, res, m) => {
405
+ const p = await projectOf(m[1]);
406
+ const t = talkId(m[2]);
407
+ if (!existsSync(threadDir(p.path, t)))
408
+ throw new HttpError(404, `no thread ${t}`);
409
+ const line = await sendTalk(p, t, talkInput(await bodyOf(req, CHAT_BODY_MAX)));
410
+ send(res, 202, { ok: true, ...(typeof line.id === 'string' ? { id: line.id } : {}) });
411
+ },
412
+ ],
413
+ [
414
+ // A picture of a thread (`att/`, where the board put it); never through a link.
415
+ 'GET',
416
+ /^\/api\/p\/([^/]+)\/talk\/([^/]+)\/att\/([0-9a-f]{8}\.(png|jpe?g|gif|webp))$/,
417
+ async (_req, res, m) => {
418
+ const p = await projectOf(m[1]);
419
+ const td = threadDir(p.path, talkId(m[2]));
420
+ const file = path.join(td, 'att', m[3]);
421
+ const chats = path.dirname(td);
422
+ for (const f of [path.dirname(chats), chats, td, path.dirname(file), file]) {
423
+ const st = await lstat(f).catch(() => null);
424
+ if (!st || st.isSymbolicLink())
425
+ throw new HttpError(404, `no picture ${m[3]}`);
426
+ }
427
+ const type = m[4] === 'jpg' ? 'jpeg' : m[4];
428
+ res.writeHead(200, { 'content-type': `image/${type}`, 'cache-control': 'private' });
429
+ res.end(await readFile(file));
430
+ },
431
+ ],
294
432
  [
295
433
  'GET',
296
434
  /^\/api\/p\/([^/]+)\/playtest$/,
@@ -328,7 +466,24 @@ export function createApp(o) {
328
466
  const domain = isCenterMove(body.cmd)
329
467
  ? undefined
330
468
  : (domains.get(p.name) ?? (await boardOf(p)).domain);
331
- const r = await cli(p, moveArgs(body, domain?.moves));
469
+ const args = moveArgs(body, domain?.moves);
470
+ const run = () => cli(p, args, undefined, moveInput(body, domain?.moves));
471
+ // An agent's proposal made (AD-16, AD-33): its record goes with the move.
472
+ const { talk, id } = (body.proposal ?? {});
473
+ let r;
474
+ if (body.proposal === undefined)
475
+ r = await run();
476
+ else {
477
+ if (typeof talk !== 'string' || typeof id !== 'string' || !/^[\w-]+$/.test(id))
478
+ throw new HttpError(400, 'a proposal names its talk and its id');
479
+ // Only a move an agent may propose: a line planted in the chat is no proposal of one.
480
+ if (!domain?.moves[String(body.cmd)]?.propose)
481
+ throw new HttpError(400, `${String(body.cmd)} is not a move an agent proposes`);
482
+ const item = typeof body.id === 'string' ? body.id : '';
483
+ const ids = idsOf(await boardOf(p));
484
+ r = await acceptProposal(p, talk, id, String(body.cmd), item, ids, run);
485
+ broadcast({ type: 'talks', project: p.name });
486
+ }
332
487
  broadcast({ type: 'board', project: p.name });
333
488
  send(res, 200, { ok: r.ok, out: r.out.trim(), err: briefError(r.err) });
334
489
  },
@@ -382,15 +537,6 @@ export function createApp(o) {
382
537
  send(res, 200, { ok: true });
383
538
  },
384
539
  ],
385
- [
386
- // The resume a usage limit scheduled; the queue stays paused.
387
- 'DELETE',
388
- /^\/api\/p\/([^/]+)\/schedule$/,
389
- async (_req, res, m) => {
390
- cancelResume((await projectOf(m[1])).name);
391
- send(res, 200, { ok: true });
392
- },
393
- ],
394
540
  [
395
541
  'DELETE',
396
542
  /^\/api\/p\/([^/]+)\/reports\/(r\d+)$/,
@@ -28,12 +28,40 @@ function images(v) {
28
28
  return { media_type: type, data };
29
29
  });
30
30
  }
31
+ const SLUG = /^[a-z0-9][a-z0-9-]*$/;
32
+ /**
33
+ * What a message attaches (Round2-review §3): an item, a file of the project. They go into the
34
+ * message's text, as a line the agent reads: it opens them itself.
35
+ */
36
+ function attachLine(v) {
37
+ if (v === undefined)
38
+ return '';
39
+ if (!Array.isArray(v) || v.length > 10)
40
+ throw bad('attach is a list of up to 10');
41
+ const refs = v.map((a) => {
42
+ const { kind, ref } = (a ?? {});
43
+ if (kind === 'item' && typeof ref === 'string' && SLUG.test(ref))
44
+ return `item ${ref} (gcf/work/${ref}.md)`;
45
+ // A project path, as the operator names it: relative, inside the project, nothing a shell
46
+ // would expand (`~`, `%VAR%`, `$VAR`) and no drive or scheme (`:`).
47
+ const file = typeof ref === 'string' ? ref.trim() : '';
48
+ if (kind === 'file' &&
49
+ file &&
50
+ file.length <= 300 &&
51
+ !/^[\\/~]/.test(file) &&
52
+ !/[:%$]/.test(file) &&
53
+ !file.split(/[\\/]/).some((part) => part.trim() === '..'))
54
+ return `file ${file}`;
55
+ throw bad('an attachment is {kind: item, ref: <id>} or {kind: file, ref: <project path>}');
56
+ });
57
+ return refs.length ? `\n\n[attached: ${refs.join('; ')}]` : '';
58
+ }
31
59
  /** The line a request writes into the chat input: a message, a stop of the step, an answer. */
32
60
  export function chatInput(body) {
33
61
  if (body.type === 'interrupt')
34
62
  return { type: 'interrupt' };
35
63
  if (body.type === 'say') {
36
- const { text } = body;
64
+ const text = typeof body.text === 'string' ? body.text + attachLine(body.attach) : body.text;
37
65
  if (typeof text !== 'string' || !text.trim() || text.length > TEXT_MAX)
38
66
  throw bad(`a message is text, up to ${TEXT_MAX} characters`);
39
67
  const list = images(body.images);
@@ -52,3 +80,16 @@ export function chatInput(body) {
52
80
  }
53
81
  throw bad('type is say, interrupt or answer');
54
82
  }
83
+ /** The line a request writes into a project chat thread: an item chat's, a card's, a handoff. */
84
+ export function talkInput(body) {
85
+ if (body.type === 'handoff')
86
+ return { type: 'handoff' };
87
+ if (body.type !== 'allow' && body.type !== 'deny')
88
+ return chatInput(body);
89
+ const id = body.request_id;
90
+ if (typeof id !== 'string' || !/^[A-Za-z0-9_][\w-]*$/.test(id))
91
+ throw bad(`${body.type} names its request_id`);
92
+ if (body.type === 'deny')
93
+ return { type: 'deny', request_id: id };
94
+ return { type: 'allow', request_id: id, always: body.always === true };
95
+ }
@@ -63,7 +63,10 @@ async function inside(root, file) {
63
63
  * start. One decoder for the stream: a letter cut between two reads stays whole.
64
64
  */
65
65
  export function followLog(root, id, res, ext = 'log') {
66
- const file = path.join(root, '.gcf-session', 'runs', `${id}.${ext}`);
66
+ follow(root, path.join(root, '.gcf-session', 'runs', `${id}.${ext}`), res, ext !== 'log');
67
+ }
68
+ /** Follow `file` of the project as it grows, as `followLog` does; `whole`: from its start. */
69
+ export function follow(root, file, res, whole) {
67
70
  openStream(res);
68
71
  let pos = -1;
69
72
  let decoder = new StringDecoder('utf8');
@@ -72,7 +75,7 @@ export function followLog(root, id, res, ext = 'log') {
72
75
  return;
73
76
  const { size } = await stat(file);
74
77
  if (pos < 0)
75
- pos = ext === 'log' ? Math.max(0, size - 256 * 1024) : 0;
78
+ pos = whole ? 0 : Math.max(0, size - 256 * 1024);
76
79
  if (size < pos) {
77
80
  pos = 0;
78
81
  decoder = new StringDecoder('utf8');
@@ -0,0 +1,28 @@
1
+ // `node mcp.js <moves file>`: the center's MCP server `gcf` (docs/Session-Engine.md AD-12…AD-15),
2
+ // on stdio. A project chat's agent starts it from the MCP config the board writes beside the
3
+ // thread (talks.ts); the moves file holds the domain's moves with `propose`. Each is a tool,
4
+ // `propose_<key>`: it checks the fields and answers, nothing more. The session engine sees the
5
+ // call succeed and writes the `proposal` event; the operator's click makes the move.
6
+ import { readFileSync } from 'node:fs';
7
+ import { McpServer, fromJsonSchema } from '@modelcontextprotocol/server';
8
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
9
+ import { checkProposal, toolOf, toolSchema } from './propose.js';
10
+ const PROPOSED = 'Proposed. The operator sees it as a card in the chat and makes it with one click, or edits ' +
11
+ 'it first. Do not make the move yourself.';
12
+ const moves = JSON.parse(readFileSync(process.argv[2], 'utf8'));
13
+ const server = new McpServer({ name: 'gcf', version: '1.0.0' });
14
+ for (const [key, spec] of Object.entries(moves))
15
+ server.registerTool(toolOf(key), {
16
+ description: `Propose to the operator: ${spec.label}. ${spec.help ?? ''} ` +
17
+ 'The operator decides; nothing changes until they click.',
18
+ inputSchema: fromJsonSchema(toolSchema(spec)),
19
+ }, async (args) => {
20
+ const problems = checkProposal(spec, args);
21
+ return problems.length
22
+ ? {
23
+ isError: true,
24
+ content: [{ type: 'text', text: `Not proposed: ${problems.join('; ')}.` }],
25
+ }
26
+ : { content: [{ type: 'text', text: PROPOSED }] };
27
+ });
28
+ await server.connect(new StdioServerTransport());
@@ -98,6 +98,9 @@ function fieldArgs(f, b) {
98
98
  return tagList(b, f.key, flag);
99
99
  if (f.kind === 'choice')
100
100
  return choice(f, b, flag);
101
+ // Its text goes on stdin (moveInput): the file `-`.
102
+ if (f.stdin)
103
+ return (f.required ? required(b, f.key) : text(b, f.key)) ? [`--${flag}-file=-`] : [];
101
104
  return f.required ? [`--${flag}=${required(b, f.key)}`] : opt(b, f.key, flag);
102
105
  }
103
106
  /** A move by its domain form: its words with the target, then each field that goes. */
@@ -105,6 +108,14 @@ function domainMoveArgs(spec, b) {
105
108
  const words = spec.args.flatMap((w) => w === '{id}' ? [id(b)] : w === '{ids}' ? runIds(b) : [w]);
106
109
  return [...words, ...spec.fields.filter((f) => applies(f, b)).flatMap((f) => fieldArgs(f, b))];
107
110
  }
111
+ /** The text a move's `stdin` field sends on stdin (AD-39), or undefined. */
112
+ export function moveInput(b, moves = {}) {
113
+ const cmd = typeof b.cmd === 'string' ? b.cmd : '';
114
+ if (!Object.hasOwn(moves, cmd))
115
+ return undefined;
116
+ const f = moves[cmd].fields.find((x) => x.stdin && applies(x, b));
117
+ return f ? text(b, f.key) : undefined;
118
+ }
108
119
  /** Whether a move is the center's own: its arguments need no domain. */
109
120
  export const isCenterMove = (cmd) => typeof cmd === 'string' && Object.hasOwn(MOVES, cmd);
110
121
  /**
@@ -0,0 +1,96 @@
1
+ /** The fields of a run an agent does not choose: the operator's run settings. */
2
+ const NOT_PROPOSED = new Set(['model', 'effort']);
3
+ const SLUG = '^[a-z0-9]+(-[a-z0-9]+)*$';
4
+ const TAG = '^[a-z0-9][a-z0-9:-]{0,39}$';
5
+ /** The tool's name for a move. */
6
+ export const toolOf = (key) => `propose_${key.replaceAll('-', '_')}`;
7
+ /** The fields an agent may propose: the form's, without the hidden ones and the run's. */
8
+ export const proposed = (spec) => spec.fields.filter((f) => !f.hidden && !NOT_PROPOSED.has(f.key));
9
+ /** The schema of one field by its kind; every kind has one (`never` holds the switch whole). */
10
+ export function fieldSchema(f) {
11
+ const about = [f.label, f.help].filter(Boolean).join(': ');
12
+ const kind = f.kind;
13
+ let s;
14
+ switch (kind) {
15
+ case 'slug':
16
+ s = { type: 'string', pattern: SLUG };
17
+ break;
18
+ case 'text':
19
+ case 'longtext':
20
+ s = { type: 'string', ...(f.max ? { maxLength: f.max } : {}) };
21
+ break;
22
+ case 'choice':
23
+ // An empty option means "the default": leaving the field out says it.
24
+ s = { type: 'string', enum: (f.options ?? []).map((o) => o.value).filter(Boolean) };
25
+ break;
26
+ case 'list':
27
+ s = { type: 'array', items: { type: 'string' } };
28
+ break;
29
+ case 'ids':
30
+ s = { type: 'array', items: { type: 'string', pattern: SLUG } };
31
+ break;
32
+ case 'tags':
33
+ s = { type: 'array', items: { type: 'string', pattern: TAG } };
34
+ break;
35
+ case 'remove':
36
+ s = { type: 'boolean' };
37
+ break;
38
+ case 'rank':
39
+ s = { type: 'integer', minimum: 1 };
40
+ break;
41
+ default: {
42
+ const none = kind;
43
+ throw new Error(`no schema for a field of kind ${String(none)}`);
44
+ }
45
+ }
46
+ const choices = (f.options ?? []).filter((o) => o.value && o.help);
47
+ const helps = choices.length
48
+ ? ` (${choices.map((o) => `${o.value}: ${o.help}`).join('; ')})`
49
+ : '';
50
+ const when = f.when ? ` Only when ${f.when.key} is ${f.when.is.join(' or ')}.` : '';
51
+ return { ...s, description: `${about}${helps}.${when}` };
52
+ }
53
+ /** A move's tool input schema: an object of its proposed fields, nothing else. */
54
+ export function toolSchema(spec) {
55
+ const fields = proposed(spec);
56
+ return {
57
+ type: 'object',
58
+ properties: Object.fromEntries(fields.map((f) => [f.key, fieldSchema(f)])),
59
+ required: fields.filter((f) => f.required && !f.when).map((f) => f.key),
60
+ additionalProperties: false,
61
+ };
62
+ }
63
+ const given = (v) => v !== undefined && v !== null && v !== '';
64
+ /**
65
+ * The problems of a proposal the schema cannot see (AD-36), each a sentence for the agent: a
66
+ * field it may not fill, one that goes only with another's value, one that value requires.
67
+ * The defaults count as given. Empty when it holds.
68
+ */
69
+ export function checkProposal(spec, args) {
70
+ const fields = new Map(spec.fields.map((f) => [f.key, f]));
71
+ const values = Object.fromEntries(spec.fields.filter((f) => f.default !== undefined).map((f) => [f.key, f.default]));
72
+ const problems = [];
73
+ for (const [key, v] of Object.entries(args)) {
74
+ const f = fields.get(key);
75
+ if (!f)
76
+ problems.push(`${key} is not a field of this move`);
77
+ else if (f.hidden || NOT_PROPOSED.has(key))
78
+ problems.push(`${key} is the operator's to set, not proposed`);
79
+ else if (given(v))
80
+ values[key] = v;
81
+ }
82
+ for (const f of proposed(spec)) {
83
+ if (!f.when)
84
+ continue;
85
+ const holds = f.when.is.includes(String(values[f.when.key] ?? ''));
86
+ const is = `${f.when.key} ${f.when.is.join(' or ')}`;
87
+ if (!holds && given(args[f.key]))
88
+ problems.push(`${f.key} goes only with ${is}`);
89
+ if (holds && f.required && !given(values[f.key]))
90
+ problems.push(`${f.key} is required for ${is}`);
91
+ }
92
+ for (const f of proposed(spec))
93
+ if (typeof args[f.key] === 'string' && f.max && args[f.key].length > f.max)
94
+ problems.push(`${f.key} is up to ${f.max} characters`);
95
+ return problems;
96
+ }