visualproof 0.10.0 → 0.11.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.
@@ -1,69 +1,79 @@
1
- // Agents the server runs (AgentSpec decision 10; the owner's decisions of 2026-11-08, experimental,
2
- // behind --claude-oauth): an agent made in Share to run "on this server", on its maker's Claude Code
3
- // OAuth token (server/claudetokens.ts), so that it stays without being shared again.
1
+ // The server's own agent, running (AgentSpec decision 10; the owner's decisions of 2026-11-08 for
2
+ // 0.11, experimental, behind --claude-oauth): one AI agent per VisualProof server, on the Claude Code
3
+ // OAuth token its operator gave at the start (server/serveragent.ts), which everyone with a name talks
4
+ // with. It replaces 0.10's agents run per person, on the token each gave in Share.
4
5
  //
5
- // It is an agent like any other (decisions 7–9): a token of its own, its name, level and maker, its
6
- // private channel and the public one. What differs is who listens for it: the server, here, holding
7
- // its inbox open in-process (server/talk.ts, as GET /api/agent/inbox does), so that it is *listening*
8
- // while nobody writes, at no cost. What is handed to it starts one turn of its own Claude Code
9
- // session: `claude -p`, the session resumed (`--session-id` at its first turn, `--resume` after), the
10
- // batch on stdin, as wait_for_message words it. What comes during a turn waits for the next. Between
11
- // turns nothing runs. A new conversation (a divider) starts a new session: what came before is gone
12
- // from it, as it cannot be from a session someone runs in a terminal.
6
+ // It is an agent like those people share with (decisions 7–9) — a token of its own, its name, the
7
+ // server's level, the public channel — but for whom it talks with: every person with a name has a
8
+ // private channel with it, which nobody else reads (server/talk.ts, personalChannel), and anyone
9
+ // mentions it in the public channel. **Every conversation is its own Claude Code session**: each
10
+ // person's private channel one, the public channel (the mentions handed to it) one. What one person
11
+ // says privately never enters another's session nor the public one. A person may start a new
12
+ // conversation in their own channel (a divider): a new session for that channel alone. The public
13
+ // session is never reset by people; Claude Code compacts it as it grows.
13
14
  //
14
- // It is trusted with Claude Code's own tools (the owner's decisions of 2026-11-08, after the first
15
- // version, which had VisualProof's alone): a shell, files, the web, subagents, without asking
15
+ // Nothing listens by waiting: the server is told of every message as it is written (Talk.onPosted),
16
+ // and what is handed to the agent starts one turn of that conversation's session — `claude -p`, the
17
+ // session resumed (`--session-id` at its first turn, `--resume` after), the batch on stdin, as
18
+ // wait_for_message words it. Per session one turn at a time: what comes meanwhile goes in its next.
19
+ // At most MAX_RUNNING turns run at once, all conversations together; the others wait their turn,
20
+ // oldest first. A turn's answer goes back to its own conversation: its MCP server says which turn it
21
+ // is (VISUALPROOF_TURN, in that turn's mcp.json: X-VisualProof-Turn on each request), and the reply
22
+ // tool's default is that turn's channel, so that turns running at once never mix (it may also write
23
+ // in the public channel). Between turns nothing runs.
24
+ //
25
+ // It is trusted with Claude Code's own tools (the owner's decisions of 2026-11-08, after a first
26
+ // version with VisualProof's alone): a shell, files, the web, subagents, without asking
16
27
  // (`--permission-mode bypassPermissions`), on this machine as the server's user, the project's
17
28
  // folder added (`--add-dir`): it reads the code directly, changes it and builds it with Lake when
18
- // asked (SPEC.md, as the owner changed it that day). In a branch the server follows, the project is
19
- // the deployment's clone, which the next commit built resets: its ground rules say so. What it is
20
- // denied by Claude Code's rules (`denied`): the site folder through the file tools (the tokens, the
21
- // links); and the tools that reach beyond this agent, to its maker's Claude account and their other
22
- // sessions (remote triggers, messages to other sessions, crons, workflows, worktrees). The shell is
23
- // not confined by these rules: it is trusted. A turn may build at length: while it runs the agent
24
- // counts as seen every minute (not offline), and what its shell leaves running goes with the turn
25
- // (its process group). VisualProof's
26
- // MCP server alone is its MCP server (`--strict-mcp-config`); a configuration folder of its own
27
- // (CLAUDE_CONFIG_DIR: nothing of the server user's settings, hooks, plugins or memory), no CLAUDE.md
29
+ // asked (SPEC.md). In a branch the server follows, the project is the deployment's clone, which the
30
+ // next commit built resets: its ground rules say so. What it is denied by Claude Code's rules
31
+ // (`denied`): the site folder through the file tools (the tokens, the links, the conversations); and
32
+ // the tools that reach beyond this agent, to the operator's Claude account and their other sessions
33
+ // (remote triggers, messages to other sessions, crons, workflows, worktrees). The shell is not
34
+ // confined by these rules: it is trusted, and what keeps one person's words from another is the
35
+ // ground rules (prompt.ts, hostedPrompt), not a wall — SECURITY.md says so. What a turn's shell leaves
36
+ // running goes with the turn (its process group). VisualProof's MCP server alone is its MCP server
37
+ // (`--strict-mcp-config`); a configuration folder of each session's own (CLAUDE_CONFIG_DIR: nothing of
38
+ // the server user's settings, hooks, plugins or memory, nor of another conversation's), no CLAUDE.md
28
39
  // read (CLAUDE_CODE_DISABLE_CLAUDE_MDS: one in a folder above would be), no auto-memory, no bundled
29
40
  // skills, no auto-update. The MCP server is the very file agents download (mcp/visualproof-mcp.mjs),
30
- // with the agent's token, at this server's address on this machine, its files in the agent's folder
31
- // (VISUALPROOF_FILES). Nothing secret is on a command line: the agent's token is in its mcp.json
41
+ // with the agent's token, at this server's address on this machine, its files in the conversation's
42
+ // folder (VISUALPROOF_FILES). Nothing secret is on a command line: the agent's token is in mcp.json
32
43
  // (0600), the Claude token in the environment, the messages on stdin.
33
44
  //
34
- // Each agent's folder, `<cache>/agents/<token id>/` (0700): `work/` (the empty folder it runs in),
35
- // `claude/` (its Claude Code configuration and sessions), `files/`, `mcp.json`, `prompt.md` (its
36
- // ground rules, appended to Claude Code's system prompt), `session.json`, and `batch.json` while a
37
- // turn runs or waits for the usage limit: a batch a stop of the server cut short is handed again once
38
- // at the next start, saying so. The folder goes when the token ends.
45
+ // Its folder, `<cache>/agents/<token id>/` (0700), holds one folder per conversation: `public/`, and
46
+ // `p-<16 hex>/` for a person's (their channel's digest). Each has `work/` (the empty folder it runs
47
+ // in), `claude/` (its Claude Code configuration and session), `files/`, `mcp.json`, `prompt.md` (its
48
+ // ground rules, appended to Claude Code's system prompt), `session.json`, and `batch.json` while
49
+ // something is not answered: what a stop of the server cut short, or what waited for the usage limit
50
+ // or a refused token, is handed again once at the next start, saying so.
39
51
  //
40
- // What can go wrong is said where it was asked, as the agent's message: its Claude token refused
41
- // (then the agent goes offline until its maker gives another in Share), the usage limit reached (it
42
- // answers once the limit resets: the batch waits, and so does what comes meanwhile), a turn past its
43
- // time, Claude Code missing or failing.
52
+ // What can go wrong is said where it was asked, as the agent's message, per conversation: the token
53
+ // refused (the agent is then offline for everyone until the operator fixes the file and restarts),
54
+ // the usage limit reached (it answers once the limit resets: the batch waits, and so does what comes
55
+ // meanwhile, said once in each conversation that waits), a turn past its time, a session Claude Code
56
+ // no longer has (a new one, once), Claude Code missing or failing.
44
57
  import { spawn } from "node:child_process";
45
58
  import { randomUUID } from "node:crypto";
46
- import { accessSync, constants as fsConstants, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
59
+ import { accessSync, constants as fsConstants, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
47
60
  import { homedir } from "node:os";
48
61
  import { delimiter, join } from "node:path";
49
62
  import { DETACH, end, grouped } from "./children.js";
50
- import { PUBLIC } from "./talk.js";
63
+ import { earlierOf, isPersonal, PUBLIC } from "./talk.js";
51
64
  import { hostedPrompt } from "./prompt.js";
52
65
  import { mentioned } from "../shared/mentions.js";
53
- import { madeBy } from "../shared/collab.js";
54
66
  /** how long a turn may take before it is stopped */
55
67
  export const TURN_MS = 60 * 60_000;
56
68
  /** how many model turns (tool calls and answers) one batch may take */
57
69
  export const MAX_TURNS = 100;
58
- /** how many agents in force each person may run on the server */
59
- export const PER_PERSON = 2;
60
- /** how long one in-process wait lasts: the longest an agent may wait (server/talk.ts, MAX_WAIT_S) */
61
- const LISTEN_MS = 1800_000;
70
+ /** how many turns run at once, every conversation together (the owner's decision of 2026-11-08) */
71
+ export const MAX_RUNNING = 3;
62
72
  /** a usage limit whose reset Claude Code did not say is tried again after this */
63
73
  const LIMIT_RETRY_MS = 15 * 60_000;
64
- /** What an agent the server runs is denied, by Claude Code's permission rules: the site folder
65
- * through the file tools, and the tools that reach its maker's Claude account or their other
66
- * sessions. A rule's absolute path starts with `//`. */
74
+ /** What the server's agent is denied, by Claude Code's permission rules: the site folder through the
75
+ * file tools, and the tools that reach the operator's Claude account or their other sessions. A
76
+ * rule's absolute path starts with `//`. */
67
77
  export function denied(site) {
68
78
  const under = (dir) => `/${dir.replace(/\/+$/, "")}/**`;
69
79
  return [
@@ -98,219 +108,314 @@ export function findClaude(env = process.env) {
98
108
  return null;
99
109
  }
100
110
  export class Hosted {
111
+ /** the agent's token's id */
112
+ id;
113
+ /** told when the state of a person's conversation changed, for their pages (server/live.ts) */
114
+ onSession = () => { };
101
115
  o;
102
- runners = new Map();
116
+ dir;
117
+ sessions = new Map();
118
+ turns = new Map();
103
119
  closed = false;
120
+ /** why it cannot run: Claude Code missing, or its token refused; null while it can */
121
+ down;
122
+ /** the usage limit: no turn before then */
123
+ pausedUntil = 0;
124
+ limitTimer = null;
125
+ /** its state as a whole, as presence was last told it, and since when */
126
+ told = { state: "listening", since: Date.now() };
127
+ lastSeen = null;
128
+ born = Date.now();
104
129
  constructor(o) {
105
130
  this.o = o;
106
- mkdirSync(o.root, { recursive: true, mode: 0o700 });
131
+ this.id = o.record.id;
132
+ this.dir = join(o.root, this.id);
133
+ this.down = o.claude ? null : "Claude Code (claude) is not on the server's machine";
134
+ mkdirSync(this.dir, { recursive: true, mode: 0o700 });
107
135
  }
108
- /** Whether agents can run here: Claude Code is on this machine. */
136
+ /** Whether it can run: Claude Code is here, and its token was not refused. */
109
137
  get available() {
110
- return this.o.claude !== null;
138
+ return this.down === null && !this.closed;
139
+ }
140
+ /** Why it cannot run, where it cannot. */
141
+ get offline() {
142
+ return this.down;
111
143
  }
112
144
  /** Whether a turn runs now (the server waits for none to restart into a patch). */
113
145
  get busy() {
114
- return [...this.runners.values()].some((r) => r.turn !== null);
146
+ return this.turns.size > 0;
147
+ }
148
+ /** How many turns run now, and the conversations waiting their turn, oldest first (tests). */
149
+ get running() {
150
+ return this.turns.size;
115
151
  }
116
- /** Every agent the server runs that is in force: listened for again (the server's start). */
152
+ get queue() {
153
+ return this.waiting().map((s) => s.channel);
154
+ }
155
+ /** The conversations of the last run, at the server's start: each session resumed where it was,
156
+ * and what a stop cut short handed again once, saying so. */
117
157
  restore() {
118
- for (const r of this.o.tokens.inForce())
119
- if (r.runs === "server")
120
- this.start(r);
121
- }
122
- /** Listen for an agent the server runs: just made in Share, or at the server's start. Nothing
123
- * happens where it is listened for already, or its maker has no Claude token in use. */
124
- start(record) {
125
- if (this.closed || record.runs !== "server" || this.runners.has(record.id))
126
- return;
127
- if (!this.o.claude || !this.o.claudeTokens.forMaker(record))
158
+ let names = [];
159
+ try {
160
+ names = readdirSync(this.dir);
161
+ }
162
+ catch {
128
163
  return;
129
- const dir = join(this.o.root, record.id);
130
- for (const d of [dir, join(dir, "work"), join(dir, "claude"), join(dir, "files")])
131
- mkdirSync(d, { recursive: true, mode: 0o700 });
132
- const kept = readJson(join(dir, "session.json"));
133
- const r = {
134
- id: record.id,
135
- dir,
136
- stop: new AbortController(),
137
- turn: null,
138
- session: typeof kept?.session === "string" && /^[0-9a-f-]{36}$/.test(kept.session) ? kept.session : randomUUID(),
139
- started: kept?.started === true,
140
- context: [],
141
- pending: [],
142
- pausedUntil: 0,
143
- };
144
- // a batch a stop of the server cut short, or that waited for the usage limit: handed again once
145
- const cut = readJson(join(dir, "batch.json"));
146
- if (typeof cut?.text === "string" && cut.text.trim())
147
- r.pending.push(`(VisualProof stopped while you were answering what follows, or it waited for the usage limit: answer it now.)\n\n${cut.text}`);
148
- this.saveSession(r);
149
- this.runners.set(r.id, r);
150
- void this.loop(r).catch((e) => this.o.log(`agent ${r.id}: ${e instanceof Error ? e.message : String(e)}`)).finally(() => {
151
- if (this.runners.get(r.id) === r)
152
- this.runners.delete(r.id);
153
- });
154
- }
155
- /** Its token ended (revoked, expired): its turn stops, its loop ends, its folder goes. */
156
- ended(id) {
157
- const r = this.runners.get(id);
158
- if (r)
159
- this.halt(r);
160
- rmSync(join(this.o.root, id), { recursive: true, force: true });
161
- }
162
- /** A holder's Claude token was given, replaced, refused or removed: their agents start, or stop. */
163
- changed(who) {
164
- for (const rec of this.o.tokens.inForce()) {
165
- if (rec.runs !== "server" || !madeBy(rec, who))
164
+ }
165
+ for (const name of names) {
166
+ const kept = readJson(join(this.dir, name, "session.json"));
167
+ const channel = typeof kept?.channel === "string" ? kept.channel : null;
168
+ if (!channel || subOf(channel, this.id) !== name)
166
169
  continue;
167
- const r = this.runners.get(rec.id);
168
- if (this.o.claudeTokens.forMaker(rec)) {
169
- if (!r)
170
- this.start(rec);
171
- }
172
- else if (r) {
173
- // what it was to answer stays, for a token given anew to answer
174
- this.halt(r, true);
175
- this.o.talk.left(rec.id);
170
+ const s = this.session(channel, typeof kept.with === "string" ? kept.with : null);
171
+ if (typeof kept.session === "string" && /^[0-9a-f-]{36}$/.test(kept.session))
172
+ s.session = kept.session;
173
+ s.started = kept.started === true;
174
+ s.handed = typeof kept.handed === "number" ? kept.handed : 0;
175
+ const cut = readJson(join(s.dir, "batch.json"));
176
+ const items = Array.isArray(cut?.items) ? cut.items.filter((x) => x && typeof x.id === "number" && typeof x.text === "string") : [];
177
+ const dropped = items.filter((x) => x.again).length;
178
+ if (dropped)
179
+ this.o.log(` the server's agent: ${dropped} message${dropped === 1 ? "" : "s"} cut short by a stop twice, not handed again`);
180
+ s.pending = items.filter((x) => !x.again).map((x) => ({ id: x.id, text: x.text, again: true }));
181
+ if (s.pending.length) {
182
+ s.notes = ["(VisualProof stopped while you were answering what follows, or it waited for the usage limit or its token: answer it now.)"];
183
+ s.waiting = Date.now();
176
184
  }
185
+ this.saveSession(s);
186
+ this.saveBatch(s);
177
187
  }
188
+ this.pump();
178
189
  }
179
- /** Its maker's Stop: the turn running ends, and what it was answering with it. False where none
180
- * runs. */
181
- stopTurn(id) {
182
- const t = this.runners.get(id)?.turn;
183
- if (!t)
184
- return false;
185
- t.why = "stop";
186
- end(t.child);
187
- return true;
190
+ // ---------------------------------------------------------------- what is written to it
191
+ /** A message was written (server/talk.ts, onPosted): a person's in their channel with it, or one
192
+ * in the public channel that mentions it, goes in that conversation's next turn; a divider in a
193
+ * person's channel starts a new conversation there. */
194
+ posted(channel, m) {
195
+ if (this.closed)
196
+ return;
197
+ if (channel === PUBLIC) {
198
+ if (m.kind !== "person" || !m.to?.includes(this.id))
199
+ return;
200
+ this.add(this.session(PUBLIC, null), m);
201
+ return;
202
+ }
203
+ if (!isPersonal(channel) || !channel.startsWith(`${this.id}-`))
204
+ return;
205
+ if (m.kind === "person")
206
+ this.add(this.session(channel, m.from), m);
207
+ else if (m.kind === "divider")
208
+ this.renew(this.session(channel, m.from));
188
209
  }
189
- /** Whether `id` is listened for here now. */
190
- running(id) {
191
- return this.runners.has(id);
210
+ add(s, m) {
211
+ if (s.channel !== PUBLIC)
212
+ s.with = m.from;
213
+ s.pending.push({ id: m.id, text: said(m) });
214
+ s.waiting ??= Date.now();
215
+ this.saveBatch(s);
216
+ this.changed(s);
217
+ this.pump();
192
218
  }
193
- /** The server stops: every turn with it (each batch kept, to be handed again at the next start). */
194
- close() {
195
- this.closed = true;
196
- for (const r of this.runners.values())
197
- this.halt(r, true);
198
- }
199
- halt(r, keepBatch = false) {
200
- r.stop.abort();
201
- if (r.turn)
202
- end(r.turn.child);
203
- if (!keepBatch)
204
- rmSync(join(r.dir, "batch.json"), { force: true });
205
- this.runners.delete(r.id);
206
- }
207
- async loop(r) {
208
- const talk = this.o.talk;
209
- while (!r.stop.signal.aborted) {
210
- const rec = this.o.tokens.get(r.id);
211
- if (!rec || rec.runs !== "server")
212
- return;
213
- const claudeToken = this.o.claudeTokens.forMaker(rec);
214
- if (!claudeToken)
215
- return;
216
- const now = Date.now();
217
- const paused = r.pausedUntil > now;
218
- // with something to answer and no limit in the way, nothing to wait for but what is there
219
- const wait = r.pending.length && !paused ? 0 : paused ? Math.min(r.pausedUntil - now, LISTEN_MS) : LISTEN_MS;
220
- const got = await talk.wait(r.id, wait, { signal: r.stop.signal, session: r.session });
221
- if ("ended" in got || "gone" in got)
222
- return;
223
- this.take(r, got.messages);
224
- if (!r.pending.length || r.pausedUntil > Date.now())
225
- continue;
226
- await this.turn(r, rec, claudeToken);
219
+ /** A new conversation in a person's channel: a new session for it alone, and what came before
220
+ * gone from it — a turn running stops, its answer with it. */
221
+ renew(s) {
222
+ if (s.turn) {
223
+ s.turn.why = "new";
224
+ if (s.turn.child)
225
+ end(s.turn.child);
227
226
  }
227
+ s.session = randomUUID();
228
+ s.started = false;
229
+ s.batch = [];
230
+ s.pending = [];
231
+ s.notes = [];
232
+ s.waiting = null;
233
+ rmSync(join(s.dir, "batch.json"), { force: true });
234
+ this.saveSession(s);
235
+ this.changed(s);
228
236
  }
229
- /** What a wait handed over, into what the next turn says: a new conversation starts a new session
230
- * and drops what came before it; what came before (a first wait's) is context, needed only by a
231
- * session that has not had it — unless it holds mentions never handed, which may still ask
232
- * something; people's messages are to be answered. */
233
- take(r, messages) {
234
- for (const m of messages) {
235
- if (m.kind === "divider") {
236
- r.session = randomUUID();
237
- r.started = false;
238
- r.context = [];
239
- r.pending = [];
240
- rmSync(join(r.dir, "batch.json"), { force: true });
241
- this.saveSession(r);
242
- }
243
- else if (m.kind === "earlier") {
244
- if (m.missed)
245
- r.pending.push(m.text);
246
- else if (!r.started)
247
- r.context.push(m.text);
237
+ /** The conversation of `channel`, made where there is none yet. */
238
+ session(channel, who) {
239
+ let s = this.sessions.get(channel);
240
+ if (!s) {
241
+ const dir = join(this.dir, subOf(channel, this.id));
242
+ for (const d of [dir, join(dir, "work"), join(dir, "claude"), join(dir, "files")])
243
+ mkdirSync(d, { recursive: true, mode: 0o700 });
244
+ s = { channel, dir, with: who, session: randomUUID(), started: false, batch: [], pending: [], handed: 0, notes: [], waiting: null, turn: null, toldLimit: false, told: null, since: Date.now() };
245
+ this.sessions.set(channel, s);
246
+ this.saveSession(s);
247
+ }
248
+ return s;
249
+ }
250
+ // ---------------------------------------------------------------- turns
251
+ /** The conversations waiting their turn, oldest first. */
252
+ waiting() {
253
+ return [...this.sessions.values()].filter((s) => s.waiting !== null && !s.turn && s.pending.length).sort((a, b) => a.waiting - b.waiting);
254
+ }
255
+ /** Start what may start: the oldest waiting, while fewer than MAX_RUNNING run, the usage limit not
256
+ * in the way. A conversation the limit holds is told so, once. */
257
+ pump() {
258
+ if (this.closed || this.down)
259
+ return;
260
+ const now = Date.now();
261
+ if (this.pausedUntil > now) {
262
+ for (const s of this.waiting())
263
+ if (!s.toldLimit) {
264
+ s.toldLimit = true;
265
+ this.say(s, limitWords(this.pausedUntil));
266
+ }
267
+ if (!this.limitTimer) {
268
+ this.limitTimer = setTimeout(() => {
269
+ this.limitTimer = null;
270
+ for (const s of this.sessions.values())
271
+ s.toldLimit = false;
272
+ this.pump();
273
+ }, this.pausedUntil - now + 50);
274
+ this.limitTimer.unref?.();
248
275
  }
249
- else if (m.kind === "person")
250
- r.pending.push(said(m));
276
+ return;
277
+ }
278
+ const max = this.o.maxRunning ?? MAX_RUNNING;
279
+ for (const s of this.waiting()) {
280
+ if (this.turns.size >= max)
281
+ break;
282
+ void this.run(s).catch((e) => this.o.log(`the server's agent: ${e instanceof Error ? e.message : String(e)}`));
251
283
  }
252
284
  }
253
- async turn(r, rec, claudeToken) {
254
- const vpa = this.o.tokens.token(r.id);
285
+ /** One turn of a conversation: what it was handed, answered in its session; then the next. */
286
+ async run(s) {
287
+ const rec = this.o.tokens.get(this.id);
288
+ const vpa = this.o.tokens.token(this.id);
255
289
  const address = this.o.address();
256
- if (!vpa || !address)
290
+ if (!rec || !vpa || !address)
257
291
  return;
258
- const text = batchText(r, rec);
259
- writeFileSync(join(r.dir, "batch.json"), JSON.stringify({ text: [...r.pending].join("\n\n") }), { mode: 0o600 });
260
- this.prepare(r, rec, vpa.token, address);
261
- let out = await this.run(r, text, claudeToken);
262
- // a session Claude Code no longer has (its folder was cleared): a new one, once
263
- if (out.noSession && !r.stop.signal.aborted) {
264
- r.session = randomUUID();
265
- r.started = false;
266
- this.saveSession(r);
267
- out = await this.run(r, batchText(r, rec), claudeToken);
292
+ const turn = { id: randomUUID(), child: null, why: null, started: Date.now(), replied: false, doing: null, status: null };
293
+ s.batch = s.pending.splice(0);
294
+ s.handed = Math.max(s.handed, ...s.batch.map((x) => x.id));
295
+ s.waiting = null;
296
+ s.turn = turn;
297
+ this.turns.set(turn.id, s);
298
+ this.lastSeen = Date.now();
299
+ this.saveSession(s);
300
+ this.saveBatch(s);
301
+ this.changed(s);
302
+ try {
303
+ this.prepare(s, rec, vpa.token, address, turn.id);
304
+ let out = await this.spawn(s, turn, this.text(s, rec));
305
+ // a session Claude Code no longer has (its folder was cleared): a new one, once, told what
306
+ // came before in its conversation
307
+ if (out.noSession && !turn.why && !this.closed) {
308
+ s.session = randomUUID();
309
+ s.started = false;
310
+ this.saveSession(s);
311
+ out = await this.spawn(s, turn, this.text(s, rec));
312
+ }
313
+ this.after(s, rec, turn, out);
268
314
  }
269
- const why = r.turn?.why ?? null;
270
- r.turn = null;
271
- if (r.stop.signal.aborted)
315
+ finally {
316
+ this.turns.delete(turn.id);
317
+ if (s.turn === turn)
318
+ s.turn = null;
319
+ this.lastSeen = Date.now();
320
+ if (!this.closed) {
321
+ if (s.pending.length && s.waiting === null)
322
+ s.waiting = Date.now();
323
+ s.since = Date.now();
324
+ this.changed(s);
325
+ this.pump();
326
+ }
327
+ }
328
+ }
329
+ /** What a turn came to, said where it was asked: its answer, or why there is none. */
330
+ after(s, rec, turn, out) {
331
+ // the server stopped (the batch stays in batch.json, for the next start), or a new
332
+ // conversation began meanwhile (nothing of this one stays)
333
+ if (this.closed || turn.why === "new")
272
334
  return;
273
- const channel = this.o.talk.lastChannel(r.id);
274
- const say = (s) => this.post(r, rec, channel, s);
335
+ const say = (text) => this.say(s, text);
336
+ const keep = () => {
337
+ s.pending = [...s.batch, ...s.pending];
338
+ s.batch = [];
339
+ s.waiting = Date.now();
340
+ this.saveBatch(s);
341
+ };
275
342
  if (out.spawnError) {
276
- say(`I cannot run: Claude Code could not be started on the server (${out.spawnError}).`);
277
- return this.giveUp(r);
343
+ keep();
344
+ this.fail(`Claude Code could not be started on the server (${out.spawnError})`);
345
+ return say(`I cannot run: Claude Code could not be started on the server (${out.spawnError}). The server's operator can fix it and restart the server; I answer then.`);
278
346
  }
279
347
  if (out.refused) {
280
- say(`I cannot answer: Claude Code refused ${rec.by}'s token (expired, or revoked). ${rec.by} can give a new one in Share (AI agent), and I answer then.`);
281
- // the batch stays, for the new token to answer
282
- this.o.claudeTokens.refuse(claudeToken);
283
- return;
348
+ keep();
349
+ this.fail("Claude Code refused the server's Claude token (expired, or revoked)");
350
+ return say("I cannot answer: Claude Code refused this server's Claude token (expired, or revoked). The server's operator gives it a new one (--claude-oauth) and restarts the server; I answer what you wrote then.");
284
351
  }
285
352
  if (out.limit) {
286
- const at = out.limit.resetsAt ?? Date.now() + LIMIT_RETRY_MS;
287
- r.pausedUntil = at;
288
- say(`${rec.by}'s Claude usage limit is reached: I answer once it resets, ${new Date(at).toISOString().replace("T", " ").replace(/:\d\d(\.\d+)?Z$/, " UTC")}. What you write meanwhile waits.`);
289
- return;
353
+ keep();
354
+ this.pausedUntil = Math.max(this.pausedUntil, out.limit.resetsAt ?? Date.now() + LIMIT_RETRY_MS);
355
+ s.toldLimit = true;
356
+ return say(limitWords(this.pausedUntil));
290
357
  }
291
- r.started = true;
292
- this.saveSession(r);
293
- r.pending = [];
294
- r.context = [];
295
- rmSync(join(r.dir, "batch.json"), { force: true });
296
- if (why === "stop")
358
+ s.started = true;
359
+ s.batch = [];
360
+ s.notes = [];
361
+ this.saveSession(s);
362
+ this.saveBatch(s);
363
+ if (turn.why === "stop")
297
364
  return;
298
- if (why === "time")
299
- return void say(`I was stopped: my answer took longer than ${Math.round((this.o.turnMs ?? TURN_MS) / 60_000)} minutes.`);
365
+ if (turn.why === "time")
366
+ return say(`I was stopped: my answer took longer than ${Math.round((this.o.turnMs ?? TURN_MS) / 60_000)} minutes.`);
300
367
  const res = out.result;
301
368
  if (!res || res.is_error || out.exit !== 0) {
302
369
  const line = (res?.result ?? "").split("\n")[0].slice(0, 300) || `it exited with ${out.exit}`;
303
- return void say(`Claude Code failed on the server: ${line}`);
370
+ return say(`Claude Code failed on the server: ${line}`);
304
371
  }
305
372
  // the answer is the reply tool's; a turn that replied nothing says its last words instead
306
373
  const last = (res.result ?? "").trim();
307
- if (!out.replied && last)
374
+ if (!out.replied && !turn.replied && last)
308
375
  say(last);
309
376
  }
310
- /** The agent's folder, ready for a turn: the MCP server, its configuration and the ground rules,
311
- * written afresh (the server's address and version may have changed since). */
312
- prepare(r, rec, vpa, address) {
313
- const mcp = join(r.dir, "visualproof-mcp.mjs");
377
+ /** It cannot run: offline for everyone, until the operator fixes it and restarts the server. */
378
+ fail(why) {
379
+ if (this.down)
380
+ return;
381
+ this.down = why;
382
+ this.o.log(`the server's agent is offline: ${why}`);
383
+ this.o.talk.refresh(this.id);
384
+ for (const s of this.sessions.values())
385
+ this.changed(s);
386
+ }
387
+ /** What a turn hands Claude Code: a first line that is never a slash command, what came before
388
+ * where its session does not hold it, what is to be answered, and how to answer. */
389
+ text(s, rec) {
390
+ const n = s.batch.length;
391
+ const pub = s.channel === PUBLIC;
392
+ const from = pub ? "from the public channel, mentioning you" : `from ${s.with ?? "a person"}, in your private conversation with them`;
393
+ const head = `${n === 1 ? "A message" : `${n} messages, in order,`} ${from}:`;
394
+ const how = pub
395
+ ? "Answer with the reply tool: it goes to the public channel, which everyone with a name reads."
396
+ : `Answer with the reply tool: it goes back to this conversation, which ${s.with ?? "they"} alone ${s.with ? "reads" : "read"} (channel "public" writes in the public channel instead, which everyone reads: never repeat there what was said here).`;
397
+ return [
398
+ `VisualProof — ${head}`,
399
+ ...this.context(s),
400
+ ...s.notes,
401
+ ...s.batch.map((x) => x.text),
402
+ `${how} Move your own view to what you explain first (the view tool). You are ${rec.name}; then end your turn: the next messages come by themselves.`,
403
+ ].join("\n\n");
404
+ }
405
+ /** What came before in a person's conversation, for a session that does not hold it (a new one
406
+ * that replaced one lost): its channel since the last divider, before what is handed now. */
407
+ context(s) {
408
+ if (s.started || s.channel === PUBLIC)
409
+ return [];
410
+ const first = Math.min(...s.batch.map((x) => x.id).filter((id) => id > 0), Infinity);
411
+ const told = this.o.talk.conversation(s.channel).messages.filter((m) => m.id < first && m.kind !== "divider");
412
+ const e = earlierOf(told, true);
413
+ return e ? [e.text] : [];
414
+ }
415
+ /** The conversation's folder, ready for a turn: the MCP server, its configuration (with the turn
416
+ * it is) and the ground rules, written afresh (the server's address and version may have changed). */
417
+ prepare(s, rec, vpa, address, turn) {
418
+ const mcp = join(s.dir, "visualproof-mcp.mjs");
314
419
  writeFileSync(mcp, this.o.mcpServer(), { mode: 0o600 });
315
420
  const config = {
316
421
  mcpServers: {
@@ -318,51 +423,51 @@ export class Hosted {
318
423
  type: "stdio",
319
424
  command: this.o.node ?? process.execPath,
320
425
  args: [mcp],
321
- env: { VISUALPROOF_URL: address, VISUALPROOF_TOKEN: vpa, VISUALPROOF_FILES: join(r.dir, "files"), VISUALPROOF_WAIT_SECONDS: "50" },
426
+ env: { VISUALPROOF_URL: address, VISUALPROOF_TOKEN: vpa, VISUALPROOF_FILES: join(s.dir, "files"), VISUALPROOF_WAIT_SECONDS: "50", VISUALPROOF_TURN: turn },
322
427
  },
323
428
  },
324
429
  };
325
- writeFileSync(join(r.dir, "mcp.json"), JSON.stringify(config), { mode: 0o600 });
326
- writeFileSync(join(r.dir, "prompt.md"), hostedPrompt({ record: rec, project: this.o.project(), root: this.o.projectRoot(), files: join(r.dir, "files"), site: this.o.site, followed: this.o.followed?.() ?? null }), { mode: 0o600 });
430
+ writeFileSync(join(s.dir, "mcp.json"), JSON.stringify(config), { mode: 0o600 });
431
+ writeFileSync(join(s.dir, "prompt.md"), hostedPrompt({ record: rec, with: s.channel === PUBLIC ? null : (s.with ?? "a person"), project: this.o.project(), root: this.o.projectRoot(), files: join(s.dir, "files"), site: this.o.site, followed: this.o.followed?.() ?? null }), { mode: 0o600 });
327
432
  }
328
- /** One `claude -p` of the agent's session, `text` on stdin, read as stream-json. */
329
- run(r, text, claudeToken) {
433
+ /** One `claude -p` of the conversation's session, `text` on stdin, read as stream-json. */
434
+ spawn(s, turn, text) {
330
435
  const out = { exit: null, result: null, replied: false, refused: false, limit: null, noSession: false, spawnError: null };
331
436
  const args = [
332
437
  "-p", "--output-format", "stream-json", "--verbose",
333
- ...(r.started ? ["--resume", r.session] : ["--session-id", r.session]),
334
- "--strict-mcp-config", "--mcp-config", join(r.dir, "mcp.json"),
438
+ ...(s.started ? ["--resume", s.session] : ["--session-id", s.session]),
439
+ "--strict-mcp-config", "--mcp-config", join(s.dir, "mcp.json"),
335
440
  "--add-dir", this.o.projectRoot(),
336
441
  "--permission-mode", "bypassPermissions", "--permission-prompts", "none",
337
442
  "--disallowedTools", ...denied(this.o.site),
338
443
  "--max-turns", String(this.o.maxTurns ?? MAX_TURNS),
339
- "--append-system-prompt-file", join(r.dir, "prompt.md"),
444
+ "--append-system-prompt-file", join(s.dir, "prompt.md"),
340
445
  ];
341
446
  const env = {
342
447
  PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin",
343
448
  HOME: process.env.HOME ?? homedir(),
344
449
  LANG: process.env.LANG ?? "C.UTF-8",
345
450
  ...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}),
346
- CLAUDE_CONFIG_DIR: join(r.dir, "claude"),
347
- CLAUDE_CODE_OAUTH_TOKEN: claudeToken,
451
+ CLAUDE_CONFIG_DIR: join(s.dir, "claude"),
452
+ CLAUDE_CODE_OAUTH_TOKEN: this.o.claudeToken,
348
453
  ...QUIET,
349
454
  };
455
+ const started = s.started;
350
456
  return new Promise((done) => {
351
457
  let child;
352
458
  try {
353
- child = grouped(spawn(this.o.claude, args, { cwd: join(r.dir, "work"), env, stdio: ["pipe", "pipe", "pipe"], detached: DETACH }));
459
+ child = grouped(spawn(this.o.claude, args, { cwd: join(s.dir, "work"), env, stdio: ["pipe", "pipe", "pipe"], detached: DETACH }));
354
460
  }
355
461
  catch (e) {
356
462
  out.spawnError = e instanceof Error ? e.message : String(e);
357
463
  return done(out);
358
464
  }
359
- r.turn = { child, why: null };
360
- // a build may run long without a request of VisualProof's: the agent is seen, not offline
361
- const beat = setInterval(() => this.o.talk.seen(r.id, null), 60_000);
362
- beat.unref?.();
465
+ turn.child = child;
466
+ // stopped meanwhile (Stop, a new conversation, the server's stop) before it began
467
+ if (turn.why || this.closed)
468
+ end(child);
363
469
  const timer = setTimeout(() => {
364
- if (r.turn)
365
- r.turn.why = "time";
470
+ turn.why ??= "time";
366
471
  end(child);
367
472
  }, this.o.turnMs ?? TURN_MS);
368
473
  let buf = "";
@@ -388,7 +493,6 @@ export class Hosted {
388
493
  child.stdin.end(text);
389
494
  child.on("close", (code) => {
390
495
  clearTimeout(timer);
391
- clearInterval(beat);
392
496
  // what its shell left running goes with the turn
393
497
  if (DETACH && child.pid)
394
498
  try {
@@ -401,30 +505,152 @@ export class Hosted {
401
505
  read(buf, out);
402
506
  out.exit = code;
403
507
  // a resume of a session it does not have says so, before any turn
404
- if (r.started && !out.result?.result && /no conversation found/i.test(err))
508
+ if (started && !out.result?.result && /no conversation found/i.test(err))
405
509
  out.noSession = true;
406
- else if (r.started && out.result?.is_error && /no conversation found/i.test(out.result.result ?? ""))
510
+ else if (started && out.result?.is_error && /no conversation found/i.test(out.result.result ?? ""))
407
511
  out.noSession = true;
408
- if (code !== 0 && !out.result && err.trim() && !out.noSession)
409
- this.o.log(`agent ${r.id}: claude: ${err.trim().split("\n").slice(-3).join(" / ").split(claudeToken).join("<token>")}`);
512
+ if (code !== 0 && !out.result && err.trim() && !out.noSession && !turn.why)
513
+ this.o.log(`the server's agent: claude: ${err.trim().split("\n").slice(-3).join(" / ").split(this.o.claudeToken).join("<token>")}`);
410
514
  done(out);
411
515
  });
412
516
  });
413
517
  }
414
- /** The agent's message where it was asked: in its private channel, or the public one. */
415
- post(r, rec, channel, text) {
518
+ /** The agent's message in a conversation: a person's channel, or the public one. */
519
+ say(s, text) {
520
+ const rec = this.o.tokens.get(this.id);
521
+ if (!rec)
522
+ return;
416
523
  const mentions = mentioned(text, this.o.mentionable());
417
- this.o.talk.post(channel === "public" ? PUBLIC : r.id, { from: rec.name, kind: "agent", text, ...(mentions.length ? { mentions } : {}) }, r.id);
524
+ this.o.talk.post(s.channel, { from: rec.name, kind: "agent", text, ...(mentions.length ? { mentions } : {}) }, this.id);
525
+ }
526
+ // ---------------------------------------------------------------- people's controls
527
+ /** A person's Stop (POST /api/chat/stop), in their own conversation: its turn ends, and what it
528
+ * was answering with it. False where none runs. */
529
+ stopTurn(channel) {
530
+ const t = this.sessions.get(channel)?.turn;
531
+ if (!t || t.why)
532
+ return false;
533
+ t.why = "stop";
534
+ if (t.child)
535
+ end(t.child);
536
+ return true;
537
+ }
538
+ /** Its token ended (it is never revoked from the page; a test may): every turn stops, its folder goes. */
539
+ ended(id) {
540
+ if (id !== this.id)
541
+ return;
542
+ this.close();
543
+ rmSync(this.dir, { recursive: true, force: true });
418
544
  }
419
- /** The agent cannot run: offline, until it is started again. */
420
- giveUp(r) {
421
- this.halt(r, true);
422
- this.o.talk.left(r.id);
545
+ /** The server stops: every turn with it (each batch kept, to be handed again at the next start). */
546
+ close() {
547
+ this.closed = true;
548
+ if (this.limitTimer)
549
+ clearTimeout(this.limitTimer);
550
+ this.limitTimer = null;
551
+ for (const s of this.turns.values())
552
+ if (s.turn?.child)
553
+ end(s.turn.child);
554
+ }
555
+ // ---------------------------------------------------------------- the turns, for the agents' API
556
+ turnOf(turn) {
557
+ const s = turn ? this.turns.get(turn) : undefined;
558
+ return s ? { channel: s.channel, kind: s.channel === PUBLIC ? "public" : "private" } : null;
559
+ }
560
+ seen(turn, doing) {
561
+ const s = turn ? this.turns.get(turn) : undefined;
562
+ this.lastSeen = Date.now();
563
+ if (!s?.turn || doing === null || s.turn.doing === doing)
564
+ return;
565
+ s.turn.doing = doing;
566
+ this.changed(s);
567
+ }
568
+ setStatus(turn, text) {
569
+ const s = turn ? this.turns.get(turn) : undefined;
570
+ if (!s?.turn)
571
+ return null;
572
+ s.turn.status = text || null;
573
+ this.changed(s);
574
+ return this.sessionTalk(s.channel);
423
575
  }
424
- saveSession(r) {
425
- writeFileSync(join(r.dir, "session.json"), JSON.stringify({ session: r.session, started: r.started }), { mode: 0o600 });
576
+ replied(turn) {
577
+ const s = turn ? this.turns.get(turn) : undefined;
578
+ if (!s?.turn)
579
+ return;
580
+ s.turn.replied = true;
581
+ s.turn.doing = null;
582
+ s.turn.status = null;
583
+ this.changed(s);
584
+ }
585
+ // ---------------------------------------------------------------- states
586
+ /** Its state as a whole, as presence lists it: offline where it cannot run; thinking while a turn
587
+ * has not replied yet, working while turns run that did; listening otherwise. What it does is
588
+ * shown only of the public conversation's turn: a person's is theirs (`sessionTalk`). */
589
+ talk(now = Date.now()) {
590
+ const running = [...this.turns.values()].map((s) => s.turn).filter(Boolean);
591
+ const state = this.down ? "offline" : running.some((t) => !t.replied) ? "thinking" : running.length ? "working" : "listening";
592
+ if (state !== this.told.state)
593
+ this.told = { state, since: now };
594
+ const pub = this.sessions.get(PUBLIC);
595
+ const t = pub?.turn ?? null;
596
+ return {
597
+ state,
598
+ since: new Date(this.told.since).toISOString(),
599
+ doing: t && state !== "offline" ? t.doing : null,
600
+ status: t && state !== "offline" ? t.status : null,
601
+ read: 0,
602
+ readPublic: pub?.handed ?? 0,
603
+ lastSeen: running.length ? new Date(now).toISOString() : this.lastSeen === null ? null : new Date(this.lastSeen).toISOString(),
604
+ };
605
+ }
606
+ /** Its state in one conversation (a person's channel), as that person's tab shows it: offline where
607
+ * it cannot run; thinking while its turn runs (working once it replied), with what it does;
608
+ * waiting its turn (`queued`) while other conversations' turns take all there is; listening. */
609
+ sessionTalk(channel, now = Date.now()) {
610
+ const s = this.sessions.get(channel);
611
+ const t = s?.turn ?? null;
612
+ const base = { read: s?.handed ?? 0, readPublic: this.sessions.get(PUBLIC)?.handed ?? 0, lastSeen: this.lastSeen === null ? null : new Date(this.lastSeen).toISOString() };
613
+ const at = (ms) => new Date(ms).toISOString();
614
+ if (this.down)
615
+ return { state: "offline", since: at(s?.since ?? this.born), doing: null, status: null, ...base };
616
+ if (t)
617
+ return { state: t.replied ? "working" : "thinking", since: at(t.started), doing: t.doing, status: t.status, ...base, lastSeen: at(now) };
618
+ if (s && s.waiting !== null)
619
+ return { state: "thinking", since: at(s.waiting), doing: null, status: null, ...base, queued: true };
620
+ return { state: "listening", since: at(s?.since ?? this.born), doing: null, status: null, ...base };
621
+ }
622
+ /** A conversation's state may have changed: its person's pages are told where it did, and
623
+ * presence the agent's as a whole. */
624
+ changed(s) {
625
+ this.o.talk.refresh(this.id);
626
+ if (s.channel === PUBLIC)
627
+ return;
628
+ const t = this.sessionTalk(s.channel);
629
+ const was = s.told;
630
+ s.told = t;
631
+ if (!was || was.state !== t.state || was.since !== t.since || was.doing !== t.doing || was.status !== t.status || was.read !== t.read || was.queued !== t.queued)
632
+ this.onSession(s.channel, t);
633
+ }
634
+ saveSession(s) {
635
+ writeFileSync(join(s.dir, "session.json"), JSON.stringify({ channel: s.channel, session: s.session, started: s.started, with: s.with, handed: s.handed }), { mode: 0o600 });
636
+ }
637
+ /** What is not answered yet — the running turn's batch, what came since — kept for a start after a
638
+ * stop; nothing kept where everything is answered. */
639
+ saveBatch(s) {
640
+ const items = [...s.batch, ...s.pending];
641
+ if (!items.length)
642
+ return void rmSync(join(s.dir, "batch.json"), { force: true });
643
+ writeFileSync(join(s.dir, "batch.json"), JSON.stringify({ items }), { mode: 0o600 });
426
644
  }
427
645
  }
646
+ /** A conversation's folder: `public`, or a person's by their channel's digest. */
647
+ function subOf(channel, token) {
648
+ return channel === PUBLIC ? "public" : `p-${channel.slice(token.length + 1).replace(/[^0-9a-f]/g, "")}`;
649
+ }
650
+ /** The usage limit, in the agent's words, with when it resets. */
651
+ function limitWords(at) {
652
+ return `The Claude usage limit of this server's account is reached: I answer once it resets, ${new Date(at).toISOString().replace("T", " ").replace(/:\d\d(\.\d+)?Z$/, " UTC")}. What you write meanwhile waits.`;
653
+ }
428
654
  /** One line of Claude Code's stream-json, into what the turn came to. */
429
655
  function read(line, out) {
430
656
  if (!line.trim())
@@ -452,24 +678,13 @@ function read(line, out) {
452
678
  out.limit ??= { resetsAt: null };
453
679
  }
454
680
  }
455
- /** A person's message as the agent is handed it: as wait_for_message words it (mcp/visualproof-mcp.mjs). */
681
+ /** A person's message as the agent is handed it, as wait_for_message words it
682
+ * (mcp/visualproof-mcp.mjs): in a person's own conversation, or the public channel's mention. */
456
683
  function said(m) {
457
684
  const where = m.where?.inWords ? `, on ${m.where.inWords.replace(/\.$/, "")}` : "";
458
- const how = m.channel === "public" ? " in the public channel, mentioning you" : " to you, in your private channel";
685
+ const how = m.channel === "public" ? " in the public channel, mentioning you" : " to you, in your private conversation with them";
459
686
  return `${m.from} wrote${how}${where} (${m.channel === "public" ? "public " : ""}message ${m.id}, ${m.at}):\n${m.text}`;
460
687
  }
461
- /** What a turn hands Claude Code: a first line that is never a slash command, what came before,
462
- * what is to be answered, and how to answer. */
463
- function batchText(r, rec) {
464
- const n = r.pending.length;
465
- const head = n === 1 ? "A message from the page:" : `${n} messages from the page, in order:`;
466
- return [
467
- `VisualProof — ${head}`,
468
- ...r.context,
469
- ...r.pending,
470
- `Answer with the reply tool (it goes back where the last message came from; channel "public" writes in the public channel), after moving your own view to what you explain (the view tool). You are ${rec.name}; then end your turn: the next messages come by themselves.`,
471
- ].join("\n\n");
472
- }
473
688
  function readJson(file) {
474
689
  try {
475
690
  return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null;