visualproof 0.8.2 → 0.10.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 +12 -9
- package/dist/assets/tips/tour-library.webp +0 -0
- package/dist/assets/tips/tour-source.webp +0 -0
- package/dist/assets/tips/tour.json +90 -90
- package/dist/extractor/Extract.lean +34 -11
- package/dist/mcp/visualproof-mcp.mjs +30 -5
- package/dist/server/agent.js +19 -7
- package/dist/server/agententry.js +13 -6
- package/dist/server/agentexport.js +2 -1
- package/dist/server/agentfollow.js +13 -3
- package/dist/server/agentlean.js +91 -1
- package/dist/server/agentnotes.js +6 -4
- package/dist/server/agentread.js +33 -1
- package/dist/server/app.js +7 -3
- package/dist/server/appagent.js +1 -1
- package/dist/server/appgraph.js +24 -0
- package/dist/server/appshare.js +119 -1
- package/dist/server/apptalk.js +26 -0
- package/dist/server/boardspots.js +1 -1
- package/dist/server/children.js +6 -2
- package/dist/server/claudetokens.js +113 -0
- package/dist/server/doctor.js +7 -0
- package/dist/server/goals.js +224 -0
- package/dist/server/hosted.js +480 -0
- package/dist/server/hover.js +281 -8
- package/dist/server/live.js +34 -2
- package/dist/server/main.js +30 -2
- package/dist/server/mcptools.js +15 -7
- package/dist/server/options.js +30 -2
- package/dist/server/presence.js +2 -2
- package/dist/server/prompt.js +25 -0
- package/dist/server/readonlygate.js +2 -1
- package/dist/server/reviewapi.js +5 -2
- package/dist/server/status.js +43 -5
- package/dist/server/tokens.js +7 -4
- package/dist/shared/build.js +9 -0
- package/dist/shared/collab.js +17 -2
- package/dist/shared/declfind.js +23 -3
- package/dist/shared/goals.js +309 -0
- package/dist/shared/hygiene.js +18 -0
- package/dist/shared/noteplace.js +45 -19
- package/dist/shared/scope.js +74 -45
- package/dist/shared/sharesnap.js +4 -2
- package/dist/web/bundle/app.js +2368 -591
- package/dist/web/index.html +2 -1
- package/dist/web/src/highlight.js +53 -3
- package/dist/web/style.css +151 -0
- package/docs/agent-api/README.md +1 -1
- package/docs/agent-api/mcp.md +4 -2
- package/docs/agent-api/notes.md +3 -2
- package/docs/agent-api/reading.md +38 -2
- package/docs/agent-api/talking.md +7 -0
- package/docs/agent-api/words.md +3 -2
- package/package.json +1 -1
|
@@ -0,0 +1,480 @@
|
|
|
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.
|
|
4
|
+
//
|
|
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.
|
|
13
|
+
//
|
|
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
|
|
16
|
+
// (`--permission-mode bypassPermissions`), on this machine as the server's user, the project's
|
|
17
|
+
// 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
|
|
28
|
+
// read (CLAUDE_CODE_DISABLE_CLAUDE_MDS: one in a folder above would be), no auto-memory, no bundled
|
|
29
|
+
// 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
|
|
32
|
+
// (0600), the Claude token in the environment, the messages on stdin.
|
|
33
|
+
//
|
|
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.
|
|
39
|
+
//
|
|
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.
|
|
44
|
+
import { spawn } from "node:child_process";
|
|
45
|
+
import { randomUUID } from "node:crypto";
|
|
46
|
+
import { accessSync, constants as fsConstants, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
47
|
+
import { homedir } from "node:os";
|
|
48
|
+
import { delimiter, join } from "node:path";
|
|
49
|
+
import { DETACH, end, grouped } from "./children.js";
|
|
50
|
+
import { PUBLIC } from "./talk.js";
|
|
51
|
+
import { hostedPrompt } from "./prompt.js";
|
|
52
|
+
import { mentioned } from "../shared/mentions.js";
|
|
53
|
+
import { madeBy } from "../shared/collab.js";
|
|
54
|
+
/** how long a turn may take before it is stopped */
|
|
55
|
+
export const TURN_MS = 60 * 60_000;
|
|
56
|
+
/** how many model turns (tool calls and answers) one batch may take */
|
|
57
|
+
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;
|
|
62
|
+
/** a usage limit whose reset Claude Code did not say is tried again after this */
|
|
63
|
+
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 `//`. */
|
|
67
|
+
export function denied(site) {
|
|
68
|
+
const under = (dir) => `/${dir.replace(/\/+$/, "")}/**`;
|
|
69
|
+
return [
|
|
70
|
+
...["Read", "Edit", "Write"].map((t) => `${t}(${under(site)})`),
|
|
71
|
+
"RemoteTrigger", "SendMessage", "ListAgents", "CronCreate", "CronDelete", "CronList", "ScheduleWakeup", "Workflow", "EnterWorktree", "ExitWorktree",
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
/** the environment Claude Code is run with, beside PATH, HOME, LANG, its folder and the token */
|
|
75
|
+
const QUIET = {
|
|
76
|
+
CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
|
|
77
|
+
CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1",
|
|
78
|
+
CLAUDE_CODE_DISABLE_BUNDLED_SKILLS: "1",
|
|
79
|
+
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
|
|
80
|
+
DISABLE_AUTOUPDATER: "1",
|
|
81
|
+
};
|
|
82
|
+
/** Claude Code's `claude`, where it is: on PATH, else where its installer puts it (~/.local/bin); null
|
|
83
|
+
* where there is none. */
|
|
84
|
+
export function findClaude(env = process.env) {
|
|
85
|
+
const dirs = [...(env.PATH ?? "").split(delimiter).filter(Boolean), join(env.HOME ?? homedir(), ".local", "bin")];
|
|
86
|
+
for (const d of dirs) {
|
|
87
|
+
const f = join(d, "claude");
|
|
88
|
+
try {
|
|
89
|
+
if (statSync(f).isFile()) {
|
|
90
|
+
accessSync(f, fsConstants.X_OK);
|
|
91
|
+
return f;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// not here
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
export class Hosted {
|
|
101
|
+
o;
|
|
102
|
+
runners = new Map();
|
|
103
|
+
closed = false;
|
|
104
|
+
constructor(o) {
|
|
105
|
+
this.o = o;
|
|
106
|
+
mkdirSync(o.root, { recursive: true, mode: 0o700 });
|
|
107
|
+
}
|
|
108
|
+
/** Whether agents can run here: Claude Code is on this machine. */
|
|
109
|
+
get available() {
|
|
110
|
+
return this.o.claude !== null;
|
|
111
|
+
}
|
|
112
|
+
/** Whether a turn runs now (the server waits for none to restart into a patch). */
|
|
113
|
+
get busy() {
|
|
114
|
+
return [...this.runners.values()].some((r) => r.turn !== null);
|
|
115
|
+
}
|
|
116
|
+
/** Every agent the server runs that is in force: listened for again (the server's start). */
|
|
117
|
+
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))
|
|
128
|
+
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))
|
|
166
|
+
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);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
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;
|
|
188
|
+
}
|
|
189
|
+
/** Whether `id` is listened for here now. */
|
|
190
|
+
running(id) {
|
|
191
|
+
return this.runners.has(id);
|
|
192
|
+
}
|
|
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);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
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);
|
|
248
|
+
}
|
|
249
|
+
else if (m.kind === "person")
|
|
250
|
+
r.pending.push(said(m));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
async turn(r, rec, claudeToken) {
|
|
254
|
+
const vpa = this.o.tokens.token(r.id);
|
|
255
|
+
const address = this.o.address();
|
|
256
|
+
if (!vpa || !address)
|
|
257
|
+
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);
|
|
268
|
+
}
|
|
269
|
+
const why = r.turn?.why ?? null;
|
|
270
|
+
r.turn = null;
|
|
271
|
+
if (r.stop.signal.aborted)
|
|
272
|
+
return;
|
|
273
|
+
const channel = this.o.talk.lastChannel(r.id);
|
|
274
|
+
const say = (s) => this.post(r, rec, channel, s);
|
|
275
|
+
if (out.spawnError) {
|
|
276
|
+
say(`I cannot run: Claude Code could not be started on the server (${out.spawnError}).`);
|
|
277
|
+
return this.giveUp(r);
|
|
278
|
+
}
|
|
279
|
+
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;
|
|
284
|
+
}
|
|
285
|
+
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;
|
|
290
|
+
}
|
|
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")
|
|
297
|
+
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.`);
|
|
300
|
+
const res = out.result;
|
|
301
|
+
if (!res || res.is_error || out.exit !== 0) {
|
|
302
|
+
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}`);
|
|
304
|
+
}
|
|
305
|
+
// the answer is the reply tool's; a turn that replied nothing says its last words instead
|
|
306
|
+
const last = (res.result ?? "").trim();
|
|
307
|
+
if (!out.replied && last)
|
|
308
|
+
say(last);
|
|
309
|
+
}
|
|
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");
|
|
314
|
+
writeFileSync(mcp, this.o.mcpServer(), { mode: 0o600 });
|
|
315
|
+
const config = {
|
|
316
|
+
mcpServers: {
|
|
317
|
+
visualproof: {
|
|
318
|
+
type: "stdio",
|
|
319
|
+
command: this.o.node ?? process.execPath,
|
|
320
|
+
args: [mcp],
|
|
321
|
+
env: { VISUALPROOF_URL: address, VISUALPROOF_TOKEN: vpa, VISUALPROOF_FILES: join(r.dir, "files"), VISUALPROOF_WAIT_SECONDS: "50" },
|
|
322
|
+
},
|
|
323
|
+
},
|
|
324
|
+
};
|
|
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 });
|
|
327
|
+
}
|
|
328
|
+
/** One `claude -p` of the agent's session, `text` on stdin, read as stream-json. */
|
|
329
|
+
run(r, text, claudeToken) {
|
|
330
|
+
const out = { exit: null, result: null, replied: false, refused: false, limit: null, noSession: false, spawnError: null };
|
|
331
|
+
const args = [
|
|
332
|
+
"-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"),
|
|
335
|
+
"--add-dir", this.o.projectRoot(),
|
|
336
|
+
"--permission-mode", "bypassPermissions", "--permission-prompts", "none",
|
|
337
|
+
"--disallowedTools", ...denied(this.o.site),
|
|
338
|
+
"--max-turns", String(this.o.maxTurns ?? MAX_TURNS),
|
|
339
|
+
"--append-system-prompt-file", join(r.dir, "prompt.md"),
|
|
340
|
+
];
|
|
341
|
+
const env = {
|
|
342
|
+
PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin",
|
|
343
|
+
HOME: process.env.HOME ?? homedir(),
|
|
344
|
+
LANG: process.env.LANG ?? "C.UTF-8",
|
|
345
|
+
...(process.env.TMPDIR ? { TMPDIR: process.env.TMPDIR } : {}),
|
|
346
|
+
CLAUDE_CONFIG_DIR: join(r.dir, "claude"),
|
|
347
|
+
CLAUDE_CODE_OAUTH_TOKEN: claudeToken,
|
|
348
|
+
...QUIET,
|
|
349
|
+
};
|
|
350
|
+
return new Promise((done) => {
|
|
351
|
+
let child;
|
|
352
|
+
try {
|
|
353
|
+
child = grouped(spawn(this.o.claude, args, { cwd: join(r.dir, "work"), env, stdio: ["pipe", "pipe", "pipe"], detached: DETACH }));
|
|
354
|
+
}
|
|
355
|
+
catch (e) {
|
|
356
|
+
out.spawnError = e instanceof Error ? e.message : String(e);
|
|
357
|
+
return done(out);
|
|
358
|
+
}
|
|
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?.();
|
|
363
|
+
const timer = setTimeout(() => {
|
|
364
|
+
if (r.turn)
|
|
365
|
+
r.turn.why = "time";
|
|
366
|
+
end(child);
|
|
367
|
+
}, this.o.turnMs ?? TURN_MS);
|
|
368
|
+
let buf = "";
|
|
369
|
+
let err = "";
|
|
370
|
+
child.stdout.setEncoding("utf8");
|
|
371
|
+
child.stdout.on("data", (d) => {
|
|
372
|
+
buf += d;
|
|
373
|
+
for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) {
|
|
374
|
+
const line = buf.slice(0, i);
|
|
375
|
+
buf = buf.slice(i + 1);
|
|
376
|
+
read(line, out);
|
|
377
|
+
}
|
|
378
|
+
});
|
|
379
|
+
child.stderr.setEncoding("utf8");
|
|
380
|
+
child.stderr.on("data", (d) => {
|
|
381
|
+
if (err.length < 4000)
|
|
382
|
+
err += d;
|
|
383
|
+
});
|
|
384
|
+
child.on("error", (e) => {
|
|
385
|
+
out.spawnError = e.message;
|
|
386
|
+
});
|
|
387
|
+
child.stdin.on("error", () => { });
|
|
388
|
+
child.stdin.end(text);
|
|
389
|
+
child.on("close", (code) => {
|
|
390
|
+
clearTimeout(timer);
|
|
391
|
+
clearInterval(beat);
|
|
392
|
+
// what its shell left running goes with the turn
|
|
393
|
+
if (DETACH && child.pid)
|
|
394
|
+
try {
|
|
395
|
+
process.kill(-child.pid, "SIGTERM");
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
// nothing left
|
|
399
|
+
}
|
|
400
|
+
if (buf.trim())
|
|
401
|
+
read(buf, out);
|
|
402
|
+
out.exit = code;
|
|
403
|
+
// 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))
|
|
405
|
+
out.noSession = true;
|
|
406
|
+
else if (r.started && out.result?.is_error && /no conversation found/i.test(out.result.result ?? ""))
|
|
407
|
+
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>")}`);
|
|
410
|
+
done(out);
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
/** The agent's message where it was asked: in its private channel, or the public one. */
|
|
415
|
+
post(r, rec, channel, text) {
|
|
416
|
+
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);
|
|
418
|
+
}
|
|
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);
|
|
423
|
+
}
|
|
424
|
+
saveSession(r) {
|
|
425
|
+
writeFileSync(join(r.dir, "session.json"), JSON.stringify({ session: r.session, started: r.started }), { mode: 0o600 });
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
/** One line of Claude Code's stream-json, into what the turn came to. */
|
|
429
|
+
function read(line, out) {
|
|
430
|
+
if (!line.trim())
|
|
431
|
+
return;
|
|
432
|
+
let e; // eslint-disable-line @typescript-eslint/no-explicit-any
|
|
433
|
+
try {
|
|
434
|
+
e = JSON.parse(line);
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (e.type === "assistant")
|
|
440
|
+
for (const c of e.message?.content ?? [])
|
|
441
|
+
if (c?.type === "tool_use" && c.name === "mcp__visualproof__reply")
|
|
442
|
+
out.replied = true;
|
|
443
|
+
if (e.type === "system" && e.subtype === "api_retry" && (e.error === "authentication_failed" || e.error_status === 401))
|
|
444
|
+
out.refused = true;
|
|
445
|
+
if (e.type === "rate_limit_event" && e.rate_limit_info?.status === "rejected")
|
|
446
|
+
out.limit = { resetsAt: typeof e.rate_limit_info.resetsAt === "number" ? e.rate_limit_info.resetsAt * 1000 : null };
|
|
447
|
+
if (e.type === "result") {
|
|
448
|
+
out.result = e;
|
|
449
|
+
if (e.is_error && e.api_error_status === 401)
|
|
450
|
+
out.refused = true;
|
|
451
|
+
if (e.is_error && (e.api_error_status === 429 || /hit your .*limit|usage limit/i.test(String(e.result ?? ""))))
|
|
452
|
+
out.limit ??= { resetsAt: null };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
/** A person's message as the agent is handed it: as wait_for_message words it (mcp/visualproof-mcp.mjs). */
|
|
456
|
+
function said(m) {
|
|
457
|
+
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";
|
|
459
|
+
return `${m.from} wrote${how}${where} (${m.channel === "public" ? "public " : ""}message ${m.id}, ${m.at}):\n${m.text}`;
|
|
460
|
+
}
|
|
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
|
+
function readJson(file) {
|
|
474
|
+
try {
|
|
475
|
+
return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null;
|
|
476
|
+
}
|
|
477
|
+
catch {
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
}
|