codex working ish
This commit is contained in:
11 files changed
+1742
-146
No files matched your search
@@ -1,16 +1,22 @@
|
||||
# Electron TODO Monorepo (Turborepo + Bun)
|
||||
# CodeThing (Electron + Vite + Bun)
|
||||
|
||||
A long-lived Electron starter focused on:
|
||||
CodeThing is a desktop shell for coding agents. This first implementation is:
|
||||
|
||||
1. Performance: Vite renderer, small typed IPC surface, serialized persistence writes.
|
||||
2. Maintainability: strict TypeScript, explicit package boundaries, isolated renderer.
|
||||
3. Modern best practices: Bun workspaces, Turborepo task graph, shared contracts.
|
||||
1. Codex-first: connects to `codex app-server` and streams turn/item events.
|
||||
2. Provider-ready: renderer speaks a provider abstraction so Claude Code can plug in later.
|
||||
3. Typed end-to-end: contracts validate payloads at preload/main boundaries.
|
||||
|
||||
## Workspace layout
|
||||
|
||||
- `apps/desktop`: Electron main + preload process.
|
||||
- `apps/renderer`: React + Vite + Tailwind renderer UI.
|
||||
- `packages/contracts`: shared runtime-validated schemas and IPC/type contracts.
|
||||
- `/apps/desktop`: Electron main + preload process, includes provider and Codex session managers.
|
||||
- `/apps/renderer`: React + Vite UI for session control, conversation, and protocol event stream.
|
||||
- `/packages/contracts`: shared Zod schemas + TypeScript types for IPC and provider events.
|
||||
|
||||
## Codex prerequisites
|
||||
|
||||
- Install Codex CLI so `codex` is on your PATH.
|
||||
- Authenticate Codex before running CodeThing (for example via API key or ChatGPT auth supported by Codex).
|
||||
- CodeThing starts the server via `codex app-server` per session.
|
||||
|
||||
## Security and boundary model
|
||||
|
||||
@@ -25,18 +31,20 @@ A long-lived Electron starter focused on:
|
||||
- `bun run dev`: starts contract build/watch, renderer dev server, and Electron process.
|
||||
- `bun run build`: builds contracts, renderer, and desktop bundles through Turbo.
|
||||
- `bun run typecheck`: strict TypeScript checks for all packages.
|
||||
- `bun run test`: runs workspace tests.
|
||||
|
||||
Optional:
|
||||
- `ELECTRON_RENDERER_PORT=5180 bun run dev` if `5173` is already in use.
|
||||
|
||||
## Notes for future native bindings
|
||||
## Provider architecture
|
||||
|
||||
Add new main-process capabilities by extending `packages/contracts` first:
|
||||
The renderer now depends on `nativeApi.providers.*`:
|
||||
|
||||
1. Add schema + types for payload/result.
|
||||
2. Add an IPC channel constant.
|
||||
3. Implement `ipcMain.handle` in `apps/desktop/src/main.ts`.
|
||||
4. Expose a typed preload wrapper in `apps/desktop/src/preload.ts`.
|
||||
5. Consume only via `window.nativeApi` in renderer.
|
||||
1. `startSession`
|
||||
2. `sendTurn`
|
||||
3. `interruptTurn`
|
||||
4. `stopSession`
|
||||
5. `listSessions`
|
||||
6. `onEvent`
|
||||
|
||||
This keeps native concerns out of React and makes refactors low risk.
|
||||
Codex is the only implemented provider right now. `claudeCode` is reserved in contracts/UI but returns a not-implemented error in main-process dispatch.
|
||||
@@ -0,0 +1,690 @@
|
||||
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderTurnStartResult,
|
||||
} from "@acme/contracts";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
interface PendingRequest {
|
||||
method: string;
|
||||
timeout: ReturnType<typeof setTimeout>;
|
||||
resolve: (value: unknown) => void;
|
||||
reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
interface CodexSessionContext {
|
||||
session: ProviderSession;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
nextRequestId: number;
|
||||
stopping: boolean;
|
||||
}
|
||||
|
||||
interface JsonRpcError {
|
||||
code?: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
interface JsonRpcRequest {
|
||||
id: string | number;
|
||||
method: string;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
interface JsonRpcResponse {
|
||||
id: string | number;
|
||||
result?: unknown;
|
||||
error?: JsonRpcError;
|
||||
}
|
||||
|
||||
interface JsonRpcNotification {
|
||||
method: string;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export interface CodexAppServerManagerEvents {
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||
private readonly sessions = new Map<string, CodexSessionContext>();
|
||||
|
||||
async startSession(
|
||||
input: ProviderSessionStartInput,
|
||||
): Promise<ProviderSession> {
|
||||
const sessionId = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: input.model,
|
||||
cwd: input.cwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd: input.cwd,
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
const context: CodexSessionContext = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(
|
||||
context,
|
||||
"session/connecting",
|
||||
"Starting codex app-server",
|
||||
);
|
||||
|
||||
try {
|
||||
await this.sendRequest(context, "initialize", {
|
||||
clientInfo: {
|
||||
name: "codething_desktop",
|
||||
title: "CodeThing Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: false,
|
||||
},
|
||||
});
|
||||
|
||||
this.writeMessage(context, { method: "initialized" });
|
||||
|
||||
const threadStart = await this.sendRequest(context, "thread/start", {
|
||||
model: input.model ?? null,
|
||||
cwd: input.cwd ?? null,
|
||||
approvalPolicy: input.approvalPolicy,
|
||||
sandbox: input.sandboxMode,
|
||||
experimentalRawEvents: false,
|
||||
});
|
||||
|
||||
const threadId = this.readString(
|
||||
this.readObject(threadStart)?.thread,
|
||||
"id",
|
||||
);
|
||||
if (!threadId) {
|
||||
throw new Error("thread/start response did not include a thread id.");
|
||||
}
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "ready",
|
||||
threadId,
|
||||
});
|
||||
this.emitLifecycleEvent(
|
||||
context,
|
||||
"session/ready",
|
||||
`Connected to thread ${threadId}`,
|
||||
);
|
||||
return { ...context.session };
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to start Codex session.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
async sendTurn(
|
||||
input: ProviderSendTurnInput,
|
||||
): Promise<ProviderTurnStartResult> {
|
||||
const context = this.requireSession(input.sessionId);
|
||||
if (!context.session.threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "turn/start", {
|
||||
threadId: context.session.threadId,
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: input.input,
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const turn = this.readObject(this.readObject(response), "turn");
|
||||
const turnId = this.readString(turn, "id");
|
||||
if (!turnId) {
|
||||
throw new Error("turn/start response did not include a turn id.");
|
||||
}
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
});
|
||||
|
||||
return {
|
||||
threadId: context.session.threadId,
|
||||
turnId,
|
||||
};
|
||||
}
|
||||
|
||||
async interruptTurn(sessionId: string, turnId?: string): Promise<void> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const effectiveTurnId = turnId ?? context.session.activeTurnId;
|
||||
|
||||
if (!effectiveTurnId || !context.session.threadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.sendRequest(context, "turn/interrupt", {
|
||||
threadId: context.session.threadId,
|
||||
turnId: effectiveTurnId,
|
||||
});
|
||||
}
|
||||
|
||||
stopSession(sessionId: string): void {
|
||||
const context = this.sessions.get(sessionId);
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.stopping = true;
|
||||
|
||||
for (const pending of context.pending.values()) {
|
||||
clearTimeout(pending.timeout);
|
||||
pending.reject(new Error("Session stopped before request completed."));
|
||||
}
|
||||
context.pending.clear();
|
||||
|
||||
context.output.close();
|
||||
|
||||
if (!context.child.killed) {
|
||||
context.child.kill();
|
||||
}
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
|
||||
this.sessions.delete(sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
return Array.from(this.sessions.values(), ({ session }) => ({
|
||||
...session,
|
||||
}));
|
||||
}
|
||||
|
||||
hasSession(sessionId: string): boolean {
|
||||
return this.sessions.has(sessionId);
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
for (const sessionId of this.sessions.keys()) {
|
||||
this.stopSession(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
private requireSession(sessionId: string): CodexSessionContext {
|
||||
const context = this.sessions.get(sessionId);
|
||||
if (!context) {
|
||||
throw new Error(`Unknown session: ${sessionId}`);
|
||||
}
|
||||
|
||||
if (context.session.status === "closed") {
|
||||
throw new Error(`Session is closed: ${sessionId}`);
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
private attachProcessListeners(context: CodexSessionContext): void {
|
||||
context.output.on("line", (line) => {
|
||||
this.handleStdoutLine(context, line);
|
||||
});
|
||||
|
||||
context.child.stderr.on("data", (chunk: Buffer) => {
|
||||
const message = chunk.toString().trim();
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.emitErrorEvent(context, "process/stderr", message);
|
||||
});
|
||||
|
||||
context.child.on("error", (error) => {
|
||||
const message = error.message || "codex app-server process errored.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "process/error", message);
|
||||
});
|
||||
|
||||
context.child.on("exit", (code, signal) => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: code === 0 ? context.session.lastError : message,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/exited", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
});
|
||||
}
|
||||
|
||||
private handleStdoutLine(context: CodexSessionContext, line: string): void {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/parseError",
|
||||
"Received invalid JSON from codex app-server.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/invalidMessage",
|
||||
"Received non-object protocol message.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isServerRequest(parsed)) {
|
||||
this.handleServerRequest(context, parsed);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isServerNotification(parsed)) {
|
||||
this.handleServerNotification(context, parsed);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isResponse(parsed)) {
|
||||
this.handleResponse(context, parsed);
|
||||
return;
|
||||
}
|
||||
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/unrecognizedMessage",
|
||||
"Received protocol message in an unknown shape.",
|
||||
);
|
||||
}
|
||||
|
||||
private handleServerNotification(
|
||||
context: CodexSessionContext,
|
||||
notification: JsonRpcNotification,
|
||||
): void {
|
||||
const route = this.readRouteFields(notification.params);
|
||||
const textDelta =
|
||||
notification.method === "item/agentMessage/delta"
|
||||
? this.readString(notification.params, "delta")
|
||||
: undefined;
|
||||
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: notification.method,
|
||||
threadId: route.threadId,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
textDelta,
|
||||
payload: notification.params,
|
||||
});
|
||||
|
||||
if (notification.method === "thread/started") {
|
||||
const threadId = this.readString(
|
||||
this.readObject(notification.params)?.thread,
|
||||
"id",
|
||||
);
|
||||
if (threadId) {
|
||||
this.updateSession(context, { threadId });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (notification.method === "turn/started") {
|
||||
const turnId = this.readString(
|
||||
this.readObject(notification.params)?.turn,
|
||||
"id",
|
||||
);
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (notification.method === "turn/completed") {
|
||||
const turn = this.readObject(notification.params, "turn");
|
||||
const status = this.readString(turn, "status");
|
||||
const errorMessage = this.readString(
|
||||
this.readObject(turn, "error"),
|
||||
"message",
|
||||
);
|
||||
this.updateSession(context, {
|
||||
status: status === "failed" ? "error" : "ready",
|
||||
activeTurnId: undefined,
|
||||
lastError: errorMessage ?? context.session.lastError,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (notification.method === "error") {
|
||||
const message = this.readString(
|
||||
this.readObject(notification.params)?.error,
|
||||
"message",
|
||||
);
|
||||
const willRetry = this.readBoolean(notification.params, "willRetry");
|
||||
|
||||
this.updateSession(context, {
|
||||
status: willRetry ? "running" : "error",
|
||||
lastError: message ?? context.session.lastError,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private handleServerRequest(
|
||||
context: CodexSessionContext,
|
||||
request: JsonRpcRequest,
|
||||
): void {
|
||||
const route = this.readRouteFields(request.params);
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: request.method,
|
||||
threadId: route.threadId,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
payload: request.params,
|
||||
});
|
||||
|
||||
if (request.method === "item/commandExecution/requestApproval") {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { decision: "decline" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.method === "item/fileChange/requestApproval") {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { decision: "decline" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { answers: {} },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: `Unsupported server request: ${request.method}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private handleResponse(
|
||||
context: CodexSessionContext,
|
||||
response: JsonRpcResponse,
|
||||
): void {
|
||||
const key = String(response.id);
|
||||
const pending = context.pending.get(key);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTimeout(pending.timeout);
|
||||
context.pending.delete(key);
|
||||
|
||||
if (response.error?.message) {
|
||||
pending.reject(
|
||||
new Error(
|
||||
`${pending.method} failed: ${String(response.error.message)}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
pending.resolve(response.result);
|
||||
}
|
||||
|
||||
private async sendRequest<TResponse>(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs = 20_000,
|
||||
): Promise<TResponse> {
|
||||
const id = context.nextRequestId;
|
||||
context.nextRequestId += 1;
|
||||
|
||||
const result = await new Promise<unknown>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
context.pending.delete(String(id));
|
||||
reject(new Error(`Timed out waiting for ${method}.`));
|
||||
}, timeoutMs);
|
||||
|
||||
context.pending.set(String(id), {
|
||||
method,
|
||||
timeout,
|
||||
resolve,
|
||||
reject,
|
||||
});
|
||||
this.writeMessage(context, {
|
||||
method,
|
||||
id,
|
||||
params,
|
||||
});
|
||||
});
|
||||
|
||||
return result as TResponse;
|
||||
}
|
||||
|
||||
private writeMessage(context: CodexSessionContext, message: unknown): void {
|
||||
const encoded = JSON.stringify(message);
|
||||
if (!context.child.stdin.writable) {
|
||||
throw new Error("Cannot write to codex app-server stdin.");
|
||||
}
|
||||
|
||||
context.child.stdin.write(`${encoded}\n`);
|
||||
}
|
||||
|
||||
private emitLifecycleEvent(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "session",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
private emitErrorEvent(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
private emitEvent(event: ProviderEvent): void {
|
||||
this.emit("event", event);
|
||||
}
|
||||
|
||||
private updateSession(
|
||||
context: CodexSessionContext,
|
||||
updates: Partial<ProviderSession>,
|
||||
): void {
|
||||
context.session = {
|
||||
...context.session,
|
||||
...updates,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const candidate = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof candidate.method === "string" &&
|
||||
(typeof candidate.id === "string" || typeof candidate.id === "number")
|
||||
);
|
||||
}
|
||||
|
||||
private isServerNotification(value: unknown): value is JsonRpcNotification {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const candidate = value as Record<string, unknown>;
|
||||
return typeof candidate.method === "string" && !("id" in candidate);
|
||||
}
|
||||
|
||||
private isResponse(value: unknown): value is JsonRpcResponse {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const hasId =
|
||||
typeof candidate.id === "string" || typeof candidate.id === "number";
|
||||
const hasMethod = typeof candidate.method === "string";
|
||||
return hasId && !hasMethod;
|
||||
}
|
||||
|
||||
private readRouteFields(params: unknown): {
|
||||
threadId?: string;
|
||||
turnId?: string;
|
||||
itemId?: string;
|
||||
} {
|
||||
const route: {
|
||||
threadId?: string;
|
||||
turnId?: string;
|
||||
itemId?: string;
|
||||
} = {};
|
||||
|
||||
const threadId =
|
||||
this.readString(params, "threadId") ??
|
||||
this.readString(this.readObject(params, "thread"), "id");
|
||||
const turnId =
|
||||
this.readString(params, "turnId") ??
|
||||
this.readString(this.readObject(params, "turn"), "id");
|
||||
const itemId =
|
||||
this.readString(params, "itemId") ??
|
||||
this.readString(this.readObject(params, "item"), "id");
|
||||
|
||||
if (threadId) {
|
||||
route.threadId = threadId;
|
||||
}
|
||||
|
||||
if (turnId) {
|
||||
route.turnId = turnId;
|
||||
}
|
||||
|
||||
if (itemId) {
|
||||
route.itemId = itemId;
|
||||
}
|
||||
|
||||
return route;
|
||||
}
|
||||
|
||||
private readObject(
|
||||
value: unknown,
|
||||
key?: string,
|
||||
): Record<string, unknown> | undefined {
|
||||
const target =
|
||||
key === undefined
|
||||
? value
|
||||
: value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)[key]
|
||||
: undefined;
|
||||
|
||||
if (!target || typeof target !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return target as Record<string, unknown>;
|
||||
}
|
||||
|
||||
private readString(value: unknown, key: string): string | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const candidate = (value as Record<string, unknown>)[key];
|
||||
return typeof candidate === "string" ? candidate : undefined;
|
||||
}
|
||||
|
||||
private readBoolean(value: unknown, key: string): boolean | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const candidate = (value as Record<string, unknown>)[key];
|
||||
return typeof candidate === "boolean" ? candidate : undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { fixPath } from "./fixPath";
|
||||
fixPath();
|
||||
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { BrowserWindow, app, ipcMain, session } from "electron";
|
||||
|
||||
import {
|
||||
@@ -16,12 +16,14 @@ import {
|
||||
todoIdSchema,
|
||||
} from "@acme/contracts";
|
||||
import { ProcessManager } from "./processManager";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
import { TodoStore } from "./todoStore";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
|
||||
let todoStore: TodoStore;
|
||||
const processManager = new ProcessManager();
|
||||
const providerManager = new ProviderManager();
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
@@ -94,6 +96,47 @@ function registerIpcHandlers(): void {
|
||||
processManager.write(agentSessionIdSchema.parse(sessionId), String(data));
|
||||
},
|
||||
);
|
||||
|
||||
// Provider handlers
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerSessionStart,
|
||||
async (_event, payload: unknown) => {
|
||||
return providerManager.startSession(
|
||||
payload as Parameters<typeof providerManager.startSession>[0],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerTurnStart,
|
||||
async (_event, payload: unknown) => {
|
||||
return providerManager.sendTurn(
|
||||
payload as Parameters<typeof providerManager.sendTurn>[0],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerTurnInterrupt,
|
||||
async (_event, payload: unknown) => {
|
||||
await providerManager.interruptTurn(
|
||||
payload as Parameters<typeof providerManager.interruptTurn>[0],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerSessionStop,
|
||||
async (_event, payload: unknown) => {
|
||||
providerManager.stopSession(
|
||||
payload as Parameters<typeof providerManager.stopSession>[0],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.providerSessionList, async () => {
|
||||
return providerManager.listSessions();
|
||||
});
|
||||
}
|
||||
|
||||
async function runTerminalCommand(
|
||||
@@ -101,8 +144,8 @@ async function runTerminalCommand(
|
||||
): Promise<TerminalCommandResult> {
|
||||
const shellPath =
|
||||
process.platform === "win32"
|
||||
? process.env.ComSpec ?? "cmd.exe"
|
||||
: process.env.SHELL ?? "/bin/sh";
|
||||
? (process.env.ComSpec ?? "cmd.exe")
|
||||
: (process.env.SHELL ?? "/bin/sh");
|
||||
|
||||
const args =
|
||||
process.platform === "win32"
|
||||
@@ -169,12 +212,20 @@ function setupEventForwarding(window: BrowserWindow): void {
|
||||
}
|
||||
};
|
||||
|
||||
const onProviderEvent = (event: unknown) => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(IPC_CHANNELS.providerEvent, event);
|
||||
}
|
||||
};
|
||||
|
||||
processManager.on("output", onOutput);
|
||||
processManager.on("exit", onExit);
|
||||
providerManager.on("event", onProviderEvent);
|
||||
|
||||
window.on("closed", () => {
|
||||
processManager.off("output", onOutput);
|
||||
processManager.off("exit", onExit);
|
||||
providerManager.off("event", onProviderEvent);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -211,6 +262,7 @@ async function bootstrap(): Promise<void> {
|
||||
|
||||
app.on("before-quit", () => {
|
||||
processManager.killAll();
|
||||
providerManager.stopAll();
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
|
||||
@@ -31,6 +31,24 @@ const nativeApi: NativeApi = {
|
||||
return () => ipcRenderer.removeListener(IPC_CHANNELS.agentExit, listener);
|
||||
},
|
||||
},
|
||||
providers: {
|
||||
startSession: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerSessionStart, input),
|
||||
sendTurn: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerTurnStart, input),
|
||||
interruptTurn: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerTurnInterrupt, input),
|
||||
stopSession: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerSessionStop, input),
|
||||
listSessions: () => ipcRenderer.invoke(IPC_CHANNELS.providerSessionList),
|
||||
onEvent: (callback) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, payload: unknown) =>
|
||||
callback(payload as Parameters<typeof callback>[0]);
|
||||
ipcRenderer.on(IPC_CHANNELS.providerEvent, listener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IPC_CHANNELS.providerEvent, listener);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
contextBridge.exposeInMainWorld("nativeApi", nativeApi);
|
||||
@@ -0,0 +1,69 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderInterruptTurnInput,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
} from "@acme/contracts";
|
||||
import { CodexAppServerManager } from "./codexAppServerManager";
|
||||
|
||||
export interface ProviderManagerEvents {
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
private readonly codex = new CodexAppServerManager();
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.codex.on("event", (event) => this.emit("event", event));
|
||||
}
|
||||
|
||||
async startSession(raw: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const input = providerSessionStartInputSchema.parse(raw);
|
||||
if (input.provider !== "codex") {
|
||||
throw new Error(`Provider '${input.provider}' is not implemented yet.`);
|
||||
}
|
||||
|
||||
return this.codex.startSession(input);
|
||||
}
|
||||
|
||||
async sendTurn(raw: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
const input = providerSendTurnInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
return this.codex.sendTurn(input);
|
||||
}
|
||||
|
||||
async interruptTurn(raw: ProviderInterruptTurnInput): Promise<void> {
|
||||
const input = providerInterruptTurnInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
await this.codex.interruptTurn(input.sessionId, input.turnId);
|
||||
}
|
||||
|
||||
stopSession(raw: ProviderStopSessionInput): void {
|
||||
const input = providerStopSessionInputSchema.parse(raw);
|
||||
this.codex.stopSession(input.sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
return this.codex.listSessions();
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
this.codex.stopAll();
|
||||
}
|
||||
}
|
||||
+552
-121
@@ -1,12 +1,55 @@
|
||||
import { type FormEvent, useMemo, useState } from "react";
|
||||
import {
|
||||
type FormEvent,
|
||||
type MutableRefObject,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import type { TerminalCommandResult } from "@acme/contracts";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderKind,
|
||||
ProviderSession,
|
||||
} from "@acme/contracts";
|
||||
|
||||
interface TerminalEntry {
|
||||
type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||
|
||||
interface ChatMessage {
|
||||
id: string;
|
||||
command: string;
|
||||
result: TerminalCommandResult;
|
||||
role: "user" | "assistant";
|
||||
text: string;
|
||||
createdAt: string;
|
||||
streaming: boolean;
|
||||
}
|
||||
|
||||
const PROVIDER_OPTIONS: Array<{
|
||||
value: ProviderKind;
|
||||
label: string;
|
||||
available: boolean;
|
||||
}> = [
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
|
||||
];
|
||||
|
||||
function readNativeApi() {
|
||||
if (typeof window === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return window.nativeApi;
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function formatTimestamp(isoDate: string): string {
|
||||
@@ -17,66 +60,364 @@ function formatTimestamp(isoDate: string): string {
|
||||
}).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
function readNativeApi() {
|
||||
if (typeof window === "undefined") {
|
||||
return undefined;
|
||||
function derivePhase(session: ProviderSession | null): SessionPhase {
|
||||
if (!session || session.status === "closed") {
|
||||
return "disconnected";
|
||||
}
|
||||
|
||||
return window.nativeApi;
|
||||
if (session.status === "connecting") {
|
||||
return "connecting";
|
||||
}
|
||||
|
||||
if (session.status === "running") {
|
||||
return "running";
|
||||
}
|
||||
|
||||
return "ready";
|
||||
}
|
||||
|
||||
function evolveSession(
|
||||
previous: ProviderSession,
|
||||
event: ProviderEvent,
|
||||
): ProviderSession {
|
||||
const payload = asObject(event.payload);
|
||||
|
||||
if (event.method === "thread/started") {
|
||||
const thread = asObject(payload?.thread);
|
||||
return {
|
||||
...previous,
|
||||
threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "turn/started") {
|
||||
const turn = asObject(payload?.turn);
|
||||
return {
|
||||
...previous,
|
||||
status: "running",
|
||||
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
const turn = asObject(payload?.turn);
|
||||
const status = asString(turn?.status);
|
||||
const turnError = asObject(turn?.error);
|
||||
return {
|
||||
...previous,
|
||||
status: status === "failed" ? "error" : "ready",
|
||||
activeTurnId: undefined,
|
||||
lastError: asString(turnError?.message) ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.kind === "error") {
|
||||
return {
|
||||
...previous,
|
||||
status: "error",
|
||||
lastError: event.message ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "session/closed" || event.method === "session/exited") {
|
||||
return {
|
||||
...previous,
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: event.message ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...previous,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
function applyEventToMessages(
|
||||
previous: ChatMessage[],
|
||||
event: ProviderEvent,
|
||||
activeAssistantItemRef: MutableRefObject<string | null>,
|
||||
): ChatMessage[] {
|
||||
const payload = asObject(event.payload);
|
||||
|
||||
if (event.method === "item/started") {
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "agentMessage") {
|
||||
return previous;
|
||||
}
|
||||
|
||||
const itemId = asString(item?.id);
|
||||
if (!itemId) {
|
||||
return previous;
|
||||
}
|
||||
|
||||
activeAssistantItemRef.current = itemId;
|
||||
const seedText = asString(item?.text) ?? "";
|
||||
const filtered = previous.filter((entry) => entry.id !== itemId);
|
||||
return [
|
||||
...filtered,
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: seedText,
|
||||
createdAt: event.createdAt,
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/agentMessage/delta") {
|
||||
const itemId = event.itemId ?? asString(payload?.itemId);
|
||||
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
|
||||
if (!itemId || !delta) {
|
||||
return previous;
|
||||
}
|
||||
|
||||
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (existingIndex === -1) {
|
||||
activeAssistantItemRef.current = itemId;
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: delta,
|
||||
createdAt: event.createdAt,
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const updated = [...previous];
|
||||
const existing = updated[existingIndex];
|
||||
if (!existing) {
|
||||
return previous;
|
||||
}
|
||||
updated[existingIndex] = {
|
||||
...existing,
|
||||
text: `${existing.text}${delta}`,
|
||||
streaming: true,
|
||||
};
|
||||
return updated;
|
||||
}
|
||||
|
||||
if (event.method === "item/completed") {
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "agentMessage") {
|
||||
return previous;
|
||||
}
|
||||
|
||||
const itemId = asString(item?.id);
|
||||
if (!itemId) {
|
||||
return previous;
|
||||
}
|
||||
|
||||
const fullText = asString(item?.text);
|
||||
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (existingIndex === -1) {
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: fullText ?? "",
|
||||
createdAt: event.createdAt,
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const updated = [...previous];
|
||||
const existing = updated[existingIndex];
|
||||
if (!existing) {
|
||||
return previous;
|
||||
}
|
||||
updated[existingIndex] = {
|
||||
...existing,
|
||||
text: fullText ?? existing.text,
|
||||
streaming: false,
|
||||
};
|
||||
|
||||
if (activeAssistantItemRef.current === itemId) {
|
||||
activeAssistantItemRef.current = null;
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
return previous.map((entry) => ({ ...entry, streaming: false }));
|
||||
}
|
||||
|
||||
return previous;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const [command, setCommand] = useState("");
|
||||
const [history, setHistory] = useState<TerminalEntry[]>([]);
|
||||
const [isRunning, setIsRunning] = useState(false);
|
||||
const [provider, setProvider] = useState<ProviderKind>("codex");
|
||||
const [cwd, setCwd] = useState("");
|
||||
const [model, setModel] = useState("gpt-5.1-codex");
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [session, setSession] = useState<ProviderSession | null>(null);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [events, setEvents] = useState<ProviderEvent[]>([]);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const onSubmit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const currentSessionIdRef = useRef<string | null>(null);
|
||||
const activeAssistantItemRef = useRef<string | null>(null);
|
||||
|
||||
if (!api || isRunning) {
|
||||
useEffect(() => {
|
||||
currentSessionIdRef.current = session?.sessionId ?? null;
|
||||
}, [session?.sessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
const trimmed = command.trim();
|
||||
return api.providers.onEvent((event) => {
|
||||
const currentSessionId = currentSessionIdRef.current;
|
||||
if (!currentSessionId || currentSessionId !== event.sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((previous) => [event, ...previous].slice(0, 200));
|
||||
setSession((previous) => {
|
||||
if (!previous || previous.sessionId !== event.sessionId) {
|
||||
return previous;
|
||||
}
|
||||
return evolveSession(previous, event);
|
||||
});
|
||||
setMessages((previous) =>
|
||||
applyEventToMessages(previous, event, activeAssistantItemRef),
|
||||
);
|
||||
|
||||
if (event.kind === "error" && event.message) {
|
||||
setError(event.message);
|
||||
}
|
||||
});
|
||||
}, [api]);
|
||||
|
||||
const phase = derivePhase(session);
|
||||
|
||||
const onConnect = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!api || provider !== "codex" || isConnecting) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const nextSession = await api.providers.startSession({
|
||||
provider,
|
||||
cwd: cwd.trim() || undefined,
|
||||
model: model.trim() || undefined,
|
||||
});
|
||||
currentSessionIdRef.current = nextSession.sessionId;
|
||||
activeAssistantItemRef.current = null;
|
||||
setSession(nextSession);
|
||||
setMessages([]);
|
||||
setEvents([]);
|
||||
} catch (connectError) {
|
||||
setError(
|
||||
connectError instanceof Error
|
||||
? connectError.message
|
||||
: "Unable to connect to Codex app-server.",
|
||||
);
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onDisconnect = async () => {
|
||||
if (!api || !session) {
|
||||
return;
|
||||
}
|
||||
|
||||
await api.providers.stopSession({ sessionId: session.sessionId });
|
||||
currentSessionIdRef.current = null;
|
||||
setSession((previous) =>
|
||||
previous
|
||||
? {
|
||||
...previous,
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
: previous,
|
||||
);
|
||||
};
|
||||
|
||||
const onSendPrompt = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!api || !session || isSending) {
|
||||
return;
|
||||
}
|
||||
|
||||
const trimmed = prompt.trim();
|
||||
if (!trimmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setIsRunning(true);
|
||||
setMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
role: "user",
|
||||
text: trimmed,
|
||||
createdAt: new Date().toISOString(),
|
||||
streaming: false,
|
||||
},
|
||||
]);
|
||||
setPrompt("");
|
||||
setIsSending(true);
|
||||
|
||||
try {
|
||||
const result = await api.terminal.run({ command: trimmed });
|
||||
setHistory((previous) => [
|
||||
...previous,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
command: trimmed,
|
||||
result,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
]);
|
||||
setCommand("");
|
||||
} catch (runError) {
|
||||
const message =
|
||||
runError instanceof Error
|
||||
? runError.message
|
||||
: "Could not execute command.";
|
||||
setError(message);
|
||||
await api.providers.sendTurn({
|
||||
sessionId: session.sessionId,
|
||||
input: trimmed,
|
||||
});
|
||||
} catch (sendError) {
|
||||
setError(
|
||||
sendError instanceof Error
|
||||
? sendError.message
|
||||
: "Failed to start a Codex turn.",
|
||||
);
|
||||
} finally {
|
||||
setIsRunning(false);
|
||||
setIsSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onInterrupt = async () => {
|
||||
if (!api || !session) {
|
||||
return;
|
||||
}
|
||||
|
||||
await api.providers.interruptTurn({
|
||||
sessionId: session.sessionId,
|
||||
turnId: session.activeTurnId,
|
||||
});
|
||||
};
|
||||
|
||||
if (!api) {
|
||||
return (
|
||||
<main className="mx-auto flex min-h-screen w-full max-w-4xl items-center justify-center px-8">
|
||||
<section className="rounded-3xl border border-amber-200 bg-amber-50 px-6 py-5 text-amber-900 shadow-soft">
|
||||
<h1 className="text-lg font-semibold">Native bridge unavailable</h1>
|
||||
<p className="mt-2 text-sm">
|
||||
Launch this UI through Electron so the preload API is available.
|
||||
<main className="mx-auto flex min-h-screen w-full max-w-3xl items-center justify-center px-6 py-10">
|
||||
<section className="surface-card w-full rounded-3xl p-8">
|
||||
<p className="label-chip">CodeThing</p>
|
||||
<h1 className="mt-3 text-3xl">Native bridge unavailable</h1>
|
||||
<p className="mt-3 text-sm text-amber-100/80">
|
||||
Launch the renderer through Electron so `window.nativeApi` is
|
||||
exposed by preload.
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
@@ -84,102 +425,192 @@ export default function App() {
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex min-h-screen w-full max-w-5xl flex-col px-6 py-10 text-slate-900 sm:px-10">
|
||||
<header className="rounded-3xl border border-slate-800/80 bg-slate-900 p-7 text-slate-100 shadow-soft">
|
||||
<p className="text-xs uppercase tracking-[0.18em] text-emerald-300">
|
||||
Demo Terminal
|
||||
</p>
|
||||
<h1 className="mt-2 font-mono text-3xl font-semibold tracking-tight">
|
||||
Shell Command Runner
|
||||
<main className="mx-auto min-h-screen w-full max-w-7xl px-4 py-6 text-[#f3f0e9] sm:px-8">
|
||||
<header className="surface-card relative overflow-hidden rounded-3xl px-6 py-7 sm:px-8">
|
||||
<div className="grain absolute inset-0 pointer-events-none" />
|
||||
<p className="label-chip relative">CodeThing / Provider Shell</p>
|
||||
<h1 className="relative mt-3 text-4xl tracking-tight sm:text-5xl">
|
||||
Codex-first workspace
|
||||
</h1>
|
||||
<p className="mt-3 text-sm text-slate-300">
|
||||
Runs one command at a time in your shell and prints stdout/stderr.
|
||||
<p className="relative mt-3 max-w-3xl text-sm text-[#efe8d7]/82 sm:text-base">
|
||||
Built on the Codex app-server protocol with a provider abstraction in
|
||||
the IPC layer, so Claude Code can be added without reshaping the UI
|
||||
contract.
|
||||
</p>
|
||||
|
||||
<form className="mt-6 flex gap-3" onSubmit={onSubmit}>
|
||||
<input
|
||||
value={command}
|
||||
onChange={(event) => setCommand(event.target.value)}
|
||||
placeholder="e.g. ls -la"
|
||||
className="h-11 flex-1 rounded-xl border border-emerald-500/50 bg-slate-950 px-4 font-mono text-sm text-emerald-100 outline-none ring-0 transition focus:border-emerald-300"
|
||||
maxLength={4000}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="h-11 rounded-xl bg-emerald-500 px-5 text-sm font-semibold text-slate-950 transition hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-emerald-800 disabled:text-emerald-300"
|
||||
disabled={isRunning}
|
||||
>
|
||||
{isRunning ? "Running..." : "Run"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="h-11 rounded-xl border border-slate-600 px-5 text-sm font-medium text-slate-200 transition hover:border-slate-400 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={history.length === 0 || isRunning}
|
||||
onClick={() => setHistory([])}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
<form
|
||||
className="relative mt-6 grid gap-3 rounded-2xl border border-[#f6a40f]/30 bg-[#0f2034]/65 p-4 sm:grid-cols-6"
|
||||
onSubmit={onConnect}
|
||||
>
|
||||
<label className="sm:col-span-2">
|
||||
<span className="field-label">Provider</span>
|
||||
<select
|
||||
className="field-input"
|
||||
value={provider}
|
||||
onChange={(event) =>
|
||||
setProvider(event.target.value as ProviderKind)
|
||||
}
|
||||
disabled={isConnecting || phase !== "disconnected"}
|
||||
>
|
||||
{PROVIDER_OPTIONS.map((option) => (
|
||||
<option
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled={!option.available}
|
||||
>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="sm:col-span-2">
|
||||
<span className="field-label">Working directory</span>
|
||||
<input
|
||||
className="field-input font-mono text-xs sm:text-sm"
|
||||
value={cwd}
|
||||
onChange={(event) => setCwd(event.target.value)}
|
||||
placeholder="/Users/theo/Code/Work/..."
|
||||
disabled={isConnecting || phase !== "disconnected"}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="sm:col-span-1">
|
||||
<span className="field-label">Model</span>
|
||||
<input
|
||||
className="field-input font-mono text-xs sm:text-sm"
|
||||
value={model}
|
||||
onChange={(event) => setModel(event.target.value)}
|
||||
placeholder="gpt-5.1-codex"
|
||||
disabled={isConnecting || phase !== "disconnected"}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="sm:col-span-1 flex items-end">
|
||||
{phase === "disconnected" ? (
|
||||
<button
|
||||
type="submit"
|
||||
className="action-button action-primary w-full"
|
||||
disabled={provider !== "codex" || isConnecting}
|
||||
>
|
||||
{isConnecting ? "Connecting..." : "Connect"}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="action-button action-danger w-full"
|
||||
onClick={() => void onDisconnect()}
|
||||
>
|
||||
Disconnect
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="relative mt-4 flex flex-wrap gap-2 text-xs">
|
||||
<span className="status-pill">
|
||||
phase={phase} provider={session?.provider ?? "none"}
|
||||
</span>
|
||||
<span className="status-pill">
|
||||
thread={session?.threadId ?? "none"}
|
||||
</span>
|
||||
<span className="status-pill">
|
||||
turn={session?.activeTurnId ?? "none"}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
<div className="mt-6 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
|
||||
<div className="mt-4 rounded-2xl border border-rose-300/35 bg-rose-900/35 px-4 py-3 text-sm text-rose-100">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<section className="mt-6 flex-1 space-y-4">
|
||||
{history.length === 0 ? (
|
||||
<div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-4 py-6 text-sm text-slate-500">
|
||||
No commands run yet.
|
||||
<section className="mt-5 grid gap-4 lg:grid-cols-[2fr_1fr]">
|
||||
<article className="surface-card rounded-3xl p-4 sm:p-5">
|
||||
<h2 className="text-xl">Conversation</h2>
|
||||
<div className="mt-4 max-h-[52vh] space-y-3 overflow-y-auto pr-1">
|
||||
{messages.length === 0 ? (
|
||||
<div className="rounded-2xl border border-dashed border-[#f6d79e]/30 bg-[#0d1827]/70 px-4 py-5 text-sm text-[#d8d0c3]/75">
|
||||
No turns yet. Start a session, then send a prompt.
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{messages.map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className={`message-card ${
|
||||
entry.role === "user" ? "message-user" : "message-assistant"
|
||||
}`}
|
||||
>
|
||||
<header className="mb-2 flex items-center justify-between text-[11px] uppercase tracking-[0.12em] text-[#d8d0c3]/68">
|
||||
<span>{entry.role === "user" ? "you" : "codex"}</span>
|
||||
<span>{formatTimestamp(entry.createdAt)}</span>
|
||||
</header>
|
||||
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-6">
|
||||
{entry.text || (entry.streaming ? "..." : "(empty response)")}
|
||||
</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{history.map((entry) => (
|
||||
<article
|
||||
key={entry.id}
|
||||
className="overflow-hidden rounded-2xl border border-slate-700 bg-slate-950 shadow-soft"
|
||||
>
|
||||
<header className="flex items-center justify-between border-b border-slate-800 px-4 py-3 font-mono text-xs text-slate-300">
|
||||
<p>$ {entry.command}</p>
|
||||
<p>{formatTimestamp(entry.createdAt)}</p>
|
||||
</header>
|
||||
|
||||
<div className="space-y-3 px-4 py-4 font-mono text-sm">
|
||||
{entry.result.stdout ? (
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wide text-emerald-300">
|
||||
stdout
|
||||
</p>
|
||||
<pre className="whitespace-pre-wrap break-words text-emerald-100">
|
||||
{entry.result.stdout}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{entry.result.stderr ? (
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wide text-rose-300">
|
||||
stderr
|
||||
</p>
|
||||
<pre className="whitespace-pre-wrap break-words text-rose-200">
|
||||
{entry.result.stderr}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!entry.result.stdout && !entry.result.stderr ? (
|
||||
<p className="text-slate-400">(no output)</p>
|
||||
) : null}
|
||||
<form className="mt-4 grid gap-3" onSubmit={onSendPrompt}>
|
||||
<textarea
|
||||
className="field-input min-h-28 resize-y font-mono text-sm leading-6"
|
||||
value={prompt}
|
||||
onChange={(event) => setPrompt(event.target.value)}
|
||||
placeholder="Ask Codex to inspect, plan, or edit this project..."
|
||||
disabled={phase === "disconnected" || isSending}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
className="action-button action-primary"
|
||||
disabled={phase === "disconnected" || isSending}
|
||||
>
|
||||
{isSending ? "Starting turn..." : "Send"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="action-button action-muted"
|
||||
disabled={phase !== "running"}
|
||||
onClick={() => void onInterrupt()}
|
||||
>
|
||||
Interrupt
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</article>
|
||||
|
||||
<footer className="border-t border-slate-800 bg-slate-900/60 px-4 py-2 font-mono text-xs text-slate-400">
|
||||
exit={entry.result.code ?? "null"} signal=
|
||||
{entry.result.signal ?? "null"} timedOut=
|
||||
{entry.result.timedOut ? "yes" : "no"}
|
||||
</footer>
|
||||
</article>
|
||||
))}
|
||||
<aside className="surface-card rounded-3xl p-4 sm:p-5">
|
||||
<h2 className="text-xl">Protocol stream</h2>
|
||||
<p className="mt-2 text-xs text-[#d8d0c3]/76">
|
||||
Live notifications from the app-server (latest first).
|
||||
</p>
|
||||
<div className="mt-4 max-h-[58vh] space-y-2 overflow-y-auto pr-1">
|
||||
{events.length === 0 ? (
|
||||
<p className="rounded-xl border border-dashed border-[#f6d79e]/30 bg-[#0d1827]/70 px-3 py-4 text-xs text-[#d8d0c3]/76">
|
||||
Waiting for events...
|
||||
</p>
|
||||
) : null}
|
||||
{events.map((entry) => (
|
||||
<div key={entry.id} className="event-card">
|
||||
<p className="font-mono text-[11px] uppercase tracking-[0.12em] text-[#f8ca64]">
|
||||
{entry.method}
|
||||
</p>
|
||||
{entry.message ? (
|
||||
<p className="mt-1 text-xs text-[#efe8d7]/88">
|
||||
{entry.message}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="mt-2 text-[11px] text-[#d8d0c3]/66">
|
||||
{formatTimestamp(entry.createdAt)}
|
||||
{entry.turnId ? ` · ${entry.turnId}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
|
||||
+153
-6
@@ -1,3 +1,4 @@
|
||||
@import url("https://fonts.googleapis.com/css2?family=Fraunces:opsz,[email protected],400;9..144,600;9..144,700&family=IBM+Plex+Mono:wght@400;500;600&display=swap");
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
@@ -5,14 +6,160 @@
|
||||
}
|
||||
|
||||
:root {
|
||||
color-scheme: light;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Iowan Old Style", "Georgia", serif;
|
||||
font-family: "Fraunces", "Iowan Old Style", serif;
|
||||
min-height: 100vh;
|
||||
background:
|
||||
radial-gradient(circle at top left, #d1fae5 0%, transparent 38%),
|
||||
radial-gradient(circle at 88% 20%, #fef3c7 0%, transparent 28%),
|
||||
linear-gradient(130deg, #f8fafc 0%, #eef6f2 50%, #f8fafc 100%);
|
||||
color: #f3f0e9;
|
||||
background: radial-gradient(circle at 8% 3%, #e69f15 0%, transparent 33%),
|
||||
radial-gradient(circle at 92% 6%, #2d8ba8 0%, transparent 30%),
|
||||
linear-gradient(160deg, #050913 0%, #091320 42%, #090f1a 100%);
|
||||
}
|
||||
|
||||
pre,
|
||||
code,
|
||||
textarea,
|
||||
input,
|
||||
select {
|
||||
font-family: "IBM Plex Mono", "SFMono-Regular", Consolas, monospace;
|
||||
}
|
||||
|
||||
.surface-card {
|
||||
border: 1px solid rgba(246, 215, 158, 0.24);
|
||||
background: linear-gradient(
|
||||
140deg,
|
||||
rgba(11, 24, 40, 0.9),
|
||||
rgba(9, 16, 29, 0.84)
|
||||
), radial-gradient(circle at top, rgba(245, 166, 35, 0.15), transparent 45%);
|
||||
box-shadow: 0 28px 70px -45px rgba(0, 0, 0, 0.85), inset 0 1px 0
|
||||
rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.grain {
|
||||
opacity: 0.18;
|
||||
mix-blend-mode: soft-light;
|
||||
background-image: linear-gradient(
|
||||
45deg,
|
||||
rgba(255, 255, 255, 0.04) 25%,
|
||||
transparent 25%,
|
||||
transparent 50%,
|
||||
rgba(255, 255, 255, 0.04) 50%,
|
||||
rgba(255, 255, 255, 0.04) 75%,
|
||||
transparent 75%,
|
||||
transparent
|
||||
);
|
||||
background-size: 4px 4px;
|
||||
}
|
||||
|
||||
.label-chip {
|
||||
display: inline-flex;
|
||||
border-radius: 9999px;
|
||||
border: 1px solid rgba(246, 215, 158, 0.44);
|
||||
background: rgba(23, 38, 56, 0.55);
|
||||
padding: 0.28rem 0.72rem;
|
||||
font-size: 0.67rem;
|
||||
letter-spacing: 0.14em;
|
||||
text-transform: uppercase;
|
||||
color: #f8ca64;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
display: block;
|
||||
margin-bottom: 0.32rem;
|
||||
font-size: 0.67rem;
|
||||
letter-spacing: 0.14em;
|
||||
text-transform: uppercase;
|
||||
color: rgba(246, 233, 201, 0.82);
|
||||
}
|
||||
|
||||
.field-input {
|
||||
width: 100%;
|
||||
border-radius: 0.8rem;
|
||||
border: 1px solid rgba(246, 215, 158, 0.3);
|
||||
background: rgba(5, 12, 22, 0.85);
|
||||
padding: 0.65rem 0.75rem;
|
||||
color: #f7f1e6;
|
||||
transition: border-color 140ms ease, box-shadow 140ms ease;
|
||||
}
|
||||
|
||||
.field-input:focus {
|
||||
outline: none;
|
||||
border-color: rgba(250, 206, 99, 0.75);
|
||||
box-shadow: 0 0 0 2px rgba(250, 206, 99, 0.18);
|
||||
}
|
||||
|
||||
.action-button {
|
||||
border-radius: 0.8rem;
|
||||
padding: 0.62rem 0.9rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
transition: filter 140ms ease, transform 140ms ease;
|
||||
}
|
||||
|
||||
.action-button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.action-button:not(:disabled):hover {
|
||||
filter: brightness(1.06);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.action-primary {
|
||||
border: 1px solid rgba(250, 206, 99, 0.6);
|
||||
background: linear-gradient(140deg, #f8c861, #e59f0d);
|
||||
color: #1f2530;
|
||||
}
|
||||
|
||||
.action-danger {
|
||||
border: 1px solid rgba(252, 148, 124, 0.44);
|
||||
background: linear-gradient(140deg, #8f2c2b, #bf4738);
|
||||
color: #fff3ef;
|
||||
}
|
||||
|
||||
.action-muted {
|
||||
border: 1px solid rgba(149, 181, 205, 0.4);
|
||||
background: rgba(13, 31, 49, 0.85);
|
||||
color: #dfecfb;
|
||||
}
|
||||
|
||||
.status-pill {
|
||||
border-radius: 9999px;
|
||||
border: 1px solid rgba(246, 215, 158, 0.29);
|
||||
background: rgba(9, 20, 33, 0.9);
|
||||
padding: 0.27rem 0.64rem;
|
||||
font-family: "IBM Plex Mono", "SFMono-Regular", Consolas, monospace;
|
||||
color: rgba(248, 235, 206, 0.86);
|
||||
}
|
||||
|
||||
.message-card {
|
||||
border-radius: 1rem;
|
||||
border: 1px solid rgba(246, 215, 158, 0.25);
|
||||
background: rgba(8, 16, 27, 0.82);
|
||||
padding: 0.9rem;
|
||||
}
|
||||
|
||||
.message-user {
|
||||
border-color: rgba(111, 198, 238, 0.38);
|
||||
background: linear-gradient(
|
||||
160deg,
|
||||
rgba(14, 44, 64, 0.92),
|
||||
rgba(8, 21, 36, 0.92)
|
||||
);
|
||||
}
|
||||
|
||||
.message-assistant {
|
||||
border-color: rgba(250, 206, 99, 0.34);
|
||||
}
|
||||
|
||||
.event-card {
|
||||
border-radius: 0.85rem;
|
||||
border: 1px solid rgba(246, 215, 158, 0.2);
|
||||
background: rgba(8, 16, 27, 0.76);
|
||||
padding: 0.62rem 0.72rem;
|
||||
}
|
||||
@@ -2,3 +2,4 @@ export * from "./todo";
|
||||
export * from "./ipc";
|
||||
export * from "./agent";
|
||||
export * from "./terminal";
|
||||
export * from "./provider";
|
||||
@@ -1,4 +1,13 @@
|
||||
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderTurnStartResult,
|
||||
} from "./provider";
|
||||
import type { TerminalCommandInput, TerminalCommandResult } from "./terminal";
|
||||
import type { NewTodoInput, Todo } from "./todo";
|
||||
|
||||
@@ -13,6 +22,12 @@ export const IPC_CHANNELS = {
|
||||
agentWrite: "agent:write",
|
||||
agentOutput: "agent:output",
|
||||
agentExit: "agent:exit",
|
||||
providerSessionStart: "provider:session:start",
|
||||
providerTurnStart: "provider:turn:start",
|
||||
providerTurnInterrupt: "provider:turn:interrupt",
|
||||
providerSessionStop: "provider:session:stop",
|
||||
providerSessionList: "provider:session:list",
|
||||
providerEvent: "provider:event",
|
||||
} as const;
|
||||
|
||||
export interface NativeApi {
|
||||
@@ -32,4 +47,16 @@ export interface NativeApi {
|
||||
onOutput: (callback: (chunk: OutputChunk) => void) => () => void;
|
||||
onExit: (callback: (exit: AgentExit) => void) => () => void;
|
||||
};
|
||||
providers: {
|
||||
startSession: (
|
||||
input: ProviderSessionStartInput,
|
||||
) => Promise<ProviderSession>;
|
||||
sendTurn: (
|
||||
input: ProviderSendTurnInput,
|
||||
) => Promise<ProviderTurnStartResult>;
|
||||
interruptTurn: (input: ProviderInterruptTurnInput) => Promise<void>;
|
||||
stopSession: (input: ProviderStopSessionInput) => Promise<void>;
|
||||
listSessions: () => Promise<ProviderSession[]>;
|
||||
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
providerEventSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
} from "./provider";
|
||||
|
||||
describe("providerSessionStartInputSchema", () => {
|
||||
it("defaults to codex with safe policies", () => {
|
||||
const parsed = providerSessionStartInputSchema.parse({});
|
||||
expect(parsed.provider).toBe("codex");
|
||||
expect(parsed.approvalPolicy).toBe("never");
|
||||
expect(parsed.sandboxMode).toBe("workspace-write");
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerSendTurnInputSchema", () => {
|
||||
it("trims input text", () => {
|
||||
const parsed = providerSendTurnInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
input: " summarize this repo ",
|
||||
});
|
||||
expect(parsed.input).toBe("summarize this repo");
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerEventSchema", () => {
|
||||
it("accepts notification events with routing metadata", () => {
|
||||
const parsed = providerEventSchema.parse({
|
||||
id: "evt_1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess_1",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "item/agentMessage/delta",
|
||||
threadId: "thr_1",
|
||||
turnId: "turn_1",
|
||||
itemId: "item_1",
|
||||
textDelta: "hi",
|
||||
});
|
||||
expect(parsed.method).toBe("item/agentMessage/delta");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const providerKindSchema = z.enum(["codex", "claudeCode"]);
|
||||
|
||||
export const providerApprovalPolicySchema = z.enum([
|
||||
"untrusted",
|
||||
"on-failure",
|
||||
"on-request",
|
||||
"never",
|
||||
]);
|
||||
|
||||
export const providerSandboxModeSchema = z.enum([
|
||||
"read-only",
|
||||
"workspace-write",
|
||||
"danger-full-access",
|
||||
]);
|
||||
|
||||
export const providerSessionStatusSchema = z.enum([
|
||||
"connecting",
|
||||
"ready",
|
||||
"running",
|
||||
"error",
|
||||
"closed",
|
||||
]);
|
||||
|
||||
export const providerSessionSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
provider: providerKindSchema,
|
||||
status: providerSessionStatusSchema,
|
||||
cwd: z.string().min(1).optional(),
|
||||
model: z.string().min(1).optional(),
|
||||
threadId: z.string().min(1).optional(),
|
||||
activeTurnId: z.string().min(1).optional(),
|
||||
createdAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime(),
|
||||
lastError: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
export const providerSessionStartInputSchema = z.object({
|
||||
provider: providerKindSchema.default("codex"),
|
||||
cwd: z.string().min(1).optional(),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
approvalPolicy: providerApprovalPolicySchema.default("never"),
|
||||
sandboxMode: providerSandboxModeSchema.default("workspace-write"),
|
||||
});
|
||||
|
||||
export const providerSendTurnInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
input: z.string().trim().min(1).max(120_000),
|
||||
});
|
||||
|
||||
export const providerTurnStartResultSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const providerInterruptTurnInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
turnId: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
export const providerStopSessionInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const providerEventKindSchema = z.enum([
|
||||
"session",
|
||||
"notification",
|
||||
"request",
|
||||
"error",
|
||||
]);
|
||||
|
||||
export const providerEventSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
kind: providerEventKindSchema,
|
||||
provider: providerKindSchema,
|
||||
sessionId: z.string().min(1),
|
||||
createdAt: z.string().datetime(),
|
||||
method: z.string().min(1),
|
||||
message: z.string().min(1).optional(),
|
||||
threadId: z.string().min(1).optional(),
|
||||
turnId: z.string().min(1).optional(),
|
||||
itemId: z.string().min(1).optional(),
|
||||
textDelta: z.string().optional(),
|
||||
payload: z.unknown().optional(),
|
||||
});
|
||||
|
||||
export type ProviderKind = z.infer<typeof providerKindSchema>;
|
||||
export type ProviderApprovalPolicy = z.infer<
|
||||
typeof providerApprovalPolicySchema
|
||||
>;
|
||||
export type ProviderSandboxMode = z.infer<typeof providerSandboxModeSchema>;
|
||||
export type ProviderSessionStatus = z.infer<typeof providerSessionStatusSchema>;
|
||||
export type ProviderSession = z.infer<typeof providerSessionSchema>;
|
||||
export type ProviderSessionStartInput = z.input<
|
||||
typeof providerSessionStartInputSchema
|
||||
>;
|
||||
export type ProviderSendTurnInput = z.input<typeof providerSendTurnInputSchema>;
|
||||
export type ProviderTurnStartResult = z.infer<
|
||||
typeof providerTurnStartResultSchema
|
||||
>;
|
||||
export type ProviderInterruptTurnInput = z.input<
|
||||
typeof providerInterruptTurnInputSchema
|
||||
>;
|
||||
export type ProviderStopSessionInput = z.input<
|
||||
typeof providerStopSessionInputSchema
|
||||
>;
|
||||
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
|
||||
export type ProviderEvent = z.infer<typeof providerEventSchema>;
|
||||
Reference in new issue
Block a user