From c93244e7f456d5eb1b3e49aff78761295e52d459 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 16:45:27 +1100 Subject: [PATCH] Connect to T3 Code: auth, RPC client, shell and thread session --- .gitignore | 3 + .gitmodules | 3 + bun.lock | 89 ++++++++++++++++ package.json | 26 +++++ scripts/link-vendor.ts | 14 +++ scripts/spike-shell.ts | 25 +++++ scripts/spike-thread.ts | 25 +++++ src/client/auth.ts | 119 +++++++++++++++++++++ src/client/rpc.ts | 71 +++++++++++++ src/client/session.ts | 222 ++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 22 ++++ vendor/t3code | 1 + 12 files changed, 620 insertions(+) create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 bun.lock create mode 100644 package.json create mode 100644 scripts/link-vendor.ts create mode 100644 scripts/spike-shell.ts create mode 100644 scripts/spike-thread.ts create mode 100644 src/client/auth.ts create mode 100644 src/client/rpc.ts create mode 100644 src/client/session.ts create mode 100644 tsconfig.json create mode 160000 vendor/t3code diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ac1e8f7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules +*.log +.DS_Store diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..4bd0436 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "vendor/t3code"] + path = vendor/t3code + url = https://github.com/pingdotgg/t3code.git diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..c7d4d6f --- /dev/null +++ b/bun.lock @@ -0,0 +1,89 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "tui3", + "dependencies": { + "@opentui/core": "0.2.7", + "@opentui/react": "0.2.7", + "effect": "4.0.5", + "react": "19", + }, + "devDependencies": { + "@types/bun": "latest", + "@types/react": "^19.3.0", + "typescript": "^5.9.0", + }, + }, + }, + "packages": { + "@opentui/core": ["@opentui/core@0.2.7", "", { "dependencies": { "bun-ffi-structs": "0.2.2", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2", "yoga-layout": "3.2.1" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.2.7", "@opentui/core-darwin-x64": "0.2.7", "@opentui/core-linux-arm64": "0.2.7", "@opentui/core-linux-x64": "0.2.7", "@opentui/core-win32-arm64": "0.2.7", "@opentui/core-win32-x64": "0.2.7" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-cnN6JcaGC7SeQzobBy/CHzqUAQFtypazuw1CjQBo7WwoOiLMGubt9W5FXeF0zIrSxH2Ed6NLWhPYRg7SD4629Q=="], + + "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.2.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CAy6cL3byz2Xf6gFiJHBpcnsp/2ADEWLLOUokVypOyPLcy8GY3sPzlA4pkAjVGQMYQhDj+Y3+SXz4uTLt4AETg=="], + + "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.2.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-K06h333rMkC9cyMJr/VvcRK3ik81Admd8ZsES5uf5YXWPdYhXGf75I1T8mKIThhUmoFLb8R5xqfuPmoocsjM7Q=="], + + "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.2.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-iYWGTztbdG9yYSB5Alxuo0dWAmkWQR0+/paNWUyPOocjigmKgMmACDtHgYqa7sxkIcWgmXljt/f8rgXDG4wdMg=="], + + "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.2.7", "", { "os": "linux", "cpu": "x64" }, "sha512-tymBCfYbsDRfHQNXsolkFfaTEIDhemD4+1ZovUztQd7i+0Ggnu9WbPN1SNCiRz6PjrlaNeQzZE3Wl8FfVdw/cw=="], + + "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.2.7", "", { "os": "win32", "cpu": "arm64" }, "sha512-XLPJWdT8QOukrYDkpIng6+uNUlF66ByXcQlC3qA9JbrUTBetZhgXs8Q2jEjRfc+Ty3uh1iRSA6PgJGbbOK/f4Q=="], + + "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.2.7", "", { "os": "win32", "cpu": "x64" }, "sha512-CzVGEfqysVk8Hxcj0RDv/DtXIM6iZmbmr23kW7y8CJMPtmV1gmKI4D9abVjynWJnGbaSBnDi43mgZnGMgOdyEg=="], + + "@opentui/react": ["@opentui/react@0.2.7", "", { "dependencies": { "@opentui/core": "0.2.7", "react-reconciler": "^0.33.0" }, "peerDependencies": { "react": ">=19.2.0", "react-devtools-core": "^7.0.1", "ws": "^8.18.0" } }, "sha512-1p0TsYEgwVfJc0G0URHp9PF16JOA9aVU5PfbzH2Kx1+py3i79x47mnkUMJ9ugYxAaXLrRqbFetnq5v5L6UfI0Q=="], + + "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], + + "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], + + "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], + + "ansi-regex": ["ansi-regex@6.5.0", "", {}, "sha512-zhvbbbdt1kbw7EJ9OQoxmQcuaNR9P5kTj7e/YdmOSU10aHWbycofJxA6jKfoEy3vlLdctOF9ZHaxLtmSm998wQ=="], + + "bun-ffi-structs": ["bun-ffi-structs@0.2.2", "", { "peerDependencies": { "typescript": "^5" } }, "sha512-N/ZWtyN0piZlrXQT7TO0V+q952orYqkfhXRXM1Hcbb+R3QSiBH4vLnib187Mrs1H7pWIYECAmPeapGYDOMCl+w=="], + + "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], + + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + + "diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], + + "effect": ["effect@4.0.5", "", {}, "sha512-BY4/28NlpOd99yzmV741xbVGmp+1U7tks4oB7F/Png64bTa5tm5eCA6W0RiXsnuLDDoJpjfVSo4Dnq4BZb/89Q=="], + + "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + + "get-east-asian-width": ["get-east-asian-width@1.7.0", "", {}, "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q=="], + + "marked": ["marked@17.0.1", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg=="], + + "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], + + "react-devtools-core": ["react-devtools-core@7.0.1", "", { "dependencies": { "shell-quote": "^1.6.1", "ws": "^7" } }, "sha512-C3yNvRHaizlpiASzy7b9vbnBGLrhvdhl1CbdU6EnZgxPNbai60szdLtl+VL76UNOt5bOoVTOz5rNWZxgGt+Gsw=="], + + "react-reconciler": ["react-reconciler@0.33.0", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }, "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA=="], + + "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], + + "shell-quote": ["shell-quote@1.12.0", "", {}, "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q=="], + + "string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + + "strip-ansi": ["strip-ansi@7.1.2", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "undici-types": ["undici-types@8.12.3", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="], + + "web-tree-sitter": ["web-tree-sitter@0.25.10", "", { "peerDependencies": { "@types/emscripten": "^1.40.0" }, "optionalPeers": ["@types/emscripten"] }, "sha512-Y09sF44/13XvgVKgO2cNDw5rGk6s26MgoZPXLESvMXeefBf7i6/73eFurre0IsTW6E14Y0ArIzhUMmjoc7xyzA=="], + + "ws": ["ws@8.22.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g=="], + + "yoga-layout": ["yoga-layout@3.2.1", "", {}, "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ=="], + + "@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + + "react-devtools-core/ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="], + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..2ef2641 --- /dev/null +++ b/package.json @@ -0,0 +1,26 @@ +{ + "name": "tui3", + "version": "0.0.1", + "private": true, + "type": "module", + "bin": { + "tui3": "./src/bin.ts" + }, + "scripts": { + "dev": "bun run src/bin.ts", + "typecheck": "tsc --noEmit", + "test": "bun test", + "postinstall": "bun run scripts/link-vendor.ts" + }, + "dependencies": { + "@opentui/core": "0.2.7", + "@opentui/react": "0.2.7", + "effect": "4.0.5", + "react": "19" + }, + "devDependencies": { + "@types/bun": "latest", + "@types/react": "^19.3.0", + "typescript": "^5.9.0" + } +} diff --git a/scripts/link-vendor.ts b/scripts/link-vendor.ts new file mode 100644 index 0000000..763b506 --- /dev/null +++ b/scripts/link-vendor.ts @@ -0,0 +1,14 @@ +// Exposes the pinned T3 Code workspace packages under node_modules/@t3tools so +// their package export maps resolve. They are TypeScript sources Bun runs as-is. +import { lstat, mkdir, readdir, rm, symlink } from "node:fs/promises"; +import { join, relative } from "node:path"; + +const root = join(import.meta.dir, ".."); +const packagesDir = join(root, "vendor/t3code/packages"); +const scopeDir = join(root, "node_modules/@t3tools"); +await mkdir(scopeDir, { recursive: true }); +for (const name of await readdir(packagesDir)) { + const link = join(scopeDir, name); + await lstat(link).then(() => rm(link, { recursive: true, force: true }), () => {}); + await symlink(relative(scopeDir, join(packagesDir, name)), link, "dir"); +} diff --git a/scripts/spike-shell.ts b/scripts/spike-shell.ts new file mode 100644 index 0000000..be76645 --- /dev/null +++ b/scripts/spike-shell.ts @@ -0,0 +1,25 @@ +import { ORCHESTRATION_V2_WS_METHODS } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; +import { connect } from "../src/client/rpc.ts"; + +const program = Effect.gen(function* () { + const { rpc, target } = yield* connect; + console.log("connected to", target.httpBaseUrl); + yield* rpc[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({ omitIdleSubagents: true, omitOlderSettled: true }).pipe( + Stream.take(3), + Stream.runForEach((item) => + Effect.sync(() => { + if (item.kind === "snapshot") { + const s = item.snapshot as any; + console.log("snapshot keys:", Object.keys(s)); + console.log("projects:", s.projects?.length, "threads:", s.threads?.length); + for (const t of (s.threads ?? []).slice(0, 8)) console.log(" -", t.status, t.activityRunStatus, t.pendingRuntimeRequest ? "[NEEDS YOU]" : "", t.title); + } else console.log("item:", item.kind); + }), + ), + Effect.timeout("10 seconds"), + ); +}); +await Effect.runPromise(Effect.scoped(program)).catch((e) => { console.error("FAILED:", e); process.exit(1); }); +process.exit(0); diff --git a/scripts/spike-thread.ts b/scripts/spike-thread.ts new file mode 100644 index 0000000..cf96299 --- /dev/null +++ b/scripts/spike-thread.ts @@ -0,0 +1,25 @@ +import { T3Session } from "../src/client/session.ts"; +const s = new T3Session(); +await s.start(); +await new Promise((r) => { const off = s.onShell((st) => { if (st.status.type !== "connecting" && st.snapshot) { off(); r(); } }); }); +const shell = s.getShell(); +console.log("status", shell.status, "threads", shell.snapshot?.threads.length); +const counts: Record = {}; +for (const t of shell.snapshot!.threads) counts[t.status] = (counts[t.status] ?? 0) + 1; +console.log(counts); +const t = shell.snapshot!.threads.find((t) => t.status === "running") ?? shell.snapshot!.threads[0]!; +console.log("watching", t.title, t.status); +let events = 0; +const off = s.watchThread(t.id, (st) => { + events++; + if (st.projection && events < 4) { + const items = st.projection.visibleTurnItems; + console.log(st.status, "items", items.length, "types", [...new Set(items.map((i) => i.item.type))].join(",")); + const last = items.at(-1)?.item as any; + console.log("last:", last?.type, String(last?.text ?? last?.input ?? "").slice(0, 120)); + } + if (st.error) console.log("ERR", st.error); +}); +await Bun.sleep(5000); +console.log("updates received", events); +off(); await s.stop(); process.exit(0); diff --git a/src/client/auth.ts b/src/client/auth.ts new file mode 100644 index 0000000..3d8cef4 --- /dev/null +++ b/src/client/auth.ts @@ -0,0 +1,119 @@ +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +/** Scopes tui3 asks for: read threads, and send/approve/interrupt them. */ +export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate"] as const; + +export interface ServerTarget { + /** e.g. http://127.0.0.1:3773 */ + readonly httpBaseUrl: string; + readonly wsBaseUrl: string; +} + +export interface StoredCredential { + readonly httpBaseUrl: string; + readonly bearerToken: string; + readonly issuedAt: string; +} + +const t3Home = () => process.env.T3CODE_HOME ?? join(homedir(), ".t3"); +const configDir = () => + join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "tui3"); +const credentialPath = () => join(configDir(), "credentials.json"); + +/** Finds the local server from the runtime file T3 Code writes on startup. */ +export async function resolveLocalServer(): Promise { + const override = process.env.TUI3_SERVER; + if (override) return targetFromHttp(override); + const runtimePath = join(t3Home(), "userdata", "server-runtime.json"); + let runtime: { origin?: string; port?: number }; + try { + runtime = JSON.parse(await readFile(runtimePath, "utf8")); + } catch { + throw new Error(`No running T3 Code server found (${runtimePath} is missing). Start T3 Code, or set TUI3_SERVER.`); + } + const origin = runtime.origin ?? `http://127.0.0.1:${runtime.port ?? 3773}`; + return targetFromHttp(origin); +} + +function targetFromHttp(httpBaseUrl: string): ServerTarget { + const url = new URL(httpBaseUrl); + const ws = new URL(url); + ws.protocol = url.protocol === "https:" ? "wss:" : "ws:"; + return { httpBaseUrl: url.origin, wsBaseUrl: ws.origin }; +} + +export async function readCredential(target: ServerTarget): Promise { + if (process.env.TUI3_TOKEN) { + return { httpBaseUrl: target.httpBaseUrl, bearerToken: process.env.TUI3_TOKEN, issuedAt: "" }; + } + try { + const all: StoredCredential[] = JSON.parse(await readFile(credentialPath(), "utf8")); + return all.find((c) => c.httpBaseUrl === target.httpBaseUrl); + } catch { + return undefined; + } +} + +async function writeCredential(credential: StoredCredential): Promise { + const path = credentialPath(); + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + let all: StoredCredential[] = []; + try { + all = JSON.parse(await readFile(path, "utf8")); + } catch {} + all = [...all.filter((c) => c.httpBaseUrl !== credential.httpBaseUrl), credential]; + await writeFile(path, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 }); + await chmod(path, 0o600); +} + +/** + * Issues a scoped bearer session through the local `t3` CLI, which can mint one + * because it shares the server's data directory. Remote servers need TUI3_TOKEN. + */ +export async function issueLocalCredential(target: ServerTarget): Promise { + const t3 = process.env.TUI3_T3_BIN ?? join(t3Home(), "bin", "t3"); + const args = ["auth", "session", "issue", "--label", "tui3", "--token-only"]; + for (const scope of TUI3_SCOPES) args.push("--scope", scope); + const proc = Bun.spawn([t3, ...args], { stdout: "pipe", stderr: "pipe" }); + const [stdout, stderr, code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + const token = stdout.trim().split("\n").pop()?.trim(); + if (code !== 0 || !token) { + throw new Error(`\`t3 auth session issue\` failed (exit ${code}): ${stderr.trim() || stdout.trim()}`); + } + const credential = { httpBaseUrl: target.httpBaseUrl, bearerToken: token, issuedAt: new Date().toISOString() }; + await writeCredential(credential); + return credential; +} + +export class UnauthorizedError extends Error {} + +/** Exchanges the bearer token for a one-shot ticket and builds the socket URL. */ +export async function resolveSocketUrl( + target: ServerTarget, + credential: StoredCredential, + protocol: { param: string; version: number }, +): Promise { + const response = await fetch(`${target.httpBaseUrl}/api/auth/websocket-ticket/rpc`, { + method: "POST", + headers: { authorization: `Bearer ${credential.bearerToken}` }, + }); + if (response.status === 401 || response.status === 403) { + throw new UnauthorizedError(`T3 Code rejected tui3's token (${response.status}).`); + } + if (!response.ok) { + throw new Error(`WebSocket ticket request failed: ${response.status} ${await response.text()}`); + } + const { ticket } = (await response.json()) as { ticket: string }; + const url = new URL("/ws", target.wsBaseUrl); + url.searchParams.set("wsTicket", ticket); + url.searchParams.set(protocol.param, String(protocol.version)); + url.searchParams.set("clientSurface", "tui3"); + url.searchParams.set("connectionMethod", "direct"); + return url.toString(); +} diff --git a/src/client/rpc.ts b/src/client/rpc.ts new file mode 100644 index 0000000..983134d --- /dev/null +++ b/src/client/rpc.ts @@ -0,0 +1,71 @@ +import { + ORCHESTRATION_PROTOCOL_QUERY_PARAM, + ORCHESTRATION_PROTOCOL_VERSION, + WsRpcGroup, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schedule from "effect/Schedule"; +import type * as Scope from "effect/Scope"; +import * as RpcClient from "effect/rpc/RpcClient"; +import * as RpcSerialization from "effect/rpc/RpcSerialization"; +import * as Socket from "effect/socket/Socket"; + +import { + issueLocalCredential, + readCredential, + resolveLocalServer, + resolveSocketUrl, + UnauthorizedError, + type ServerTarget, +} from "./auth.ts"; + +const makeProtocolClient = RpcClient.make(WsRpcGroup); +export type T3Rpc = Effect.Success; + +export interface Connection { + readonly rpc: T3Rpc; + readonly target: ServerTarget; +} + +const socketUrlFor = async (target: ServerTarget) => { + const protocol = { param: ORCHESTRATION_PROTOCOL_QUERY_PARAM, version: ORCHESTRATION_PROTOCOL_VERSION }; + const existing = await readCredential(target); + if (existing) { + try { + return await resolveSocketUrl(target, existing, protocol); + } catch (error) { + // A revoked or expired token falls through to a fresh one; TUI3_TOKEN never does. + if (!(error instanceof UnauthorizedError) || process.env.TUI3_TOKEN) throw error; + } + } + return resolveSocketUrl(target, await issueLocalCredential(target), protocol); +}; + +/** Opens one authenticated socket to the T3 Code server for the life of the scope. */ +export const connect: Effect.Effect = Effect.gen(function* () { + const target = yield* Effect.tryPromise({ try: resolveLocalServer, catch: toError }); + const socketUrl = yield* Effect.tryPromise({ try: () => socketUrlFor(target), catch: toError }); + const protocol = Layer.effect( + RpcClient.Protocol, + RpcClient.makeProtocolSocket({ + pingTimeout: "15 seconds", + retryTransientErrors: false, + retryPolicy: Schedule.recurs(0), + }), + ).pipe( + Layer.provide( + Layer.mergeAll( + Socket.layerWebSocket(socketUrl, { openTimeout: "15 seconds" }).pipe( + Layer.provide(Socket.layerWebSocketConstructorGlobal), + ), + RpcSerialization.layerJson, + ), + ), + ); + const context = yield* Layer.build(protocol); + const rpc = yield* makeProtocolClient.pipe(Effect.provide(context)); + return { rpc, target }; +}); + +const toError = (cause: unknown) => (cause instanceof Error ? cause : new Error(String(cause))); diff --git a/src/client/session.ts b/src/client/session.ts new file mode 100644 index 0000000..ae0efaa --- /dev/null +++ b/src/client/session.ts @@ -0,0 +1,222 @@ +import { + CommandId, + MessageId, + ORCHESTRATION_V2_WS_METHODS, + type OrchestrationV2Command, + type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadProjection, + type ProviderApprovalDecision, + type RuntimeRequestId, + type ThreadId, +} from "@t3tools/contracts"; +import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import { applyShellStreamEvent, mergeShellSnapshotProjects } from "../../vendor/t3code/packages/client-runtime/src/state/shellReducer.ts"; +import { connect, type Connection } from "./rpc.ts"; + +export type ConnectionStatus = + | { readonly type: "connecting" } + | { readonly type: "live" } + | { readonly type: "error"; readonly message: string }; + +export interface ShellState { + readonly status: ConnectionStatus; + readonly snapshot: OrchestrationV2ShellSnapshot | null; + readonly serverUrl: string | null; +} + +export interface ThreadState { + readonly status: "loading" | "live" | "error"; + readonly projection: OrchestrationV2ThreadProjection | null; + readonly error?: string; +} + +type Listener = (value: T) => void; + +/** + * One connection to T3 Code: a live shell (projects and threads) plus on-demand + * thread subscriptions, exposed as plain listeners for the UI. + */ +export class T3Session { + private scope: Scope.Closeable | null = null; + private connection: Connection | null = null; + private shell: ShellState = { status: { type: "connecting" }, snapshot: null, serverUrl: null }; + private readonly shellListeners = new Set>(); + private readonly threads = new Map>; fiber: Fiber.Fiber | null }>(); + + async start(): Promise { + const scope = Effect.runSync(Scope.make()); + this.scope = scope; + try { + this.connection = await Effect.runPromise(connect.pipe(Scope.provide(scope))); + } catch (error) { + this.setShell({ status: { type: "error", message: messageOf(error) } }); + return; + } + this.setShell({ serverUrl: this.connection.target.httpBaseUrl }); + this.runInScope(this.shellStream()); + } + + async stop(): Promise { + const scope = this.scope; + this.scope = null; + if (scope) await Effect.runPromise(Scope.close(scope, Exit.void)); + } + + getShell(): ShellState { + return this.shell; + } + + onShell(listener: Listener): () => void { + this.shellListeners.add(listener); + listener(this.shell); + return () => this.shellListeners.delete(listener); + } + + /** Subscribes to one thread's live projection; the stream stops when the last listener leaves. */ + watchThread(threadId: ThreadId, listener: Listener): () => void { + let entry = this.threads.get(threadId); + if (!entry) { + entry = { state: { status: "loading", projection: null }, listeners: new Set(), fiber: null }; + this.threads.set(threadId, entry); + entry.fiber = this.runInScope(this.threadStream(threadId)); + } + entry.listeners.add(listener); + listener(entry.state); + return () => { + const current = this.threads.get(threadId); + if (!current) return; + current.listeners.delete(listener); + if (current.listeners.size === 0) { + this.threads.delete(threadId); + if (current.fiber) Effect.runFork(Fiber.interrupt(current.fiber)); + } + }; + } + + sendMessage(threadId: ThreadId, text: string, mode: "queue" | "steer" = "queue"): Promise { + const commandId = newCommandId(); + const running = this.threads.get(threadId)?.state.projection?.runs.findLast((run) => isActiveRun(run.status)); + return this.dispatch({ + type: "message.dispatch", + commandId, + threadId, + messageId: MessageId.make(commandId), + text, + attachments: [], + dispatchMode: + mode === "steer" && running + ? { type: "steer_active", targetRunId: running.id } + : { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + } + + respond(threadId: ThreadId, requestId: RuntimeRequestId, decision: ProviderApprovalDecision): Promise { + return this.dispatch({ type: "runtime-request.respond", commandId: newCommandId(), threadId, requestId, decision }); + } + + /** Stops whatever the thread is running, the way the GUI's stop button does. */ + stopThread(threadId: ThreadId): Promise { + return this.dispatch({ type: "thread.stop", commandId: newCommandId(), threadId }); + } + + private async dispatch(command: OrchestrationV2Command): Promise { + const rpc = this.requireConnection().rpc; + await Effect.runPromise(rpc[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](command)); + } + + private shellStream() { + const rpc = this.requireConnection().rpc; + return rpc[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({ requestCompletionMarker: true, omitIdleSubagents: true, omitOlderSettled: true }).pipe( + Stream.runForEach((item) => + Effect.sync(() => { + const previous = this.shell.snapshot; + switch (item.kind) { + case "synchronized": + this.setShell({ status: { type: "live" } }); + return; + case "snapshot": + // Follow-up snapshots that carry resolved repository roots only enrich projects. + this.setShell({ + snapshot: + item.resolvedRepositoryIdentityRoots === undefined + ? item.snapshot + : mergeShellSnapshotProjects(previous, item.snapshot, { resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots }), + }); + return; + default: + if (previous) this.setShell({ snapshot: applyShellStreamEvent(previous, item) }); + } + }), + ), + Effect.catchCause((cause) => Effect.sync(() => this.setShell({ status: { type: "error", message: prettyCause(cause) } }))), + ); + } + + private threadStream(threadId: ThreadId) { + const rpc = this.requireConnection().rpc; + return rpc[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({ threadId, requestCompletionMarker: true }).pipe( + Stream.runForEach((item) => + Effect.sync(() => { + const entry = this.threads.get(threadId); + if (!entry) return; + switch (item.kind) { + case "synchronized": + this.setThread(threadId, { status: "live" }); + return; + case "snapshot": + this.setThread(threadId, { projection: item.projection }); + return; + case "event": + this.setThread(threadId, { projection: applyOrchestrationV2ProjectionEvent(entry.state.projection, item.event) }); + return; + case "unknown-event": + return; + } + }), + ), + Effect.catchCause((cause) => Effect.sync(() => this.setThread(threadId, { status: "error", error: prettyCause(cause) }))), + ); + } + + private runInScope(effect: Effect.Effect): Fiber.Fiber { + const scope = this.scope; + if (!scope) throw new Error("Session is not started."); + return Effect.runFork(effect.pipe(Effect.forkIn(scope), Effect.flatMap(Fiber.join))); + } + + private requireConnection(): Connection { + if (!this.connection) throw new Error("Not connected to T3 Code."); + return this.connection; + } + + private setShell(patch: Partial): void { + this.shell = { ...this.shell, ...patch }; + for (const listener of this.shellListeners) listener(this.shell); + } + + private setThread(threadId: ThreadId, patch: Partial): void { + const entry = this.threads.get(threadId); + if (!entry) return; + entry.state = { ...entry.state, ...patch }; + for (const listener of entry.listeners) listener(entry.state); + } +} + +const isActiveRun = (status: string) => status === "preparing" || status === "starting" || status === "running" || status === "waiting"; + +const newCommandId = () => CommandId.make(crypto.randomUUID()); + +const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error)); + +const prettyCause = (cause: unknown) => { + const text = String((cause as { toString?: () => string })?.toString?.() ?? cause); + return text.split("\n")[0] ?? text; +}; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..4199002 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "Preserve", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "jsxImportSource": "@opentui/react", + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true, + "types": [ + "bun" + ] + }, + "include": [ + "src", + "test" + ] +} \ No newline at end of file diff --git a/vendor/t3code b/vendor/t3code new file mode 160000 index 0000000..97e35bc --- /dev/null +++ b/vendor/t3code @@ -0,0 +1 @@ +Subproject commit 97e35bcf23e4dcf34c2dcffadd37c08db0e01e52