mirror of
https://github.com/harivansh-afk/sandbox-agent.git
synced 2026-04-15 05:02:11 +00:00
feat: add process management support (#207)
* feat: improve inspector UI for processes and fix PTY terminal
- Simplify ProcessRunTab layout: compact form with collapsible Advanced section for timeout/maxOutputBytes
- Rewrite ProcessesTab: collapsible create form, lightweight list items with status dots, clean detail panel with tabs
- Extract error details: use problem.detail instead of generic "Stream Error" title for better error messages
- Fix GhosttyTerminal binary frame parsing: handle server's binary ArrayBuffer control frames (ready/exit/error)
- Enable WebSocket proxying in Vite dev server with ws: true
- Set TERM=xterm-256color default for TTY processes so tools like tmux, vim, htop work out of the box
- Remove orange gradient background from terminal container for cleaner look
- Remove orange left border from selected process list items
- Update inspector CSS with new process/terminal styles
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
* fix: address review issues and add processes documentation
- Fix unstable onExit callback in ProcessesTab (useCallback)
- Fix SSE follow stream race condition (subscribe before history read)
- Update inspector.mdx with new process management features
- Change observability icon to avoid conflict with processes
- Add docs/processes.mdx covering the full process management API
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: simplify processes doc — rename sections, remove low-level protocol
- Rename "Interactive terminals" to "Terminals" with "Connect to a terminal" sub-heading
- Add TTY process creation step at top of Terminals section
- Remove low-level WebSocket protocol table and raw WebSocket example
- Keep browser terminal emulator reference with Ghostty link
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: update GhosttyTerminal permalink to latest commit
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: use main branch permalink for GhosttyTerminal reference
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: refine process API — WebSocket binary protocol, SDK terminal session, updated tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: update GhosttyTerminal permalink to 636eefb
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* inspector: use websocket terminal API
* sdk: restore high-level terminal session
* docs: update inspector terminal permalink
* inspector: update run once placeholder
* Fix lazy install v1 API test fixture
* Add reusable React terminal component
* Fix terminal WebSocket ready state checks
---------
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
e7656d78f0
commit
febe8601f6
28 changed files with 2098 additions and 83 deletions
40
sdks/react/package.json
Normal file
40
sdks/react/package.json
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
{
|
||||
"name": "@sandbox-agent/react",
|
||||
"version": "0.2.2",
|
||||
"description": "React components for Sandbox Agent frontend integrations",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/rivet-dev/sandbox-agent"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18.3.1",
|
||||
"sandbox-agent": "^0.2.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"ghostty-web": "^0.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.3",
|
||||
"react": "^18.3.1",
|
||||
"sandbox-agent": "workspace:*",
|
||||
"tsup": "^8.0.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
271
sdks/react/src/ProcessTerminal.tsx
Normal file
271
sdks/react/src/ProcessTerminal.tsx
Normal file
|
|
@ -0,0 +1,271 @@
|
|||
"use client";
|
||||
|
||||
import type { FitAddon as GhosttyFitAddon, Terminal as GhosttyTerminal } from "ghostty-web";
|
||||
import type { CSSProperties } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { SandboxAgent, TerminalErrorStatus, TerminalExitStatus } from "sandbox-agent";
|
||||
|
||||
type ConnectionState = "connecting" | "ready" | "closed" | "error";
|
||||
|
||||
export type ProcessTerminalClient = Pick<SandboxAgent, "connectProcessTerminal">;
|
||||
|
||||
export interface ProcessTerminalProps {
|
||||
client: ProcessTerminalClient;
|
||||
processId: string;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
terminalStyle?: CSSProperties;
|
||||
height?: number | string;
|
||||
onExit?: (status: TerminalExitStatus) => void;
|
||||
onError?: (error: TerminalErrorStatus | Error) => void;
|
||||
}
|
||||
|
||||
const terminalTheme = {
|
||||
background: "#09090b",
|
||||
foreground: "#f4f4f5",
|
||||
cursor: "#f97316",
|
||||
cursorAccent: "#09090b",
|
||||
selectionBackground: "#27272a",
|
||||
black: "#18181b",
|
||||
red: "#f87171",
|
||||
green: "#4ade80",
|
||||
yellow: "#fbbf24",
|
||||
blue: "#60a5fa",
|
||||
magenta: "#f472b6",
|
||||
cyan: "#22d3ee",
|
||||
white: "#e4e4e7",
|
||||
brightBlack: "#3f3f46",
|
||||
brightRed: "#fb7185",
|
||||
brightGreen: "#86efac",
|
||||
brightYellow: "#fde047",
|
||||
brightBlue: "#93c5fd",
|
||||
brightMagenta: "#f9a8d4",
|
||||
brightCyan: "#67e8f9",
|
||||
brightWhite: "#fafafa",
|
||||
};
|
||||
|
||||
const shellStyle: CSSProperties = {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
border: "1px solid rgba(255, 255, 255, 0.1)",
|
||||
borderRadius: 10,
|
||||
background: "rgba(0, 0, 0, 0.3)",
|
||||
};
|
||||
|
||||
const statusBarStyle: CSSProperties = {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: 12,
|
||||
padding: "8px 12px",
|
||||
borderBottom: "1px solid rgba(255, 255, 255, 0.08)",
|
||||
background: "rgba(0, 0, 0, 0.2)",
|
||||
color: "rgba(244, 244, 245, 0.86)",
|
||||
fontSize: 11,
|
||||
lineHeight: 1.4,
|
||||
};
|
||||
|
||||
const hostBaseStyle: CSSProperties = {
|
||||
minHeight: 320,
|
||||
padding: 10,
|
||||
overflow: "hidden",
|
||||
};
|
||||
|
||||
const exitCodeStyle: CSSProperties = {
|
||||
fontFamily: "ui-monospace, SFMono-Regular, SF Mono, Menlo, monospace",
|
||||
opacity: 0.72,
|
||||
};
|
||||
|
||||
const getStatusColor = (state: ConnectionState): string => {
|
||||
switch (state) {
|
||||
case "ready":
|
||||
return "#4ade80";
|
||||
case "error":
|
||||
return "#fb7185";
|
||||
case "closed":
|
||||
return "#fbbf24";
|
||||
default:
|
||||
return "rgba(244, 244, 245, 0.72)";
|
||||
}
|
||||
};
|
||||
|
||||
export const ProcessTerminal = ({
|
||||
client,
|
||||
processId,
|
||||
className,
|
||||
style,
|
||||
terminalStyle,
|
||||
height = 360,
|
||||
onExit,
|
||||
onError,
|
||||
}: ProcessTerminalProps) => {
|
||||
const hostRef = useRef<HTMLDivElement | null>(null);
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>("connecting");
|
||||
const [statusMessage, setStatusMessage] = useState("Connecting to PTY...");
|
||||
const [exitCode, setExitCode] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let terminal: GhosttyTerminal | null = null;
|
||||
let fitAddon: GhosttyFitAddon | null = null;
|
||||
let session: ReturnType<ProcessTerminalClient["connectProcessTerminal"]> | null = null;
|
||||
let resizeRaf = 0;
|
||||
let removeDataListener: { dispose(): void } | null = null;
|
||||
let removeResizeListener: { dispose(): void } | null = null;
|
||||
|
||||
setConnectionState("connecting");
|
||||
setStatusMessage("Connecting to PTY...");
|
||||
setExitCode(null);
|
||||
|
||||
const syncSize = () => {
|
||||
if (!terminal || !session) {
|
||||
return;
|
||||
}
|
||||
|
||||
session.resize({
|
||||
cols: terminal.cols,
|
||||
rows: terminal.rows,
|
||||
});
|
||||
};
|
||||
|
||||
const connect = async () => {
|
||||
try {
|
||||
const ghostty = await import("ghostty-web");
|
||||
await ghostty.init();
|
||||
|
||||
if (cancelled || !hostRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
terminal = new ghostty.Terminal({
|
||||
allowTransparency: true,
|
||||
cursorBlink: true,
|
||||
cursorStyle: "block",
|
||||
fontFamily: "ui-monospace, SFMono-Regular, SF Mono, Menlo, monospace",
|
||||
fontSize: 13,
|
||||
smoothScrollDuration: 90,
|
||||
theme: terminalTheme,
|
||||
});
|
||||
fitAddon = new ghostty.FitAddon();
|
||||
|
||||
terminal.open(hostRef.current);
|
||||
const terminalRoot = hostRef.current.firstElementChild;
|
||||
if (terminalRoot instanceof HTMLElement) {
|
||||
terminalRoot.style.width = "100%";
|
||||
terminalRoot.style.height = "100%";
|
||||
}
|
||||
terminal.loadAddon(fitAddon);
|
||||
fitAddon.fit();
|
||||
fitAddon.observeResize();
|
||||
terminal.focus();
|
||||
|
||||
removeDataListener = terminal.onData((data) => {
|
||||
session?.sendInput(data);
|
||||
});
|
||||
|
||||
removeResizeListener = terminal.onResize(() => {
|
||||
if (resizeRaf) {
|
||||
window.cancelAnimationFrame(resizeRaf);
|
||||
}
|
||||
resizeRaf = window.requestAnimationFrame(syncSize);
|
||||
});
|
||||
|
||||
const nextSession = client.connectProcessTerminal(processId);
|
||||
session = nextSession;
|
||||
|
||||
nextSession.onReady((frame) => {
|
||||
if (cancelled || frame.type !== "ready") {
|
||||
return;
|
||||
}
|
||||
|
||||
setConnectionState("ready");
|
||||
setStatusMessage("Connected");
|
||||
syncSize();
|
||||
});
|
||||
|
||||
nextSession.onData((bytes) => {
|
||||
if (cancelled || !terminal) {
|
||||
return;
|
||||
}
|
||||
terminal.write(bytes);
|
||||
});
|
||||
|
||||
nextSession.onExit((frame) => {
|
||||
if (cancelled || frame.type !== "exit") {
|
||||
return;
|
||||
}
|
||||
|
||||
setConnectionState("closed");
|
||||
setExitCode(frame.exitCode ?? null);
|
||||
setStatusMessage(
|
||||
frame.exitCode == null ? "Process exited." : `Process exited with code ${frame.exitCode}.`
|
||||
);
|
||||
onExit?.(frame);
|
||||
});
|
||||
|
||||
nextSession.onError((error) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
setConnectionState("error");
|
||||
setStatusMessage(error instanceof Error ? error.message : error.message);
|
||||
onError?.(error);
|
||||
});
|
||||
|
||||
nextSession.onClose(() => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
setConnectionState((current) => (current === "error" ? current : "closed"));
|
||||
setStatusMessage((current) => (current === "Connected" ? "Terminal disconnected." : current));
|
||||
});
|
||||
} catch (error) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextError = error instanceof Error ? error : new Error("Failed to initialize terminal.");
|
||||
setConnectionState("error");
|
||||
setStatusMessage(nextError.message);
|
||||
onError?.(nextError);
|
||||
}
|
||||
};
|
||||
|
||||
void connect();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (resizeRaf) {
|
||||
window.cancelAnimationFrame(resizeRaf);
|
||||
}
|
||||
removeDataListener?.dispose();
|
||||
removeResizeListener?.dispose();
|
||||
session?.close();
|
||||
terminal?.dispose();
|
||||
};
|
||||
}, [client, onError, onExit, processId]);
|
||||
|
||||
return (
|
||||
<div className={className} style={{ ...shellStyle, ...style }}>
|
||||
<div style={statusBarStyle}>
|
||||
<span style={{ color: getStatusColor(connectionState) }}>{statusMessage}</span>
|
||||
{exitCode != null ? <span style={exitCodeStyle}>exit={exitCode}</span> : null}
|
||||
</div>
|
||||
<div
|
||||
ref={hostRef}
|
||||
role="presentation"
|
||||
style={{
|
||||
...hostBaseStyle,
|
||||
height,
|
||||
...terminalStyle,
|
||||
}}
|
||||
onClick={() => {
|
||||
hostRef.current?.querySelector("textarea")?.focus();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
6
sdks/react/src/index.ts
Normal file
6
sdks/react/src/index.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export { ProcessTerminal } from "./ProcessTerminal.tsx";
|
||||
|
||||
export type {
|
||||
ProcessTerminalClient,
|
||||
ProcessTerminalProps,
|
||||
} from "./ProcessTerminal.tsx";
|
||||
17
sdks/react/tsconfig.json
Normal file
17
sdks/react/tsconfig.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
10
sdks/react/tsup.config.ts
Normal file
10
sdks/react/tsup.config.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm"],
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
target: "es2022",
|
||||
});
|
||||
|
|
@ -56,6 +56,8 @@ import {
|
|||
type ProcessRunRequest,
|
||||
type ProcessRunResponse,
|
||||
type ProcessSignalQuery,
|
||||
type ProcessTerminalClientFrame,
|
||||
type ProcessTerminalServerFrame,
|
||||
type ProcessTerminalResizeRequest,
|
||||
type ProcessTerminalResizeResponse,
|
||||
type SessionEvent,
|
||||
|
|
@ -63,6 +65,10 @@ import {
|
|||
type SessionRecord,
|
||||
type SkillsConfig,
|
||||
type SkillsConfigQuery,
|
||||
type TerminalErrorStatus,
|
||||
type TerminalExitStatus,
|
||||
type TerminalReadyStatus,
|
||||
type TerminalResizePayload,
|
||||
} from "./types.ts";
|
||||
|
||||
const API_PREFIX = "/v1";
|
||||
|
|
@ -158,6 +164,8 @@ export interface ProcessTerminalConnectOptions extends ProcessTerminalWebSocketU
|
|||
WebSocket?: typeof WebSocket;
|
||||
}
|
||||
|
||||
export type ProcessTerminalSessionOptions = ProcessTerminalConnectOptions;
|
||||
|
||||
export class SandboxAgentError extends Error {
|
||||
readonly status: number;
|
||||
readonly problem?: ProblemDetails;
|
||||
|
|
@ -586,6 +594,173 @@ export class LiveAcpConnection {
|
|||
}
|
||||
}
|
||||
|
||||
export class ProcessTerminalSession {
|
||||
readonly socket: WebSocket;
|
||||
readonly closed: Promise<void>;
|
||||
|
||||
private readonly readyListeners = new Set<(status: TerminalReadyStatus) => void>();
|
||||
private readonly dataListeners = new Set<(data: Uint8Array) => void>();
|
||||
private readonly exitListeners = new Set<(status: TerminalExitStatus) => void>();
|
||||
private readonly errorListeners = new Set<(error: TerminalErrorStatus | Error) => void>();
|
||||
private readonly closeListeners = new Set<() => void>();
|
||||
|
||||
private closeSignalSent = false;
|
||||
private closedResolve!: () => void;
|
||||
|
||||
constructor(socket: WebSocket) {
|
||||
this.socket = socket;
|
||||
this.socket.binaryType = "arraybuffer";
|
||||
this.closed = new Promise<void>((resolve) => {
|
||||
this.closedResolve = resolve;
|
||||
});
|
||||
|
||||
this.socket.addEventListener("message", (event) => {
|
||||
void this.handleMessage(event.data);
|
||||
});
|
||||
this.socket.addEventListener("error", () => {
|
||||
this.emitError(new Error("Terminal websocket connection failed."));
|
||||
});
|
||||
this.socket.addEventListener("close", () => {
|
||||
this.closedResolve();
|
||||
for (const listener of this.closeListeners) {
|
||||
listener();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onReady(listener: (status: TerminalReadyStatus) => void): () => void {
|
||||
this.readyListeners.add(listener);
|
||||
return () => {
|
||||
this.readyListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
onData(listener: (data: Uint8Array) => void): () => void {
|
||||
this.dataListeners.add(listener);
|
||||
return () => {
|
||||
this.dataListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
onExit(listener: (status: TerminalExitStatus) => void): () => void {
|
||||
this.exitListeners.add(listener);
|
||||
return () => {
|
||||
this.exitListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
onError(listener: (error: TerminalErrorStatus | Error) => void): () => void {
|
||||
this.errorListeners.add(listener);
|
||||
return () => {
|
||||
this.errorListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
onClose(listener: () => void): () => void {
|
||||
this.closeListeners.add(listener);
|
||||
return () => {
|
||||
this.closeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
sendInput(data: string | ArrayBuffer | ArrayBufferView): void {
|
||||
const payload = encodeTerminalInput(data);
|
||||
this.sendFrame({
|
||||
type: "input",
|
||||
data: payload.data,
|
||||
encoding: payload.encoding,
|
||||
});
|
||||
}
|
||||
|
||||
resize(payload: TerminalResizePayload): void {
|
||||
this.sendFrame({
|
||||
type: "resize",
|
||||
cols: payload.cols,
|
||||
rows: payload.rows,
|
||||
});
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.socket.readyState === WS_READY_STATE_CONNECTING) {
|
||||
this.socket.addEventListener(
|
||||
"open",
|
||||
() => {
|
||||
this.close();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.socket.readyState === WS_READY_STATE_OPEN) {
|
||||
if (!this.closeSignalSent) {
|
||||
this.closeSignalSent = true;
|
||||
this.sendFrame({ type: "close" });
|
||||
}
|
||||
this.socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.socket.readyState !== WS_READY_STATE_CLOSED) {
|
||||
this.socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
private async handleMessage(data: unknown): Promise<void> {
|
||||
try {
|
||||
if (typeof data === "string") {
|
||||
const frame = parseProcessTerminalServerFrame(data);
|
||||
if (!frame) {
|
||||
this.emitError(new Error("Received invalid terminal control frame."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type === "ready") {
|
||||
for (const listener of this.readyListeners) {
|
||||
listener(frame);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.type === "exit") {
|
||||
for (const listener of this.exitListeners) {
|
||||
listener(frame);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.emitError(frame);
|
||||
return;
|
||||
}
|
||||
|
||||
const bytes = await decodeTerminalBytes(data);
|
||||
for (const listener of this.dataListeners) {
|
||||
listener(bytes);
|
||||
}
|
||||
} catch (error) {
|
||||
this.emitError(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
|
||||
private sendFrame(frame: ProcessTerminalClientFrame): void {
|
||||
if (this.socket.readyState !== WS_READY_STATE_OPEN) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.socket.send(JSON.stringify(frame));
|
||||
}
|
||||
|
||||
private emitError(error: TerminalErrorStatus | Error): void {
|
||||
for (const listener of this.errorListeners) {
|
||||
listener(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const WS_READY_STATE_CONNECTING = 0;
|
||||
const WS_READY_STATE_OPEN = 1;
|
||||
const WS_READY_STATE_CLOSED = 3;
|
||||
|
||||
export class SandboxAgent {
|
||||
private readonly baseUrl: string;
|
||||
private readonly token?: string;
|
||||
|
|
@ -1344,6 +1519,13 @@ export class SandboxAgent {
|
|||
);
|
||||
}
|
||||
|
||||
connectProcessTerminal(
|
||||
id: string,
|
||||
options: ProcessTerminalSessionOptions = {},
|
||||
): ProcessTerminalSession {
|
||||
return new ProcessTerminalSession(this.connectProcessTerminalWebSocket(id, options));
|
||||
}
|
||||
|
||||
private async getLiveConnection(agent: string): Promise<LiveAcpConnection> {
|
||||
await this.awaitHealthy();
|
||||
|
||||
|
|
@ -1757,6 +1939,91 @@ type NormalizedHealthWaitOptions =
|
|||
| { enabled: false; timeoutMs?: undefined; signal?: undefined }
|
||||
| { enabled: true; timeoutMs?: number; signal?: AbortSignal };
|
||||
|
||||
function parseProcessTerminalServerFrame(payload: string): ProcessTerminalServerFrame | null {
|
||||
try {
|
||||
const parsed = JSON.parse(payload) as unknown;
|
||||
if (!isRecord(parsed) || typeof parsed.type !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (parsed.type === "ready" && typeof parsed.processId === "string") {
|
||||
return parsed as ProcessTerminalServerFrame;
|
||||
}
|
||||
|
||||
if (
|
||||
parsed.type === "exit" &&
|
||||
(parsed.exitCode === undefined ||
|
||||
parsed.exitCode === null ||
|
||||
typeof parsed.exitCode === "number")
|
||||
) {
|
||||
return parsed as ProcessTerminalServerFrame;
|
||||
}
|
||||
|
||||
if (parsed.type === "error" && typeof parsed.message === "string") {
|
||||
return parsed as ProcessTerminalServerFrame;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function encodeTerminalInput(
|
||||
data: string | ArrayBuffer | ArrayBufferView,
|
||||
): { data: string; encoding?: "base64" } {
|
||||
if (typeof data === "string") {
|
||||
return { data };
|
||||
}
|
||||
|
||||
const bytes = encodeTerminalBytes(data);
|
||||
return {
|
||||
data: bytesToBase64(bytes),
|
||||
encoding: "base64",
|
||||
};
|
||||
}
|
||||
|
||||
function encodeTerminalBytes(data: ArrayBuffer | ArrayBufferView): Uint8Array {
|
||||
if (data instanceof ArrayBuffer) {
|
||||
return new Uint8Array(data);
|
||||
}
|
||||
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
|
||||
}
|
||||
|
||||
async function decodeTerminalBytes(data: unknown): Promise<Uint8Array> {
|
||||
if (data instanceof ArrayBuffer) {
|
||||
return new Uint8Array(data);
|
||||
}
|
||||
|
||||
if (ArrayBuffer.isView(data)) {
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
|
||||
}
|
||||
|
||||
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
||||
return new Uint8Array(await data.arrayBuffer());
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported terminal frame payload: ${String(data)}`);
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes: Uint8Array): string {
|
||||
if (typeof Buffer !== "undefined") {
|
||||
return Buffer.from(bytes).toString("base64");
|
||||
}
|
||||
|
||||
if (typeof btoa === "function") {
|
||||
let binary = "";
|
||||
const chunkSize = 0x8000;
|
||||
for (let index = 0; index < bytes.length; index += chunkSize) {
|
||||
binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
throw new Error("Base64 encoding is not available in this environment.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-select and call `authenticate` based on the agent's advertised auth methods.
|
||||
* Prefers env-var-based methods that the server process already has configured.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
export {
|
||||
LiveAcpConnection,
|
||||
ProcessTerminalSession,
|
||||
SandboxAgent,
|
||||
SandboxAgentError,
|
||||
Session,
|
||||
|
|
@ -19,6 +20,7 @@ export type {
|
|||
ProcessLogListener,
|
||||
ProcessLogSubscription,
|
||||
ProcessTerminalConnectOptions,
|
||||
ProcessTerminalSessionOptions,
|
||||
ProcessTerminalWebSocketUrlOptions,
|
||||
SandboxAgentConnectOptions,
|
||||
SandboxAgentStartOptions,
|
||||
|
|
@ -88,6 +90,11 @@ export type {
|
|||
SessionRecord,
|
||||
SkillsConfig,
|
||||
SkillsConfigQuery,
|
||||
TerminalErrorStatus,
|
||||
TerminalExitStatus,
|
||||
TerminalReadyStatus,
|
||||
TerminalResizePayload,
|
||||
TerminalStatusMessage,
|
||||
} from "./types.ts";
|
||||
|
||||
export type {
|
||||
|
|
|
|||
|
|
@ -89,6 +89,16 @@ export type ProcessTerminalServerFrame =
|
|||
| ProcessTerminalExitFrame
|
||||
| ProcessTerminalErrorFrame;
|
||||
|
||||
export type TerminalReadyStatus = ProcessTerminalReadyFrame;
|
||||
export type TerminalExitStatus = ProcessTerminalExitFrame;
|
||||
export type TerminalErrorStatus = ProcessTerminalErrorFrame;
|
||||
export type TerminalStatusMessage = ProcessTerminalServerFrame;
|
||||
|
||||
export interface TerminalResizePayload {
|
||||
cols: number;
|
||||
rows: number;
|
||||
}
|
||||
|
||||
export interface SessionRecord {
|
||||
id: string;
|
||||
agent: string;
|
||||
|
|
|
|||
|
|
@ -136,22 +136,6 @@ function writeTarChecksum(buffer: Buffer, checksum: number): void {
|
|||
buffer[155] = 0x20;
|
||||
}
|
||||
|
||||
function decodeSocketPayload(data: unknown): string {
|
||||
if (typeof data === "string") {
|
||||
return data;
|
||||
}
|
||||
if (data instanceof ArrayBuffer) {
|
||||
return Buffer.from(data).toString("utf8");
|
||||
}
|
||||
if (ArrayBuffer.isView(data)) {
|
||||
return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8");
|
||||
}
|
||||
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
||||
throw new Error("Blob socket payloads are not supported in this test");
|
||||
}
|
||||
throw new Error(`Unsupported socket payload type: ${typeof data}`);
|
||||
}
|
||||
|
||||
function decodeProcessLogData(data: string, encoding: string): string {
|
||||
if (encoding === "base64") {
|
||||
return Buffer.from(data, "base64").toString("utf8");
|
||||
|
|
@ -816,37 +800,46 @@ describe("Integration: TypeScript SDK flat session API", () => {
|
|||
const wsUrl = sdk.buildProcessTerminalWebSocketUrl(ttyProcess.id);
|
||||
expect(wsUrl.startsWith("ws://") || wsUrl.startsWith("wss://")).toBe(true);
|
||||
|
||||
const ws = sdk.connectProcessTerminalWebSocket(ttyProcess.id, {
|
||||
const session = sdk.connectProcessTerminal(ttyProcess.id, {
|
||||
WebSocket: WebSocket as unknown as typeof globalThis.WebSocket,
|
||||
});
|
||||
ws.binaryType = "arraybuffer";
|
||||
const readyFrames: string[] = [];
|
||||
const ttyOutput: string[] = [];
|
||||
const exitFrames: Array<number | null | undefined> = [];
|
||||
const terminalErrors: string[] = [];
|
||||
let closeCount = 0;
|
||||
|
||||
const socketTextFrames: string[] = [];
|
||||
const socketBinaryFrames: string[] = [];
|
||||
ws.addEventListener("message", (event) => {
|
||||
if (typeof event.data === "string") {
|
||||
socketTextFrames.push(event.data);
|
||||
return;
|
||||
}
|
||||
socketBinaryFrames.push(decodeSocketPayload(event.data));
|
||||
session.onReady((frame) => {
|
||||
readyFrames.push(frame.processId);
|
||||
});
|
||||
session.onData((bytes) => {
|
||||
ttyOutput.push(Buffer.from(bytes).toString("utf8"));
|
||||
});
|
||||
session.onExit((frame) => {
|
||||
exitFrames.push(frame.exitCode);
|
||||
});
|
||||
session.onError((error) => {
|
||||
terminalErrors.push(error instanceof Error ? error.message : error.message);
|
||||
});
|
||||
session.onClose(() => {
|
||||
closeCount += 1;
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const ready = socketTextFrames.find((frame) => frame.includes('"type":"ready"'));
|
||||
return ready;
|
||||
});
|
||||
await waitFor(() => readyFrames[0]);
|
||||
|
||||
ws.send(JSON.stringify({
|
||||
type: "input",
|
||||
data: "hello tty\n",
|
||||
}));
|
||||
session.sendInput("hello tty\n");
|
||||
|
||||
await waitFor(() => {
|
||||
const joined = socketBinaryFrames.join("");
|
||||
const joined = ttyOutput.join("");
|
||||
return joined.includes("hello tty") ? joined : undefined;
|
||||
});
|
||||
|
||||
ws.close();
|
||||
session.close();
|
||||
await session.closed;
|
||||
expect(closeCount).toBeGreaterThan(0);
|
||||
expect(exitFrames).toHaveLength(0);
|
||||
expect(terminalErrors).toEqual([]);
|
||||
|
||||
await waitForAsync(async () => {
|
||||
const processInfo = await sdk.getProcess(ttyProcess.id);
|
||||
return processInfo.status === "running" ? processInfo : undefined;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue