@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.
@@ -0,0 +1,336 @@
1
+ window.__ModuleLoader__.load({id:"@1agents/acp-service",dependencies:["react"],factory:(require)=>{var module={exports:{}};var exports=module.exports;
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/client.js
22
+ var client_exports = {};
23
+ __export(client_exports, {
24
+ AcpTools: () => AcpTools,
25
+ apply: () => apply,
26
+ choices: () => choices,
27
+ inject: () => inject
28
+ });
29
+ module.exports = __toCommonJS(client_exports);
30
+ var import_react = require("react");
31
+
32
+ // src/tool-conversation.js
33
+ var names = { execute: "Bash", read: "Read", edit: "Edit", delete: "Delete", move: "Move", search: "Search", fetch: "Fetch", think: "Think" };
34
+ function contentOf(tool) {
35
+ if (tool.content?.length) return tool.content.flatMap((item) => {
36
+ if (item.type === "content" && item.content.type === "text") return [item.content];
37
+ if (item.type === "diff") return [{ type: "text", text: `${item.path}
38
+ ---
39
+ ${item.oldText ?? ""}
40
+ +++
41
+ ${item.newText}` }];
42
+ return [];
43
+ });
44
+ if (tool.rawOutput === void 0 || tool.rawOutput === null) return [];
45
+ return [{ type: "text", text: typeof tool.rawOutput === "string" ? tool.rawOutput : JSON.stringify(tool.rawOutput, null, 2) }];
46
+ }
47
+ function rootOf(state, location) {
48
+ const { tool, requestId, turn, step } = state.data;
49
+ const name = tool.name && tool.name !== "Tool" ? tool.name : names[tool.kind] ?? tool.title ?? tool.name ?? "Tool";
50
+ const argsRaw = JSON.stringify(tool.rawInput ?? {});
51
+ const head = { callId: `${requestId}:${tool.toolCallId}`, name, argsRaw, turn, step, time: state.time, subCalls: [] };
52
+ const settled = tool.status === "completed" || tool.status === "failed";
53
+ const closed = location?.kind === "step" && location.step.status === "closed" ? location.step.end : (location?.kind === "step" || location?.kind === "turn") && location.turn.status === "closed" ? location.turn.end : void 0;
54
+ if (!settled && !closed) return { ...head, phase: "start" };
55
+ return {
56
+ kind: "tool-result",
57
+ seq: state.seq,
58
+ time: settled ? state.updatedAt : closed.time,
59
+ callId: head.callId,
60
+ call: { name, argsRaw },
61
+ callTime: state.time,
62
+ content: contentOf(tool),
63
+ isError: tool.status === "failed" || !settled,
64
+ ...!settled ? { error: { name: "Interrupted", code: "interrupted" } } : {},
65
+ meta: { acp: tool },
66
+ subCalls: []
67
+ };
68
+ }
69
+ function snapshots(event) {
70
+ const fromChunk = (chunk, time) => chunk?.type === "block-end" && chunk.block?.acpTool ? [{ data: chunk.block.acpTool, time }] : [];
71
+ if (event.type === "assistant/live-chunk") return fromChunk(event.data.chunk, event.time);
72
+ if (event.type === "assistant/message" || event.type === "assistant/attempt") {
73
+ return (event.data.stream ?? []).flatMap((record) => record.type === "chunk" ? fromChunk(record.chunk, record.time) : []);
74
+ }
75
+ return [];
76
+ }
77
+ function fold(previous, match) {
78
+ const tools = new Map(previous?.tools);
79
+ for (const { data, time } of snapshots(match.event)) {
80
+ const current = tools.get(data.tool.toolCallId);
81
+ if (current && current.data.sequence >= data.sequence) continue;
82
+ tools.set(data.tool.toolCallId, { data, seq: current?.seq ?? match.event.seq, time: current?.time ?? time, updatedAt: time });
83
+ }
84
+ return { tools, seq: previous?.seq ?? match.event.seq };
85
+ }
86
+ var toolConversationDefinition = {
87
+ kind: "oneagents-acp-tools",
88
+ target: "chat",
89
+ match: (event) => {
90
+ const first = snapshots(event)[0];
91
+ return first ? { id: first.data.requestId, role: "start" } : null;
92
+ },
93
+ start: (_context, match) => fold(void 0, match),
94
+ update: (context, match) => fold(context.state, match),
95
+ publication: () => "immediate",
96
+ buildViewNode: (context) => {
97
+ const state = context.state;
98
+ if (!state) return null;
99
+ const location = context.start?.location ?? context.matches[0]?.location ?? { kind: "unresolved" };
100
+ return {
101
+ key: context.key,
102
+ id: context.id,
103
+ kind: "oneagents-acp-tools",
104
+ target: "chat",
105
+ anchorSeq: state.seq,
106
+ location,
107
+ visibility: "visible",
108
+ data: { roots: [...state.tools.values()].map((tool) => rootOf(tool, location)) }
109
+ };
110
+ }
111
+ };
112
+
113
+ // src/client.js
114
+ var inject = ["slots", "sessions", "commandUi", "remote", "remote.session", "locale", "uiConversation"];
115
+ var dictionaries = {
116
+ zh: { toolRunning: "\u6267\u884C\u4E2D", toolFailed: "\u5931\u8D25", toolCompleted: "\u5DF2\u5B8C\u6210", toolNoOutput: "\u65E0\u8F93\u51FA", model: "\u6A21\u578B", choose: "\u9009\u62E9\u6A21\u578B", loading: "\u6B63\u5728\u8FDE\u63A5 Agent\u2026", retry: "\u91CD\u8BD5", mode: "\u6A21\u5F0F", command: "Agent \u6307\u4EE4", effort: "\u601D\u8003\u5F3A\u5EA6", unsupported: "Agent \u672A\u63D0\u4F9B\u53EF\u5207\u6362\u7684\u6A21\u578B", description: "\u9009\u62E9\u5F53\u524D Agent \u7684\u6A21\u578B", error: "\u8FDE\u63A5\u5931\u8D25", noCommands: "Agent \u5C1A\u672A\u63D0\u4F9B\u6307\u4EE4", native: "ACP \u8BBE\u7F6E" },
117
+ en: { toolRunning: "Running", toolFailed: "Failed", toolCompleted: "Completed", toolNoOutput: "No output", model: "Model", choose: "Select model", loading: "Connecting to Agent\u2026", retry: "Retry", mode: "Mode", command: "Agent commands", effort: "Reasoning effort", unsupported: "This Agent does not advertise model selection", description: "Select this Agent\u2019s model", error: "Connection failed", noCommands: "No commands advertised", native: "ACP settings" }
118
+ };
119
+ function choices(option) {
120
+ return (option.options ?? []).flatMap((item) => "group" in item ? item.options.map((value) => ({ ...value, group: item.name ?? item.group })) : [item]);
121
+ }
122
+ async function acpRequest(sessionId, change) {
123
+ const response = await fetch(`/api/1agents-acp/session?id=${encodeURIComponent(sessionId)}`, {
124
+ ...change ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(change) } : {},
125
+ credentials: "same-origin"
126
+ });
127
+ const value = await response.json();
128
+ if (!response.ok) throw new Error(value.error || `HTTP ${response.status}`);
129
+ return value;
130
+ }
131
+ var selectStyle = { maxWidth: 210, minHeight: 30, borderRadius: 7, border: "1px solid var(--dsw-alias-border-l1, #8885)", color: "inherit", background: "var(--dsw-alias-bg-base, transparent)", padding: "3px 7px", fontSize: 12 };
132
+ function Select({ title, value, rows, disabled, onSelect, placeholder }) {
133
+ return (0, import_react.createElement)(
134
+ "label",
135
+ { style: { display: "inline-flex", gap: 5, alignItems: "center", fontSize: 12 } },
136
+ (0, import_react.createElement)("span", null, title),
137
+ (0, import_react.createElement)(
138
+ "select",
139
+ { "aria-label": title, style: selectStyle, value: value ?? "", disabled, onChange: (e) => onSelect(e.target.value) },
140
+ (0, import_react.createElement)("option", { value: "", disabled: true }, placeholder || title),
141
+ rows.map((row) => (0, import_react.createElement)("option", { key: row.value, value: row.value, title: row.description }, `${row.group ? `${row.group} \xB7 ` : ""}${row.name}`))
142
+ )
143
+ );
144
+ }
145
+ function AcpTools({ node, t }) {
146
+ return (0, import_react.createElement)("div", { "data-oneagents-acp-tools": "", style: { display: "grid", gap: 6 } }, node.data.roots.map((root) => {
147
+ const running = root.phase === "start";
148
+ const tool = running ? root : root.call;
149
+ const output = running ? [] : root.content;
150
+ const acp = root.meta?.acp;
151
+ let args;
152
+ try {
153
+ args = JSON.parse(tool.argsRaw);
154
+ } catch {
155
+ args = tool.argsRaw;
156
+ }
157
+ const input = args?.command ?? args?.path ?? args?.file_path ?? acp?.title ?? tool.argsRaw;
158
+ const state = running ? "running" : root.isError ? "failed" : "completed";
159
+ const labels = { running: t("toolRunning"), failed: t("toolFailed"), completed: t("toolCompleted"), noOutput: t("toolNoOutput") };
160
+ return (0, import_react.createElement)(
161
+ "details",
162
+ {
163
+ key: root.callId,
164
+ "data-acp-call": root.callId,
165
+ "data-acp-status": state,
166
+ style: { border: "1px solid var(--dsw-alias-border-l1, #8883)", borderRadius: 8, padding: "7px 10px" }
167
+ },
168
+ (0, import_react.createElement)(
169
+ "summary",
170
+ { style: { cursor: "pointer", fontSize: 13 } },
171
+ (0, import_react.createElement)("strong", null, tool.name),
172
+ " ",
173
+ (0, import_react.createElement)("span", { style: { opacity: 0.65 } }, labels[state]),
174
+ (0, import_react.createElement)("code", { style: { display: "block", whiteSpace: "pre-wrap", overflowWrap: "anywhere", marginTop: 4 } }, typeof input === "string" ? input : JSON.stringify(input))
175
+ ),
176
+ (0, import_react.createElement)(
177
+ "pre",
178
+ { style: { whiteSpace: "pre-wrap", overflowWrap: "anywhere", maxHeight: 360, overflow: "auto", fontSize: 12 } },
179
+ output.length ? output.map((block) => block.text ?? "").join("\n") : running ? labels.running : labels.noOutput
180
+ )
181
+ );
182
+ }));
183
+ }
184
+ function apply(ctx) {
185
+ ctx.uiConversation.events.register(toolConversationDefinition);
186
+ ctx.slots.inject("conversation.chat.node", () => ctx.slots.register({
187
+ name: "conversation.chat.node",
188
+ key: "oneagents-acp-tools",
189
+ locale: "oneagentsAcp"
190
+ }, AcpTools));
191
+ ctx.effect(() => ctx.locale.register("oneagentsAcp", dictionaries));
192
+ const t = ctx.locale.bind("oneagentsAcp");
193
+ const native = /* @__PURE__ */ new Map();
194
+ const pending = /* @__PURE__ */ new Map();
195
+ const listeners = /* @__PURE__ */ new Map();
196
+ const presetOf = (id) => ctx.sessions.binding(id)?.session.projections.faceOf("agentPreset").getSnapshot();
197
+ const isAcp = (id) => String(presetOf(id) ?? "").startsWith("oneagents-acp-");
198
+ const publish = (id, value) => {
199
+ native.set(id, value);
200
+ for (const fn of listeners.get(id) ?? []) fn();
201
+ };
202
+ const load = (id) => {
203
+ if (!pending.has(id)) {
204
+ const operation = acpRequest(id).then((value) => {
205
+ publish(id, value);
206
+ return value;
207
+ }).finally(() => pending.delete(id));
208
+ pending.set(id, operation);
209
+ }
210
+ return pending.get(id);
211
+ };
212
+ const configure = async (id, configId, value) => {
213
+ const updated = await acpRequest(id, { configId, value });
214
+ publish(id, updated);
215
+ };
216
+ const reset = () => {
217
+ native.clear();
218
+ for (const set of listeners.values()) for (const fn of set) fn();
219
+ };
220
+ ctx.remote.$on("agent-preset/selected", reset);
221
+ ctx.on("connection/reset", reset);
222
+ function ModelControls({ sessionId, locked }) {
223
+ const binding = ctx.sessions.binding(sessionId);
224
+ const preset = binding.session.projections.faceOf("agentPreset");
225
+ const selection = binding.session.projections.faceOf("modelSelection");
226
+ const presetId = (0, import_react.useSyncExternalStore)((fn) => preset.subscribe(fn), () => preset.getSnapshot());
227
+ const projected = (0, import_react.useSyncExternalStore)((fn) => selection.subscribe(fn), () => selection.getSnapshot());
228
+ const capabilities = (0, import_react.useSyncExternalStore)((fn) => {
229
+ let set = listeners.get(sessionId);
230
+ if (!set) listeners.set(sessionId, set = /* @__PURE__ */ new Set());
231
+ set.add(fn);
232
+ return () => {
233
+ set.delete(fn);
234
+ };
235
+ }, () => native.get(sessionId));
236
+ const external = String(presetId ?? "").startsWith("oneagents-acp-");
237
+ const [catalog, setCatalog] = (0, import_react.useState)(null);
238
+ const [error, setError] = (0, import_react.useState)("");
239
+ const [loadError, setLoadError] = (0, import_react.useState)("");
240
+ const [busy, setBusy] = (0, import_react.useState)(false);
241
+ const [expanded, setExpanded] = (0, import_react.useState)(false);
242
+ const refresh = async () => {
243
+ try {
244
+ if (external) await load(sessionId);
245
+ else {
246
+ const result = await ctx.remote.session.modelCatalog();
247
+ if (!result.ok) throw new Error(result.error.message);
248
+ setCatalog(result.value);
249
+ }
250
+ setLoadError("");
251
+ } catch (error2) {
252
+ setLoadError(String(error2.message ?? error2));
253
+ }
254
+ };
255
+ (0, import_react.useEffect)(() => {
256
+ void refresh();
257
+ }, [sessionId, presetId]);
258
+ (0, import_react.useEffect)(() => {
259
+ if (!external) return;
260
+ const timer = setInterval(() => {
261
+ if (document.visibilityState === "visible") void refresh();
262
+ }, 5e3);
263
+ return () => clearInterval(timer);
264
+ }, [external, sessionId, presetId]);
265
+ const change = async (action) => {
266
+ setBusy(true);
267
+ setError("");
268
+ try {
269
+ await action();
270
+ } catch (error2) {
271
+ setError(String(error2.message ?? error2));
272
+ } finally {
273
+ setBusy(false);
274
+ }
275
+ };
276
+ const disabled = locked || busy;
277
+ const controls = [];
278
+ if (external && capabilities) {
279
+ const configs = capabilities.configOptions.filter((option) => option.type === "select");
280
+ const model = configs.find((option) => option.category === "model" || option.id === "model");
281
+ if (model) controls.push((0, import_react.createElement)(Select, { key: model.id, title: model.name || t("model"), value: model.currentValue, rows: choices(model), disabled, onSelect: (value) => change(() => configure(sessionId, model.id, value)) }));
282
+ else controls.push((0, import_react.createElement)("span", { key: "unsupported", title: t("unsupported"), style: { fontSize: 12 } }, `ACP \xB7 ${capabilities.agent}`));
283
+ const additional = configs.filter((option) => option !== model && !(capabilities.modes && (option.category === "mode" || option.id === "mode")));
284
+ if (additional.length || capabilities.modes) controls.push((0, import_react.createElement)("button", { key: "settings", type: "button", style: selectStyle, onClick: () => setExpanded(!expanded), "aria-expanded": expanded }, t("native")));
285
+ if (expanded) {
286
+ for (const option of additional) controls.push((0, import_react.createElement)(Select, { key: option.id, title: option.name, value: option.currentValue, rows: choices(option), disabled, onSelect: (value) => change(() => configure(sessionId, option.id, value)) }));
287
+ if (capabilities.modes) controls.push((0, import_react.createElement)(Select, { key: "mode", title: t("mode"), value: capabilities.modes.currentModeId, rows: capabilities.modes.availableModes.map((m) => ({ value: m.id, name: m.name, description: m.description })), disabled, onSelect: (value) => change(() => configure(sessionId, "$mode", value)) }));
288
+ }
289
+ } else if (!external && catalog) {
290
+ const current = projected?.next ?? catalog.default;
291
+ const rows = catalog.groups.flatMap((group) => group.models.map((model2) => ({ value: JSON.stringify([group.id, model2.id]), name: model2.name, group: group.name })));
292
+ const select = async (provider, model2, reasoningEffort) => {
293
+ const result = await ctx.remote.session.selectModel({ sessionId, provider, model: model2, ...reasoningEffort ? { reasoningEffort } : {} });
294
+ if (!result.ok) throw new Error(result.error.message);
295
+ };
296
+ controls.push((0, import_react.createElement)(Select, { key: "dsh-model", title: t("model"), value: current?.provider === "1agents-acp" ? "" : JSON.stringify([current?.provider, current?.model]), rows, disabled, placeholder: t("choose"), onSelect: (value) => change(() => select(...JSON.parse(value))) }));
297
+ const model = catalog.groups.find((g) => g.id === current?.provider)?.models.find((m) => m.id === current?.model);
298
+ if (model?.reasoning) controls.push((0, import_react.createElement)(Select, { key: "effort", title: t("effort"), value: current.reasoningEffort ?? model.reasoning.defaultEffort, rows: model.reasoning.efforts.map((e) => ({ value: e.id, name: e.name })), disabled, onSelect: (value) => change(() => select(current.provider, current.model, value)) }));
299
+ } else if (!error && !loadError) controls.push((0, import_react.createElement)("span", { key: "loading", style: { fontSize: 12 } }, t("loading")));
300
+ if (error || loadError) controls.push((0, import_react.createElement)("span", { key: "error", role: "alert", style: { color: "#c64b45", fontSize: 12, maxWidth: 360 } }, error || loadError, " ", (0, import_react.createElement)("button", { type: "button", onClick: () => {
301
+ setError("");
302
+ void refresh();
303
+ } }, t("retry"))));
304
+ return (0, import_react.createElement)("div", { "data-oneagents-acp-controls": external ? "acp" : "dsh", style: { display: "flex", alignItems: "center", flexWrap: "wrap", gap: 8 } }, controls);
305
+ }
306
+ ctx.slots.inject("conversation.input.model", () => ctx.slots.register({ name: "conversation.input.model", inject: (sessionId) => ({ sessionId }) }, ModelControls));
307
+ ctx.effect(() => ctx.commandUi.register({
308
+ name: "model",
309
+ description: () => t("description"),
310
+ available: (session) => ctx.sessions.subagentAddress(session.sessionId) === void 0,
311
+ ui: {
312
+ kind: "popupSelect",
313
+ options: async ({ sessionId }) => {
314
+ if (isAcp(sessionId)) {
315
+ const capabilities = await load(sessionId);
316
+ const model = capabilities?.configOptions.find((option) => option.category === "model" || option.id === "model");
317
+ if (!model) throw new Error(t("unsupported"));
318
+ return choices(model).map((option) => ({ id: JSON.stringify([model.id, option.value]), label: option.name, detail: option.description, active: option.value === model.currentValue }));
319
+ }
320
+ const response = await ctx.remote.session.modelCatalog();
321
+ if (!response.ok) throw new Error(response.error.message);
322
+ return response.value.groups.flatMap((group) => group.models.map((model) => ({ id: JSON.stringify([group.id, model.id]), label: model.name, detail: group.name })));
323
+ },
324
+ onSelect: async (option, { sessionId }) => {
325
+ const [key, value] = JSON.parse(option.id);
326
+ if (isAcp(sessionId)) await configure(sessionId, key, value);
327
+ else {
328
+ const result = await ctx.remote.session.selectModel({ sessionId, provider: key, model: value });
329
+ if (!result.ok) throw new Error(result.error.message);
330
+ }
331
+ }
332
+ }
333
+ }));
334
+ }
335
+
336
+ return module.exports;}});
@@ -0,0 +1,10 @@
1
+ - id: ui-model-selection
2
+ disabled: true
3
+ - insert:
4
+ - id: oneagents-acp
5
+ name: '@1agents/acp-service'
6
+ config:
7
+ serviceMode: auto
8
+ serviceUrl: http://127.0.0.1:36812
9
+ reconnectAttempts: 5
10
+ reconnectDelayMs: 1000
@@ -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;