@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, 06:00 UTC

main
mjs 341 lines 10 KB
Raw
1 #!/usr/bin/env node
2 // A stand-in `claude` CLI for staged launch videos: T3's real Claude provider runs it, and it
3 // plays the scripted turns in FAKE_CLAUDE_SCRIPT over the Agent SDK's stream-json protocol.
4 // Script format: see the launch-video SKILL.md. FAKE_CLAUDE_LOG records every line.
5 import * as NodeCrypto from "node:crypto";
6 import * as NodeFS from "node:fs";
7 import * as NodeReadline from "node:readline";
8
9 const VERSION = "2.1.329";
10 if (process.argv.includes("--version") || process.argv.includes("-v")) {
11 console.log(`${VERSION} (Claude Code)`);
12 process.exit(0);
13 }
14
15 const log = (direction, value) => {
16 if (!process.env.FAKE_CLAUDE_LOG) return;
17 NodeFS.appendFileSync(
18 process.env.FAKE_CLAUDE_LOG,
19 `${direction} ${JSON.stringify(value).slice(0, 4000)}\n`,
20 );
21 };
22 log("argv", process.argv.slice(2));
23
24 const readJson = (file, fallback) => {
25 try {
26 return JSON.parse(NodeFS.readFileSync(file, "utf8"));
27 } catch {
28 return fallback;
29 }
30 };
31 const script = readJson(process.env.FAKE_CLAUDE_SCRIPT ?? "", []);
32 const played = new Set();
33 const fill = (value) => {
34 const vars = readJson(process.env.FAKE_CLAUDE_VARS ?? "", {});
35 const walk = (v) =>
36 typeof v === "string"
37 ? v.replace(/<var:([\w-]+)>/g, (m, name) => vars[name] ?? m)
38 : Array.isArray(v)
39 ? v.map(walk)
40 : v && typeof v === "object"
41 ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]))
42 : v;
43 return walk(value);
44 };
45
46 const argValue = (name) => {
47 const i = process.argv.indexOf(name);
48 return i === -1 ? undefined : process.argv[i + 1];
49 };
50 const sessionId = argValue("--session-id") ?? argValue("--resume") ?? NodeCrypto.randomUUID();
51 let model = argValue("--model") ?? "claude-opus-5-5";
52 const cwd = process.cwd();
53 const mcpServers = {};
54 const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
55 const uuid = () => NodeCrypto.randomUUID();
56
57 const send = (message) => {
58 log("out", message);
59 process.stdout.write(`${JSON.stringify(message)}\n`);
60 };
61 const usage = {
62 input_tokens: 1,
63 cache_creation_input_tokens: 0,
64 cache_read_input_tokens: 0,
65 output_tokens: 1,
66 service_tier: "standard",
67 };
68 const assistant = (content, id = `msg_${uuid().replaceAll("-", "").slice(0, 24)}`) =>
69 send({
70 type: "assistant",
71 message: {
72 model,
73 id,
74 type: "message",
75 role: "assistant",
76 content,
77 stop_reason: null,
78 stop_sequence: null,
79 usage,
80 },
81 parent_tool_use_id: null,
82 session_id: sessionId,
83 uuid: uuid(),
84 });
85 const toolResult = (toolUseId, content, extra = {}) =>
86 send({
87 type: "user",
88 message: {
89 role: "user",
90 content: [{ tool_use_id: toolUseId, type: "tool_result", content, is_error: false }],
91 },
92 parent_tool_use_id: null,
93 session_id: sessionId,
94 uuid: uuid(),
95 timestamp: new Date().toISOString(),
96 ...extra,
97 });
98
99 // Streams text the way the CLI does with partial messages on: deltas, then the whole block.
100 const streamText = async (text, type = "text") => {
101 const id = `msg_${uuid().replaceAll("-", "").slice(0, 24)}`;
102 const delta = type === "text" ? "text_delta" : "thinking_delta";
103 const field = type === "text" ? "text" : "thinking";
104 send({
105 type: "stream_event",
106 event: {
107 type: "message_start",
108 message: { id, type: "message", role: "assistant", model, content: [], usage },
109 },
110 parent_tool_use_id: null,
111 session_id: sessionId,
112 uuid: uuid(),
113 });
114 send({
115 type: "stream_event",
116 event: {
117 type: "content_block_start",
118 index: 0,
119 content_block:
120 type === "text"
121 ? { type: "text", text: "" }
122 : { type: "thinking", thinking: "", signature: "" },
123 },
124 parent_tool_use_id: null,
125 session_id: sessionId,
126 uuid: uuid(),
127 });
128 const words = text.match(/\S+\s*|\s+/g) ?? [text];
129 for (let i = 0; i < words.length; i += 3) {
130 await sleep(35);
131 send({
132 type: "stream_event",
133 event: {
134 type: "content_block_delta",
135 index: 0,
136 delta: { type: delta, [field]: words.slice(i, i + 3).join("") },
137 },
138 parent_tool_use_id: null,
139 session_id: sessionId,
140 uuid: uuid(),
141 });
142 }
143 send({
144 type: "stream_event",
145 event: { type: "content_block_stop", index: 0 },
146 parent_tool_use_id: null,
147 session_id: sessionId,
148 uuid: uuid(),
149 });
150 assistant(
151 [
152 type === "text"
153 ? { type: "text", text }
154 : { type: "thinking", thinking: text, signature: "" },
155 ],
156 id,
157 );
158 send({
159 type: "stream_event",
160 event: { type: "message_stop" },
161 parent_tool_use_id: null,
162 session_id: sessionId,
163 uuid: uuid(),
164 });
165 };
166
167 // One MCP tools/call over streamable HTTP against the server T3 registered.
168 async function callTool(name, args) {
169 const [serverName, server] = Object.entries(mcpServers).find(([, s]) => s.url) ?? [];
170 if (!server) return { serverName: "t3-code", text: `No MCP server for ${name}` };
171 let session;
172 const post = async (body) => {
173 const response = await fetch(server.url, {
174 method: "POST",
175 headers: {
176 accept: "application/json, text/event-stream",
177 "content-type": "application/json",
178 ...server.headers,
179 ...(session && { "mcp-session-id": session }),
180 },
181 body: JSON.stringify({ jsonrpc: "2.0", ...body }),
182 });
183 session = response.headers.get("mcp-session-id") ?? session;
184 const text = await response.text();
185 const data = text.split("\n").find((line) => line.startsWith("data:"));
186 return text ? JSON.parse(data ? data.slice(5) : text) : undefined;
187 };
188 await post({
189 id: 1,
190 method: "initialize",
191 params: {
192 protocolVersion: "2025-06-18",
193 capabilities: {},
194 clientInfo: { name: "fake-claude", version: VERSION },
195 },
196 });
197 await post({ method: "notifications/initialized" });
198 const result = await post({ id: 2, method: "tools/call", params: { name, arguments: args } });
199 log("mcp", result);
200 const text =
201 (result?.result?.content ?? []).map((c) => c.text ?? "").join("\n") ||
202 JSON.stringify(result?.error ?? result);
203 return { serverName, text };
204 }
205
206 async function playTurn(prompt) {
207 let index = script.findIndex(
208 (turn, i) => !played.has(i) && turn.match && new RegExp(turn.match, "i").test(prompt),
209 );
210 if (index === -1) index = script.findIndex((turn, i) => !played.has(i) && !turn.match);
211 const turn = index === -1 ? { steps: [{ text: "Done." }] } : script[index];
212 if (index !== -1 && !turn.repeat) played.add(index);
213 send({
214 type: "system",
215 subtype: "init",
216 apiKeySource: "none",
217 claude_code_version: VERSION,
218 cwd,
219 tools: ["Bash", "Read", "Edit"],
220 mcp_servers: Object.keys(mcpServers).map((name) => ({ name, status: "connected" })),
221 model,
222 permissionMode: "bypassPermissions",
223 slash_commands: [],
224 output_style: "default",
225 skills: [],
226 plugins: [],
227 agents: [],
228 uuid: uuid(),
229 session_id: sessionId,
230 });
231 let last = "";
232 for (const step of fill(turn.steps)) {
233 if (step.wait) await sleep(step.wait);
234 if (step.think) await streamText(step.think, "thinking");
235 if (step.text) {
236 await streamText(step.text);
237 last = step.text;
238 }
239 if (step.bash) {
240 const id = `toolu_${uuid().replaceAll("-", "").slice(0, 24)}`;
241 assistant([
242 {
243 type: "tool_use",
244 id,
245 name: "Bash",
246 input: { command: step.bash, description: step.description ?? step.bash },
247 },
248 ]);
249 await sleep(step.ms ?? 1200);
250 toolResult(id, step.output ?? "", {
251 tool_use_result: {
252 stdout: step.output ?? "",
253 stderr: "",
254 interrupted: false,
255 isImage: false,
256 },
257 });
258 }
259 if (step.tool) {
260 const id = `toolu_${uuid().replaceAll("-", "").slice(0, 24)}`;
261 const serverName = Object.keys(mcpServers)[0] ?? "t3-code";
262 assistant([
263 { type: "tool_use", id, name: `mcp__${serverName}__${step.tool}`, input: step.input ?? {} },
264 ]);
265 const { text } = await callTool(step.tool, step.input ?? {}).catch((error) => ({
266 text: String(error),
267 }));
268 toolResult(id, [{ type: "text", text }]);
269 }
270 }
271 send({
272 type: "result",
273 subtype: "success",
274 is_error: false,
275 duration_ms: 4000,
276 duration_api_ms: 3500,
277 num_turns: 1,
278 result: last,
279 stop_reason: "end_turn",
280 session_id: sessionId,
281 total_cost_usd: 0,
282 usage,
283 modelUsage: {},
284 permission_denials: [],
285 uuid: uuid(),
286 });
287 }
288
289 const controlResponse = (request) => {
290 switch (request.subtype) {
291 case "initialize":
292 return {
293 commands: [],
294 output_style: "default",
295 available_output_styles: ["default"],
296 models: [],
297 account: { email: "demo@example.com", subscriptionType: "max", tokenSource: "claude.ai" },
298 };
299 case "mcp_set_servers":
300 for (const [name, config] of Object.entries(request.servers ?? {})) mcpServers[name] = config;
301 return { added: Object.keys(request.servers ?? {}), removed: [], errors: {} };
302 case "set_model":
303 model = request.model ?? model;
304 return {};
305 case "get_usage":
306 return { rate_limits_available: false, rate_limits: [] };
307 default:
308 return {};
309 }
310 };
311
312 let queue = Promise.resolve();
313 const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
314 input.on("line", (line) => {
315 if (!line.trim()) return;
316 let message;
317 try {
318 message = JSON.parse(line);
319 } catch {
320 return;
321 }
322 log("in", message);
323 if (message.type === "control_request") {
324 send({
325 type: "control_response",
326 response: {
327 subtype: "success",
328 request_id: message.request_id,
329 response: controlResponse(message.request ?? {}),
330 },
331 });
332 return;
333 }
334 if (message.type === "user") {
335 const content = message.message?.content;
336 const prompt =
337 typeof content === "string" ? content : (content ?? []).map((c) => c.text ?? "").join("\n");
338 queue = queue.then(() => playTurn(prompt)).catch((error) => log("error", String(error)));
339 }
340 });
341 input.on("close", () => queue.then(() => process.exit(0)));