Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

debug-provider-events.ts

203 lines6.5 KB

1#!/usr/bin/env bun
2/**
3 * debug-provider-events.ts — CLI script to test a provider via the harness
4 * and log every raw event for debugging.
5 *
6 * Usage:
7 * bun run scripts/debug-provider-events.ts [provider] [prompt]
8 *
9 * Examples:
10 * bun run scripts/debug-provider-events.ts codex "say hello in one word"
11 * bun run scripts/debug-provider-events.ts cursor "say hello in one word"
12 * bun run scripts/debug-provider-events.ts opencode "say hello in one word"
13 * bun run scripts/debug-provider-events.ts claudeAgent "say hello in one word"
14 *
15 * Env:
16 * T3CODE_HARNESS_PORT (default: 4321)
17 * T3CODE_HARNESS_SECRET (default: dev-harness-secret)
18 */
19​
20import {
21 HarnessClientManager,
22 type HarnessRawEvent,
23} from "../apps/server/src/provider/Layers/HarnessClientManager.ts";
24import { mapToRuntimeEvents } from "../apps/server/src/provider/Layers/codexEventMapping.ts";
25​
26const provider = process.argv[2] || "codex";
27const prompt = process.argv[3] || "say hello in one word";
28const port = Number(process.env.T3CODE_HARNESS_PORT ?? 4321);
29const secret = process.env.T3CODE_HARNESS_SECRET ?? "dev-harness-secret";
30const threadId = `debug-${Date.now()}`;
31const cwd = process.cwd();
32​
33// Timestamp helper
34const t0 = Date.now();
35const ts = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;
36​
37// Event collector
38const events: Array<{
39 ts: string;
40 kind: string;
41 method: string;
42 turnId?: string;
43 payload: unknown;
44}> = [];
45​
46console.log(`\n=== Provider Debug: ${provider} ===`);
47console.log(`Thread: ${threadId}`);
48console.log(`Prompt: "${prompt}"`);
49console.log(`Harness: ws://localhost:${port}\n`);
50​
51const mgr = new HarnessClientManager({
52 harnessPort: port,
53 harnessSecret: secret,
54 onEvent: (raw: HarnessRawEvent) => {
55 if (raw.threadId !== threadId) return; // ignore other threads
56​
57 const payload = raw.payload as Record<string, unknown> | undefined;
58 const turnId =
59 (payload?.turnId as string) ??
60 (payload?.turn_id as string) ??
61 ((payload?.turn as Record<string, unknown>)?.id as string) ??
62 ((payload?.msg as Record<string, unknown>)?.turn_id as string) ??
63 undefined;
64​
65 const entry = { ts: ts(), kind: raw.kind, method: raw.method, turnId, payload: raw.payload };
66 events.push(entry);
67​
68 // Compact log line
69 const turnTag = turnId ? ` turn=${turnId.slice(0, 8)}` : "";
70 const detail = summarize(raw.method, payload);
71 console.log(` ${ts()} [${raw.kind}] ${raw.method}${turnTag}${detail}`);
72 },
73 onSessionChanged: () => {},
74 onDisconnect: () => console.log(` ${ts()} [ws] disconnected`),
75 onReconnect: () => console.log(` ${ts()} [ws] reconnected`),
76});
77​
78function summarize(method: string, payload: Record<string, unknown> | undefined): string {
79 if (!payload) return "";
80 if (method === "content/delta") {
81 const delta = (payload.delta as string) ?? "";
82 return ` δ="${delta.slice(0, 40)}"`;
83 }
84 if (method === "item/agentMessage/delta") {
85 const delta = (payload.delta as string) ?? (payload.text as string) ?? "";
86 return ` δ="${delta.slice(0, 40)}"`;
87 }
88 if (method === "turn/started" || method === "turn/completed") {
89 const turn = payload.turn as Record<string, unknown> | undefined;
90 return ` status=${(turn?.status as string) ?? (payload.stopReason as string) ?? "ok"}`;
91 }
92 if (method === "session/started" || method === "session/ready") {
93 return "";
94 }
95 if (method.startsWith("codex/event/")) {
96 const msg = payload.msg as Record<string, unknown> | undefined;
97 const text = (msg?.text as string) ?? (msg?.last_agent_message as string) ?? "";
98 return text ? ` "${text.slice(0, 50)}"` : "";
99 }
100 if (method === "item/completed" || method === "item/started") {
101 const itemType =
102 (payload.itemType as string) ??
103 ((payload.item as Record<string, unknown>)?.type as string) ??
104 "?";
105 return ` type=${itemType}`;
106 }
107 return "";
109​
110async function run() {
111 // 1. Connect
112 console.log(`${ts()} Connecting...`);
113 await mgr.connect();
114 console.log(`${ts()} Connected\n`);
115​
116 // 2. Start session
117 console.log(`${ts()} Starting ${provider} session...`);
118 const session = await mgr.startSession({
119 threadId,
120 provider,
121 cwd,
122 runtimeMode: "full-access",
123 });
124 console.log(`${ts()} Session started: ${JSON.stringify(session)}\n`);
125​
126 // 3. Wait for session ready (some providers need time)
127 console.log(`${ts()} Waiting for session ready...`);
128 await new Promise((r) => setTimeout(r, 2000));
129​
130 // 4. Send turn
131 console.log(`${ts()} Sending turn: "${prompt}"`);
132 const turnResult = await mgr.sendTurn(threadId, {
133 input: [{ type: "text", text: prompt }],
134 });
135 console.log(`${ts()} Turn accepted: ${JSON.stringify(turnResult)}\n`);
136​
137 // 5. Wait for turn completion
138 console.log(`${ts()} Waiting for events (60s timeout)...\n`);
139 await new Promise<void>((resolve) => {
140 let settled = false;
141 const timeout = setTimeout(() => {
142 if (!settled) {
143 settled = true;
144 console.log(`\n${ts()} TIMEOUT — turn did not complete in 60s`);
145 resolve();
146 }
147 }, 60_000);
148​
149 // Check periodically if turn completed
150 const check = setInterval(() => {
151 const completed = events.find(
152 (e) => e.method === "turn/completed" || e.method === "codex/event/task_complete",
153 );
154 if (completed && !settled) {
155 settled = true;
156 clearTimeout(timeout);
157 clearInterval(check);
158 // Give 2s for any trailing events
159 setTimeout(resolve, 2000);
160 }
161 }, 500);
162 });
163​
164 // 6. Summary
165 console.log(`\n${"=".repeat(60)}`);
166 console.log(`SUMMARY: ${events.length} events received`);
167 console.log(`${"=".repeat(60)}`);
168​
169 const methods = new Map<string, number>();
170 for (const e of events) {
171 methods.set(e.method, (methods.get(e.method) ?? 0) + 1);
172 }
173 for (const [method, count] of [...methods.entries()].sort()) {
174 const turnIds = new Set(
175 events.filter((e) => e.method === method && e.turnId).map((e) => e.turnId),
176 );
177 const turnTag =
178 turnIds.size > 0
179 ? ` (turnId: ${[...turnIds].map((t) => t!.slice(0, 8)).join(", ")})`
180 : " (NO turnId)";
181 console.log(` ${method}: ${count}x${turnTag}`);
182 }
183​
184 // 7. Write full event log
185 const outPath = `/tmp/debug-${provider}-${Date.now()}.json`;
186 await Bun.write(outPath, JSON.stringify(events, null, 2));
187 console.log(`\nFull event log: ${outPath}`);
188​
189 // 8. Cleanup
190 console.log(`\n${ts()} Stopping session...`);
191 try {
192 await mgr.stopSession(threadId);
193 } catch {
194 // ok if already stopped
195 }
196 mgr.disconnect();
197 console.log(`${ts()} Done\n`);
199​
200run().catch((err) => {
201 console.error("Fatal:", err);
202 process.exit(1);
203});