@mistriwork/acp 0.0.1 → 1.4.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Baljinder Randhawa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,10 @@
1
+ # @mistriwork/acp
2
+
3
+ Agent Client Protocol (ACP) host runtime, stdio MCP client, and coding-agent presets for [mistri](https://mistriwork.dev) Apps — zero extra runtime dependencies.
4
+
5
+ ## What is in it
6
+
7
+ - **`createAcpClient`**: Full ACP v1 JSON-RPC 2.0 client over stdio subprocesses (or custom streams), with strict allowlisted child environments, detached process-group teardown, `SandboxAdapter` delegation for `fs/*` and `terminal/*`, and `PermissionBroker` integration for `session/request_permission`.
8
+ - **`createAcpAgentRuntime`**: Implements `@mistriwork/mistri/agents`'s `ExternalAgentRuntime`, folding ACP `session/update` notifications into Mistri's normalized `AgentEvent` stream (`text`, `reasoning`, `tool_call`, `tool_call_update`, `plan`, `diff`, `permission_request`, `permission_resolved`, `mode_changed`, `done`).
9
+ - **`createStdioMcpClient` / `createStdioMcpTransport`**: Spawns workspace-local stdio MCP servers with allowlisted environments and wraps them in `@mistriwork/mistri/mcp`'s `createMcpClient`.
10
+ - **Presets**: `claudeCodeAcp()`, `codexAcp()`, `geminiAcp()`, and `customAcp()`.
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Adapts an ACP coding-agent process (Claude Code, Codex, Gemini CLI, etc.) to
3
+ * Mistri's `ExternalAgentRuntime` seam (`@mistriwork/mistri/agents`), automatically
4
+ * wiring Mistri's `PermissionBroker`, `SandboxAdapter`, and scoped `mcpServers`
5
+ * (including `createScopedMcpBridge` / `createAppMcpBridgeConfig`).
6
+ */
7
+ import type { ExternalAgentRuntime } from '@mistriwork/mistri/agents';
8
+ import type { AcpClient, AcpClientOptions, AcpMcpServerSpec, AcpSessionInfo } from './types.js';
9
+ export interface AcpAgentRuntimeOptions extends Omit<AcpClientOptions, 'principal' | 'permissions' | 'sandbox'> {
10
+ /** Logical identifier for this runtime (e.g. `'claude-code'`, `'codex'`, `'gemini'`). */
11
+ readonly id: string;
12
+ /** Default workspace directory used when `prompt()` does not supply `cwd`. */
13
+ readonly defaultCwd?: string;
14
+ /** MCP servers injected into `session/new` / `session/load` (e.g., Mistri's `createScopedMcpBridge().mcpServerConfig`). */
15
+ readonly mcpServers?: readonly AcpMcpServerSpec[];
16
+ /** Optional `_meta` forwarded to `session/new` (for example Claude Code `settingSources`). */
17
+ readonly sessionMeta?: Readonly<Record<string, unknown>>;
18
+ /** Optional authentication method id invoked automatically after `initialize` if listed. */
19
+ readonly authMethodId?: string;
20
+ }
21
+ export interface AcpAgentRuntime extends ExternalAgentRuntime {
22
+ /** Underlying ACP client once started (lazy-initialized on first `prompt()`). */
23
+ getClient(): AcpClient | undefined;
24
+ /** Active ACP session info once created or loaded. */
25
+ getSession(): AcpSessionInfo | undefined;
26
+ }
27
+ /**
28
+ * Create a Mistri `ExternalAgentRuntime` backed by an ACP v1 coding agent.
29
+ * Reuses one durable ACP session across turns (or resumes `options.sessionId`) and
30
+ * returns standard Mistri `AgentTurnResult` + normalized `AgentEvent` streams.
31
+ */
32
+ export declare function createAcpAgentRuntime(options: AcpAgentRuntimeOptions): AcpAgentRuntime;
@@ -0,0 +1,102 @@
1
+ import { createAcpClient } from './client.js';
2
+ /**
3
+ * Create a Mistri `ExternalAgentRuntime` backed by an ACP v1 coding agent.
4
+ * Reuses one durable ACP session across turns (or resumes `options.sessionId`) and
5
+ * returns standard Mistri `AgentTurnResult` + normalized `AgentEvent` streams.
6
+ */
7
+ export function createAcpAgentRuntime(options) {
8
+ let client;
9
+ let session;
10
+ const ensureClient = (turnOpts) => {
11
+ if (client)
12
+ return client;
13
+ client = createAcpClient({
14
+ ...options,
15
+ cwd: turnOpts.cwd ?? options.cwd ?? options.defaultCwd,
16
+ principal: turnOpts.principal,
17
+ permissions: turnOpts.permissions,
18
+ sandbox: turnOpts.sandbox,
19
+ });
20
+ return client;
21
+ };
22
+ const ensureSession = async (acp, turnOpts) => {
23
+ if (session && (!turnOpts.sessionId || session.sessionId === turnOpts.sessionId)) {
24
+ return session;
25
+ }
26
+ const init = await acp.initialize(turnOpts.signal);
27
+ if (options.authMethodId && init.authMethods.some((m) => m.id === options.authMethodId)) {
28
+ await acp.authenticate(options.authMethodId, turnOpts.signal);
29
+ }
30
+ const cwd = turnOpts.cwd ?? options.defaultCwd ?? options.cwd ?? process.cwd();
31
+ const mcpServers = options.mcpServers ?? [];
32
+ if (turnOpts.sessionId && init.agentCapabilities.loadSession) {
33
+ session = await acp.loadSession({
34
+ sessionId: turnOpts.sessionId,
35
+ cwd,
36
+ mcpServers,
37
+ signal: turnOpts.signal,
38
+ });
39
+ }
40
+ else {
41
+ session = await acp.newSession({
42
+ cwd,
43
+ mcpServers,
44
+ mode: turnOpts.mode ?? turnOpts.permissions?.getMode(),
45
+ _meta: options.sessionMeta,
46
+ signal: turnOpts.signal,
47
+ });
48
+ }
49
+ return session;
50
+ };
51
+ return Object.freeze({
52
+ id: options.id,
53
+ kind: 'acp',
54
+ getClient: () => client,
55
+ getSession: () => session,
56
+ async prompt(userText, turnOpts) {
57
+ const acp = ensureClient(turnOpts);
58
+ const sess = await ensureSession(acp, turnOpts);
59
+ if (turnOpts.mode) {
60
+ await acp.setMode(sess.sessionId, turnOpts.mode, turnOpts.signal).catch(() => { });
61
+ }
62
+ const res = await acp.prompt(sess.sessionId, userText, {
63
+ signal: turnOpts.signal,
64
+ emit: turnOpts.emit,
65
+ });
66
+ const steps = res.toolCalls.map((call) => ({
67
+ id: call.toolCallId,
68
+ tool: call.kind ?? 'tool',
69
+ label: call.title,
70
+ ...(call.status === 'failed' ? { failed: true } : {}),
71
+ }));
72
+ return {
73
+ agentId: options.id,
74
+ text: res.text,
75
+ reasoning: res.reasoning ? [{ id: `reason_${sess.sessionId}`, text: res.reasoning }] : [],
76
+ steps,
77
+ blocks: [],
78
+ artifacts: [],
79
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
80
+ totalTokens: 0,
81
+ modelSteps: Math.max(1, steps.length),
82
+ stopReason: res.stopReason,
83
+ };
84
+ },
85
+ async setMode(mode) {
86
+ if (client && session) {
87
+ await client.setMode(session.sessionId, mode);
88
+ }
89
+ },
90
+ async cancel(sessionId) {
91
+ const target = sessionId ?? session?.sessionId;
92
+ if (client && target)
93
+ client.cancel(target);
94
+ },
95
+ async close() {
96
+ const closing = client;
97
+ client = undefined;
98
+ session = undefined;
99
+ await closing?.close();
100
+ },
101
+ });
102
+ }
@@ -0,0 +1,54 @@
1
+ import type { AssistantModel } from '@mistriwork/mistri/agents';
2
+ export type CliAgentKind = 'claude' | 'codex' | 'opencode' | 'custom';
3
+ export interface CliAgentAdapterOptions {
4
+ readonly kind: CliAgentKind;
5
+ /** Working directory for spawned CLI commands. Defaults to `process.cwd()`. */
6
+ readonly cwd?: string;
7
+ /** Override the executable path/name (required when `kind === 'custom'`). */
8
+ readonly command?: string;
9
+ /** Extra CLI arguments appended before the prompt (or full argument builder when `buildArgs` is set). */
10
+ readonly args?: readonly string[];
11
+ /** Custom argument builder taking the prompt string and returning argv. */
12
+ readonly buildArgs?: (prompt: string, options?: CliAgentRunOptions) => readonly string[];
13
+ /** Optional default model name forwarded to the CLI when supported. */
14
+ readonly model?: string;
15
+ /** Default timeout in milliseconds before terminating the process tree (default 120_000). */
16
+ readonly timeoutMs?: number;
17
+ /** Maximum stdout/stderr bytes retained per run (default 512 KiB). */
18
+ readonly maxOutputBytes?: number;
19
+ /** Explicit environment variables added to the sanitized child environment. */
20
+ readonly extraEnv?: Readonly<Record<string, string>>;
21
+ /** Host environment variable names explicitly allowed through to the child process. */
22
+ readonly passThroughEnv?: readonly string[];
23
+ }
24
+ export interface CliAgentRunOptions {
25
+ readonly cwd?: string;
26
+ readonly model?: string;
27
+ readonly timeoutMs?: number;
28
+ readonly signal?: AbortSignal;
29
+ /** Optional streaming callback invoked with each UTF-8 stdout chunk as it arrives. */
30
+ readonly onStdout?: (chunk: string) => void;
31
+ }
32
+ export interface CliAgentRunResult {
33
+ readonly exitCode: number;
34
+ readonly stdout: string;
35
+ readonly stderr: string;
36
+ readonly durationMs: number;
37
+ readonly timedOut: boolean;
38
+ readonly command: string;
39
+ }
40
+ export interface CliAgentAdapter {
41
+ readonly kind: CliAgentKind;
42
+ readonly command: string;
43
+ /** Check whether the CLI binary exists and is executable without invoking a model turn. */
44
+ isAvailable(): Promise<boolean>;
45
+ /** Execute one prompt turn against the local CLI subprocess with bounded output and timeout control. */
46
+ run(prompt: string, options?: CliAgentRunOptions): Promise<CliAgentRunResult>;
47
+ /** Wrap this CLI adapter as a Mistri `AssistantModel` for `runAgentTurn` or `withModelFallback`. */
48
+ asModel(): AssistantModel;
49
+ }
50
+ /**
51
+ * Create a safe, sanitized-env subprocess adapter for local coding CLIs
52
+ * (`claude`, `codex`, `opencode`, or `custom`), runnable standalone or via `.asModel()`.
53
+ */
54
+ export declare function createCliAgentAdapter(options: CliAgentAdapterOptions): CliAgentAdapter;
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Thin subprocess adapter for invoking locally installed non-ACP coding CLIs
3
+ * (`claude`, `codex`, `opencode`, or a custom command) with sanitized child
4
+ * environments, PATH availability probing, bounded stdout/stderr capture,
5
+ * process-group timeout/abort teardown, and an optional `AssistantModel` bridge.
6
+ */
7
+ import { constants as fsConstants } from 'node:fs';
8
+ import { access } from 'node:fs/promises';
9
+ import { delimiter, isAbsolute, join } from 'node:path';
10
+ import { killProcessTree, spawnManagedSubprocess } from './env.js';
11
+ const DEFAULT_TIMEOUT_MS = 120_000;
12
+ const DEFAULT_MAX_OUTPUT_BYTES = 512 * 1024;
13
+ function defaultCommandFor(kind) {
14
+ if (kind === 'claude')
15
+ return 'claude';
16
+ if (kind === 'codex')
17
+ return 'codex';
18
+ if (kind === 'opencode')
19
+ return 'opencode';
20
+ throw new TypeError('createCliAgentAdapter: "command" is required when kind is "custom".');
21
+ }
22
+ function defaultArgsFor(kind, prompt, model, extraArgs) {
23
+ if (kind === 'claude') {
24
+ return ['-p', prompt, '--output-format', 'text', ...(model ? ['--model', model] : []), ...extraArgs];
25
+ }
26
+ if (kind === 'codex') {
27
+ return ['exec', ...(model ? ['--model', model] : []), ...extraArgs, prompt];
28
+ }
29
+ if (kind === 'opencode') {
30
+ return ['run', ...(model ? ['--model', model] : []), ...extraArgs, prompt];
31
+ }
32
+ return [...extraArgs, prompt];
33
+ }
34
+ async function isExecutable(filePath) {
35
+ try {
36
+ await access(filePath, fsConstants.X_OK);
37
+ return true;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ async function probeCommandOnPath(command) {
44
+ if (!command.trim())
45
+ return false;
46
+ if (isAbsolute(command) || command.includes('/') || command.includes('\\')) {
47
+ return isExecutable(command);
48
+ }
49
+ const pathEnv = process.env.PATH ?? '';
50
+ const dirs = pathEnv.split(delimiter).filter(Boolean);
51
+ const exts = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];
52
+ for (const dir of dirs) {
53
+ for (const ext of exts) {
54
+ if (await isExecutable(join(dir, `${command}${ext}`)))
55
+ return true;
56
+ }
57
+ }
58
+ return false;
59
+ }
60
+ function appendBounded(chunks, totalRef, chunk, limit) {
61
+ if (totalRef.bytes >= limit)
62
+ return;
63
+ const remaining = limit - totalRef.bytes;
64
+ const slice = chunk.byteLength > remaining ? chunk.subarray(0, remaining) : chunk;
65
+ chunks.push(slice);
66
+ totalRef.bytes += slice.byteLength;
67
+ }
68
+ function promptFromModelRequest(request) {
69
+ const parts = [];
70
+ if (request.system.trim())
71
+ parts.push(request.system.trim());
72
+ for (const msg of request.messages) {
73
+ const text = typeof msg.content === 'string'
74
+ ? msg.content
75
+ : msg.content
76
+ .map((block) => {
77
+ if (block.type === 'text' && typeof block.text === 'string')
78
+ return block.text;
79
+ if (block.type === 'tool_result' && typeof block.content === 'string')
80
+ return block.content;
81
+ return '';
82
+ })
83
+ .filter(Boolean)
84
+ .join('\n');
85
+ if (text.trim())
86
+ parts.push(`${msg.role}: ${text.trim()}`);
87
+ }
88
+ return parts.join('\n\n');
89
+ }
90
+ /**
91
+ * Create a safe, sanitized-env subprocess adapter for local coding CLIs
92
+ * (`claude`, `codex`, `opencode`, or `custom`), runnable standalone or via `.asModel()`.
93
+ */
94
+ export function createCliAgentAdapter(options) {
95
+ const command = options.command?.trim() || defaultCommandFor(options.kind);
96
+ const extraArgs = options.args ?? [];
97
+ const defaultTimeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
98
+ const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
99
+ const run = async (prompt, runOptions) => {
100
+ const model = runOptions?.model ?? options.model;
101
+ const args = options.buildArgs ? [...options.buildArgs(prompt, runOptions)] : defaultArgsFor(options.kind, prompt, model, extraArgs);
102
+ const timeoutMs = runOptions?.timeoutMs ?? defaultTimeoutMs;
103
+ const started = Date.now();
104
+ const child = spawnManagedSubprocess({
105
+ command,
106
+ args,
107
+ cwd: runOptions?.cwd ?? options.cwd,
108
+ extraEnv: options.extraEnv,
109
+ passThroughEnv: options.passThroughEnv,
110
+ });
111
+ child.stdin?.end();
112
+ const outChunks = [];
113
+ const errChunks = [];
114
+ const outBytes = { bytes: 0 };
115
+ const errBytes = { bytes: 0 };
116
+ child.stdout?.on('data', (chunk) => {
117
+ appendBounded(outChunks, outBytes, chunk, maxOutputBytes);
118
+ if (runOptions?.onStdout)
119
+ runOptions.onStdout(chunk.toString('utf8'));
120
+ });
121
+ child.stderr?.on('data', (chunk) => appendBounded(errChunks, errBytes, chunk, maxOutputBytes));
122
+ let timedOut = false;
123
+ let settled = false;
124
+ const result = await new Promise((resolve, reject) => {
125
+ const finish = (exitCode) => {
126
+ if (settled)
127
+ return;
128
+ settled = true;
129
+ clearTimeout(timer);
130
+ runOptions?.signal?.removeEventListener('abort', onAbort);
131
+ resolve({
132
+ exitCode,
133
+ stdout: Buffer.concat(outChunks).toString('utf8'),
134
+ stderr: Buffer.concat(errChunks).toString('utf8'),
135
+ durationMs: Date.now() - started,
136
+ timedOut,
137
+ command,
138
+ });
139
+ };
140
+ const onAbort = () => {
141
+ void killProcessTree(child).finally(() => finish(130));
142
+ };
143
+ if (runOptions?.signal?.aborted) {
144
+ onAbort();
145
+ return;
146
+ }
147
+ runOptions?.signal?.addEventListener('abort', onAbort, { once: true });
148
+ const timer = setTimeout(() => {
149
+ timedOut = true;
150
+ void killProcessTree(child).finally(() => finish(124));
151
+ }, timeoutMs);
152
+ timer.unref?.();
153
+ child.once('error', (error) => {
154
+ if (settled)
155
+ return;
156
+ settled = true;
157
+ clearTimeout(timer);
158
+ runOptions?.signal?.removeEventListener('abort', onAbort);
159
+ reject(error);
160
+ });
161
+ child.once('close', (code) => {
162
+ finish(code ?? (timedOut ? 124 : 1));
163
+ });
164
+ });
165
+ return result;
166
+ };
167
+ const asModel = () => ({
168
+ async stream(request, sink, signal) {
169
+ const prompt = promptFromModelRequest(request);
170
+ const emit = typeof sink === 'function' ? sink : sink.onText;
171
+ const res = await run(prompt, {
172
+ signal,
173
+ ...(request.model ? { model: request.model } : {}),
174
+ ...(emit ? { onStdout: emit } : {}),
175
+ });
176
+ if (res.timedOut) {
177
+ throw new Error(`CLI agent "${command}" timed out after ${res.durationMs}ms.`);
178
+ }
179
+ if (res.exitCode !== 0) {
180
+ throw new Error(`CLI agent "${command}" exited with code ${res.exitCode}: ${res.stderr.trim() || res.stdout.trim()}`);
181
+ }
182
+ const text = res.stdout.trim();
183
+ return {
184
+ content: text ? [{ type: 'text', text }] : [],
185
+ stopReason: 'end_turn',
186
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
187
+ };
188
+ },
189
+ });
190
+ return Object.freeze({
191
+ kind: options.kind,
192
+ command,
193
+ isAvailable: () => probeCommandOnPath(command),
194
+ run,
195
+ asModel,
196
+ });
197
+ }
@@ -0,0 +1,6 @@
1
+ import { type AcpClient, type AcpClientOptions } from './types.js';
2
+ /**
3
+ * Create an ACP v1 client connected to either a spawned coding-agent subprocess
4
+ * or an in-memory stream pair.
5
+ */
6
+ export declare function createAcpClient(options: AcpClientOptions): AcpClient;