@1agents/acp-service 0.4.0 → 0.5.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,4 @@
1
+ export declare function discoverPresets(serviceUrl: string): Promise<Array<{
2
+ id: string;
3
+ label: string;
4
+ }>>;
@@ -0,0 +1,20 @@
1
+ /** Service-owned harness inventory; the plugin never probes its own host or maintains a harness list. */
2
+ import { object } from './transport.js';
3
+ export async function discoverPresets(serviceUrl) {
4
+ const response = await fetch(new URL('/agents', serviceUrl), { signal: AbortSignal.timeout(10_000) });
5
+ if (!response.ok)
6
+ throw new Error(`ACP discovery failed: HTTP ${response.status}`);
7
+ const body = object(await response.json());
8
+ if (!Array.isArray(body.agents))
9
+ throw new Error('ACP discovery requires an agents array');
10
+ const agents = new Map();
11
+ for (const value of body.agents) {
12
+ const agent = object(value);
13
+ if (typeof agent.id !== 'string' || !/^[a-z0-9_-]+$/i.test(agent.id) || typeof agent.label !== 'string' || typeof agent.chat_ready !== 'boolean') {
14
+ throw new Error('Invalid ACP discovery entry');
15
+ }
16
+ if (agent.chat_ready)
17
+ agents.set(agent.id, { id: agent.id, label: agent.label });
18
+ }
19
+ return [...agents.values()];
20
+ }
@@ -0,0 +1,54 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session';
3
+ import { AcpAdapter, type Config } from './adapter.js';
4
+ /** Whether a provider is enabled and advertised by the configured service. */
5
+ export interface ImportAvailability {
6
+ available: boolean;
7
+ agent?: string;
8
+ reason?: string;
9
+ }
10
+ /** Original native identity, workspace and the reader’s ordered historical events. */
11
+ export interface NativeSessionInput {
12
+ provider: string;
13
+ nativeSessionId: string;
14
+ cwd: string;
15
+ /** Current DSH events, contiguous from sequence zero. */
16
+ events: readonly SessionEvent[];
17
+ }
18
+ /** Completed restoration and workspace attachment, safe for client navigation. */
19
+ export interface ImportResult {
20
+ success: true;
21
+ dshSessionId: SessionId;
22
+ workspace: string;
23
+ workspaceId: string;
24
+ agent: string;
25
+ continuation: 'native';
26
+ }
27
+ declare module '@deepseek-ai/cordis' {
28
+ interface Context {
29
+ oneagentsAcpSessions: NativeSessions;
30
+ }
31
+ }
32
+ /** Owns import identities and serializes retries through remote import, local creation and workspace attachment. */
33
+ export declare class NativeSessions {
34
+ private readonly ctx;
35
+ private readonly adapter;
36
+ private readonly config;
37
+ private readonly state;
38
+ private readonly pending;
39
+ private disposed;
40
+ constructor(ctx: Context, adapter: AcpAdapter, config: Config);
41
+ /** Check configured Agent availability without starting or restoring a native session.
42
+ * @param provider Reader provider identifier.
43
+ * @returns Availability, registry Agent and an actionable failure reason when unavailable.
44
+ */
45
+ availability(provider: string): Promise<ImportAvailability>;
46
+ /** Restore one native session; repeated calls return its existing DSH identity and never replace its history.
47
+ * @param input Native identity, original workspace and historical events.
48
+ * @returns The attached DSH session after native restoration succeeds.
49
+ */
50
+ importSession(input: NativeSessionInput): Promise<ImportResult>;
51
+ /** Stop new admissions and await callers already creating or attaching a session. */
52
+ dispose(): Promise<void>;
53
+ private admit;
54
+ }
@@ -0,0 +1,133 @@
1
+ /** Native-session admission shared by DSH plugins. Reading history remains the caller's responsibility. */
2
+ import { createHash } from 'node:crypto';
3
+ import { realpath, stat } from 'node:fs/promises';
4
+ import { isAbsolute } from 'node:path';
5
+ import { discoverPresets } from './discovery.js';
6
+ import { State } from './state.js';
7
+ const providers = { claude: 'claude', codex: 'codex', grok: 'grok-build' };
8
+ /** Owns import identities and serializes retries through remote import, local creation and workspace attachment. */
9
+ export class NativeSessions {
10
+ ctx;
11
+ adapter;
12
+ config;
13
+ state;
14
+ pending = new Map();
15
+ disposed = false;
16
+ constructor(ctx, adapter, config) {
17
+ this.ctx = ctx;
18
+ this.adapter = adapter;
19
+ this.config = config;
20
+ this.state = new State(config.stateDirectory);
21
+ }
22
+ /** Check configured Agent availability without starting or restoring a native session.
23
+ * @param provider Reader provider identifier.
24
+ * @returns Availability, registry Agent and an actionable failure reason when unavailable.
25
+ */
26
+ async availability(provider) {
27
+ const agent = Object.hasOwn(providers, provider) ? providers[provider] : undefined;
28
+ if (!agent)
29
+ return { available: false, reason: `暂不支持 ${provider} 原会话续聊,可继续只读查看` };
30
+ if (this.disposed || !this.config.agents.includes(agent))
31
+ return { available: false, agent, reason: `ACP 未启用 ${agent}` };
32
+ try {
33
+ const agents = await discoverPresets(this.config.serviceUrl);
34
+ return agents.some(value => value.id === agent)
35
+ ? { available: true, agent }
36
+ : { available: false, agent, reason: `${agent} 尚未就绪,请检查安装和 ACP 配置` };
37
+ }
38
+ catch (error) {
39
+ return { available: false, agent, reason: `ACP 服务不可用:${error instanceof Error ? error.message : String(error)}` };
40
+ }
41
+ }
42
+ /** Restore one native session; repeated calls return its existing DSH identity and never replace its history.
43
+ * @param input Native identity, original workspace and historical events.
44
+ * @returns The attached DSH session after native restoration succeeds.
45
+ */
46
+ async importSession(input) {
47
+ if (this.disposed)
48
+ throw new Error('ACP plugin has been stopped');
49
+ const identity = JSON.stringify([new URL(this.config.serviceUrl).href, input.provider, input.nativeSessionId]);
50
+ const id = `session-acp-${createHash('sha256').update(identity).digest('hex')}`;
51
+ const previous = this.pending.get(id);
52
+ if (previous) {
53
+ await previous;
54
+ // Re-check this caller's cwd even when it raced another import.
55
+ return this.importSession(input);
56
+ }
57
+ const operation = this.admit(id, input);
58
+ this.pending.set(id, operation);
59
+ try {
60
+ return await operation;
61
+ }
62
+ finally {
63
+ if (this.pending.get(id) === operation)
64
+ this.pending.delete(id);
65
+ }
66
+ }
67
+ /** Stop new admissions and await callers already creating or attaching a session. */
68
+ async dispose() {
69
+ this.disposed = true;
70
+ await Promise.allSettled(this.pending.values());
71
+ }
72
+ async admit(id, input) {
73
+ const available = await this.availability(input.provider);
74
+ if (!available.available || !available.agent)
75
+ throw new Error(available.reason);
76
+ if (!input.nativeSessionId.trim())
77
+ throw new Error('Native session ID is required');
78
+ if (!isAbsolute(input.cwd))
79
+ throw new Error('原会话缺少绝对工作目录,无法续聊');
80
+ let cwd;
81
+ try {
82
+ cwd = await realpath(input.cwd);
83
+ if (!(await stat(cwd)).isDirectory())
84
+ throw new Error('Not a directory');
85
+ }
86
+ catch (error) {
87
+ throw new Error(`原会话工作目录不可用:${input.cwd}`, { cause: error });
88
+ }
89
+ const agent = available.agent;
90
+ const preset = `oneagents-acp-${agent}`;
91
+ const endpoint = new URL(`/agents/${encodeURIComponent(agent)}`, this.config.serviceUrl);
92
+ endpoint.protocol = endpoint.protocol === 'https:' ? 'wss:' : 'ws:';
93
+ let binding = this.state.get(id);
94
+ if (binding && (binding.cwd !== cwd || binding.agent !== agent || binding.endpoint !== endpoint.href
95
+ || binding.imported?.provider !== input.provider || binding.imported.nativeSessionId !== input.nativeSessionId)) {
96
+ throw new Error('Imported session binding does not match the native session or workspace');
97
+ }
98
+ const existing = await this.ctx.sessionPersistence.stat(id);
99
+ const live = this.ctx.agents.get(id);
100
+ const header = live?.session.header ?? existing?.header;
101
+ if (header && (!binding || header.cwd !== cwd || header.agentPreset !== preset))
102
+ throw new Error('DSH session identity is already in use');
103
+ if (!header) {
104
+ // Use DSH's validation before contacting the native Agent. No session is published here.
105
+ this.ctx.sessions.prepare(id, { seed: input.events, meta: { cwd, agentPreset: preset } });
106
+ await this.ctx.agentPresets.resolve(preset);
107
+ }
108
+ if (!binding) {
109
+ binding = { ...await this.adapter.importNative(agent, cwd, input.nativeSessionId), imported: {
110
+ provider: input.provider, nativeSessionId: input.nativeSessionId, messageIds: [],
111
+ } };
112
+ // The service ID survives local creation/attachment failure and plugin restart.
113
+ this.state.save(id, binding);
114
+ }
115
+ if (!header) {
116
+ binding.imported.messageIds = input.events.flatMap(event => event.type === 'user/message' ? [event.data.id] : []);
117
+ this.state.save(id, binding);
118
+ await this.ctx.agents.create({
119
+ sessionId: id, seed: input.events,
120
+ meta: { cwd, agentPreset: preset },
121
+ agentOptions: { provider: '1agents-acp', model: agent },
122
+ setup: async (scope) => { await this.ctx.agentPresets.mount(scope, preset); },
123
+ });
124
+ }
125
+ const resolved = await this.ctx.sessionController.resolveAgent(id);
126
+ if ('error' in resolved)
127
+ throw resolved.error;
128
+ await this.adapter.describe(resolved.agent);
129
+ const workspace = await this.ctx.workspaceRegistry.create(cwd);
130
+ await workspace.attachSession(id);
131
+ return { success: true, dshSessionId: id, workspace: cwd, workspaceId: workspace.id, agent, continuation: 'native' };
132
+ }
133
+ }
@@ -0,0 +1,5 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { type Config } from './adapter.js';
3
+ import { type ServiceOptions } from './service-process.js';
4
+ export { name, inject } from '@1agents/acp-service';
5
+ export declare function apply(ctx: Context, input?: Partial<Config & ServiceOptions>): Promise<void>;
@@ -0,0 +1,84 @@
1
+ /** Installable Cordis bundle. Uses only existing Host services and preset registrations. */
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { AcpAdapter } from './adapter.js';
5
+ import { discoverPresets } from './discovery.js';
6
+ import { NativeSessions } from './imports.js';
7
+ import { acquireService, resolveServiceOptions } from './service-process.js';
8
+ export { name, inject } from '@1agents/acp-service';
9
+ export async function apply(ctx, input = {}) {
10
+ const homePath = ctx.get('dshHomePath');
11
+ const home = homePath ? homePath() : process.env.DSH_HOME || join(homedir(), '.dsh');
12
+ const service = resolveServiceOptions(input);
13
+ const { serviceUrl } = service;
14
+ await ctx.effect(async () => acquireService(service));
15
+ const presets = input.agents === undefined
16
+ ? await discoverPresets(serviceUrl)
17
+ : [...new Set(input.agents)].map(id => ({ id, label: id }));
18
+ const config = {
19
+ serviceUrl, agents: presets.map(preset => preset.id),
20
+ stateDirectory: input.stateDirectory ?? join(home, 'plugins', '1agents-acp', 'sessions'),
21
+ reconnectAttempts: input.reconnectAttempts ?? 5, reconnectDelayMs: input.reconnectDelayMs ?? 1000,
22
+ };
23
+ if (config.agents.some(a => !/^[a-z0-9_-]+$/i.test(a)))
24
+ throw new Error('agents must contain ACP registry names');
25
+ if (!Number.isSafeInteger(config.reconnectAttempts) || config.reconnectAttempts < 0 || !Number.isSafeInteger(config.reconnectDelayMs) || config.reconnectDelayMs < 1)
26
+ throw new Error('Invalid ACP reconnect policy');
27
+ const adapter = new AcpAdapter(ctx, config);
28
+ ctx.effect(() => ctx.llm.registerAdapter(['1agents-acp'], adapter));
29
+ const nativeSessions = new NativeSessions(ctx, adapter, config);
30
+ ctx.provide('oneagentsAcpSessions', nativeSessions);
31
+ ctx.effect(() => async () => { await Promise.all([nativeSessions.dispose(), adapter.dispose()]); });
32
+ ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: '/api/1agents-acp', handler: async (req, res) => {
33
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
34
+ res.setHeader('Cache-Control', 'no-store');
35
+ try {
36
+ const url = new URL(req.url, 'http://localhost');
37
+ if (url.pathname !== '/api/1agents-acp/session' || !['GET', 'POST'].includes(req.method)) {
38
+ res.statusCode = 404;
39
+ res.end('{}');
40
+ return;
41
+ }
42
+ const id = url.searchParams.get('id');
43
+ if (!id || id.length > 256)
44
+ throw new Error('Session id required');
45
+ const resolved = await ctx.sessionController.resolveAgent(id);
46
+ if ('error' in resolved)
47
+ throw resolved.error;
48
+ const agent = resolved.agent;
49
+ if (req.method === 'GET') {
50
+ res.end(JSON.stringify(await adapter.describe(agent)));
51
+ return;
52
+ }
53
+ if (req.headers.origin && new URL(req.headers.origin).host !== req.headers.host)
54
+ throw new Error('Cross-origin configuration is not allowed');
55
+ let body = '';
56
+ for await (const chunk of req) {
57
+ body += String(chunk);
58
+ if (body.length > 16384)
59
+ throw new Error('Request body too large');
60
+ }
61
+ const value = JSON.parse(body);
62
+ if (typeof value.configId !== 'string' || typeof value.value !== 'string')
63
+ throw new Error('configId and value must be strings');
64
+ res.end(JSON.stringify(await adapter.configure(agent, value.configId, value.value)));
65
+ }
66
+ catch (error) {
67
+ res.statusCode = 400;
68
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
69
+ }
70
+ } }));
71
+ for (const { id: agent, label } of presets) {
72
+ const dispose = await ctx.agentPresets.register({
73
+ id: `oneagents-acp-${agent}`,
74
+ name: `ACP · ${label}`,
75
+ description: `当前会话直接连接 ${agent};切换 Agent 请新建会话。`,
76
+ order: 20,
77
+ plugins: [
78
+ { id: 'persona', name: '@deepseek-ai/dsh-persona', config: { prefix: '', complete: true, includeRuntimeContext: false } },
79
+ { id: 'acp-session', name: '@1agents/acp-service/dsh/preset', config: { agent } },
80
+ ],
81
+ });
82
+ ctx.effect(() => dispose);
83
+ }
84
+ }
@@ -0,0 +1,7 @@
1
+ /** A standing preset binds its sessions to one external Agent. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ export declare const name = "oneagents-acp-preset";
4
+ export declare const inject: string[];
5
+ export declare function apply(ctx: Context, config: {
6
+ agent: string;
7
+ }): void;
@@ -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,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
+ }>;