@1agents/acp-service 0.4.0 → 0.5.1
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/README.md +14 -2
- package/dist/src/acp-connection.js +11 -6
- package/dist/src/bridge.js +10 -1
- package/dist/src/dsh.d.ts +6 -0
- package/dist/src/dsh.js +9 -0
- package/dist/src/package.d.ts +3 -0
- package/dist/src/package.js +3 -0
- package/package.json +43 -9
- package/vendor/dsh/LICENSE +21 -0
- package/vendor/dsh/README.md +101 -0
- package/vendor/dsh/adapter.d.ts +82 -0
- package/vendor/dsh/adapter.js +460 -0
- package/vendor/dsh/client.js +336 -0
- package/vendor/dsh/cordis.patch.yml +10 -0
- package/vendor/dsh/discovery.d.ts +4 -0
- package/vendor/dsh/discovery.js +20 -0
- package/vendor/dsh/imports.d.ts +54 -0
- package/vendor/dsh/imports.js +133 -0
- package/vendor/dsh/index.d.ts +5 -0
- package/vendor/dsh/index.js +84 -0
- package/vendor/dsh/preset.d.ts +7 -0
- package/vendor/dsh/preset.js +10 -0
- package/vendor/dsh/service-process.d.ts +10 -0
- package/vendor/dsh/service-process.js +150 -0
- package/vendor/dsh/service-worker.d.ts +1 -0
- package/vendor/dsh/service-worker.js +43 -0
- package/vendor/dsh/state.d.ts +22 -0
- package/vendor/dsh/state.js +47 -0
- package/vendor/dsh/tool-events.d.ts +26 -0
- package/vendor/dsh/tool-events.js +13 -0
- package/vendor/dsh/transport.d.ts +18 -0
- package/vendor/dsh/transport.js +71 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export const name = 'oneagents-acp-preset';
|
|
2
|
+
export const inject = ['agents', 'llm'];
|
|
3
|
+
export function apply(ctx, config) {
|
|
4
|
+
if (!/^[a-z0-9_-]+$/i.test(config.agent))
|
|
5
|
+
throw new Error('Invalid ACP Agent name');
|
|
6
|
+
ctx.on('agent/request', async (_event, next) => {
|
|
7
|
+
await next();
|
|
8
|
+
return { provider: '1agents-acp', model: config.agent };
|
|
9
|
+
});
|
|
10
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface ServiceOptions {
|
|
2
|
+
serviceUrl: string;
|
|
3
|
+
serviceMode: 'auto' | 'external';
|
|
4
|
+
serviceStartupTimeoutMs: number;
|
|
5
|
+
serviceShutdownTimeoutMs: number;
|
|
6
|
+
}
|
|
7
|
+
/** Validate lifecycle options before any process or connection is created. */
|
|
8
|
+
export declare function resolveServiceOptions(input: Partial<ServiceOptions>): ServiceOptions;
|
|
9
|
+
/** Acquire a shared local process lease; release waits for owned process exit, never kills an existing server. */
|
|
10
|
+
export declare function acquireService(options: ServiceOptions): Promise<() => Promise<void>>;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/** Own local ACP service processes; existing and remote servers keep their external owner. */
|
|
2
|
+
import { fork } from 'node:child_process';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
const leases = new Map();
|
|
5
|
+
/** Validate lifecycle options before any process or connection is created. */
|
|
6
|
+
export function resolveServiceOptions(input) {
|
|
7
|
+
const result = {
|
|
8
|
+
serviceUrl: input.serviceUrl ?? 'http://127.0.0.1:36812',
|
|
9
|
+
serviceMode: input.serviceMode ?? 'auto',
|
|
10
|
+
serviceStartupTimeoutMs: input.serviceStartupTimeoutMs ?? 15_000,
|
|
11
|
+
serviceShutdownTimeoutMs: input.serviceShutdownTimeoutMs ?? 5_000,
|
|
12
|
+
};
|
|
13
|
+
const url = new URL(result.serviceUrl);
|
|
14
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
15
|
+
throw new Error('serviceUrl must use http or https');
|
|
16
|
+
if (!['auto', 'external'].includes(result.serviceMode))
|
|
17
|
+
throw new Error('serviceMode must be auto or external');
|
|
18
|
+
for (const value of [result.serviceStartupTimeoutMs, result.serviceShutdownTimeoutMs]) {
|
|
19
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > 2_147_483_647)
|
|
20
|
+
throw new Error('ACP service timeouts must be integers between 1 and 2147483647');
|
|
21
|
+
}
|
|
22
|
+
if (url.port === '0')
|
|
23
|
+
throw new Error('serviceUrl needs a stable, nonzero port for saved sessions');
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
function refused(error) {
|
|
27
|
+
if (!error || typeof error !== 'object')
|
|
28
|
+
return false;
|
|
29
|
+
if (error instanceof AggregateError)
|
|
30
|
+
return error.errors.length > 0 && error.errors.every(refused);
|
|
31
|
+
if ('code' in error && error.code === 'ECONNREFUSED')
|
|
32
|
+
return true;
|
|
33
|
+
return 'cause' in error && refused(error.cause);
|
|
34
|
+
}
|
|
35
|
+
async function running(url, timeout) {
|
|
36
|
+
let response;
|
|
37
|
+
try {
|
|
38
|
+
response = await fetch(new URL('/health', url), { signal: AbortSignal.timeout(timeout), redirect: 'error' });
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (refused(error))
|
|
42
|
+
return false;
|
|
43
|
+
throw new Error(`ACP health check failed at ${url.origin}`, { cause: error });
|
|
44
|
+
}
|
|
45
|
+
if (!response.ok)
|
|
46
|
+
throw new Error(`ACP health check failed: HTTP ${response.status} at ${url.origin}`);
|
|
47
|
+
const body = await response.json();
|
|
48
|
+
if (!body || typeof body !== 'object' || !('service' in body) || body.service !== 'acp-service' || !('status' in body) || body.status !== 'ok') {
|
|
49
|
+
throw new Error(`The listener at ${url.origin} is not a healthy ACP service`);
|
|
50
|
+
}
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
async function start(options, url) {
|
|
54
|
+
if (await running(url, options.serviceStartupTimeoutMs))
|
|
55
|
+
return async () => { };
|
|
56
|
+
const child = fork(fileURLToPath(new URL('./service-worker.js', import.meta.url)), [], {
|
|
57
|
+
execArgv: [], stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
|
58
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
|
|
59
|
+
});
|
|
60
|
+
const ready = Promise.withResolvers();
|
|
61
|
+
const closed = Promise.withResolvers();
|
|
62
|
+
let ended = false;
|
|
63
|
+
child.once('error', error => ready.reject(error));
|
|
64
|
+
child.once('close', (code, signal) => {
|
|
65
|
+
ended = true;
|
|
66
|
+
ready.reject(new Error(`Managed ACP service exited (${signal ?? code})`));
|
|
67
|
+
closed.resolve();
|
|
68
|
+
});
|
|
69
|
+
child.on('message', message => {
|
|
70
|
+
if (!message || typeof message !== 'object' || !('type' in message))
|
|
71
|
+
return;
|
|
72
|
+
if (message.type === 'ready')
|
|
73
|
+
ready.resolve();
|
|
74
|
+
if (message.type === 'error' && 'message' in message && typeof message.message === 'string')
|
|
75
|
+
ready.reject(new Error(message.message));
|
|
76
|
+
});
|
|
77
|
+
let stopping;
|
|
78
|
+
const stop = () => stopping ??= (async () => {
|
|
79
|
+
if (ended)
|
|
80
|
+
return;
|
|
81
|
+
child.kill('SIGTERM');
|
|
82
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), options.serviceShutdownTimeoutMs);
|
|
83
|
+
try {
|
|
84
|
+
await closed.promise;
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
}
|
|
89
|
+
})();
|
|
90
|
+
const timer = setTimeout(() => ready.reject(new Error(`ACP service startup timed out after ${options.serviceStartupTimeoutMs}ms`)), options.serviceStartupTimeoutMs);
|
|
91
|
+
child.send({ host: url.hostname.replace(/^\[|\]$/g, ''), port: Number(url.port || 80), shutdownTimeoutMs: options.serviceShutdownTimeoutMs }, error => { if (error)
|
|
92
|
+
ready.reject(error); });
|
|
93
|
+
try {
|
|
94
|
+
await ready.promise;
|
|
95
|
+
if (!await running(url, options.serviceStartupTimeoutMs))
|
|
96
|
+
throw new Error('ACP service exited during startup');
|
|
97
|
+
return stop;
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
await stop();
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Acquire a shared local process lease; release waits for owned process exit, never kills an existing server. */
|
|
108
|
+
export async function acquireService(options) {
|
|
109
|
+
const url = new URL(options.serviceUrl);
|
|
110
|
+
const local = url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
|
|
111
|
+
&& url.pathname === '/' && !url.search && !url.hash && !url.username && !url.password;
|
|
112
|
+
if (options.serviceMode === 'external' || !local)
|
|
113
|
+
return async () => { };
|
|
114
|
+
const key = url.origin;
|
|
115
|
+
let lease = leases.get(key);
|
|
116
|
+
if (lease?.closing) {
|
|
117
|
+
await lease.closing;
|
|
118
|
+
return acquireService(options);
|
|
119
|
+
}
|
|
120
|
+
if (!lease) {
|
|
121
|
+
lease = { users: 0, ready: start(options, url) };
|
|
122
|
+
leases.set(key, lease);
|
|
123
|
+
}
|
|
124
|
+
lease.users++;
|
|
125
|
+
let stop;
|
|
126
|
+
try {
|
|
127
|
+
stop = await lease.ready;
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (--lease.users === 0)
|
|
131
|
+
leases.delete(key);
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
let released = false;
|
|
135
|
+
return async () => {
|
|
136
|
+
if (released)
|
|
137
|
+
return;
|
|
138
|
+
released = true;
|
|
139
|
+
if (--lease.users !== 0)
|
|
140
|
+
return;
|
|
141
|
+
lease.closing = stop();
|
|
142
|
+
try {
|
|
143
|
+
await lease.closing;
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
if (leases.get(key) === lease)
|
|
147
|
+
leases.delete(key);
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
let startup;
|
|
2
|
+
let stopping = false;
|
|
3
|
+
let shutdownTimeoutMs = 5_000;
|
|
4
|
+
async function shutdown() {
|
|
5
|
+
if (stopping)
|
|
6
|
+
return;
|
|
7
|
+
stopping = true;
|
|
8
|
+
const timer = setTimeout(() => process.exit(1), shutdownTimeoutMs);
|
|
9
|
+
try {
|
|
10
|
+
await (await startup)?.close();
|
|
11
|
+
}
|
|
12
|
+
finally {
|
|
13
|
+
clearTimeout(timer);
|
|
14
|
+
process.exit(0);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
process.once('disconnect', () => { void shutdown(); });
|
|
18
|
+
process.once('SIGTERM', () => { void shutdown(); });
|
|
19
|
+
process.once('SIGINT', () => { void shutdown(); });
|
|
20
|
+
process.once('message', message => {
|
|
21
|
+
if (!message || typeof message !== 'object' || !('host' in message) || typeof message.host !== 'string'
|
|
22
|
+
|| !('port' in message) || typeof message.port !== 'number' || !Number.isSafeInteger(message.port) || message.port < 1 || message.port > 65535
|
|
23
|
+
|| !('shutdownTimeoutMs' in message) || typeof message.shutdownTimeoutMs !== 'number' || !Number.isSafeInteger(message.shutdownTimeoutMs) || message.shutdownTimeoutMs < 1) {
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
if (stopping)
|
|
27
|
+
return;
|
|
28
|
+
shutdownTimeoutMs = message.shutdownTimeoutMs;
|
|
29
|
+
const { host, port } = message;
|
|
30
|
+
startup = import('@1agents/acp-service/service').then(service => service.serveAcpService({ host, port, report: false }));
|
|
31
|
+
void startup.then(() => {
|
|
32
|
+
if (!stopping && process.connected)
|
|
33
|
+
process.send?.({ type: 'ready' });
|
|
34
|
+
}, error => {
|
|
35
|
+
if (process.connected)
|
|
36
|
+
process.send?.({ type: 'error', message: error instanceof Error ? error.message : String(error) }, () => process.exit(1));
|
|
37
|
+
else
|
|
38
|
+
process.exit(1);
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
if (!process.connected)
|
|
42
|
+
void shutdown();
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface NativeImport {
|
|
2
|
+
provider: string;
|
|
3
|
+
nativeSessionId: string;
|
|
4
|
+
/** Imported user messages must never be sent as fresh prompts. */
|
|
5
|
+
messageIds: string[];
|
|
6
|
+
}
|
|
7
|
+
export interface Binding {
|
|
8
|
+
agent: string;
|
|
9
|
+
cwd: string;
|
|
10
|
+
endpoint: string;
|
|
11
|
+
sessionId: string;
|
|
12
|
+
/** Absent on bindings created before native imports were supported. */
|
|
13
|
+
restoreMethod?: 'session/load' | 'session/resume';
|
|
14
|
+
imported?: NativeImport;
|
|
15
|
+
}
|
|
16
|
+
export declare class State {
|
|
17
|
+
readonly directory: string;
|
|
18
|
+
constructor(directory: string);
|
|
19
|
+
private path;
|
|
20
|
+
get(id: string): Binding | undefined;
|
|
21
|
+
save(id: string, binding: Binding): void;
|
|
22
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Plugin-owned identities. DSH session files are never rewritten. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
export class State {
|
|
6
|
+
directory;
|
|
7
|
+
constructor(directory) {
|
|
8
|
+
this.directory = directory;
|
|
9
|
+
}
|
|
10
|
+
path(id) { return join(this.directory, createHash('sha256').update(id).digest('hex') + '.json'); }
|
|
11
|
+
get(id) {
|
|
12
|
+
try {
|
|
13
|
+
return decodeBinding(JSON.parse(readFileSync(this.path(id), 'utf8')));
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (error.code === 'ENOENT')
|
|
17
|
+
return;
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
save(id, binding) {
|
|
22
|
+
mkdirSync(this.directory, { recursive: true, mode: 0o700 });
|
|
23
|
+
const path = this.path(id), temp = path + '.' + randomUUID();
|
|
24
|
+
writeFileSync(temp, JSON.stringify(binding) + '\n', { flag: 'wx', mode: 0o600 });
|
|
25
|
+
renameSync(temp, path);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** Validate plugin-owned JSON while accepting legacy bindings without an explicit restore method. */
|
|
29
|
+
function decodeBinding(value) {
|
|
30
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
31
|
+
throw new Error('Invalid ACP binding');
|
|
32
|
+
const binding = value;
|
|
33
|
+
if (['agent', 'cwd', 'endpoint', 'sessionId'].some(key => typeof binding[key] !== 'string' || !binding[key]))
|
|
34
|
+
throw new Error('Invalid ACP binding identity');
|
|
35
|
+
if (binding.restoreMethod !== undefined && binding.restoreMethod !== 'session/load' && binding.restoreMethod !== 'session/resume')
|
|
36
|
+
throw new Error('Invalid ACP restore method');
|
|
37
|
+
if (binding.imported !== undefined) {
|
|
38
|
+
if (!binding.imported || typeof binding.imported !== 'object' || Array.isArray(binding.imported))
|
|
39
|
+
throw new Error('Invalid ACP native import');
|
|
40
|
+
const imported = binding.imported;
|
|
41
|
+
if (typeof imported.provider !== 'string' || typeof imported.nativeSessionId !== 'string'
|
|
42
|
+
|| !Array.isArray(imported.messageIds) || !imported.messageIds.every(id => typeof id === 'string')
|
|
43
|
+
|| binding.restoreMethod !== 'session/resume')
|
|
44
|
+
throw new Error('Invalid ACP native import');
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Display metadata on empty stream blocks never becomes a local tool request. */
|
|
2
|
+
import type { SessionUpdate } from '@agentclientprotocol/sdk';
|
|
3
|
+
type ToolUpdate = Extract<SessionUpdate, {
|
|
4
|
+
sessionUpdate: 'tool_call' | 'tool_call_update';
|
|
5
|
+
}>;
|
|
6
|
+
export interface RemoteTool {
|
|
7
|
+
toolCallId: string;
|
|
8
|
+
title?: string | null;
|
|
9
|
+
name?: string;
|
|
10
|
+
status?: ToolUpdate['status'];
|
|
11
|
+
kind?: ToolUpdate['kind'];
|
|
12
|
+
rawInput?: unknown;
|
|
13
|
+
rawOutput?: unknown;
|
|
14
|
+
content?: ToolUpdate['content'];
|
|
15
|
+
locations?: ToolUpdate['locations'];
|
|
16
|
+
}
|
|
17
|
+
export interface ToolEvent {
|
|
18
|
+
turn: number;
|
|
19
|
+
step: number;
|
|
20
|
+
requestId: string;
|
|
21
|
+
sequence: number;
|
|
22
|
+
tool: RemoteTool;
|
|
23
|
+
}
|
|
24
|
+
/** ACP updates replace supplied fields and leave omitted fields intact. */
|
|
25
|
+
export declare function mergeTool(previous: RemoteTool | undefined, update: ToolUpdate): RemoteTool;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** ACP updates replace supplied fields and leave omitted fields intact. */
|
|
2
|
+
export function mergeTool(previous, update) {
|
|
3
|
+
const tool = { ...previous, toolCallId: update.toolCallId };
|
|
4
|
+
for (const key of ['title', 'status', 'kind', 'rawInput', 'rawOutput', 'content', 'locations']) {
|
|
5
|
+
if (update[key] !== undefined && (update[key] !== null || key === 'rawInput' || key === 'rawOutput'))
|
|
6
|
+
Object.assign(tool, { [key]: update[key] });
|
|
7
|
+
}
|
|
8
|
+
// The service's friendly name is display metadata, separate from ACP's title.
|
|
9
|
+
const name = update._meta?.['1agents']?.toolName;
|
|
10
|
+
if (name && (name !== 'Tool' || !tool.name))
|
|
11
|
+
tool.name = name;
|
|
12
|
+
return tool;
|
|
13
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** ACP SDK client over the service's WebSocket transport. */
|
|
2
|
+
import { type Stream, type SessionUpdate, type RequestPermissionRequest, type RequestPermissionResponse } from '@agentclientprotocol/sdk';
|
|
3
|
+
import { WebSocket } from 'ws';
|
|
4
|
+
export type JsonObject = Record<string, unknown>;
|
|
5
|
+
export declare function object(value: unknown): JsonObject;
|
|
6
|
+
export declare function stream(ws: WebSocket): Stream;
|
|
7
|
+
export interface Handlers {
|
|
8
|
+
update(update: SessionUpdate): void;
|
|
9
|
+
permission(params: RequestPermissionRequest, signal: AbortSignal): Promise<RequestPermissionResponse>;
|
|
10
|
+
question(params: JsonObject, signal: AbortSignal): Promise<JsonObject>;
|
|
11
|
+
plan(params: JsonObject, signal: AbortSignal): Promise<JsonObject>;
|
|
12
|
+
}
|
|
13
|
+
export declare function connect(endpoint: string, handlers: Handlers, signal: AbortSignal): Promise<{
|
|
14
|
+
rpc: import("@agentclientprotocol/sdk").ClientContext;
|
|
15
|
+
ws: WebSocket;
|
|
16
|
+
close: () => void;
|
|
17
|
+
closed: Promise<void>;
|
|
18
|
+
}>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** ACP SDK client over the service's WebSocket transport. */
|
|
2
|
+
import { client } from '@agentclientprotocol/sdk';
|
|
3
|
+
import { WebSocket } from 'ws';
|
|
4
|
+
export function object(value) {
|
|
5
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
6
|
+
throw new Error('Expected an ACP object');
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
export function stream(ws) {
|
|
10
|
+
let readableClosed = false;
|
|
11
|
+
return {
|
|
12
|
+
readable: new ReadableStream({ start(controller) {
|
|
13
|
+
ws.on('message', raw => {
|
|
14
|
+
if (readableClosed)
|
|
15
|
+
return;
|
|
16
|
+
try {
|
|
17
|
+
controller.enqueue(JSON.parse(raw.toString()));
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
ws.close(1002, 'Invalid JSON');
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
ws.once('close', () => {
|
|
24
|
+
if (readableClosed)
|
|
25
|
+
return;
|
|
26
|
+
readableClosed = true;
|
|
27
|
+
controller.close();
|
|
28
|
+
});
|
|
29
|
+
ws.on('error', () => ws.close());
|
|
30
|
+
}, cancel() { readableClosed = true; ws.close(); } }),
|
|
31
|
+
writable: new WritableStream({ write(message) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
34
|
+
return reject(new Error('ACP disconnected'));
|
|
35
|
+
ws.send(JSON.stringify(message), error => error ? reject(error) : resolve());
|
|
36
|
+
});
|
|
37
|
+
} }),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export async function connect(endpoint, handlers, signal) {
|
|
41
|
+
signal.throwIfAborted();
|
|
42
|
+
const ws = new WebSocket(endpoint, { handshakeTimeout: 10_000 });
|
|
43
|
+
const abort = () => ws.terminate();
|
|
44
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
45
|
+
try {
|
|
46
|
+
await new Promise((resolve, reject) => {
|
|
47
|
+
ws.once('open', resolve);
|
|
48
|
+
ws.once('error', reject);
|
|
49
|
+
ws.once('close', () => reject(new Error('ACP connection closed')));
|
|
50
|
+
});
|
|
51
|
+
const connection = client().onNotification('session/update', ({ params }) => handlers.update(params.update))
|
|
52
|
+
.onRequest('session/request_permission', ({ params, signal }) => handlers.permission(params, signal))
|
|
53
|
+
.onRequest('_x.ai/ask_user_question', object, ({ params, signal }) => handlers.question(params, signal))
|
|
54
|
+
.onRequest('_x.ai/exit_plan_mode', object, ({ params, signal }) => handlers.plan(params, signal))
|
|
55
|
+
.connect(stream(ws));
|
|
56
|
+
const initialized = await connection.agent.request('initialize', {
|
|
57
|
+
protocolVersion: 1, clientInfo: { name: 'dsh-acp', version: '0.1.0' },
|
|
58
|
+
clientCapabilities: { _meta: { '1agents': { version: 1 } } },
|
|
59
|
+
}, { cancellationSignal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]) });
|
|
60
|
+
if (initialized.protocolVersion !== 1 || !initialized.agentCapabilities?._meta?.['1agents'])
|
|
61
|
+
throw new Error('Requires acp-service 0.2 with 1agents turn recovery');
|
|
62
|
+
return { rpc: connection.agent, ws, close: () => ws.close(), closed: connection.closed };
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
ws.terminate();
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
signal.removeEventListener('abort', abort);
|
|
70
|
+
}
|
|
71
|
+
}
|