Connect to T3 Code: auth, RPC client, shell and thread session

This commit is contained in:
Callum Alpass committed 2026-11-02 16:45:27 +11:00
commit c93244e7f4
12 files changed
+620

No files matched your search

+119
View File
@@ -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<ServerTarget> {
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<StoredCredential | undefined> {
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<void> {
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<StoredCredential> {
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<string> {
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();
}
+71
View File
@@ -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<typeof makeProtocolClient>;
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<Connection, Error, Scope.Scope> = 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)));
+222
View File
@@ -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<T> = (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<Listener<ShellState>>();
private readonly threads = new Map<ThreadId, { state: ThreadState; listeners: Set<Listener<ThreadState>>; fiber: Fiber.Fiber<unknown, unknown> | null }>();
async start(): Promise<void> {
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<void> {
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<ShellState>): () => 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<ThreadState>): () => 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<void> {
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<void> {
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<void> {
return this.dispatch({ type: "thread.stop", commandId: newCommandId(), threadId });
}
private async dispatch(command: OrchestrationV2Command): Promise<void> {
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<A, E>(effect: Effect.Effect<A, E>): Fiber.Fiber<unknown, unknown> {
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<ShellState>): void {
this.shell = { ...this.shell, ...patch };
for (const listener of this.shellListeners) listener(this.shell);
}
private setThread(threadId: ThreadId, patch: Partial<ThreadState>): 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;
};