@qlairoslabs/acp-client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,193 @@
1
+ /// <reference types="bun" />
2
+ // The ONLY module that touches the SDK or spawns a process. Wraps
3
+ // @agentclientprotocol/sdk: spawn → ndjson stream → ClientSideConnection. Everything
4
+ // above this layer is protocol-plumbing-agnostic. See SPEC.md "Architecture".
5
+
6
+ import * as acp from "@agentclientprotocol/sdk";
7
+ import type * as schema from "@agentclientprotocol/sdk";
8
+ import { ProcessCrashError } from "../errors.ts";
9
+
10
+ export interface AcpTransportOptions {
11
+ /** Full command to spawn: [...execPrefix, ...adapter.command]. */
12
+ command: string[];
13
+ /** cwd for the spawned process. Omit for `docker exec` (host path won't resolve in-container). */
14
+ cwd?: string;
15
+ env?: Record<string, string>;
16
+
17
+ /** A session/update notification arrived. */
18
+ onUpdate?: (notification: schema.SessionNotification) => void;
19
+ /** The agent asked for permission (blocking — must resolve to an outcome). */
20
+ onPermissionRequest?: (
21
+ params: schema.RequestPermissionRequest,
22
+ ) => Promise<schema.RequestPermissionResponse>;
23
+ /** The agent wants to read a file from the client. */
24
+ onReadTextFile?: (
25
+ params: schema.ReadTextFileRequest,
26
+ ) => Promise<schema.ReadTextFileResponse>;
27
+ /** The agent wants to write a file via the client. */
28
+ onWriteTextFile?: (
29
+ params: schema.WriteTextFileRequest,
30
+ ) => Promise<schema.WriteTextFileResponse>;
31
+ /** A line of stderr from the process. */
32
+ onStderr?: (line: string) => void;
33
+ /** The process exited unexpectedly (not via stop()). */
34
+ onCrash?: (code: number | null) => void;
35
+ }
36
+
37
+ export class AcpTransport {
38
+ private proc: ReturnType<typeof Bun.spawn> | null = null;
39
+ private connection: acp.ClientSideConnection | null = null;
40
+ private stopping = false;
41
+
42
+ constructor(private opts: AcpTransportOptions) {}
43
+
44
+ async start(): Promise<void> {
45
+ if (this.proc) return;
46
+
47
+ // A TransformStream gives us a real WritableStream<Uint8Array> for the SDK —
48
+ // Bun's FileSink (from stdin:"pipe") lacks getWriter().
49
+ const stdinTransform = new TransformStream<Uint8Array, Uint8Array>();
50
+
51
+ const proc = Bun.spawn(this.opts.command, {
52
+ cwd: this.opts.cwd,
53
+ env: { ...process.env, ...(this.opts.env ?? {}) },
54
+ stdin: stdinTransform.readable,
55
+ stdout: "pipe",
56
+ stderr: "pipe",
57
+ });
58
+ this.proc = proc;
59
+
60
+ const stream = acp.ndJsonStream(
61
+ stdinTransform.writable,
62
+ proc.stdout as ReadableStream<Uint8Array>,
63
+ );
64
+ const handler = new ClientHandler(this.opts);
65
+ this.connection = new acp.ClientSideConnection(() => handler, stream);
66
+
67
+ if (proc.stderr) this.pumpStderr(proc.stderr as ReadableStream<Uint8Array>);
68
+
69
+ proc.exited
70
+ .then((code) => {
71
+ if (this.proc === proc && !this.stopping) {
72
+ this.proc = null;
73
+ this.connection = null;
74
+ this.opts.onCrash?.(code ?? null);
75
+ }
76
+ })
77
+ .catch(() => {});
78
+ }
79
+
80
+ async stop(): Promise<void> {
81
+ this.stopping = true;
82
+ if (!this.proc) return;
83
+ try {
84
+ this.proc.kill("SIGTERM");
85
+ } catch {
86
+ /* already exited */
87
+ }
88
+ this.proc = null;
89
+ this.connection = null;
90
+ }
91
+
92
+ private conn(): acp.ClientSideConnection {
93
+ if (!this.connection) throw new ProcessCrashError(null, "ACP transport not started");
94
+ return this.connection;
95
+ }
96
+
97
+ // --- protocol methods (thin pass-through to the SDK) ----------------------------
98
+
99
+ initialize(params: schema.InitializeRequest): Promise<schema.InitializeResponse> {
100
+ return this.conn().initialize(params);
101
+ }
102
+ newSession(params: schema.NewSessionRequest): Promise<schema.NewSessionResponse> {
103
+ return this.conn().newSession(params);
104
+ }
105
+ loadSession(params: schema.LoadSessionRequest): Promise<schema.LoadSessionResponse> {
106
+ return this.conn().loadSession(params);
107
+ }
108
+ forkSession(params: schema.ForkSessionRequest): Promise<schema.ForkSessionResponse> {
109
+ return this.conn().unstable_forkSession(params);
110
+ }
111
+ resumeSession(params: schema.ResumeSessionRequest): Promise<schema.ResumeSessionResponse> {
112
+ return this.conn().resumeSession(params);
113
+ }
114
+ listSessions(params: schema.ListSessionsRequest): Promise<schema.ListSessionsResponse> {
115
+ return this.conn().listSessions(params);
116
+ }
117
+ prompt(params: schema.PromptRequest): Promise<schema.PromptResponse> {
118
+ return this.conn().prompt(params);
119
+ }
120
+ cancel(params: schema.CancelNotification): Promise<void> {
121
+ return this.conn().cancel(params);
122
+ }
123
+ authenticate(params: schema.AuthenticateRequest): Promise<schema.AuthenticateResponse> {
124
+ return this.conn().authenticate(params);
125
+ }
126
+ setSessionConfigOption(
127
+ params: schema.SetSessionConfigOptionRequest,
128
+ ): Promise<schema.SetSessionConfigOptionResponse> {
129
+ return this.conn().setSessionConfigOption(params);
130
+ }
131
+
132
+ /** Race a promise against process exit — catches dead/unauthenticated binaries early. */
133
+ raceExit<T>(p: Promise<T>): Promise<T> {
134
+ if (!this.proc) return p;
135
+ const exit = this.proc.exited.then((code) => {
136
+ throw new ProcessCrashError(
137
+ code ?? null,
138
+ `ACP server exited (code ${code ?? "?"}) before the operation completed — ` +
139
+ `verify the provider binary is installed and authenticated`,
140
+ );
141
+ });
142
+ return Promise.race([p, exit as Promise<never>]);
143
+ }
144
+
145
+ private async pumpStderr(stream: ReadableStream<Uint8Array>): Promise<void> {
146
+ const reader = stream.getReader();
147
+ const dec = new TextDecoder();
148
+ let buf = "";
149
+ for (;;) {
150
+ const { value, done } = await reader.read();
151
+ if (done) break;
152
+ buf += dec.decode(value, { stream: true });
153
+ let i;
154
+ while ((i = buf.indexOf("\n")) >= 0) {
155
+ const line = buf.slice(0, i).trim();
156
+ buf = buf.slice(i + 1);
157
+ if (line) this.opts.onStderr?.(line);
158
+ }
159
+ }
160
+ const tail = buf.trim();
161
+ if (tail) this.opts.onStderr?.(tail);
162
+ }
163
+ }
164
+
165
+ /** Routes SDK client-side callbacks to the transport's option handlers. */
166
+ class ClientHandler implements acp.Client {
167
+ constructor(private opts: AcpTransportOptions) {}
168
+
169
+ async sessionUpdate(params: schema.SessionNotification): Promise<void> {
170
+ this.opts.onUpdate?.(params);
171
+ }
172
+
173
+ async requestPermission(
174
+ params: schema.RequestPermissionRequest,
175
+ ): Promise<schema.RequestPermissionResponse> {
176
+ if (this.opts.onPermissionRequest) return this.opts.onPermissionRequest(params);
177
+ return { outcome: { outcome: "cancelled" } };
178
+ }
179
+
180
+ async readTextFile(
181
+ params: schema.ReadTextFileRequest,
182
+ ): Promise<schema.ReadTextFileResponse> {
183
+ if (this.opts.onReadTextFile) return this.opts.onReadTextFile(params);
184
+ return { content: "" };
185
+ }
186
+
187
+ async writeTextFile(
188
+ params: schema.WriteTextFileRequest,
189
+ ): Promise<schema.WriteTextFileResponse> {
190
+ if (this.opts.onWriteTextFile) return this.opts.onWriteTextFile(params);
191
+ return {};
192
+ }
193
+ }
package/src/types.ts ADDED
@@ -0,0 +1,112 @@
1
+ // Core shared types — the OUTPUT contract.
2
+ // These are what every client (AcpClient, and later PtyClient) produces, so callers
3
+ // render against these regardless of which mode is active. See SPEC.md.
4
+
5
+ /**
6
+ * A slash command the AGENT itself exposes (e.g. codex /model, kimi /sessions), learned
7
+ * from the `available_commands_update` notification. Invoke with the `//name` passthrough.
8
+ */
9
+ export interface AgentCommand {
10
+ name: string;
11
+ description: string;
12
+ }
13
+
14
+ /** Token accounting for a turn. Nullable per-field — not all providers report all of it. */
15
+ export interface Usage {
16
+ inputTokens: number;
17
+ outputTokens: number;
18
+ cacheReadTokens?: number;
19
+ cacheWriteTokens?: number;
20
+ /** Only providers that do extended thinking report this. */
21
+ thoughtTokens?: number;
22
+ }
23
+
24
+ /**
25
+ * The result of a single prompt turn.
26
+ *
27
+ * `status` carries cancel/error state so the caller can react (mark not-delivered,
28
+ * errored, etc.) — but interpreting it is the caller's concern. On cancellation the
29
+ * call RESOLVES (not rejects) with whatever partial text arrived.
30
+ */
31
+ export interface PromptResult {
32
+ /** Accumulated response text (partial if cancelled). */
33
+ text: string;
34
+ /** Raw protocol stop reason: "end_turn" | "cancelled" | "max_tokens" | ... */
35
+ stopReason: string;
36
+ status: "completed" | "cancelled" | "error";
37
+ usage: Usage | null;
38
+ }
39
+
40
+ /**
41
+ * Real-time, observation-only events during a turn — separate from the response text.
42
+ * Fire-and-forget; the caller renders them if it wants. (Permission requests are NOT
43
+ * here — they are blocking and handled via PromptHandlers.onPermissionRequest.)
44
+ */
45
+ export type ActivityEvent =
46
+ | { kind: "thinking"; text: string }
47
+ | {
48
+ kind: "tool";
49
+ toolCallId: string;
50
+ title?: string;
51
+ toolKind: string;
52
+ status: string;
53
+ rawInput?: unknown;
54
+ }
55
+ | { kind: "tool_update"; toolCallId: string; status: string }
56
+ | { kind: "plan"; entries: PlanEntry[] };
57
+
58
+ export interface PlanEntry {
59
+ content: string;
60
+ priority: "high" | "medium" | "low";
61
+ status: "pending" | "in_progress" | "completed";
62
+ }
63
+
64
+ /** Outcome the caller returns from a permission request. */
65
+ export type PermissionOutcome =
66
+ | { outcome: "selected"; optionId: string }
67
+ | { outcome: "cancelled" };
68
+
69
+ /** A permission request surfaced to the caller. The agent BLOCKS until this resolves. */
70
+ export interface PermissionRequest {
71
+ toolCallId: string;
72
+ title?: string;
73
+ options: Array<{ optionId: string; name: string; kind: string }>;
74
+ /** The raw SDK request, for callers that need fields we haven't surfaced. */
75
+ raw: unknown;
76
+ }
77
+
78
+ /** Per-prompt callbacks. All optional. */
79
+ export interface PromptHandlers {
80
+ /** Partial response text (agent_message_chunk) as it streams. */
81
+ onChunk?: (text: string) => void;
82
+ /** Observation-only activity (thinking, tool calls, plan). */
83
+ onActivity?: (event: ActivityEvent) => void;
84
+ /**
85
+ * Blocking permission request. Must return an outcome. If omitted, the client
86
+ * falls back to its configured `defaultPermission`.
87
+ */
88
+ onPermissionRequest?: (
89
+ request: PermissionRequest,
90
+ ) => PermissionOutcome | Promise<PermissionOutcome>;
91
+ }
92
+
93
+ /** Attachment passed alongside a prompt (e.g. an image). */
94
+ export interface Attachment {
95
+ data: ArrayBuffer;
96
+ mimeType: string;
97
+ }
98
+
99
+ /** A session as reported by the agent via session/list (the authoritative source). */
100
+ export interface SessionListEntry {
101
+ sessionId: string;
102
+ cwd: string;
103
+ title?: string;
104
+ updatedAt?: string;
105
+ }
106
+
107
+ /** Result of a paginated session/list call. */
108
+ export interface SessionListPage {
109
+ sessions: SessionListEntry[];
110
+ /** Pass back as `cursor` to fetch the next page; absent when there are no more. */
111
+ nextCursor?: string;
112
+ }
package/src/updates.ts ADDED
@@ -0,0 +1,45 @@
1
+ // Maps raw session/update notifications into our output-contract types.
2
+ // `agent_message_chunk` → response text; everything else → ActivityEvent.
3
+ // See SPEC.md "Protocol facts": all agent→client events are session/update,
4
+ // discriminated by `sessionUpdate`.
5
+
6
+ import type * as schema from "@agentclientprotocol/sdk";
7
+ import type { ActivityEvent, PlanEntry } from "./types.ts";
8
+
9
+ /** Response text from an agent_message_chunk, or "" for any other update. */
10
+ export function extractChunkText(update: schema.SessionUpdate): string {
11
+ const u = update as Record<string, any>;
12
+ if (u.sessionUpdate !== "agent_message_chunk") return "";
13
+ const content = u.content;
14
+ return content?.type === "text" ? (content.text ?? "") : "";
15
+ }
16
+
17
+ /** Map an update to an ActivityEvent, or null if it carries no observable activity. */
18
+ export function toActivityEvent(update: schema.SessionUpdate): ActivityEvent | null {
19
+ const u = update as Record<string, any>;
20
+ switch (u.sessionUpdate) {
21
+ case "agent_thought_chunk": {
22
+ const text = u.content?.type === "text" ? (u.content.text ?? "") : "";
23
+ return text ? { kind: "thinking", text } : null;
24
+ }
25
+ case "tool_call":
26
+ return {
27
+ kind: "tool",
28
+ toolCallId: u.toolCallId,
29
+ title: u.title,
30
+ toolKind: u.kind ?? "other",
31
+ status: u.status ?? "pending",
32
+ rawInput: u.rawInput ?? undefined,
33
+ };
34
+ case "tool_call_update":
35
+ return {
36
+ kind: "tool_update",
37
+ toolCallId: u.toolCallId,
38
+ status: u.status ?? "in_progress",
39
+ };
40
+ case "plan":
41
+ return { kind: "plan", entries: (u.entries ?? []) as PlanEntry[] };
42
+ default:
43
+ return null;
44
+ }
45
+ }