@1agents/acp-service 0.3.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.
Files changed (98) hide show
  1. package/README.md +69 -33
  2. package/dist/bin/acp-service.js +2 -2
  3. package/dist/src/bridge.d.ts +2 -2
  4. package/dist/src/bridge.js +1 -1
  5. package/dist/src/catalog.js +20 -3
  6. package/dist/src/dsh.d.ts +6 -0
  7. package/dist/src/dsh.js +9 -0
  8. package/dist/src/manifest.js +1 -1
  9. package/dist/src/package.d.ts +3 -0
  10. package/dist/src/package.js +3 -0
  11. package/package.json +65 -13
  12. package/vendor/dsh/LICENSE +21 -0
  13. package/vendor/dsh/README.md +101 -0
  14. package/vendor/dsh/adapter.d.ts +82 -0
  15. package/vendor/dsh/adapter.js +449 -0
  16. package/vendor/dsh/client.js +207 -0
  17. package/vendor/dsh/cordis.patch.yml +10 -0
  18. package/vendor/dsh/discovery.d.ts +4 -0
  19. package/vendor/dsh/discovery.js +20 -0
  20. package/vendor/dsh/imports.d.ts +54 -0
  21. package/vendor/dsh/imports.js +133 -0
  22. package/vendor/dsh/index.d.ts +5 -0
  23. package/vendor/dsh/index.js +84 -0
  24. package/vendor/dsh/preset.d.ts +7 -0
  25. package/vendor/dsh/preset.js +10 -0
  26. package/vendor/dsh/service-process.d.ts +10 -0
  27. package/vendor/dsh/service-process.js +150 -0
  28. package/vendor/dsh/service-worker.d.ts +1 -0
  29. package/vendor/dsh/service-worker.js +43 -0
  30. package/vendor/dsh/state.d.ts +22 -0
  31. package/vendor/dsh/state.js +47 -0
  32. package/vendor/dsh/transport.d.ts +18 -0
  33. package/vendor/dsh/transport.js +71 -0
  34. package/vendor/runtime/LICENSE +21 -0
  35. package/vendor/runtime/README.md +115 -0
  36. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js +806 -0
  37. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +1 -0
  38. package/vendor/runtime/dist/agent-registry.d.ts +70 -0
  39. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -0
  40. package/vendor/runtime/dist/agent-registry.js +2 -0
  41. package/vendor/runtime/dist/cli-DUHyAADv.js +182 -0
  42. package/vendor/runtime/dist/cli-DUHyAADv.js.map +1 -0
  43. package/vendor/runtime/dist/cli.d.ts +12 -0
  44. package/vendor/runtime/dist/cli.d.ts.map +1 -0
  45. package/vendor/runtime/dist/cli.js +2632 -0
  46. package/vendor/runtime/dist/cli.js.map +1 -0
  47. package/vendor/runtime/dist/client-DjkWknf7.d.ts +262 -0
  48. package/vendor/runtime/dist/client-DjkWknf7.d.ts.map +1 -0
  49. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  50. package/vendor/runtime/dist/docs-site/CLI.html +832 -0
  51. package/vendor/runtime/dist/docs-site/CNAME +1 -0
  52. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  53. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  54. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  55. package/vendor/runtime/dist/docs-site/config.html +450 -0
  56. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  57. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  58. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  59. package/vendor/runtime/dist/docs-site/flows.html +497 -0
  60. package/vendor/runtime/dist/docs-site/index.html +367 -0
  61. package/vendor/runtime/dist/docs-site/install.html +386 -0
  62. package/vendor/runtime/dist/docs-site/llms.txt +35 -0
  63. package/vendor/runtime/dist/docs-site/output-formats.html +403 -0
  64. package/vendor/runtime/dist/docs-site/permissions.html +413 -0
  65. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  66. package/vendor/runtime/dist/docs-site/proof-2026-07-18-grok-ext-methods/index.html +336 -0
  67. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  68. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  69. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  70. package/vendor/runtime/dist/docs-site/session-control.html +406 -0
  71. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  72. package/vendor/runtime/dist/docs-site/sessions.html +486 -0
  73. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  74. package/vendor/runtime/dist/flows-CiJSCy4D.js +2474 -0
  75. package/vendor/runtime/dist/flows-CiJSCy4D.js.map +1 -0
  76. package/vendor/runtime/dist/flows.d.ts +334 -0
  77. package/vendor/runtime/dist/flows.d.ts.map +1 -0
  78. package/vendor/runtime/dist/flows.js +2 -0
  79. package/vendor/runtime/dist/invocation-options-BlIySxIw.js +345 -0
  80. package/vendor/runtime/dist/invocation-options-BlIySxIw.js.map +1 -0
  81. package/vendor/runtime/dist/ipc-BlljKR2b.js +5336 -0
  82. package/vendor/runtime/dist/ipc-BlljKR2b.js.map +1 -0
  83. package/vendor/runtime/dist/output-BzXQKArM.js +1012 -0
  84. package/vendor/runtime/dist/output-BzXQKArM.js.map +1 -0
  85. package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js +8867 -0
  86. package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js.map +1 -0
  87. package/vendor/runtime/dist/runtime.d.ts +1156 -0
  88. package/vendor/runtime/dist/runtime.d.ts.map +1 -0
  89. package/vendor/runtime/dist/runtime.js +3675 -0
  90. package/vendor/runtime/dist/runtime.js.map +1 -0
  91. package/vendor/runtime/dist/session-options-ORCchZGk.d.ts +426 -0
  92. package/vendor/runtime/dist/session-options-ORCchZGk.d.ts.map +1 -0
  93. package/vendor/runtime/dist/session-watch-BiBTBMz4.js +76 -0
  94. package/vendor/runtime/dist/session-watch-BiBTBMz4.js.map +1 -0
  95. package/vendor/runtime/dist/watch-iYiP-lOo.js +85 -0
  96. package/vendor/runtime/dist/watch-iYiP-lOo.js.map +1 -0
  97. package/vendor/runtime/package.json +46 -0
  98. package/vendor/runtime/skills/acpx/SKILL.md +688 -0
@@ -0,0 +1,82 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { Agent } from '@deepseek-ai/dsh-agent';
3
+ import type { LlmAdapter, GenerateOptions, StreamChunk, LlmModelInfo } from '@deepseek-ai/dsh-llm';
4
+ import type { SessionConfigOption, SessionModeState, AvailableCommand } from '@agentclientprotocol/sdk';
5
+ import { type Binding } from './state.js';
6
+ export interface Config {
7
+ serviceUrl: string;
8
+ agents: string[];
9
+ stateDirectory: string;
10
+ reconnectAttempts: number;
11
+ reconnectDelayMs: number;
12
+ }
13
+ export interface Capabilities {
14
+ agent: string;
15
+ commands: AvailableCommand[];
16
+ configOptions: SessionConfigOption[];
17
+ modes?: SessionModeState;
18
+ }
19
+ export declare class AcpAdapter implements LlmAdapter {
20
+ private ctx;
21
+ private config;
22
+ private state;
23
+ private controllers;
24
+ private jobs;
25
+ private links;
26
+ private connections;
27
+ private capabilities;
28
+ private commandScopes;
29
+ private commandContexts;
30
+ private commandDisposers;
31
+ private output;
32
+ private lifetime;
33
+ constructor(ctx: Context, config: Config);
34
+ providerInfo(provider: string): {
35
+ id: string;
36
+ name: string;
37
+ };
38
+ providerRetryPolicy(): {
39
+ mode: "normal";
40
+ maxRetries: number;
41
+ retryableCodes: never[];
42
+ initialDelayMs: number;
43
+ maxDelayMs: number;
44
+ jitterRatio: number;
45
+ };
46
+ imageRequestPricing(): undefined;
47
+ listModels(provider: string): Promise<LlmModelInfo[]>;
48
+ resolveModel(provider: string, model: string): Promise<{
49
+ provider: string;
50
+ id: string;
51
+ name: string;
52
+ inputModalities: "text"[];
53
+ }>;
54
+ prepareCall(provider: string, model: string): Promise<{
55
+ model: {
56
+ provider: string;
57
+ id: string;
58
+ name: string;
59
+ inputModalities: "text"[];
60
+ };
61
+ stream: (o: GenerateOptions) => AsyncIterable<StreamChunk>;
62
+ }>;
63
+ dispose(): Promise<void>;
64
+ agentName(agent: Agent): string | undefined;
65
+ describe(agent: Agent): Promise<Capabilities | null>;
66
+ configure(agent: Agent, configId: string, value: string): Promise<Capabilities>;
67
+ /** Import native history without prompting; callers persist the returned service identity before creating DSH history.
68
+ * @param name Configured ACP registry identifier.
69
+ * @param cwd Existing original working directory.
70
+ * @param nativeSessionId Original Agent session identifier.
71
+ * @returns Binding using the service’s new identity and resume restoration mode.
72
+ */
73
+ importNative(name: string, cwd: string, nativeSessionId: string): Promise<Binding>;
74
+ private publishCommands;
75
+ private connection;
76
+ private openConnection;
77
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
78
+ private permission;
79
+ private question;
80
+ private plan;
81
+ private run;
82
+ }
@@ -0,0 +1,449 @@
1
+ /** Presents an external Agent's output through DSH's existing streaming surface. */
2
+ import { createHash } from 'node:crypto';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { connect, object } from './transport.js';
6
+ import { State } from './state.js';
7
+ /** Producer/consumer queue; errors are delivered after already received chunks. */
8
+ class Queue {
9
+ values = [];
10
+ done = false;
11
+ error;
12
+ wake = Promise.withResolvers();
13
+ push(value) { this.values.push(value); this.wake.resolve(); }
14
+ end(error) { this.done = true; this.error = error; this.wake.resolve(); }
15
+ async *read() {
16
+ while (true) {
17
+ while (this.values.length)
18
+ yield this.values.shift();
19
+ if (this.done) {
20
+ if (this.error)
21
+ throw this.error;
22
+ return;
23
+ }
24
+ await this.wake.promise;
25
+ this.wake = Promise.withResolvers();
26
+ }
27
+ }
28
+ }
29
+ export class AcpAdapter {
30
+ ctx;
31
+ config;
32
+ state;
33
+ controllers = new Map();
34
+ jobs = new Set();
35
+ links = new Map();
36
+ connections = new Map();
37
+ capabilities = new Map();
38
+ commandScopes = new Map();
39
+ commandContexts = new Map();
40
+ commandDisposers = new Map();
41
+ output = new Map();
42
+ lifetime = new AbortController();
43
+ constructor(ctx, config) {
44
+ this.ctx = ctx;
45
+ this.config = config;
46
+ this.state = new State(config.stateDirectory);
47
+ }
48
+ providerInfo(provider) { return { id: provider, name: 'ACP Agents' }; }
49
+ providerRetryPolicy() { return { mode: 'normal', maxRetries: 0, retryableCodes: [], initialDelayMs: 1000, maxDelayMs: 1000, jitterRatio: 0 }; }
50
+ imageRequestPricing() { return undefined; }
51
+ async listModels(provider) {
52
+ return [];
53
+ }
54
+ async resolveModel(provider, model) {
55
+ if (!this.config.agents.includes(model))
56
+ throw new Error(`ACP Agent is not configured: ${model}`);
57
+ return { provider, id: model, name: `ACP · ${model}`, inputModalities: ['text'] };
58
+ }
59
+ async prepareCall(provider, model) { return { model: await this.resolveModel(provider, model), stream: (o) => this.stream(o) }; }
60
+ async dispose() {
61
+ for (const c of this.controllers.values())
62
+ c.abort();
63
+ this.lifetime.abort();
64
+ await Promise.allSettled(this.jobs);
65
+ for (const link of await Promise.allSettled(this.links.values()))
66
+ if (link.status === 'fulfilled')
67
+ link.value.close();
68
+ for (const disposers of this.commandDisposers.values())
69
+ for (const dispose of disposers)
70
+ dispose();
71
+ this.links.clear();
72
+ await Promise.allSettled([...this.commandScopes.values()].map(dispose => dispose()));
73
+ this.commandScopes.clear();
74
+ this.commandContexts.clear();
75
+ }
76
+ agentName(agent) {
77
+ const preset = this.ctx.sessionProjections.stateOf(agent.session, 'agentPreset');
78
+ if (typeof preset !== 'string' || !preset.startsWith('oneagents-acp-'))
79
+ return;
80
+ const name = preset.slice('oneagents-acp-'.length);
81
+ return this.config.agents.includes(name) ? name : undefined;
82
+ }
83
+ async describe(agent) {
84
+ if (!this.agentName(agent))
85
+ return null;
86
+ await this.connection(agent);
87
+ return this.capabilities.get(agent.id);
88
+ }
89
+ async configure(agent, configId, value) {
90
+ if (this.controllers.has(agent.id))
91
+ throw new Error('Wait for the current ACP turn to finish before changing configuration');
92
+ const link = await this.connection(agent);
93
+ const sessionId = this.state.get(agent.id).sessionId;
94
+ const capabilities = this.capabilities.get(agent.id);
95
+ if (configId === '$mode') {
96
+ if (!capabilities.modes?.availableModes.some(m => m.id === value))
97
+ throw new Error('Unknown ACP mode');
98
+ await link.rpc.request('session/set_mode', { sessionId, modeId: value });
99
+ capabilities.modes.currentModeId = value;
100
+ }
101
+ else {
102
+ const option = capabilities.configOptions.find(o => o.id === configId);
103
+ if (!option)
104
+ throw new Error('Unknown ACP configuration');
105
+ const result = await link.rpc.request('session/set_config_option', { sessionId, configId, value });
106
+ capabilities.configOptions = result.configOptions;
107
+ }
108
+ return capabilities;
109
+ }
110
+ /** Import native history without prompting; callers persist the returned service identity before creating DSH history.
111
+ * @param name Configured ACP registry identifier.
112
+ * @param cwd Existing original working directory.
113
+ * @param nativeSessionId Original Agent session identifier.
114
+ * @returns Binding using the service’s new identity and resume restoration mode.
115
+ */
116
+ async importNative(name, cwd, nativeSessionId) {
117
+ if (!this.config.agents.includes(name))
118
+ throw new Error(`ACP Agent is not configured: ${name}`);
119
+ const endpoint = new URL(`/agents/${encodeURIComponent(name)}`, this.config.serviceUrl);
120
+ endpoint.protocol = endpoint.protocol === 'https:' ? 'wss:' : 'ws:';
121
+ const task = (async () => {
122
+ const link = await connect(endpoint.href, {
123
+ update: () => { },
124
+ permission: async () => ({ outcome: { outcome: 'cancelled' } }),
125
+ question: async () => ({ outcome: 'cancelled' }),
126
+ plan: async () => ({ outcome: 'abandoned' }),
127
+ }, this.lifetime.signal);
128
+ try {
129
+ const result = object(await link.rpc.request('_1agents/session/import', {
130
+ sessionId: nativeSessionId, cwd, mcpServers: [],
131
+ _meta: { '1agents': { permissionMode: 'approve-reads' } },
132
+ }, { cancellationSignal: AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(60_000)]) }));
133
+ if (typeof result.sessionId !== 'string' || !result.sessionId)
134
+ throw new Error('ACP import returned no service session ID');
135
+ return { agent: name, cwd, endpoint: endpoint.href, sessionId: result.sessionId, restoreMethod: 'session/resume' };
136
+ }
137
+ finally {
138
+ link.close();
139
+ await link.closed;
140
+ }
141
+ })();
142
+ const settled = task.then(() => { }, () => { });
143
+ this.jobs.add(settled);
144
+ try {
145
+ return await task;
146
+ }
147
+ finally {
148
+ this.jobs.delete(settled);
149
+ }
150
+ }
151
+ publishCommands(agent, commands) {
152
+ const scope = this.commandContexts.get(agent.id);
153
+ if (!scope)
154
+ return; // A final transport notification may follow Agent disposal.
155
+ for (const dispose of this.commandDisposers.get(agent.id) ?? [])
156
+ dispose();
157
+ const disposers = [];
158
+ this.commandDisposers.set(agent.id, disposers);
159
+ for (const command of commands) {
160
+ // /model is the client picker over the Agent's advertised model options.
161
+ if (command.name === 'model' || !/^[a-z][a-z0-9_-]*$/.test(command.name))
162
+ continue;
163
+ disposers.push(scope.commands.register({
164
+ name: command.name, description: command.description || `ACP /${command.name}`,
165
+ ...(command.input ? { input: { hint: command.input.hint || 'Arguments' } } : {}),
166
+ handler: ({ rawInput }) => {
167
+ agent.followup({ id: randomUUID(), role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: `/${command.name}${rawInput}` }] });
168
+ return { kind: 'success' };
169
+ },
170
+ }));
171
+ }
172
+ }
173
+ async connection(agent) {
174
+ const operation = (this.connections.get(agent.id) ?? Promise.resolve())
175
+ .catch(() => undefined).then(() => this.openConnection(agent));
176
+ this.connections.set(agent.id, operation);
177
+ try {
178
+ return await operation;
179
+ }
180
+ finally {
181
+ if (this.connections.get(agent.id) === operation)
182
+ this.connections.delete(agent.id);
183
+ }
184
+ }
185
+ async openConnection(agent) {
186
+ const name = this.agentName(agent);
187
+ if (!name)
188
+ throw new Error('ACP is available only in an ACP Agent preset; start a new ACP session');
189
+ const cwd = agent.session.header.cwd;
190
+ if (!cwd)
191
+ throw new Error('Create the ACP session in a workspace first');
192
+ const endpoint = new URL(`/agents/${encodeURIComponent(name)}`, this.config.serviceUrl);
193
+ endpoint.protocol = endpoint.protocol === 'https:' ? 'wss:' : 'ws:';
194
+ let binding = this.state.get(agent.id);
195
+ if (binding && (binding.agent !== name || binding.cwd !== cwd || binding.endpoint !== endpoint.href)) {
196
+ const boundary = this.ctx.sessionProjections.stateOf(agent.session, 'turnBoundary');
197
+ const previousEndpoint = new URL(`/agents/${encodeURIComponent(binding.agent)}`, this.config.serviceUrl);
198
+ previousEndpoint.protocol = endpoint.protocol;
199
+ if (binding.imported || !boundary || boundary.openTurnStartSeq !== null || boundary.lastTurn > 0
200
+ || binding.agent === name || binding.cwd !== cwd || binding.endpoint !== previousEndpoint.href) {
201
+ throw new Error('This session is bound to another ACP Agent or endpoint; start a new session');
202
+ }
203
+ // Capability discovery may bind a draft before its first turn.
204
+ // Retire its transport and commands before initializing the selected Agent.
205
+ (await this.links.get(agent.id))?.close();
206
+ this.links.delete(agent.id);
207
+ this.capabilities.delete(agent.id);
208
+ for (const dispose of this.commandDisposers.get(agent.id) ?? [])
209
+ dispose();
210
+ this.commandDisposers.delete(agent.id);
211
+ binding = undefined;
212
+ }
213
+ const existing = this.links.get(agent.id);
214
+ if (existing)
215
+ return existing;
216
+ const operation = (async () => {
217
+ if (!this.commandContexts.has(agent.id)) {
218
+ const fiber = await agent.ctx.inject(['commands'], scope => {
219
+ this.commandContexts.set(agent.id, scope);
220
+ scope.effect(() => () => {
221
+ this.controllers.get(agent.id)?.abort();
222
+ void this.links.get(agent.id)?.then(link => link.close(), () => { });
223
+ this.links.delete(agent.id);
224
+ this.commandContexts.delete(agent.id);
225
+ this.commandScopes.delete(agent.id);
226
+ this.capabilities.delete(agent.id);
227
+ this.commandDisposers.delete(agent.id);
228
+ });
229
+ });
230
+ this.commandScopes.set(agent.id, async () => fiber.dispose());
231
+ }
232
+ const capabilities = { agent: name, commands: [], configOptions: [] };
233
+ this.capabilities.set(agent.id, capabilities);
234
+ const interactionSignal = (signal) => AbortSignal.any([signal, this.lifetime.signal, ...(this.controllers.has(agent.id) ? [this.controllers.get(agent.id).signal] : [])]);
235
+ const link = await connect(endpoint.href, {
236
+ update: update => {
237
+ if (this.capabilities.get(agent.id) !== capabilities)
238
+ return;
239
+ if (update.sessionUpdate === 'available_commands_update') {
240
+ capabilities.commands = update.availableCommands;
241
+ this.publishCommands(agent, update.availableCommands);
242
+ }
243
+ else if (update.sessionUpdate === 'config_option_update')
244
+ capabilities.configOptions = update.configOptions;
245
+ else if (update.sessionUpdate === 'current_mode_update' && capabilities.modes)
246
+ capabilities.modes.currentModeId = update.currentModeId;
247
+ this.output.get(agent.id)?.(update);
248
+ },
249
+ permission: (p, s) => this.permission(agent, p, interactionSignal(s)),
250
+ question: (p, s) => this.question(agent, p, interactionSignal(s)),
251
+ plan: (p, s) => this.plan(agent, p, interactionSignal(s)),
252
+ }, this.lifetime.signal);
253
+ try {
254
+ const params = { cwd, mcpServers: [], _meta: { '1agents': { permissionMode: 'approve-reads' } } };
255
+ const cancellationSignal = AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(60_000)]);
256
+ const result = binding
257
+ ? await link.rpc.request(binding.restoreMethod ?? 'session/load', { ...params, sessionId: binding.sessionId }, { cancellationSignal })
258
+ : await link.rpc.request('session/new', params, { cancellationSignal });
259
+ if (!binding)
260
+ this.state.save(agent.id, { agent: name, endpoint: endpoint.href, cwd, sessionId: result.sessionId });
261
+ capabilities.configOptions = result.configOptions ?? capabilities.configOptions;
262
+ capabilities.modes = result.modes ?? undefined;
263
+ void link.closed.then(() => { if (this.links.get(agent.id) === operation)
264
+ this.links.delete(agent.id); });
265
+ return link;
266
+ }
267
+ catch (error) {
268
+ link.close();
269
+ throw error;
270
+ }
271
+ })();
272
+ this.links.set(agent.id, operation);
273
+ try {
274
+ return await operation;
275
+ }
276
+ catch (error) {
277
+ if (this.links.get(agent.id) === operation)
278
+ this.links.delete(agent.id);
279
+ throw error;
280
+ }
281
+ }
282
+ async *stream(options) {
283
+ const agent = options.sessionId ? this.ctx.agents.get(options.sessionId) : undefined;
284
+ if (!agent || options.purpose)
285
+ throw new Error('ACP requires a foreground DSH session; auxiliary model calls are unsupported');
286
+ if (this.controllers.has(agent.id))
287
+ throw new Error('ACP session already has a running request');
288
+ const controller = new AbortController();
289
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
290
+ signal.addEventListener('abort', () => controller.abort(), { once: true });
291
+ this.controllers.set(agent.id, controller);
292
+ const queue = new Queue();
293
+ const task = this.run(agent, options, signal, queue).then(() => queue.end(), error => queue.end(error));
294
+ this.jobs.add(task);
295
+ try {
296
+ yield* queue.read();
297
+ }
298
+ finally {
299
+ controller.abort();
300
+ await task;
301
+ this.jobs.delete(task);
302
+ this.controllers.delete(agent.id);
303
+ }
304
+ }
305
+ async permission(agent, params, signal) {
306
+ const allow = params.options.find(o => o.kind === 'allow_once');
307
+ const deny = params.options.find(o => o.kind === 'reject_once');
308
+ if (!allow)
309
+ return { outcome: { outcome: 'cancelled' } };
310
+ const decision = await this.ctx.approval.request({ agent, toolName: params.toolCall.title || 'ACP tool',
311
+ reason: JSON.stringify(params.toolCall.rawInput ?? params.toolCall.content ?? {}, null, 2), signal });
312
+ const selected = decision === 'allowed-once' ? allow : decision === 'rejected' ? deny : undefined;
313
+ return { outcome: selected ? { outcome: 'selected', optionId: selected.optionId } : { outcome: 'cancelled' } };
314
+ }
315
+ async question(agent, p, signal) {
316
+ const questions = (Array.isArray(p.questions) ? p.questions : []).map((value, i) => {
317
+ const q = object(value);
318
+ return { id: String(i), question: String(q.question ?? ''), header: typeof q.header === 'string' ? q.header : undefined,
319
+ options: Array.isArray(q.options) ? q.options.map(value => { const o = object(value); return { label: String(o.label), description: typeof o.description === 'string' ? o.description : undefined }; }) : undefined,
320
+ multiSelect: q.multiSelect === true };
321
+ });
322
+ try {
323
+ const result = await this.ctx.userQuestions.ask({ agent, questions, signal });
324
+ return { outcome: 'accepted', answers: Object.fromEntries(result.answers.map(a => [questions[Number(a.id)].question, a.custom || (a.selected.length === 1 ? a.selected[0] : a.selected)])) };
325
+ }
326
+ catch (error) {
327
+ if (signal.aborted)
328
+ return { outcome: 'cancelled' };
329
+ throw error;
330
+ }
331
+ }
332
+ async plan(agent, p, signal) {
333
+ try {
334
+ const result = await this.ctx.userQuestions.ask({ agent, signal, questions: [{ id: 'plan', question: 'ACP Agent 请求执行计划', detail: String(p.planContent ?? ''), options: [{ label: '批准' }, { label: '拒绝' }], intent: { kind: 'plan-review', approve: '批准' } }] });
335
+ return { outcome: result.answers[0]?.selected.includes('批准') ? 'approved' : 'rejected' };
336
+ }
337
+ catch (error) {
338
+ if (signal.aborted)
339
+ return { outcome: 'abandoned' };
340
+ throw error;
341
+ }
342
+ }
343
+ async run(agent, options, signal, queue) {
344
+ const cwd = agent.session.header.cwd;
345
+ if (!cwd)
346
+ throw new Error('Create the ACP session in a workspace first');
347
+ // Only newly admitted input goes to the stateful remote Agent. Its native
348
+ // conversation already owns prior turns and tool results.
349
+ let start = options.messages.length - 1;
350
+ while (start >= 0 && options.messages[start].role !== 'assistant')
351
+ start--;
352
+ if (this.agentName(agent) !== options.model)
353
+ throw new Error('ACP is available only in its matching Agent preset; start a new ACP session');
354
+ const importedIds = new Set(this.state.get(agent.id)?.imported?.messageIds ?? []);
355
+ const input = options.messages.slice(start + 1).filter(m => m.role === 'user' && m.source?.kind === 'user' && (m.id === undefined || !importedIds.has(m.id)));
356
+ const blocks = input.flatMap(m => m.content);
357
+ if (!blocks.length || blocks.some(b => b.type !== 'text'))
358
+ throw new Error('This ACP plugin currently accepts text prompts only');
359
+ const text = blocks.map(b => b.text).join('\n\n');
360
+ const requestId = 'dsh-' + createHash('sha256').update(JSON.stringify([agent.id, input.map(m => m.id)])).digest('hex');
361
+ const endpoint = new URL(`/agents/${encodeURIComponent(options.model)}`, this.config.serviceUrl);
362
+ endpoint.protocol = endpoint.protocol === 'https:' ? 'wss:' : 'ws:';
363
+ let binding = this.state.get(agent.id);
364
+ if (binding && (binding.agent !== options.model || binding.cwd !== cwd || binding.endpoint !== endpoint.href))
365
+ throw new Error('This session is bound to another ACP Agent or endpoint; start a new session');
366
+ const seen = new Set();
367
+ let index = 0, current, content = '', answer = '';
368
+ const endBlock = () => { if (current) {
369
+ queue.push({ type: 'block-end', index, block: { type: current, text: content } });
370
+ index++;
371
+ current = undefined;
372
+ content = '';
373
+ } };
374
+ const emit = (kind, text) => {
375
+ if (!text)
376
+ return;
377
+ if (current !== kind) {
378
+ endBlock();
379
+ current = kind;
380
+ queue.push({ type: 'block-start', index, blockType: kind });
381
+ }
382
+ content += text;
383
+ if (kind === 'text')
384
+ answer += text;
385
+ queue.push(kind === 'text' ? { type: 'text-delta', index, text } : { type: 'reasoning-delta', index, text });
386
+ };
387
+ const update = (u) => {
388
+ const meta = u._meta?.['1agents'];
389
+ if (meta?.turnId !== requestId)
390
+ return;
391
+ if (typeof meta.sequence !== 'number')
392
+ return;
393
+ if (seen.has(meta.sequence))
394
+ return;
395
+ seen.add(meta.sequence);
396
+ if ((u.sessionUpdate === 'agent_message_chunk' || u.sessionUpdate === 'agent_thought_chunk') && u.content.type === 'text')
397
+ emit(u.sessionUpdate === 'agent_message_chunk' ? 'text' : 'reasoning', u.content.text);
398
+ else if (u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update') {
399
+ // External tools execute inside the remote Agent. Never emit local
400
+ // tool-call chunks: DSH would execute those calls a second time.
401
+ const title = 'title' in u && u.title ? u.title : u.toolCallId;
402
+ emit('reasoning', `\n[ACP ${u.status ?? 'tool'}] ${title}\n`);
403
+ }
404
+ };
405
+ let active;
406
+ const cancel = () => { if (binding)
407
+ void active?.rpc.notify('session/cancel', { sessionId: binding.sessionId }).catch(() => { }); };
408
+ signal.addEventListener('abort', cancel, { once: true });
409
+ try {
410
+ for (let attempt = 0;; attempt++) {
411
+ signal.throwIfAborted();
412
+ try {
413
+ this.output.set(agent.id, update);
414
+ active = await this.connection(agent);
415
+ binding = this.state.get(agent.id);
416
+ signal.throwIfAborted();
417
+ const result = await active.rpc.request('session/prompt', { sessionId: binding.sessionId, prompt: [{ type: 'text', text }],
418
+ _meta: { '1agents': { turnManaged: true, turnId: requestId, requestId } } }, { cancellationSignal: signal });
419
+ signal.throwIfAborted();
420
+ const meta = result._meta?.['1agents'];
421
+ if (!answer && typeof meta?.finalAnswer === 'string')
422
+ emit('text', meta.finalAnswer);
423
+ endBlock();
424
+ queue.push(result.stopReason === 'cancelled' ? { type: 'finish', reason: { kind: 'aborted', failure: { code: 'ABORTED', message: 'ACP turn cancelled' } } } : { type: 'finish', reason: result.stopReason === 'max_tokens' ? { kind: 'max-tokens' } : { kind: 'stop' } });
425
+ return;
426
+ }
427
+ catch (error) {
428
+ if (signal.aborted) {
429
+ endBlock();
430
+ queue.push({ type: 'finish', reason: { kind: 'aborted', failure: { code: 'ABORTED', message: 'ACP turn cancelled' } } });
431
+ return;
432
+ }
433
+ // Only transport loss is retried. The managed request ID makes an
434
+ // uncertain delivery idempotent; provider errors remain errors.
435
+ if ((active && active.ws.readyState === 1) || attempt >= this.config.reconnectAttempts)
436
+ throw error;
437
+ await delay(this.config.reconnectDelayMs, undefined, { signal });
438
+ }
439
+ finally {
440
+ active = undefined;
441
+ }
442
+ }
443
+ }
444
+ finally {
445
+ signal.removeEventListener('abort', cancel);
446
+ this.output.delete(agent.id);
447
+ }
448
+ }
449
+ }