Repository navigation
Expand file tree
/
Copy pathagent.ts
More file actions
923 lines (855 loc) · 43.4 KB
/
Copy pathagent.ts
File metadata and controls
923 lines (855 loc) · 43.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
// catpad's agent: the tool definitions every backend shares, and the backends.
//
// claude Claude Code, headless (`claude -p`), one process per user
// message. It reaches the tools through this server's own MCP
// endpoint, /mcp.
// codex Codex, headless (`codex exec --json`), the same way: one
// process per message, the tools through /mcp.
// openai Any OpenAI-compatible chat completions server (Ollama, LM
// Studio, llama.cpp, vLLM). This file owns the loop and calls
// the tools in-process.
// functorial The Functorial Agent: a hosted OpenAI-compatible endpoint with
// an API key, driven by the same loop as `openai`.
// none No agent. The page shows `hint`.
//
// Which one runs, first match wins:
//
// 1. the one the user connected in "Connect your agent" (the page), kept
// in DATA/agent.json with its model, URL and key
// 2. CATPAD_AGENT: claude | codex | openai | functorial | none
// 3. openai when CATPAD_LLM_URL is set, else claude when `claude` is on
// PATH, else codex when `codex` is, else none
//
// CATPAD_AGENT_MODEL the model Claude Code or Codex uses, optional
// CATPAD_LLM_URL e.g. http://127.0.0.1:11434/v1
// CATPAD_LLM_MODEL the model name the server knows
// CATPAD_LLM_KEY sent as a bearer token, optional
// CATPAD_FUNCTORIAL_URL the Functorial Agent's endpoint (FUNCTORIAL_URL below)
// CATPAD_FUNCTORIAL_KEY its API key
import { spawn, type Subprocess } from "bun";
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
import { join } from "path";
import { DATA, ROOT } from "./paths";
import { machine } from "./web/machine.js";
export type AgentEvent =
| { kind: "user"; text: string }
| { kind: "start" }
| { kind: "text"; text: string }
| { kind: "tool"; id: string; name: string; summary: string }
| { kind: "tool-result"; id: string; ok: boolean; summary: string }
| { kind: "error"; text: string }
| { kind: "done" }
| { kind: "reset" };
export interface ToolResult { text: string; isError: boolean }
export type CallTool = (name: string, args: any) => Promise<ToolResult>;
export type BackendName = "claude" | "codex" | "openai" | "functorial" | "none";
export const BACKENDS: BackendName[] = ["claude", "codex", "openai", "functorial", "none"];
export interface AgentInfo { backend: BackendName; label: string; model?: string; hint?: string }
// What runs the agent, as the user picked it. `key` is a secret: it is kept in
// DATA/agent.json (readable by the user alone) and never sent to a page.
export interface AgentChoice { backend: BackendName; model?: string; url?: string; key?: string }
// ---------- the connection, kept ----------
// The Functorial Agent's endpoint. It speaks the OpenAI chat completions API
// with tool calls, and takes a Functorial API key as a bearer token. Editable
// in the dialog, for a staging endpoint or a self-hosted one.
export const FUNCTORIAL_URL = process.env.CATPAD_FUNCTORIAL_URL || "https://agent.functorial.inc/v1";
// Per backend what the user last set, so switching away and back keeps it.
interface Settings {
backend?: BackendName;
claude?: { model?: string };
codex?: { model?: string };
openai?: { url?: string; model?: string; key?: string };
functorial?: { url?: string; model?: string; key?: string };
}
const SETTINGS = join(DATA, "agent.json");
export function readSettings(): Settings {
try { return JSON.parse(readFileSync(SETTINGS, "utf8")); } catch { return {}; }
}
function writeSettings(s: Settings) {
mkdirSync(DATA, { recursive: true });
writeFileSync(SETTINGS + ".part", JSON.stringify(s, null, 2) + "\n", { mode: 0o600 });
chmodSync(SETTINGS + ".part", 0o600);
renameSync(SETTINGS + ".part", SETTINGS);
}
// A choice with what was saved for its backend filled in: an empty key in a
// choice means "the one I gave before", so the page never has to hold it.
function complete(c: AgentChoice): AgentChoice {
const s = readSettings();
const saved: { model?: string; url?: string; key?: string } = (c.backend !== "none" && (s as any)[c.backend]) || {};
const env = c.backend === "functorial" ? { url: process.env.CATPAD_FUNCTORIAL_URL, key: process.env.CATPAD_FUNCTORIAL_KEY }
: c.backend === "openai" ? { url: process.env.CATPAD_LLM_URL, model: process.env.CATPAD_LLM_MODEL, key: process.env.CATPAD_LLM_KEY }
: { model: process.env.CATPAD_AGENT_MODEL };
const pick = (k: "model" | "url" | "key") => (c[k]?.trim() || saved[k] || (env as any)[k] || undefined);
return { backend: c.backend, model: pick("model"), url: pick("url") ?? (c.backend === "functorial" ? FUNCTORIAL_URL : undefined), key: pick("key") };
}
// What the page may see of the saved connection: everything but the keys.
export function settingsForPage() {
const s = readSettings();
const strip = (x?: { url?: string; model?: string; key?: string }) => (x ? { url: x.url, model: x.model, hasKey: !!x.key } : undefined);
return {
backend: s.backend ?? null,
claude: s.claude, codex: s.codex,
openai: strip(s.openai) ?? (process.env.CATPAD_LLM_URL ? { url: process.env.CATPAD_LLM_URL, model: process.env.CATPAD_LLM_MODEL, hasKey: !!process.env.CATPAD_LLM_KEY } : undefined),
functorial: { ...strip(s.functorial), url: s.functorial?.url || FUNCTORIAL_URL, hasKey: !!(s.functorial?.key || process.env.CATPAD_FUNCTORIAL_KEY) },
};
}
// The choice catpad starts with (see the top of this file for the order).
function startingChoice(): AgentChoice {
const s = readSettings();
if (s.backend && BACKENDS.includes(s.backend)) return complete({ backend: s.backend });
const env = process.env.CATPAD_AGENT?.toLowerCase() as BackendName | undefined;
if (env && BACKENDS.includes(env)) return complete({ backend: env });
if (process.env.CATPAD_LLM_URL) return complete({ backend: "openai" });
if (Bun.which("claude")) return complete({ backend: "claude" });
if (Bun.which("codex")) return complete({ backend: "codex" });
return { backend: "none" };
}
// ---------- what is there to connect to ----------
// Runs a short command and gives back what it printed, or null when it could not run.
async function quick(cmd: string[], ms = 6000): Promise<{ code: number | null; out: string } | null> {
try {
const p = spawn(cmd, { stdout: "pipe", stderr: "pipe", stdin: "ignore" });
const timer = setTimeout(() => p.kill(), ms);
const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
clearTimeout(timer);
return { code: await p.exited, out: (out + "\n" + err).trim() };
} catch { return null; }
}
// The models an OpenAI-compatible server says it has, or why it could not be asked.
export async function listModels(url: string, key?: string, ms = 5000): Promise<{ models: string[] } | { error: string }> {
const base = url.replace(/\/+$/, "");
try {
const res = await fetch(`${base}/models`, { headers: key ? { authorization: `Bearer ${key}` } : {}, signal: AbortSignal.timeout(ms) });
if (res.status === 401 || res.status === 403) return { error: key ? "The server refused the key." : "The server wants an API key." };
if (!res.ok) return { error: `${base}/models answered HTTP ${res.status}.` };
const j: any = await res.json();
const models = (j.data ?? j.models ?? []).map((m: any) => String(m.id ?? m.name ?? m)).filter(Boolean);
return { models };
} catch (e: any) {
return { error: e?.name === "TimeoutError" ? `${base} did not answer.` : `Could not reach ${base}: ${e?.message ?? e}` };
}
}
// The usual ports of the local model servers people run.
const LOCAL_SERVERS = [
{ name: "Ollama", port: 11434 },
{ name: "LM Studio", port: 1234 },
{ name: "llama.cpp", port: 8080 },
{ name: "vLLM", port: 8000 },
{ name: "Jan", port: 1337 },
];
export interface Probe {
claude: { installed: boolean; version?: string; signedIn: boolean | null; account?: string; install: string; signIn: string };
codex: { installed: boolean; version?: string; signedIn: boolean | null; account?: string; install: string; signIn: string };
local: { name: string; url: string; models: string[] }[];
}
// What can run the agent on this machine, as the dialog shows it.
export async function probeAgents(): Promise<Probe> {
const claudeBin = Bun.which("claude"), codexBin = Bun.which("codex");
const [cv, cs, xv, xs, ...local] = await Promise.all([
claudeBin ? quick([claudeBin, "--version"]) : null,
claudeBin ? quick([claudeBin, "auth", "status"]) : null,
codexBin ? quick([codexBin, "--version"]) : null,
codexBin ? quick([codexBin, "login", "status"]) : null,
...LOCAL_SERVERS.map(async (s) => {
const url = `http://127.0.0.1:${s.port}/v1`;
const r = await listModels(url, undefined, 800);
return "models" in r ? { name: s.name, url, models: r.models } : null;
}),
]);
let claudeAuth: any = null;
try { claudeAuth = cs ? JSON.parse(cs.out.slice(cs.out.indexOf("{"))) : null; } catch {}
return {
claude: {
installed: !!claudeBin,
version: cv?.out.split(/\s/)[0],
signedIn: claudeAuth ? !!claudeAuth.loggedIn : null,
account: claudeAuth?.authMethod,
install: "npm install -g @anthropic-ai/claude-code",
signIn: "claude auth login",
},
codex: {
installed: !!codexBin,
version: xv?.out.match(/\d+\.\d+\.\d+\S*/)?.[0],
signedIn: xs ? xs.code === 0 : null,
// "Logged in using ChatGPT" → "ChatGPT"
account: xs?.code === 0 ? xs.out.split("\n")[0].replace(/^logged in (using|with)\s*/i, "") || undefined : undefined,
install: "npm install -g @openai/codex",
signIn: "codex login",
},
local: local.filter((x): x is { name: string; url: string; models: string[] } => !!x),
};
}
// Whether a choice would work, without making it. `models` is what the
// server offers, for the page to choose from.
export async function testChoice(given: AgentChoice): Promise<{ ok: boolean; text: string; models?: string[] }> {
const c = complete(given);
if (c.backend === "none") return { ok: true, text: "No agent: the notes, the Lean and the diagrams work, and you write the Lean yourself." };
if (c.backend === "claude" || c.backend === "codex") {
const p = (await probeAgents())[c.backend];
const name = c.backend === "claude" ? "Claude Code" : "Codex";
if (!p.installed) return { ok: false, text: `${name} is not installed. In a terminal: ${p.install}` };
if (p.signedIn === false) return { ok: false, text: `${name} is installed but not signed in. In a terminal: ${p.signIn}` };
return { ok: true, text: `${name} ${p.version ?? ""} is ready${p.account ? ` (${p.account})` : ""}.`.replace(" ", " ") };
}
if (!c.url) return { ok: false, text: "Give the server's URL, for example http://127.0.0.1:11434/v1." };
if (c.backend === "functorial" && !c.key) return { ok: false, text: "The Functorial Agent needs your Functorial API key." };
const r = await listModels(c.url, c.key);
if ("error" in r) return { ok: false, text: r.error };
if (c.model && r.models.length && !r.models.includes(c.model)) return { ok: false, text: `The server has no model named ${c.model}.`, models: r.models };
const model = c.model || r.models[0];
return { ok: true, text: model ? `Connected to ${c.url}: ${model}${r.models.length > 1 ? ` (and ${r.models.length - 1} more)` : ""}.` : `Reached ${c.url}. Pick a model.`, models: r.models };
}
export interface Selection { from: "notes" | "lean"; text: string }
// ---------- tools ----------
// One definition, used by MCP (`inputSchema`) and by the OpenAI loop (`parameters`).
export const TOOLS: { name: string; description: string; inputSchema: any }[] = [
{
name: "read_pad",
description:
E870
"Read the whole pad: the user's notes, the Lean buffer with line numbers (1-based, as in the editor's gutter), " +
"Lean's messages, and a summary of every diagram (items, terms, types, whether each typechecked, TeX render errors). " +
"Waits for a check in flight. Call it at the start of every turn and whenever you are unsure what the buffer holds.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "write_lean",
description:
"Replace the whole Lean buffer with `code`, check it, and return Lean's report (messages and diagrams). " +
"Do not add imports: the buffer is already checked on top of `import Mathlib` and the diagram prelude. " +
"Fails if the user edited the buffer since you last read it; then call read_pad and try again. " +
"Prefer edit_lean for local changes, so the user's own edits elsewhere survive.",
inputSchema: {
type: "object",
properties: { code: { type: "string", description: "The complete new buffer." } },
required: ["code"],
additionalProperties: false,
},
},
{
name: "edit_lean",
description:
"Replace an exact substring of the Lean buffer, check, and return Lean's report. `old` must occur exactly once " +
"unless replace_all is true; include enough surrounding text to make it unique. Whitespace and indentation must match exactly. " +
"An empty `new` deletes `old`.",
inputSchema: {
type: "object",
properties: {
old: { type: "string", description: "The exact text to replace." },
new: { type: "string", description: "The text to put in its place." },
replace_all: { type: "boolean", description: "Replace every occurrence. Default false." },
},
required: ["old", "new"],
additionalProperties: false,
},
},
{
name: "goal_at",
description:
"The tactic goal(s) at a position in the buffer, from the Lean language server. `line` is 1-based (the editor's gutter), " +
"`column` is 0-based. Put the position inside a `by` block, e.g. at the start of a tactic line.",
inputSchema: {
type: "object",
properties: { line: { type: "integer", minimum: 1 }, column: { type: "integer", minimum: 0 } },
required: ["line", "column"],
additionalProperties: false,
},
},
{
name: "hover_at",
description:
"What the Lean language server shows on hover at a position: the type of the term there and its docstring. " +
"`line` is 1-based (the editor's gutter), `column` is 0-based.",
inputSchema: {
type: "object",
properties: { line: { type: "integer", minimum: 1 }, column: { type: "integer", minimum: 0 } },
required: ["line", "column"],
additionalProperties: false,
},
},
];
export const TOOL_NAMES = new Set(TOOLS.map((t) => t.name));
const clip = (s: string, n: number) => {
const " ").trim();
return one.length > n ? one.slice(0, n - 1) + "…" : one;
};
// One short line for the chat log: what a tool call is about to do.
export function summarizeCall(name: string, args: any): string {
args ??= {};
switch (name) {
case "read_pad": return "read the pad";
case "write_lean": {
const code = String(args.code ?? "");
return `replace the buffer (${code.split("\n").length} lines)`;
}
case "edit_lean": {
const old = String(args.old ?? ""), nu = String(args.new ?? "");
const verb = nu === "" ? "delete" : "replace";
return `${verb} "${clip(old, 48)}"${nu === "" ? "" : ` with "${clip(nu, 48)}"`}${args.replace_all ? " (all)" : ""}`;
}
case "goal_at": return `goal at ${args.line}:${args.column}`;
case "hover_at": return `hover at ${args.line}:${args.column}`;
default: return name;
}
}
// A tool's text starts with a one-line headline; that is the result's summary.
export function summarizeResult(text: string): string {
return clip(text.split("\n").find((l) => l.trim()) ?? "", 140);
}
// A request the server fills in and sends on the user's behalf: agent/<name>.md,
// with {{placeholders}}. Read each time, so editing the file changes the next request.
export function readTemplate(name: string): string {
try {
return readFileSync(join(ROOT, "agent", `${name}.md`), "utf8");
} catch {
return "The diagram \"{{title}}\" (lines {{from}}-{{to}}) has items that do not check yet:\n{{items}}\n\nMake them check by editing the Lean and the terms they are bound to. Keep every item, its name and its position.";
}
}
export function readPrompt(): string {
try {
return readFileSync(join(ROOT, "agent/prompt.md"), "utf8");
} catch {
return "You are catpad's assistant. Use the tools to read and edit the Lean buffer.";
}
}
// ---------- the agent ----------
type Emit = (ev: AgentEvent) => void;
interface Backend {
info: AgentInfo;
// Runs one user turn to the end, emitting text and tool events. Throws on failure.
run(message: string, emit: Emit, signal: AbortSignal): Promise<void>;
reset(): void;
// What it takes to have this conversation again exactly as it is now, as
// JSON, or null when there is no conversation. `load` takes one back and
// returns whether the backend can go on from it. `rewind` says the
// conversation may have gone on past that state since (the user went back
// in the history), so the backend must not pick up what came after.
save(): unknown;
load(state: unknown, rewind: boolean): boolean;
}
export interface AgentOptions {
port: number;
cacheDir: string;
call: CallTool;
// The compact snapshot that prefixes every user turn.
snapshot: (selection: Selection | null) => string;
broadcast: (ev: AgentEvent) => void;
onTurnEnd?: () => void;
// After a turn's `done` is in the log: the conversation is whole again.
onIdle?: () => void;
}
// A restored conversation, as text for a backend that never had it. Tool
// results are not in the log, only their one-line summaries.
function transcript(log: AgentEvent[], max = 24000): string | null {
const out: string[] = [];
for (const ev of log) {
if (ev.kind === "user") out.push(`User: ${ev.text}`);
else if (ev.kind === "text") out.push(`You: ${ev.text}`);
else if (ev.kind === "tool") out.push(`(you called ${ev.name} ${ev.summary})`);
else if (ev.kind === "error") out.push(`(error: ${ev.text})`);
}
if (!out.length) return null;
const all = out.join("\n\n");
const body = all.length > max ? "… (the beginning is cut)\n" + all.slice(all.length - max) : all;
return `<earlier-conversation>\nThis conversation was restored from the pad's history. It is what you and the user said up to the point the pad has been put back to, and nothing after it. You no longer have your tool results from it: read the pad before you edit.\n\n${body}\n</earlier-conversation>`;
}
export class Agent {
info: AgentInfo;
log: AgentEvent[] = [];
private backend: Backend | null;
private ctl: AbortController | null = null;
// A turn: idle → running → idle, by way of `stopping` when the user stops
// it. Only an idle agent takes a message, and the pad commits only then.
private turn = machine("turn", "idle", {
idle: { SEND: "running" },
running: { STOP: "stopping", END: "idle" },
stopping: { END: "idle" },
});
get busy(): boolean { return !this.turn.is("idle"); }
// After a restore the backend has to pick the conversation up where the
// restored log ends. `exact`: it was given its own state of that moment and
// goes on from there. `primer`: it has no such state (or `exact` failed), so
// it starts afresh and the log goes in front of the next message as text.
// Either way it knows the restored conversation and nothing after it.
private exact = false;
private primer: string | null = null;
constructor(private o: AgentOptions) {
const made = makeBackend(startingChoice(), o);
this.backend = "backend" in made ? made.backend : null;
this.info = this.backend?.info ?? noneInfo("why" in made ? made.why : undefined);
}
// Connects another backend, from the dialog. The conversation stays: the new
// backend is told it as text with the next message, as after a restore. The
// choice is kept for the next start. Returns why not, or null.
connect(given: AgentChoice): string | null {
if (this.busy) return "The agent is working. Stop it first, or wait.";
const choice = complete(given);
const made = makeBackend(choice, this.o);
if ("why" in made && choice.backend !== "none") return made.why;
const s = readSettings();
s.backend = choice.backend;
if (choice.backend === "claude" || choice.backend === "codex") s[choice.backend] = { model: choice.model };
if (choice.backend === "openai" || choice.backend === "functorial") s[choice.backend] = { url: choice.url, model: choice.model, key: choice.key };
writeSettings(s);
this.backend?.reset();
this.backend = "backend" in made ? made.backend : null;
this.info = this.backend?.info ?? noneInfo("No agent is connected. Pick one in AI → Connect Your Agent.");
this.exact = false;
this.primer = transcript(this.log);
return null;
}
private emit = (ev: AgentEvent) => {
// The log is what a reloaded page redraws, so consecutive text deltas are kept as one.
const last = this.log[this.log.length - 1];
if (ev.kind === "text" && last?.kind === "text") this.log[this.log.length - 1] = { kind: "text", text: last.text + ev.text };
else this.log.push({ ...ev });
if (this.log.length > 2000) this.log.splice(0, this.log.length - 2000);
this.o.broadcast(ev);
};
// Returns an error to give the sender alone, or null when the turn started.
// `shown` is what the conversation shows for the message, when the message
// itself is a long request catpad wrote on the user's behalf.
send(text: string, sel
2360
ection: Selection | null, shown?: string): string | null {
if (!this.backend) return this.info.hint ?? "No agent is configured.";
if (this.busy) return "The agent is still working on the last message. Stop it first, or wait.";
if (!text.trim()) return "Empty message.";
this.turn.send("SEND");
const ctl = (this.ctl = new AbortController());
this.emit({ kind: "user", text: shown ?? text });
this.emit({ kind: "start" });
// The log up to this turn, for the fallback below.
const before = this.log.slice(0, -2);
const turn = `${this.o.snapshot(selection)}\n\n${text}`;
const message = this.primer ? `${this.primer}\n\n${turn}` : turn;
const exact = this.exact;
this.primer = null;
this.exact = false;
const backend = this.backend;
(async () => {
let said = 0;
const emit: Emit = (ev) => { said++; this.emit(ev); };
try {
try {
await backend.run(message, emit, ctl.signal);
} catch (e) {
// The backend could not go on from its restored state (Claude Code
// deletes old sessions, for one). Start afresh from the text instead.
if (!exact || said || ctl.signal.aborted) throw e;
backend.reset();
const primer = transcript(before);
await backend.run(primer ? `${primer}\n\n${turn}` : turn, emit, ctl.signal);
}
} catch (e: any) {
if (!ctl.signal.aborted) this.emit({ kind: "error", text: String(e?.message ?? e) });
}
if (ctl.signal.aborted) this.emit({ kind: "error", text: "Stopped." });
this.ctl = null;
this.turn.send("END");
try { this.o.onTurnEnd?.(); } catch {}
this.emit({ kind: "done" });
try { this.o.onIdle?.(); } catch {}
})();
return null;
}
// The backend's state, for a commit: see `restore`.
state(): unknown {
const data = this.backend?.save();
return data == null ? null : { backend: this.info.backend, data };
}
// Puts back a conversation from the pad's history: the log the pages show,
// and the context the backend works from. `state` is what `state()` gave
// when the commit was made. With it the backend goes on from exactly that
// moment: what was said later is not in its context. Without it (another
// backend, an old commit) it starts afresh and is told the log as text with
// the next message. Nothing is broadcast: the caller tells the pages.
restore(log: AgentEvent[], state?: any, rewind = true) {
this.stop();
this.backend?.reset();
this.log = log.map((ev) => ({ ...ev }));
this.exact = !!this.backend && state?.backend === this.info.backend && this.backend.load(state.data, rewind);
this.primer = this.exact ? null : transcript(this.log);
}
stop() { if (this.turn.send("STOP")) this.ctl?.abort(); }
reset() {
this.stop();
this.backend?.reset();
this.primer = null;
this.exact = false;
this.log = [];
this.emit({ kind: "reset" });
this.log = [];
}
}
function noneInfo(hint?: string): AgentInfo {
return {
backend: "none",
label: "No agent",
hint: hint ?? "No agent is connected. Connect Claude Code, Codex, a local model or the Functorial Agent: AI → Connect Your Agent.",
};
}
// The backend a choice describes, or why it cannot run.
function makeBackend(c: AgentChoice, o: AgentOptions): { backend: Backend } | { why: string } {
switch (c.backend) {
case "claude": {
const bin = Bun.which("claude");
return bin ? { backend: new ClaudeBackend(bin, o, c.model) } : { why: "Claude Code is not installed, or not on the PATH catpad sees." };
}
case "codex": {
const bin = Bun.which("codex");
return bin ? { backend: new CodexBackend(bin, o, c.model) } : { why: "Codex is not installed, or not on the PATH catpad sees." };
}
case "openai":
case "functorial":
if (!c.url) return { why: "The model server's URL is missing." };
if (c.backend === "functorial" && !c.key) return { why: "The Functorial Agent needs an API key." };
return { backend: new OpenAIBackend(o, { kind: c.backend, url: c.url, model: c.model, key: c.key }) };
default:
return { why: "No agent is connected. Pick one in AI → Connect Your Agent." };
}
}
// ---------- claude ----------
// Variables Claude Code sets for its own child processes. When catpad itself
// runs inside a Claude Code session they must not reach the headless agent,
// or it takes itself for a subagent of that session.
const INHERITED = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_EFFORT|CLAUDE_CODE_(ENTRYPOINT|SESSION_ID|CHILD_SESSION|CHILD_NOTES_DIR|SESSION_ATTENDED|EXECPATH|MESSAGING_SOCKET|MESSAGING_TOKEN|SSE_PORT))$/;
class ClaudeBackend implements Backend {
info: AgentInfo;
private session: string | null = null;
// The last entry of the session that this conversation has: the message the next turn follows.
private last: string | null = null;
// Set by `load`: the session may go on past `last` (the user went back in
// the history), so the next turn resumes it at `last`, in a copy of its own.
private rewind = false;
private cwd: string;
constructor(private bin: string, private o: AgentOptions, private model?: string) {
this.info = { backend: "claude", label: this.model ? `Claude Code (${this.model})` : "Claude Code", model: this.model };
this.cwd = join(o.cacheDir, "agent");
mkdirSync(this.cwd, { recursive: true });
}
reset() { this.session = null; this.last = null; this.rewind = false; }
save() { return this.session && this.last ? { session: this.session, at: this.last } : null; }
// Claude Code can resume a session at any message of it, so a rewind is exact too.
load(s: any, _rewind: boolean) {
if (typeof s?.session !== "string" || typeof s?.at !== "string") return false;
this.session = s.session;
this.last = s.at;
this.rewind = true;
return true;
}
args(): string[] {
// `client=catpad-agent` tells the endpoint not to send the prompt again as
// MCP instructions: it is already the system prompt.
const mcp = { mcpServers: { catpad: { type: "http", url: `http://127.0.0.1:${this.o.port}/mcp?client=catpad-agent` } } };
const a = [
this.bin, "-p",
"--output-format", "stream-json", "--verbose", "--include-partial-messages",
"--system-prompt", readPrompt(),
// No built-in tools (no shell, no file access): only catpad's.
"--tools", "",
"--mcp-config", JSON.stringify(mcp), "--strict-mcp-config",
"--allowedTools", TOOLS.map((t) => `mcp__catpad__${t.name}`).join(","),
// Allowed tools run without asking; anything else is refused, never prompted for.
"--permission-mode", "dontAsk",
// No user, project or local settings: the user's hooks, plugins and permission rules stay out.
"--setting-sources", "",
"--disable-slash-commands",
];
if (this.session) a.push("--resume", this.session);
// Only the session up to and including `last`, as a new session: the
// original keeps its later turns, for the commits that still point at them.
if (this.session && this.rewind && this.last) a.push("--resume-session-at", this.last, "--fork-session");
if (this.model) a.push("--model", this.model);
return a;
}
async run(message: string, emit: Emit, signal: AbortSignal) {
const env: Record<string, string> = {};
for (const [k, v] of Object.entries(process.env)) if (v != null && !INHERITED.test(k)) env[k] = v;
// The user's CLAUDE.md files and auto-memory are about their own projects, not
// this pad. (--setting-sources "" keeps out settings and hooks, but not these.)
env.CLAUDE_CODE_DISABLE_CLAUDE_MDS = "1";
env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = "1";
const proc = spawn(this.args(), { cwd: this.cwd, env, stdin: "pipe", stdout: "pipe", stderr: "pipe" });
const kill = () => { try { proc.kill("SIGTERM"); } catch {} };
signal.addEventListener("abort", kill, { once: true });
proc.stdin.write(message);
proc.stdin.end();
const stderr = new Response(proc.stderr).text();
let result: any = null;
let sawText = false;
const tools = new Map<string, string>(); // tool_use id -> name
try {
let buf = "";
const dec = new TextDecoder();
for await (const chunk of proc.stdout) {
buf += dec.decode(chunk, { stream: true });
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line) continue;
let m: any;
try { m = JSON.parse(line); } catch { continue; }
if (process.env.CATPAD_DEBUG && process.env.CATPAD_DEBUG !== "0") console.log("claude:", line.slice(0, 300));
if (m.session_id && m.session_id !== this.session) { this.session = m.session_id; this.rewind = false; }
if ((m.type === "assistant" || m.type === "user") && typeof m.uuid === "string") { this.last = m.uuid; this.rewind = false; }
if (m.type === "system" && m.subtype === "init") {
const s = (m.mcp_servers ?? []).find((x: any) => x.name === "catpad");
if (s && s.status !== "connected") emit({ kind: "error", text: `Claude Code could not reach catpad's MCP endpoint (${s.status}).` });
} else if (m.type === "stream_event") {
const ev = m.event;
if (ev?.type === "content_block_delta" && ev.delta?.type === "text_delta" && ev.delta.text) {
sawText = true;
emit({ kind: "text", text: ev.delta.text });
}
} else if (m.type === "assistant") {
for (const b of m.message?.content ?? []) {
if (b.type !== "tool_use") continue;
const name = String(b.name).replace(/^mcp__catpad__/, "");
tools.set(b.id, name);
emit({ kind: "tool", id: b.id, name, summary: summarizeCall(name, b.input) });
}
} else if (m.type === "user") {
const content = m.message?.content;
for (const b of Array.isArray(content) ? content : []) {
if (b.type !== "tool_result") continue;
const text = typeof b.content === "string" ? b.content : (b.content ?? []).map((c: any) => c.text ?? "").join("\n");
emit({ kind: "tool-result", id: b.tool_use_id, ok: !b.is_error, summary: summarizeResult(text) });
}
} else if (m.type === "result") {
result = m;
}
}
}
} finally {
signal.removeEventListener("abort", kill);
}
const code = await proc.exited;
if (signal.aborted) return;
if (result?.is_error || (result && result.subtype !== "success")) {
const why = result.result || (result.errors ?? []).join("; ") || result.subtype;
// A conversation that cannot be resumed is started again next time.
if (/no conversation found/i.test(String(why))) this.reset();
throw new Error(`Claude Code: ${why}`);
}
if (!result) {
const err = (await stderr).trim();
if (/no conversation found/i.test(err)) this.reset();
throw new Error(`Claude Code exited (${code})${err ? `: ${err.split("\n").slice(-5).join(" ")}` : " without a result"}`);
}
// Without partial messages (an older Claude Code), the final text is all there is.
if (!sawText && result.result) emit({ kind: "text", text: String(result.result) });
}
}
// ---------- codex ----------
// Codex in headless mode: `codex exec --json`, one process per user message,
// the conversation a Codex thread that the next message resumes. catpad's
// tools come from this server's MCP endpoint, approved in advance (Codex asks
// before an MCP call otherwise, and nobody is there to answer). The user's
// own Codex configuration stays out (--ignore-user-config): their MCP servers,
// profiles and model provider are about their projects, not this pad. Its
// shell runs read-only, in an empty directory of its own.
class CodexBackend implements Backend {
info: AgentInfo;
private thread: string | null = null;
private cwd: string;
constructor(private bin: string, private o: AgentOptions, private model?: string) {
this.info = { backend: "codex", label: model ? `Codex (${model})` : "Codex", model };
this.cwd = join(o.cacheDir, "agent-codex");
mkdirSync(this.cwd, { recursive: true });
}
reset() { this.thread = null; }
save() { return this.thread ? { thread: this.thread } : null; }
// A Codex thread can be resumed only at its end, so after a rewind it would
// know what came later: then it starts afresh and is told the conversation.
load(s: any, rewind: boolean) {
if (rewind || typeof s?.thread !== "string") return false;
this.thread = s.thread;
return true;
}
args(): string[] {
const set = (key: string, value: string) => ["-c", `${key}=${JSON.stringify(value)}`]; // a JSON string is a TOML string
const a = [this.bin, "exec"];
if (this.thread) a.push("resume");
a.push(
"--json", "--ignore-user-config", "--skip-git-repo-check",
...set("mcp_servers.catpad.url", `http://127.0.0.1:${this.o.port}/mcp?client=catpad-agent`),
...set("mcp_servers.catpad.default_tools_approval_mode", "approve"),
...set("sandbox_mode", "read-only"),
...set("developer_instructions", readPrompt()),
);
if (this.model) a.push(...set("model", this.model));
if (this.thread) a.push(this.thread);
a.push("-"); // the message comes on stdin
return a;
}
async run(message: string, emit: Emit, signal: AbortSignal) {
const proc = spawn(this.args(), { cwd: this.cwd, stdin: "pipe", stdout: "pipe", stderr: "pipe" });
const kill = () => { try { proc.kill("SIGTERM"); } catch {} };
signal.addEventListener("abort", kill, { once: true });
proc.stdin.write(message);
proc.stdin.end();
const stderr = new Response(proc.stderr).text();
let failure: string | null = null;
let finished = false;
let said = 0;
const started = new Set<string>();
const tool = (it: any) => (it.type === "mcp_tool_call" ? String(it.tool) : "shell");
try {
let buf = "";
const dec = new TextDecoder();
for await (const chunk of proc.stdout) {
buf += dec.decode(chunk, { stream: true });
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line) continue;
let m: any;
try { m = JSON.parse(line); } catch { continue; }
if (process.env.CATPAD_DEBUG && process.env.CATPAD_DEBUG !== "0") console.log("codex:", line.slice(0, 300));
const it = m.item;
if (m.type === "thread.started" && m.thread_id) this.thread = m.thread_id;
else if (m.type === "turn.completed") finished = true;
else if (m.type === "turn.failed") failure = m.error?.message ?? "the turn failed";
else if (m.type === "error") failure = m.message ?? "Codex reported an error";
else if ((m.type === "item.started" || m.type === "item.completed") && it) {
const isTool = it.type === "mcp_tool_call" || it.type === "command_execution";
if (isTool && !started.has(it.id)) {
started.add(it.id);
emit({ kind: "tool", id: it.id, name: tool(it), summary: it.type === "mcp_tool_call" ? summarizeCall(it.tool, it.arguments) : clip(String(it.command ?? ""), 100) });
}
if (m.type !== "item.completed") continue;
if (it.type === "agent_message" && it.text) {
// Each message is whole; the log joins consecutive text, so they are kept apart here.
emit({ kind: "text", text: (said++ ? "\n\n" : "") + it.text });
} else if (it.type === "mcp_tool_call") {
const text = (it.result?.content ?? []).map((c: any) => c.text ?? "").join("\n");
emit({ kind: "tool-result", id: it.id, ok: it.status === "completed" && !it.error, summary: it.error?.message ? clip(it.error.message, 140) : summarizeResult(text) });
} else if (it.type === "command_execution") {
emit({ kind: "tool-result", id: it.id, ok: it.exit_code === 0, summary: clip(String(it.aggregated_output ?? `exit ${it.exit_code}`), 140) });
}
}
}
}
} finally {
signal.removeEventListener("abort", kill);
}
const code = await proc.exited;
if (signal.aborted) return;
const err = (await stderr).trim();
if (failure || !finished) {
const why = failure ?? (err ? err.split("\n").slice(-5).join(" ") : `exited (${code}) without finishing the turn`);
// A thread Codex no longer has is started again next time.
if (/thread|session|rollout/i.test(why) && /not found|no such|missing/i.test(why)) this.reset();
throw new Error(`Codex: ${why}`);
}
}
}
// ---------- openai, and the Functorial Agent ----------
const MAX_STEPS = 25;
class OpenAIBackend implements Backend {
info: AgentInfo;
private url: string;
private model: string;
private key?: string;
private history: any[] = [];
constructor(private o: AgentOptions, c: { kind: "openai" | "functorial"; url: string; model?: string; key?: string }) {
this.url = c.url.replace(/\/+$/, "");
this.model = c.model || "default";
this.key = c.key;
let host = this.url;
try { host = new URL(this.url).host; } catch {}
this.info = c.kind === "functorial"
? { backend: "functorial", label: c.model ? `Functorial Agent (${c.model})` : "Functorial Agent", model: c.model }
: { backend: "openai", label: `${this.model} at ${host}`, model: this.model };
}
reset() { this.history = []; }
// The messages themselves are the state: a copy of them is the conversation.
save() { return this.history.length ? structuredClone(this.history) : null; }
load(s: any, _rewind: boolean) {
if (!Array.isArray(s)) return false;
this.history = structuredClone(s);
return true;
}
private tools() {
return TOOLS.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.inputSchema } }));
}
async run(message: string, emit: Emit, signal: AbortSignal) {
this.history.push({ role: "user", content: message });
for (let step = 0; step < MAX_STEPS; step++) {
const { content, calls } = await this.complete(emit, signal);
const msg: any = { role: "assistant", content: content || null };
if (calls.length) msg.tool_calls = calls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.args || "{}" } }));
this.history.push(msg);
if (!calls.length) return;
for (const c of calls) {
// The history must answer every call, even when the turn is stopped half way.
if (signal.aborted) { this.history.push({ role: "tool", tool_call_id: c.id, content: "Not run: the user stopped the turn." }); continue; }
let args: any;
try { args = c.args.trim() ? JSON.parse(c.args) : {}; } catch { args = null; }
emit({ kind: "tool", id: c.id, name: c.name, summary: summarizeCall(c.name, args) });
let r: ToolResult;
if (args == null) r = { text: `The arguments were not valid JSON: ${c.args.slice(0, 200)}`, isError: true };
else if (!TOOL_NAMES.has(c.name)) r = { text: `There is no tool named ${c.name}. The tools are: ${[...TOOL_NAMES].join(", ")}.`, isError: true };
else {
try { r = await this.o.call(c.name, args); } catch (e: any) { r = { text: String(e?.message ?? e), isError: true }; }
}
emit({ kind: "tool-result", id: c.id, ok: !r.isError, summary: summarizeResult(r.text) });
this.history.push({ role: "tool", tool_call_id: c.id, content: r.text });
}
if (signal.aborted) return;
}
throw new Error(`Stopped after ${MAX_STEPS} model calls in one turn.`);
}
// One streamed chat completion. Text deltas go out as they arrive; tool calls are assembled.
private async complete(emit: Emit, signal: AbortSignal): Promise<{ content: string; calls: { id: string; name: string; args: string }[] }> {
const headers: Record<string, string> = { "content-type": "application/json" };
if (this.key) headers.authorization = `Bearer ${this.key}`;
const res = await fetch(`${this.url}/chat/completions`, {
method: "POST",
headers,
signal,
body: JSON.stringify({
model: this.model,
stream: true,
messages: [{ role: "system", content: readPrompt() }, ...this.history],
tools: this.tools(),
}),
});
if (!res.ok || !res.body) throw new Error(`${this.url}/chat/completions: HTTP ${res.status} ${(await res.text().catch(() => "")).slice(0, 300)}`);
let content = "";
const calls: { id: string; name: string; args: string }[] = [];
const dec = new TextDecoder();
let buf = "";
const take = (data: string) => {
if (data === "[DONE]") return;
let j: any;
try { j = JSON.parse(data); } catch { return; }
if (j.error) throw new Error(`model server: ${j.error.message ?? JSON.stringify(j.error)}`);
const d = j.choices?.[0]?.delta ?? j.choices?.[0]?.message;
if (!d) return;
if (typeof d.content === "string" && d.content) {
content += d.content;
emit({ kind: "text", text: d.content });
}
for (const tc of d.tool_calls ?? []) {
const i = Number.isInteger(tc.index) ? tc.index : calls.length;
const c = (calls[i] ??= { id: "", name: "", args: "" });
if (tc.id) c.id = tc.id;
if (tc.function?.name) c.name += tc.function.name;
if (tc.function?.arguments != null) c.args += typeof tc.function.arguments === "string" ? tc.function.arguments : JSON.stringify(tc.function.arguments);
}
};
for await (const chunk of res.body) {
buf += dec.decode(chunk, { stream: true });
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (line.startsWith("data:")) take(line.slice(5).trim());
}
}
if (buf.trim().startsWith("data:")) take(buf.trim().slice(5).trim());
const out = calls.filter(Boolean).map((c, i) => ({ ...c, id: c.id || `call_${Date.now().toString(36)}_${i}` }));
return { content, calls: out };
}
}