repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ui/runtime.ts
RawFile outline
- UiRuntimeStatus line 27
- UiRuntime line 37
- CreateUiRuntimeOptions line 45
- createUiRuntime line 57
- publish line 74
- onState line 93
- onEvent line 99
- currentStatus line 125
- redrawQr line 154
- open line 160
- stop line 164
- handleBrowserMessage line 178
- BrowserMessage line 293
- isBrowserMessage line 319
- type line 321
- text line 323
- events line 325
- clientId line 332
- id line 334
- widgetId line 337
- label line 338
- widgetId line 342
- text line 343
- widgetId line 347
- message line 348
- responseInput line 358
- writeSmokeUrl line 366
- mapRpcState line 373
- normalizeRpcEvent line 379
- assistantText line 406
- content line 408
- text line 414
- text line 415
- isRpcMessageUpdate line 421
- type line 427
- assistantMessageEvent line 428
- isRpcToolEvent line 433
- type line 439
- type line 440
- toolCallId line 441
- toolName line 442
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import {
abortCurrent,
cycleModel,
runBash,
runSlashCommand,
sendPrompt,
} from "./command-adapter";
import { parseComposerInput } from "./composer";
import { EventStore } from "./events";
import {
extensionUiEventFromRequest,
extensionUiResponseCommand,
isExtensionUiRequest,
} from "./extension-ui";
import { LifecycleTracker } from "./lifecycle";
import { chooseLanAddress } from "./network";
import { openBrowser } from "./open";
import { renderQr } from "./qr";
import { type RpcClient, type StartRpcOptions, startRpc } from "./rpc";
import { startUiServer, type UiServer, type UiServerState } from "./server";
import { seedUiSession, type UiSeedSessionManager } from "./session-seed";
import { TelemetryAggregator, type TelemetryEvent } from "./telemetry";
import { renderUiWidget } from "./terminal-widget";
export type UiRuntimeStatus = {
active: boolean;
url?: string;
state: UiServerState | "starting" | "stopped" | "error";
clients: number;
rpcState?: string;
sessionPath?: string;
lastError?: string;
};
export type UiRuntime = {
status(): UiRuntimeStatus;
widgetLines(): string[];
redrawQr(): Promise<void>;
open(): Promise<void>;
stop(reason: string): Promise<void>;
};
export type CreateUiRuntimeOptions = {
sessionLabel: string;
cwd?: string;
address?: string;
preferredPort?: number;
openBrowser?: boolean;
onChange?: () => void;
sessionManager?: UiSeedSessionManager;
startRpcBridge?: (options: StartRpcOptions) => RpcClient;
events?: EventStore;
};
export async function createUiRuntime(
options: CreateUiRuntimeOptions,
): Promise<UiRuntime> {
let state: UiRuntimeStatus = { active: false, state: "starting", clients: 0 };
let qr = "";
let server: UiServer | undefined;
let rpc: RpcClient | undefined;
let sessionPath: string | undefined;
let rpcState: string | undefined;
const events = options.events ?? new EventStore();
const telemetry = new TelemetryAggregator();
const lifecycle = new LifecycleTracker();
const lifecycleTimer = setInterval(() => {
for (const event of lifecycle.check()) publish(event);
}, 5_000);
if (typeof lifecycleTimer.unref === "function") lifecycleTimer.unref();
const publish = (input: Parameters<EventStore["append"]>[0]) => {
const event = events.append(input);
server?.publish(event);
return event;
};
if (options.sessionManager) {
const seed = seedUiSession({
cwd: options.cwd ?? process.cwd(),
sessionManager: options.sessionManager,
});
sessionPath = seed.path;
if (seed.warning)
publish({ type: "log", level: "warning", message: seed.warning });
publish({ type: "state", state: "rpc-starting" });
rpcState = "starting";
rpc = (options.startRpcBridge ?? startRpc)({
sessionPath,
cwd: options.cwd ?? process.cwd(),
onState(next) {
rpcState = next;
publish({ type: "state", state: mapRpcState(next) });
state = currentStatus();
options.onChange?.();
},
onEvent(event) {
const normalized = normalizeRpcEvent(event);
if (normalized) publish(normalized);
},
});
}
const address = options.address ?? chooseLanAddress();
server = await startUiServer({
address,
preferredPort: options.preferredPort,
events,
snapshotStatus: rpcState ? mapRpcState(rpcState) : "waiting",
onBrowserMessage: async (message) => {
await handleBrowserMessage(message, rpc, publish, telemetry, lifecycle);
},
onClientState: () => {
state = currentStatus();
options.onChange?.();
},
});
qr = await renderQr(server.publicUrl);
writeSmokeUrl(server.publicUrl);
state = currentStatus();
if (options.openBrowser !== false) await openBrowser(server.baseUrl);
function currentStatus(): UiRuntimeStatus {
if (!server) return { active: false, state: "stopped", clients: 0 };
return {
active: server.state() !== "stopped",
url: server.baseUrl,
state: server.state(),
clients: server.clients(),
rpcState,
sessionPath,
};
}
return {
status: () => state,
widgetLines: () => {
if (!server || !state.url) return [];
return renderUiWidget({
url: state.url,
qr,
state: state.state,
sessionLabel: options.sessionLabel,
clients: state.clients,
rpcState: state.rpcState,
sessionPath: state.sessionPath
? path.basename(state.sessionPath)
: undefined,
lastError: state.lastError,
});
},
async redrawQr() {
if (!server) return;
qr = await renderQr(server.publicUrl);
state = currentStatus();
options.onChange?.();
},
async open() {
if (!server) return;
await openBrowser(server.baseUrl);
},
async stop(reason: string) {
clearInterval(lifecycleTimer);
const currentServer = server;
const currentRpc = rpc;
server = undefined;
rpc = undefined;
state = { active: false, state: "stopped", clients: 0 };
options.onChange?.();
await currentRpc?.close(reason);
if (currentServer) await currentServer.close(reason);
},
};
}
async function handleBrowserMessage(
message: unknown,
rpc: RpcClient | undefined,
publish: (input: Parameters<EventStore["append"]>[0]) => unknown,
telemetry: TelemetryAggregator,
lifecycle: LifecycleTracker,
): Promise<void> {
if (!rpc || !isBrowserMessage(message)) return;
if (message.type === "abort") {
await abortCurrent(rpc);
publish({
type: "state",
state: "rpc-connected",
message: "abort requested",
});
return;
}
if (message.type === "cycle_model" || message.type === "cycle-model") {
await cycleModel(rpc);
publish({
type: "state",
state: "rpc-connected",
message: "model cycle requested",
});
return;
}
if (message.type === "toggle-expand") {
publish({ type: "log", level: "info", message: "toggle expand requested" });
return;
}
if (message.type === "lifecycle_heartbeat") {
lifecycle.heartbeat(message.clientId);
return;
}
if (message.type === "lifecycle_reconnect") {
publish(lifecycle.reconnect(message.clientId));
return;
}
if (message.type === "lifecycle_close") {
publish(lifecycle.close(message.clientId));
return;
}
if (message.type === "lifecycle_pagehide") {
publish(lifecycle.pagehide(message.clientId));
return;
}
if (message.type === "telemetry_batch") {
for (const event of message.events) telemetry.add(event);
publish({
type: "log",
level: "info",
message: "browser digest will be sent",
});
return;
}
if (message.type === "ui_response") {
await rpc.send(
extensionUiResponseCommand(message.id, responseInput(message)),
);
return;
}
if (message.type === "widget_action") {
publish({
type: "widget_action",
widgetId: message.widgetId,
label: message.label,
payload: message.payload,
});
return;
}
if (message.type === "widget_prompt") {
const text = `[widget ${message.widgetId}] ${message.text}`;
publish({
type: "widget_action",
widgetId: message.widgetId,
label: "prompt",
payload: { text: message.text },
});
await sendPrompt(rpc, text);
return;
}
if (message.type === "widget_notify") {
publish({
type: "ui_notify",
requestId: message.widgetId,
message: message.message,
});
return;
}
if (message.type === "widget_error") {
publish({
type: "widget_error",
widgetId: message.widgetId,
message: message.message,
});
return;
}
const parsed = parseComposerInput(message.text);
if (parsed.kind === "bash") {
publish({ type: "message", role: "user", text: message.text });
await runBash(rpc, parsed.command, parsed.excludeFromContext);
return;
}
if (parsed.kind === "slash") {
publish({ type: "message", role: "user", text: parsed.text });
await runSlashCommand(rpc, parsed.command, parsed.args);
return;
}
publish({ type: "message", role: "user", text: parsed.text });
await sendPrompt(rpc, parsed.text, {
digest: () => telemetry.digest(),
clearDigest: () => telemetry.clear(),
});
}
type BrowserMessage =
| { type: "prompt"; text: string }
| { type: "abort" }
| { type: "cycle_model" }
| { type: "cycle-model" }
| { type: "toggle-expand" }
| { type: "telemetry_batch"; events: TelemetryEvent[] }
| { type: "lifecycle_heartbeat"; clientId: string }
| { type: "lifecycle_reconnect"; clientId: string }
| { type: "lifecycle_close"; clientId: string }
| { type: "lifecycle_pagehide"; clientId: string }
| ({ type: "ui_response"; id: string } & (
| { value: string }
| { confirmed: boolean }
| { cancelled: true }
))
| {
type: "widget_action";
widgetId: string;
label: string;
payload?: unknown;
}
| { type: "widget_prompt"; widgetId: string; text: string }
| { type: "widget_notify"; widgetId: string; message: string }
| { type: "widget_error"; widgetId: string; message: string };
function isBrowserMessage(value: unknown): value is BrowserMessage {
if (!value || typeof value !== "object") return false;
const type = (value as { type?: unknown }).type;
if (type === "prompt")
return typeof (value as { text?: unknown }).text === "string";
if (type === "telemetry_batch")
return Array.isArray((value as { events?: unknown }).events);
if (
type === "lifecycle_heartbeat" ||
type === "lifecycle_reconnect" ||
type === "lifecycle_close" ||
type === "lifecycle_pagehide"
)
return typeof (value as { clientId?: unknown }).clientId === "string";
if (type === "ui_response")
return typeof (value as { id?: unknown }).id === "string";
if (type === "widget_action")
return (
typeof (value as { widgetId?: unknown }).widgetId === "string" &&
typeof (value as { label?: unknown }).label === "string"
);
if (type === "widget_prompt")
return (
typeof (value as { widgetId?: unknown }).widgetId === "string" &&
typeof (value as { text?: unknown }).text === "string"
);
if (type === "widget_notify" || type === "widget_error")
return (
typeof (value as { widgetId?: unknown }).widgetId === "string" &&
typeof (value as { message?: unknown }).message === "string"
);
return (
type === "abort" ||
type === "cycle_model" ||
type === "cycle-model" ||
type === "toggle-expand"
);
}
function responseInput(
message: Extract<BrowserMessage, { type: "ui_response" }>,
) {
if ("value" in message) return { value: message.value };
if ("confirmed" in message) return { confirmed: message.confirmed };
return { cancelled: true as const };
}
function writeSmokeUrl(url: string): void {
const target = process.env.PI_UI_SMOKE_URL_FILE;
if (!target) return;
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, `${url}\n`, { encoding: "utf8" });
}
function mapRpcState(state: string) {
if (state === "connected") return "rpc-connected";
if (state === "exit") return "rpc-dead";
return "rpc-starting";
}
export function normalizeRpcEvent(
event: unknown,
): Parameters<EventStore["append"]>[0] | undefined {
if (isExtensionUiRequest(event)) return extensionUiEventFromRequest(event);
if (isRpcMessageUpdate(event)) {
return {
type: "message",
role: "assistant",
text: assistantText(event.message),
streamId: "assistant-stream",
};
}
if (isRpcToolEvent(event)) {
return {
type: "tool",
phase: event.type.endsWith("start")
? "start"
: event.type.endsWith("end")
? "end"
: "update",
toolCallId: event.toolCallId,
name: event.toolName,
};
}
return undefined;
}
function assistantText(message: unknown): string {
if (!message || typeof message !== "object") return "";
const content = (message as { content?: unknown }).content;
if (!Array.isArray(content)) return "";
return content
.map((item) =>
item &&
typeof item === "object" &&
typeof (item as { text?: unknown }).text === "string"
? (item as { text: string }).text
: "",
)
.join("");
}
function isRpcMessageUpdate(
event: unknown,
): event is { message: unknown; assistantMessageEvent: { delta: string } } {
return (
!!event &&
typeof event === "object" &&
(event as { type?: unknown }).type === "message_update" &&
typeof (event as { assistantMessageEvent?: { delta?: unknown } })
.assistantMessageEvent?.delta === "string"
);
}
function isRpcToolEvent(
event: unknown,
): event is { type: string; toolCallId: string; toolName: string } {
return (
!!event &&
typeof event === "object" &&
typeof (event as { type?: unknown }).type === "string" &&
(event as { type: string }).type.startsWith("tool_execution_") &&
typeof (event as { toolCallId?: unknown }).toolCallId === "string" &&
typeof (event as { toolName?: unknown }).toolName === "string"
);
}