visualproof 0.9.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.
- package/README.md +7 -3
- package/dist/mcp/visualproof-mcp.mjs +36 -6
- package/dist/server/agent.js +7 -1
- package/dist/server/agententry.js +29 -11
- package/dist/server/agenttalk.js +46 -4
- package/dist/server/app.js +6 -1
- package/dist/server/appagent.js +8 -2
- package/dist/server/appshare.js +27 -4
- package/dist/server/apptalk.js +56 -16
- package/dist/server/children.js +6 -2
- package/dist/server/doctor.js +8 -0
- package/dist/server/hosted.js +695 -0
- package/dist/server/live.js +56 -13
- package/dist/server/main.js +44 -0
- package/dist/server/mcptools.js +4 -2
- package/dist/server/options.js +38 -1
- package/dist/server/presence.js +2 -2
- package/dist/server/prompt.js +33 -0
- package/dist/server/serveragent.js +117 -0
- package/dist/server/talk.js +39 -3
- package/dist/server/tokens.js +17 -4
- package/dist/shared/collab.js +13 -3
- package/dist/web/bundle/app.js +266 -60
- package/dist/web/index.html +1 -0
- package/dist/web/style.css +33 -10
- package/docs/agent-api/mcp.md +4 -1
- package/docs/agent-api/talking.md +24 -0
- package/package.json +1 -1
|
@@ -0,0 +1,695 @@
|
|
|
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.
|
|
5
|
+
//
|
|
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.
|
|
14
|
+
//
|
|
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
|
|
27
|
+
// (`--permission-mode bypassPermissions`), on this machine as the server's user, the project's
|
|
28
|
+
// folder added (`--add-dir`): it reads the code directly, changes it and builds it with Lake when
|
|
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
|
|
39
|
+
// read (CLAUDE_CODE_DISABLE_CLAUDE_MDS: one in a folder above would be), no auto-memory, no bundled
|
|
40
|
+
// skills, no auto-update. The MCP server is the very file agents download (mcp/visualproof-mcp.mjs),
|
|
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
|
|
43
|
+
// (0600), the Claude token in the environment, the messages on stdin.
|
|
44
|
+
//
|
|
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.
|
|
51
|
+
//
|
|
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.
|
|
57
|
+
import { spawn } from "node:child_process";
|
|
58
|
+
import { randomUUID } from "node:crypto";
|
|
59
|
+
import { accessSync, constants as fsConstants, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
60
|
+
import { homedir } from "node:os";
|
|
61
|
+
import { delimiter, join } from "node:path";
|
|
62
|
+
import { DETACH, end, grouped } from "./children.js";
|
|
63
|
+
import { earlierOf, isPersonal, PUBLIC } from "./talk.js";
|
|
64
|
+
import { hostedPrompt } from "./prompt.js";
|
|
65
|
+
import { mentioned } from "../shared/mentions.js";
|
|
66
|
+
/** how long a turn may take before it is stopped */
|
|
67
|
+
export const TURN_MS = 60 * 60_000;
|
|
68
|
+
/** how many model turns (tool calls and answers) one batch may take */
|
|
69
|
+
export const MAX_TURNS = 100;
|
|
70
|
+
/** how many turns run at once, every conversation together (the owner's decision of 2026-11-08) */
|
|
71
|
+
export const MAX_RUNNING = 3;
|
|
72
|
+
/** a usage limit whose reset Claude Code did not say is tried again after this */
|
|
73
|
+
const LIMIT_RETRY_MS = 15 * 60_000;
|
|
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 `//`. */
|
|
77
|
+
export function denied(site) {
|
|
78
|
+
const under = (dir) => `/${dir.replace(/\/+$/, "")}/**`;
|
|
79
|
+
return [
|
|
80
|
+
...["Read", "Edit", "Write"].map((t) => `${t}(${under(site)})`),
|
|
81
|
+
"RemoteTrigger", "SendMessage", "ListAgents", "CronCreate", "CronDelete", "CronList", "ScheduleWakeup", "Workflow", "EnterWorktree", "ExitWorktree",
|
|
82
|
+
];
|
|
83
|
+
}
|
|
84
|
+
/** the environment Claude Code is run with, beside PATH, HOME, LANG, its folder and the token */
|
|
85
|
+
const QUIET = {
|
|
86
|
+
CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
|
|
87
|
+
CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1",
|
|
88
|
+
CLAUDE_CODE_DISABLE_BUNDLED_SKILLS: "1",
|
|
89
|
+
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
|
|
90
|
+
DISABLE_AUTOUPDATER: "1",
|
|
91
|
+
};
|
|
92
|
+
/** Claude Code's `claude`, where it is: on PATH, else where its installer puts it (~/.local/bin); null
|
|
93
|
+
* where there is none. */
|
|
94
|
+
export function findClaude(env = process.env) {
|
|
95
|
+
const dirs = [...(env.PATH ?? "").split(delimiter).filter(Boolean), join(env.HOME ?? homedir(), ".local", "bin")];
|
|
96
|
+
for (const d of dirs) {
|
|
97
|
+
const f = join(d, "claude");
|
|
98
|
+
try {
|
|
99
|
+
if (statSync(f).isFile()) {
|
|
100
|
+
accessSync(f, fsConstants.X_OK);
|
|
101
|
+
return f;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// not here
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
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 = () => { };
|
|
115
|
+
o;
|
|
116
|
+
dir;
|
|
117
|
+
sessions = new Map();
|
|
118
|
+
turns = new Map();
|
|
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();
|
|
129
|
+
constructor(o) {
|
|
130
|
+
this.o = o;
|
|
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 });
|
|
135
|
+
}
|
|
136
|
+
/** Whether it can run: Claude Code is here, and its token was not refused. */
|
|
137
|
+
get available() {
|
|
138
|
+
return this.down === null && !this.closed;
|
|
139
|
+
}
|
|
140
|
+
/** Why it cannot run, where it cannot. */
|
|
141
|
+
get offline() {
|
|
142
|
+
return this.down;
|
|
143
|
+
}
|
|
144
|
+
/** Whether a turn runs now (the server waits for none to restart into a patch). */
|
|
145
|
+
get busy() {
|
|
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;
|
|
151
|
+
}
|
|
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. */
|
|
157
|
+
restore() {
|
|
158
|
+
let names = [];
|
|
159
|
+
try {
|
|
160
|
+
names = readdirSync(this.dir);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return;
|
|
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)
|
|
169
|
+
continue;
|
|
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();
|
|
184
|
+
}
|
|
185
|
+
this.saveSession(s);
|
|
186
|
+
this.saveBatch(s);
|
|
187
|
+
}
|
|
188
|
+
this.pump();
|
|
189
|
+
}
|
|
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));
|
|
209
|
+
}
|
|
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();
|
|
218
|
+
}
|
|
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);
|
|
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);
|
|
236
|
+
}
|
|
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?.();
|
|
275
|
+
}
|
|
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)}`));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
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);
|
|
289
|
+
const address = this.o.address();
|
|
290
|
+
if (!rec || !vpa || !address)
|
|
291
|
+
return;
|
|
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);
|
|
314
|
+
}
|
|
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")
|
|
334
|
+
return;
|
|
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
|
+
};
|
|
342
|
+
if (out.spawnError) {
|
|
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.`);
|
|
346
|
+
}
|
|
347
|
+
if (out.refused) {
|
|
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.");
|
|
351
|
+
}
|
|
352
|
+
if (out.limit) {
|
|
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));
|
|
357
|
+
}
|
|
358
|
+
s.started = true;
|
|
359
|
+
s.batch = [];
|
|
360
|
+
s.notes = [];
|
|
361
|
+
this.saveSession(s);
|
|
362
|
+
this.saveBatch(s);
|
|
363
|
+
if (turn.why === "stop")
|
|
364
|
+
return;
|
|
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.`);
|
|
367
|
+
const res = out.result;
|
|
368
|
+
if (!res || res.is_error || out.exit !== 0) {
|
|
369
|
+
const line = (res?.result ?? "").split("\n")[0].slice(0, 300) || `it exited with ${out.exit}`;
|
|
370
|
+
return say(`Claude Code failed on the server: ${line}`);
|
|
371
|
+
}
|
|
372
|
+
// the answer is the reply tool's; a turn that replied nothing says its last words instead
|
|
373
|
+
const last = (res.result ?? "").trim();
|
|
374
|
+
if (!out.replied && !turn.replied && last)
|
|
375
|
+
say(last);
|
|
376
|
+
}
|
|
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");
|
|
419
|
+
writeFileSync(mcp, this.o.mcpServer(), { mode: 0o600 });
|
|
420
|
+
const config = {
|
|
421
|
+
mcpServers: {
|
|
422
|
+
visualproof: {
|
|
423
|
+
type: "stdio",
|
|
424
|
+
command: this.o.node ?? process.execPath,
|
|
425
|
+
args: [mcp],
|
|
426
|
+
env: { VISUALPROOF_URL: address, VISUALPROOF_TOKEN: vpa, VISUALPROOF_FILES: join(s.dir, "files"), VISUALPROOF_WAIT_SECONDS: "50", VISUALPROOF_TURN: turn },
|
|
427
|
+
},
|
|
428
|
+
},
|
|
429
|
+
};
|
|
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 });
|
|
432
|
+
}
|
|
433
|
+
/** One `claude -p` of the conversation's session, `text` on stdin, read as stream-json. */
|
|
434
|
+
spawn(s, turn, text) {
|
|
435
|
+
const out = { exit: null, result: null, replied: false, refused: false, limit: null, noSession: false, spawnError: null };
|
|
436
|
+
const args = [
|
|
437
|
+
"-p", "--output-format", "stream-json", "--verbose",
|
|
438
|
+
...(s.started ? ["--resume", s.session] : ["--session-id", s.session]),
|
|
439
|
+
"--strict-mcp-config", "--mcp-config", join(s.dir, "mcp.json"),
|
|
440
|
+
"--add-dir", this.o.projectRoot(),
|
|
441
|
+
"--permission-mode", "bypassPermissions", "--permission-prompts", "none",
|
|
442
|
+
"--disallowedTools", ...denied(this.o.site),
|
|
443
|
+
"--max-turns", String(this.o.maxTurns ?? MAX_TURNS),
|
|
444
|
+
"--append-system-prompt-file", join(s.dir, "prompt.md"),
|
|
445
|
+
];
|
|
446
|
+
const env = {
|
|
447
|
+
PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin",
|
|
448
|
+
HOME: process.env.HOME ?? homedir(),
|
|
449
|
+
LANG: process.env.LANG ?? "C.UTF-8",
|
|
450
|
+
...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}),
|
|
451
|
+
CLAUDE_CONFIG_DIR: join(s.dir, "claude"),
|
|
452
|
+
CLAUDE_CODE_OAUTH_TOKEN: this.o.claudeToken,
|
|
453
|
+
...QUIET,
|
|
454
|
+
};
|
|
455
|
+
const started = s.started;
|
|
456
|
+
return new Promise((done) => {
|
|
457
|
+
let child;
|
|
458
|
+
try {
|
|
459
|
+
child = grouped(spawn(this.o.claude, args, { cwd: join(s.dir, "work"), env, stdio: ["pipe", "pipe", "pipe"], detached: DETACH }));
|
|
460
|
+
}
|
|
461
|
+
catch (e) {
|
|
462
|
+
out.spawnError = e instanceof Error ? e.message : String(e);
|
|
463
|
+
return done(out);
|
|
464
|
+
}
|
|
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);
|
|
469
|
+
const timer = setTimeout(() => {
|
|
470
|
+
turn.why ??= "time";
|
|
471
|
+
end(child);
|
|
472
|
+
}, this.o.turnMs ?? TURN_MS);
|
|
473
|
+
let buf = "";
|
|
474
|
+
let err = "";
|
|
475
|
+
child.stdout.setEncoding("utf8");
|
|
476
|
+
child.stdout.on("data", (d) => {
|
|
477
|
+
buf += d;
|
|
478
|
+
for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) {
|
|
479
|
+
const line = buf.slice(0, i);
|
|
480
|
+
buf = buf.slice(i + 1);
|
|
481
|
+
read(line, out);
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
child.stderr.setEncoding("utf8");
|
|
485
|
+
child.stderr.on("data", (d) => {
|
|
486
|
+
if (err.length < 4000)
|
|
487
|
+
err += d;
|
|
488
|
+
});
|
|
489
|
+
child.on("error", (e) => {
|
|
490
|
+
out.spawnError = e.message;
|
|
491
|
+
});
|
|
492
|
+
child.stdin.on("error", () => { });
|
|
493
|
+
child.stdin.end(text);
|
|
494
|
+
child.on("close", (code) => {
|
|
495
|
+
clearTimeout(timer);
|
|
496
|
+
// what its shell left running goes with the turn
|
|
497
|
+
if (DETACH && child.pid)
|
|
498
|
+
try {
|
|
499
|
+
process.kill(-child.pid, "SIGTERM");
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
// nothing left
|
|
503
|
+
}
|
|
504
|
+
if (buf.trim())
|
|
505
|
+
read(buf, out);
|
|
506
|
+
out.exit = code;
|
|
507
|
+
// a resume of a session it does not have says so, before any turn
|
|
508
|
+
if (started && !out.result?.result && /no conversation found/i.test(err))
|
|
509
|
+
out.noSession = true;
|
|
510
|
+
else if (started && out.result?.is_error && /no conversation found/i.test(out.result.result ?? ""))
|
|
511
|
+
out.noSession = true;
|
|
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>")}`);
|
|
514
|
+
done(out);
|
|
515
|
+
});
|
|
516
|
+
});
|
|
517
|
+
}
|
|
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;
|
|
523
|
+
const mentions = mentioned(text, this.o.mentionable());
|
|
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 });
|
|
544
|
+
}
|
|
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);
|
|
575
|
+
}
|
|
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 });
|
|
644
|
+
}
|
|
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
|
+
}
|
|
654
|
+
/** One line of Claude Code's stream-json, into what the turn came to. */
|
|
655
|
+
function read(line, out) {
|
|
656
|
+
if (!line.trim())
|
|
657
|
+
return;
|
|
658
|
+
let e; // eslint-disable-line @typescript-eslint/no-explicit-any
|
|
659
|
+
try {
|
|
660
|
+
e = JSON.parse(line);
|
|
661
|
+
}
|
|
662
|
+
catch {
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
if (e.type === "assistant")
|
|
666
|
+
for (const c of e.message?.content ?? [])
|
|
667
|
+
if (c?.type === "tool_use" && c.name === "mcp__visualproof__reply")
|
|
668
|
+
out.replied = true;
|
|
669
|
+
if (e.type === "system" && e.subtype === "api_retry" && (e.error === "authentication_failed" || e.error_status === 401))
|
|
670
|
+
out.refused = true;
|
|
671
|
+
if (e.type === "rate_limit_event" && e.rate_limit_info?.status === "rejected")
|
|
672
|
+
out.limit = { resetsAt: typeof e.rate_limit_info.resetsAt === "number" ? e.rate_limit_info.resetsAt * 1000 : null };
|
|
673
|
+
if (e.type === "result") {
|
|
674
|
+
out.result = e;
|
|
675
|
+
if (e.is_error && e.api_error_status === 401)
|
|
676
|
+
out.refused = true;
|
|
677
|
+
if (e.is_error && (e.api_error_status === 429 || /hit your .*limit|usage limit/i.test(String(e.result ?? ""))))
|
|
678
|
+
out.limit ??= { resetsAt: null };
|
|
679
|
+
}
|
|
680
|
+
}
|
|
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. */
|
|
683
|
+
function said(m) {
|
|
684
|
+
const where = m.where?.inWords ? `, on ${m.where.inWords.replace(/\.$/, "")}` : "";
|
|
685
|
+
const how = m.channel === "public" ? " in the public channel, mentioning you" : " to you, in your private conversation with them";
|
|
686
|
+
return `${m.from} wrote${how}${where} (${m.channel === "public" ? "public " : ""}message ${m.id}, ${m.at}):\n${m.text}`;
|
|
687
|
+
}
|
|
688
|
+
function readJson(file) {
|
|
689
|
+
try {
|
|
690
|
+
return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null;
|
|
691
|
+
}
|
|
692
|
+
catch {
|
|
693
|
+
return null;
|
|
694
|
+
}
|
|
695
|
+
}
|