@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 262 lines 9.56 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalJsonInEffect:off globalConsole:off - a tiny stdio ACP agent spawned by the server; plain Node keeps it dependency-free.
2 /**
3 * A scripted stand-in for the `fx` CLI, registered as an Fx provider instance so the
4 * server streams deterministic replies with no model. A `[[eval:<script>]]` marker in
5 * the prompt picks the reply; see `scriptOf`. `hold` scripts wait for a release file
6 * named after the marker's key in `T3_EVAL_FX_CONTROL_DIR`.
7 */
8 import * as NodeFS from "node:fs";
9 import * as NodePath from "node:path";
10 import * as NodeReadline from "node:readline";
11
12 const MODEL = "eval/scripted";
13
14 type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
15 interface Message {
16 readonly id?: number | string;
17 readonly method?: string;
18 readonly params?: { [key: string]: Json };
19 readonly result?: Json;
20 readonly error?: Json;
21 }
22
23 const controlDir = process.env.T3_EVAL_FX_CONTROL_DIR ?? "";
24 const send = (message: object) => process.stdout.write(`${JSON.stringify(message)}\n`);
25 const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
26 const update = (sessionId: string, value: object) =>
27 send({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: value } });
28
29 const select = (id: string, category: string, currentValue: string, values: string[]) => ({
30 id,
31 name: id,
32 category,
33 type: "select",
34 currentValue,
35 options: values.map((value) => ({ value, name: value })),
36 });
37 // The Fx adapter needs a mode option and the modes list; it sets mode and effort per session.
38 const configOptions = [
39 select("model", "model", MODEL, [MODEL]),
40 select("mode", "mode", "full-access", ["auto", "ask", "full-access"]),
41 select("effort", "thought_level", "auto", ["auto", "low", "medium", "high"]),
42 ];
43 const modes = {
44 currentModeId: "full-access",
45 availableModes: ["auto", "ask", "full-access"].map((id) => ({ id, name: id })),
46 };
47
48 let nextOutgoingId = 1_000_000;
49 const pendingReplies = new Map<number, (message: Message) => void>();
50 const cancelled = new Set<string>();
51 let sessionCount = 0;
52
53 function request(method: string, params: object): Promise<Message> {
54 const id = nextOutgoingId++;
55 send({ jsonrpc: "2.0", id, method, params });
56 return new Promise((resolve) => pendingReplies.set(id, resolve));
57 }
58
59 /** Paragraphs of plain filler with a heading every fifth paragraph, so the feed lays out like a real reply. */
60 export function fillerText(words: number, seed = 0): string {
61 const vocabulary =
62 "the agent reads the file then edits the module and runs the focused test before it writes a short summary of what changed and why the change is safe".split(
63 " ",
64 );
65 const out: string[] = [];
66 let paragraph: string[] = [];
67 for (let index = 0; index < words; index++) {
68 paragraph.push(vocabulary[(index * 7 + seed) % vocabulary.length]!);
69 if (paragraph.length === 60 || index === words - 1) {
70 const count = out.length;
71 out.push(`${count % 5 === 0 ? `## Part ${count / 5 + 1}\n\n` : ""}${paragraph.join(" ")}.`);
72 paragraph = [];
73 }
74 }
75 return out.join("\n\n");
76 }
77
78 interface Script {
79 readonly kind: "reply" | "stream" | "hold" | "question" | "subagents" | "fail";
80 readonly words: number;
81 readonly chunkMs: number;
82 readonly key: string;
83 }
84
85 /** `[[eval:stream:3000:40]]` streams 3000 words in 40 ms chunks; `[[eval:hold:k]]` replies when `k` is released. */
86 export function scriptOf(prompt: string): Script {
87 const marker = /\[\[eval:([a-z]+)(?::([^\]:]+))?(?::([^\]:]+))?\]\]/.exec(prompt);
88 const kind = marker?.[1];
89 if (kind === "stream")
90 return {
91 kind,
92 words: Number(marker?.[2] ?? 3000),
93 chunkMs: Number(marker?.[3] ?? 40),
94 key: "",
95 };
96 if (kind === "hold" || kind === "subagents" || kind === "question")
97 return { kind, words: 40, chunkMs: 0, key: marker?.[2] ?? kind };
98 if (kind === "fail") return { kind, words: 0, chunkMs: 0, key: "" };
99 return { kind: "reply", words: 40, chunkMs: 0, key: "" };
100 }
101
102 async function waitForRelease(sessionId: string, key: string) {
103 const file = NodePath.join(controlDir, `release-${key}`);
104 while (!cancelled.has(sessionId) && !NodeFS.existsSync(file)) await sleep(100);
105 }
106
107 async function streamText(sessionId: string, text: string, chunkMs: number, messageId: string) {
108 const tokens = text.split(/(?<= )/);
109 for (let index = 0; index < tokens.length; index += 4) {
110 if (cancelled.has(sessionId)) return;
111 update(sessionId, {
112 sessionUpdate: "agent_message_chunk",
113 messageId,
114 content: { type: "text", text: tokens.slice(index, index + 4).join("") },
115 });
116 if (chunkMs > 0) await sleep(chunkMs);
117 }
118 }
119
120 async function runPrompt(sessionId: string, prompt: string, turn: number): Promise<object> {
121 const script = scriptOf(prompt);
122 const messageId = `${sessionId}-m${turn}`;
123 if (script.kind === "fail") throw new Error("Scripted provider failure.");
124 if (script.kind === "hold") await waitForRelease(sessionId, script.key);
125 if (script.kind === "question") {
126 const reply = await request("elicitation/create", {
127 sessionId,
128 mode: "form",
129 message: "Which option should I use?",
130 requestedSchema: {
131 type: "object",
132 properties: {
133 choice: {
134 type: "string",
135 title: "Option",
136 description: "Which option should I use?",
137 enum: ["First", "Second"],
138 },
139 },
140 required: ["choice"],
141 },
142 });
143 if (reply.error) return { stopReason: "cancelled" };
144 }
145 if (script.kind === "subagents") {
146 for (const name of ["one", "two"]) {
147 const toolCallId = `${sessionId}-sub-${name}-${turn}`;
148 update(sessionId, {
149 sessionUpdate: "tool_call",
150 toolCallId,
151 name: "subagent",
152 title: `Subagent · read ${name}`,
153 kind: "other",
154 status: "pending",
155 rawInput: { request: { action: "run", task: `Read file ${name}` } },
156 });
157 update(sessionId, { sessionUpdate: "tool_call_update", toolCallId, status: "in_progress" });
158 }
159 await waitForRelease(sessionId, script.key);
160 for (const name of ["one", "two"])
161 update(sessionId, {
162 sessionUpdate: "tool_call_update",
163 toolCallId: `${sessionId}-sub-${name}-${turn}`,
164 status: "completed",
165 content: [
166 {
167 type: "content",
168 // A long reply gives the child thread something to scroll.
169 content: {
170 type: "text",
171 text: JSON.stringify({ ok: true, result: fillerText(1500, turn) }),
172 },
173 },
174 ],
175 });
176 }
177 if (cancelled.has(sessionId)) return { stopReason: "cancelled" };
178 await streamText(sessionId, fillerText(script.words, turn), script.chunkMs, messageId);
179 return { stopReason: cancelled.has(sessionId) ? "cancelled" : "end_turn" };
180 }
181
182 const turns = new Map<string, number>();
183
184 async function handle(message: Message) {
185 if (message.method === undefined) {
186 if (typeof message.id === "number") pendingReplies.get(message.id)?.(message);
187 return;
188 }
189 const reply = (result: object) => send({ jsonrpc: "2.0", id: message.id, result });
190 const params = message.params ?? {};
191 const sessionId = typeof params.sessionId === "string" ? params.sessionId : "";
192 switch (message.method) {
193 case "initialize":
194 return reply({
195 protocolVersion: 1,
196 agentCapabilities: {
197 loadSession: true,
198 promptCapabilities: { image: true, audio: false, embeddedContext: true },
199 mcpCapabilities: { http: true, sse: true, acp: true },
200 sessionCapabilities: { list: {}, resume: {}, close: {}, systemPrompt: {} },
201 },
202 agentInfo: { name: "fx", title: "fx", version: "0.0.14" },
203 authMethods: [],
204 });
205 case "session/new": {
206 sessionCount += 1;
207 const sessionId = `eval-session-${process.pid}-${sessionCount}`;
208 return reply({ sessionId, configOptions, modes });
209 }
210 case "session/load":
211 case "session/resume":
212 return reply({ configOptions, modes });
213 case "session/set_config_option":
214 return reply({ configOptions });
215 case "session/cancel":
216 cancelled.add(sessionId);
217 return;
218 case "session/prompt": {
219 cancelled.delete(sessionId);
220 const turn = (turns.get(sessionId) ?? 0) + 1;
221 turns.set(sessionId, turn);
222 const blocks = Array.isArray(params.prompt) ? params.prompt : [];
223 const text = blocks
224 .map((block) =>
225 block && typeof block === "object" && !Array.isArray(block) ? block.text : "",
226 )
227 .filter((value) => typeof value === "string")
228 .join("\n");
229 try {
230 return reply(await runPrompt(sessionId, text, turn));
231 } catch (error) {
232 return send({
233 jsonrpc: "2.0",
234 id: message.id,
235 error: { code: -32603, message: error instanceof Error ? error.message : String(error) },
236 });
237 }
238 }
239 default:
240 if (message.id !== undefined) return reply({});
241 }
242 }
243
244 function main(args: ReadonlyArray<string>) {
245 const probes: Record<string, string> = {
246 "--version": "fx 0.0.14",
247 status: JSON.stringify({ auth: "eval", model: MODEL }),
248 models: JSON.stringify({ ids: [MODEL] }),
249 };
250 const probe = probes[args[0] ?? ""];
251 if (probe !== undefined) return console.log(probe);
252 if (args[0] !== "acp") {
253 console.error(`fake-fx: unsupported command ${args.join(" ")}`);
254 process.exitCode = 2;
255 return;
256 }
257 NodeReadline.createInterface({ input: process.stdin }).on("line", (line) => {
258 if (line.trim()) void handle(JSON.parse(line) as Message);
259 });
260 }
261
262 if (import.meta.main) main(process.argv.slice(2));