@1agents/acp-service 0.10.5 → 0.10.6

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/vendor/dsh/a2a.js CHANGED
@@ -13,7 +13,10 @@ export async function mountDshA2A(ctx, options, stateDirectory, diagnostics, ses
13
13
  const { workbench: _workbench, ...serverOptions } = options;
14
14
  const server = await createA2AServer({ ...serverOptions, token, backend: new DshA2ABackend(ctx, diagnostics, sessions),
15
15
  stateDirectory: options.stateDirectory ?? stateDirectory,
16
- publicUrl: options.publicUrl ?? `http://127.0.0.1:${ctx.webServer.port}` });
16
+ publicUrl: options.publicUrl ?? `http://127.0.0.1:${ctx.webServer.port}`,
17
+ storage: { onConflict: 'readonly' } });
18
+ if (server.mode === 'read-only')
19
+ console.warn('oneagents-acp A2A storage is read-only because another instance owns it');
17
20
  const routes = [];
18
21
  try {
19
22
  routes.push(ctx.webServer.register({ kind: 'exact', path: '/.well-known/agent-card.json', handler: server.cardHandler }));
@@ -1,7 +1,7 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
2
  import type { Agent } from '@deepseek-ai/dsh-agent';
3
3
  import type { LlmAdapter, GenerateOptions, StreamChunk, LlmModelInfo } from '@deepseek-ai/dsh-llm';
4
- import type { Diagnostics } from './diagnostics.js';
4
+ import type { DiagnosticLog } from './diagnostics.js';
5
5
  import type { McpServer, SessionConfigOption, SessionModeState, AvailableCommand } from '@agentclientprotocol/sdk';
6
6
  import { type Binding } from './state.js';
7
7
  import type { ProcessRequestClient } from './process-requests.js';
@@ -58,7 +58,7 @@ export declare class AcpAdapter implements LlmAdapter {
58
58
  private readonly sessionSettings;
59
59
  /** MCP servers offered when a session is created or restored, such as the A2A hand-back tool. */
60
60
  mcpServersFor?: (sessionId: string) => McpServer[];
61
- constructor(ctx: Context, config: Config, diagnostics?: Diagnostics, processRequests?: ProcessRequestClient);
61
+ constructor(ctx: Context, config: Config, diagnostics?: DiagnosticLog, processRequests?: ProcessRequestClient);
62
62
  providerInfo(provider: string): {
63
63
  id: string;
64
64
  name: string;
@@ -53,14 +53,14 @@ ${item.newText}` }];
53
53
  if (content.length || tool.rawOutput == null) return content;
54
54
  return [{ type: "text", text: typeof tool.rawOutput === "string" ? tool.rawOutput : JSON.stringify(tool.rawOutput, null, 2) }];
55
55
  }
56
- function rootOf(state, location2) {
56
+ function rootOf(state, location) {
57
57
  const { tool, requestId, turn, step } = state.data;
58
58
  const name = tool.name && tool.name !== "Tool" ? tool.name : names[tool.kind] ?? tool.title ?? tool.name ?? "Tool";
59
59
  const input = tool.rawInput ?? (tool.locations?.[0]?.path ? { path: tool.locations[0].path } : tool.title ? { description: tool.title } : {});
60
60
  const argsRaw = JSON.stringify(input);
61
61
  const head = { callId: `${requestId}:${tool.toolCallId}`, name, argsRaw, turn, step, time: state.time, subCalls: [] };
62
62
  const settled = tool.status === "completed" || tool.status === "failed";
63
- const closed = location2?.kind === "step" && location2.step.status === "closed" ? location2.step.end : (location2?.kind === "step" || location2?.kind === "turn") && location2.turn.status === "closed" ? location2.turn.end : void 0;
63
+ 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;
64
64
  if (!settled && !closed) return { ...head, phase: "start" };
65
65
  return {
66
66
  kind: "tool-result",
@@ -137,10 +137,10 @@ var toolConversationDefinition = {
137
137
  buildViewNode: (context) => {
138
138
  const state = context.state;
139
139
  if (!state?.acp) return null;
140
- const location2 = context.start?.location ?? context.matches[0]?.location ?? { kind: "unresolved" };
140
+ const location = context.start?.location ?? context.matches[0]?.location ?? { kind: "unresolved" };
141
141
  const parts = [];
142
142
  for (const [index, block] of [...state.blocks].sort(([a], [b]) => a - b)) {
143
- if (block.kind === "tool") parts.push({ kind: "tool", root: rootOf(state.tools.get(block.id), location2) });
143
+ if (block.kind === "tool") parts.push({ kind: "tool", root: rootOf(state.tools.get(block.id), location) });
144
144
  else if (block.text.trim()) {
145
145
  const last = parts.at(-1);
146
146
  if (last?.kind === block.kind) last.text += block.text;
@@ -148,7 +148,7 @@ var toolConversationDefinition = {
148
148
  }
149
149
  }
150
150
  if (!parts.length) return null;
151
- const status = state.final ? "settled" : location2.kind === "step" && location2.step.status === "closed" ? "interrupted" : "running";
151
+ const status = state.final ? "settled" : location.kind === "step" && location.step.status === "closed" ? "interrupted" : "running";
152
152
  const turn = context.matches[0].event.data.turn, step = context.matches[0].event.data.step;
153
153
  const text = parts.filter((part) => part.kind === "text").map((part) => part.text).join("\n");
154
154
  const blocks = [{ kind: "text", text: text || parts.filter((part) => part.kind === "tool").map((part) => part.root.name ?? part.root.call.name).join(", ") || "ACP" }];
@@ -158,7 +158,7 @@ var toolConversationDefinition = {
158
158
  kind: "assistant-step",
159
159
  target: "chat",
160
160
  anchorSeq: state.seq,
161
- location: location2,
161
+ location,
162
162
  visibility: "visible",
163
163
  data: {
164
164
  status,
@@ -264,11 +264,10 @@ function installTranscriptView(ctx) {
264
264
  }
265
265
 
266
266
  // src/client.js
267
- var inject = ["slots", "sessions", "commandUi", "remote", "remote.session", "locale", "uiConversation", "conversation", "uiWorkspace"];
268
- var WORKBENCH_PANEL = "oneagents-a2a-workbench";
267
+ var inject = ["slots", "sessions", "commandUi", "remote", "remote.session", "locale", "uiConversation", "conversation"];
269
268
  var dictionaries = {
270
- zh: { toolGroup: "\u5DF2\u8C03\u7528 {count} \u4E2A\u5DE5\u5177", model: "\u6A21\u578B", choose: "\u9009\u62E9\u6A21\u578B", loading: "\u6B63\u5728\u8FDE\u63A5 Agent\u2026", loadingModels: "\u6B63\u5728\u52A0\u8F7D\u6A21\u578B\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", activeWriter: "\u539F\u4F1A\u8BDD\u6B63\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u8FD0\u884C\uFF0C\u53EF\u67E5\u770B\u5386\u53F2\uFF1B\u5360\u7528\u89E3\u9664\u540E\u81EA\u52A8\u6062\u590D\u8F93\u5165\u3002", workbench: "A2A \u5DE5\u4F5C\u53F0", a2aRunning: "A2A \u4EFB\u52A1\u6B63\u5728\u6B64\u4F1A\u8BDD\u6267\u884C\uFF0C\u7ED3\u675F\u540E\u53EF\u4EBA\u5DE5\u63A5\u7BA1\u3002" },
271
- en: { toolGroup: "{count} tool calls", model: "Model", choose: "Select model", loading: "Connecting to Agent\u2026", loadingModels: "Loading models\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", activeWriter: "The original session is running in another client. History is available; input resumes when it is released.", workbench: "A2A Workbench", a2aRunning: "An A2A task is running in this session; you can take over once it ends." }
269
+ zh: { toolGroup: "\u5DF2\u8C03\u7528 {count} \u4E2A\u5DE5\u5177", model: "\u6A21\u578B", choose: "\u9009\u62E9\u6A21\u578B", loading: "\u6B63\u5728\u8FDE\u63A5 Agent\u2026", loadingModels: "\u6B63\u5728\u52A0\u8F7D\u6A21\u578B\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", activeWriter: "\u539F\u4F1A\u8BDD\u6B63\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u8FD0\u884C\uFF0C\u53EF\u67E5\u770B\u5386\u53F2\uFF1B\u5360\u7528\u89E3\u9664\u540E\u81EA\u52A8\u6062\u590D\u8F93\u5165\u3002" },
270
+ en: { toolGroup: "{count} tool calls", model: "Model", choose: "Select model", loading: "Connecting to Agent\u2026", loadingModels: "Loading models\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", activeWriter: "The original session is running in another client. History is available; input resumes when it is released." }
272
271
  };
273
272
  function choices(option) {
274
273
  return (option.options ?? []).flatMap((item) => "group" in item ? item.options.map((value) => ({ ...value, group: item.name ?? item.group })) : [item]);
@@ -524,29 +523,6 @@ function apply(ctx) {
524
523
  return (0, import_react2.createElement)("div", { "data-oneagents-acp-controls": external ? "acp" : "dsh", style: { display: "flex", alignItems: "center", flexWrap: "wrap", gap: 8 } }, controls);
525
524
  }
526
525
  ctx.slots.inject("conversation.input.model", () => ctx.slots.register({ name: "conversation.input.model", inject: (sessionId) => ({ sessionId }) }, ModelControls));
527
- function WorkbenchPanel() {
528
- const frame = (0, import_react2.useRef)(null);
529
- (0, import_react2.useEffect)(() => {
530
- const onMessage = (event) => {
531
- if (event.origin !== location.origin || event.source !== frame.current?.contentWindow) return;
532
- const { type, sessionId } = event.data ?? {};
533
- if (type === "1agents:open-session" && typeof sessionId === "string" && sessionId) ctx.uiWorkspace.openSession(sessionId);
534
- };
535
- window.addEventListener("message", onMessage);
536
- return () => window.removeEventListener("message", onMessage);
537
- }, []);
538
- return (0, import_react2.createElement)("iframe", { ref: frame, src: "/workbench/ui/", title: t("workbench"), style: { display: "block", width: "100%", height: "100%", border: 0 } });
539
- }
540
- function WorkbenchIcon({ size }) {
541
- return (0, import_react2.createElement)(
542
- "svg",
543
- { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.75, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true },
544
- (0, import_react2.createElement)("rect", { x: 3, y: 4, width: 18, height: 16, rx: 2 }),
545
- (0, import_react2.createElement)("path", { d: "M9 4v16M13 9h5M13 13h5" })
546
- );
547
- }
548
- ctx.slots.inject("main", () => ctx.slots.register({ name: "main", key: WORKBENCH_PANEL }, WorkbenchPanel));
549
- ctx.slots.inject("sidebar.panellist", () => ctx.slots.register({ name: "sidebar.panellist", id: WORKBENCH_PANEL, order: 20, label: () => t("workbench") }, WorkbenchIcon));
550
526
  ctx.effect(() => ctx.commandUi.register({
551
527
  name: "model",
552
528
  description: () => t("description"),
@@ -4,7 +4,8 @@
4
4
  - id: oneagents-acp
5
5
  name: '@1agents/acp-service'
6
6
  config:
7
- # Shared ACP daemon; do not fork one service per DSH profile.
7
+ # Connect to the shared local ACP daemon. Start it once with
8
+ # `acp-service serve --port 36812`; the DSH host does not own it.
8
9
  serviceMode: external
9
10
  serviceUrl: http://127.0.0.1:36812
10
11
  reconnectAttempts: 5
@@ -11,6 +11,15 @@ declare const identitySchema: z.ZodObject<{
11
11
  requestIds: z.ZodArray<z.ZodString>;
12
12
  }, z.core.$strict>;
13
13
  export type DiagnosticIdentity = z.infer<typeof identitySchema>;
14
+ /** Methods the adapter and A2A backend actually call. A follower may implement them in memory. */
15
+ export interface DiagnosticLog {
16
+ begin(identity: DiagnosticIdentity): Promise<string>;
17
+ submitted(id: string): Promise<void>;
18
+ confirmed(id: string): Promise<void>;
19
+ settle(id: string, error?: SafeError): Promise<void>;
20
+ find(sessionId: string, requestId: string, turn?: number, turnStartSeq?: number): SafeError | undefined;
21
+ close(): Promise<void>;
22
+ }
14
23
  /** Shared by the owned Adapter and A2A backend; every mutating method awaits durability. */
15
24
  export declare class Diagnostics {
16
25
  private readonly domain;
@@ -35,8 +44,11 @@ export declare class Diagnostics {
35
44
  close(): Promise<void>;
36
45
  }
37
46
  /** Own the official storage plugins until A2A and native calls have drained. */
38
- export declare function openDiagnostics(directory: string): Promise<{
39
- diagnostics: Diagnostics;
47
+ export declare function openDiagnostics(directory: string, options?: {
48
+ onConflict?: 'throw' | 'readonly';
49
+ }): Promise<{
50
+ diagnostics: DiagnosticLog;
40
51
  close: () => Promise<void>;
52
+ mode: 'read-write' | 'read-only';
41
53
  }>;
42
54
  export {};
@@ -6,7 +6,7 @@ import * as StorageDomain from '@deepseek-ai/dsh-storage-domain';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { z } from 'dsh-zod';
8
8
  import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
9
- import { DirectoryLease } from '@1agents/acp-service/a2a';
9
+ import { DirectoryLease, isStorageBusy } from '@1agents/acp-service/a2a';
10
10
  import { toSafeError } from '@1agents/acp-service/runtime';
11
11
  const identitySchema = z.object({
12
12
  sessionId: z.string().min(1).max(256), turn: z.number().int().nonnegative(),
@@ -137,11 +137,86 @@ export class Diagnostics {
137
137
  /** Drain writes before unloading; the owner first drains A2A and the Adapter. */
138
138
  async close() { this.closed = true; await this.chain; await this.domain.close(); }
139
139
  }
140
+ /** Process-local diagnostics. Used when another instance already owns the directory, so chat can continue without writing its files. */
141
+ class MemoryDiagnostics {
142
+ serial = 0;
143
+ records = new Map();
144
+ closed = false;
145
+ begin(identity) {
146
+ if (this.closed)
147
+ return Promise.reject(new Error('ACP diagnostics are closed'));
148
+ const snapshot = identitySchema.parse(identity);
149
+ const serial = this.serial + 1;
150
+ if (!Number.isSafeInteger(serial))
151
+ return Promise.reject(new Error('ACP diagnostic sequence exhausted'));
152
+ const id = randomUUID();
153
+ this.records.set(id, { id, serial, identity: snapshot, phase: 'prepared' });
154
+ this.serial = serial;
155
+ return Promise.resolve(id);
156
+ }
157
+ submitted(id) {
158
+ return this.update(id, record => {
159
+ if (record.phase !== 'prepared' && record.phase !== 'submitted')
160
+ throw new Error('ACP diagnostic attempt already confirmed');
161
+ return { ...record, phase: 'submitted' };
162
+ });
163
+ }
164
+ confirmed(id) {
165
+ return this.update(id, record => {
166
+ if (record.phase === 'settled')
167
+ throw new Error('ACP diagnostic attempt already settled');
168
+ return { ...record, phase: 'confirmed' };
169
+ });
170
+ }
171
+ settle(id, error) {
172
+ const safe = error === undefined ? undefined : errorSchema.parse({
173
+ category: error.category, retryable: error.retryable, outcomeUnknown: error.outcomeUnknown, origin: error.origin,
174
+ ...(error.providerCode === undefined ? {} : { providerCode: error.providerCode }),
175
+ ...(error.code === undefined ? {} : { code: error.code }),
176
+ ...(error.detailCode === undefined ? {} : { detailCode: error.detailCode }),
177
+ });
178
+ return this.update(id, record => {
179
+ if (record.phase === 'settled')
180
+ throw new Error('ACP diagnostic attempt already settled');
181
+ return { ...record, phase: 'settled', ...(safe === undefined ? {} : { error: safe }) };
182
+ });
183
+ }
184
+ find(sessionId, requestId, turn, turnStartSeq) {
185
+ const records = [...this.records.values()].filter(record => record.identity.sessionId === sessionId && record.identity.requestIds.includes(requestId)
186
+ && (turn === undefined || record.identity.turn === turn)
187
+ && (turnStartSeq === undefined || record.identity.turnStartSeq === turnStartSeq));
188
+ const record = records.sort((a, b) => b.serial - a.serial)[0];
189
+ if (!record)
190
+ return;
191
+ return record.error ? toSafeError(record.error, { trustedProjection: true, origin: 'dsh', operationId: requestId })
192
+ : toSafeError(undefined, { origin: 'dsh', operationId: requestId, outcomeUnknown: record.phase === 'submitted' });
193
+ }
194
+ async close() { this.closed = true; }
195
+ update(id, change) {
196
+ if (this.closed)
197
+ return Promise.reject(new Error('ACP diagnostics are closed'));
198
+ const current = this.records.get(id);
199
+ if (!current)
200
+ return Promise.reject(new Error('ACP diagnostic attempt is missing'));
201
+ this.records.set(id, change(current));
202
+ return Promise.resolve();
203
+ }
204
+ }
140
205
  /** Own the official storage plugins until A2A and native calls have drained. */
141
- export async function openDiagnostics(directory) {
206
+ export async function openDiagnostics(directory, options) {
207
+ let lease;
208
+ try {
209
+ lease = new DirectoryLease(directory);
210
+ }
211
+ catch (error) {
212
+ if (options?.onConflict === 'readonly' && isStorageBusy(error)) {
213
+ const diagnostics = new MemoryDiagnostics();
214
+ return { diagnostics, mode: 'read-only', close: () => diagnostics.close() };
215
+ }
216
+ throw error;
217
+ }
142
218
  // The host's shared facility can close concurrently during root teardown.
143
219
  // This private composition gives the consumer an explicit drain-before-close order.
144
- const lease = new DirectoryLease(directory);
145
220
  const storage = new Context();
146
221
  try {
147
222
  await storage.plugin(Storage);
@@ -150,7 +225,7 @@ export async function openDiagnostics(directory) {
150
225
  await mounted.await();
151
226
  const diagnostics = await Diagnostics.open(storage.storageDomain);
152
227
  let closing;
153
- return { diagnostics, close: () => closing ??= (async () => {
228
+ return { diagnostics, mode: 'read-write', close: () => closing ??= (async () => {
154
229
  try {
155
230
  await diagnostics.close();
156
231
  }
@@ -11,9 +11,7 @@ import { createWorkbenchProcessClient } from './process-requests.js';
11
11
  import { selectAcpRoute } from './preset-route.js';
12
12
  import { registerNativeApprovals } from './native-approvals.js';
13
13
  import { defineTool } from '@deepseek-ai/dsh-tools';
14
- import { WORKBENCH_UI_PATH } from '@1agents/acp-service/a2a';
15
14
  import { REVIEW_SUBMIT_PATH, ReviewHandBack, SUBMIT_DESCRIPTION, SUBMIT_TOOL, SUMMARY_DESCRIPTION } from './review.js';
16
- import { workbenchHandler } from './workbench.js';
17
15
  import { createTicketGateway, runTicketTool, ticketTools } from './ticket-tools.js';
18
16
  import { TICKET_PATH } from './ticket-spec.js';
19
17
  export { name, inject } from '@1agents/acp-service';
@@ -36,8 +34,10 @@ export async function apply(ctx, input = {}) {
36
34
  throw new Error('agents must contain ACP registry names');
37
35
  if (!Number.isSafeInteger(config.reconnectAttempts) || config.reconnectAttempts < 0 || !Number.isSafeInteger(config.reconnectDelayMs) || config.reconnectDelayMs < 1)
38
36
  throw new Error('Invalid ACP reconnect policy');
39
- const diagnosticOwner = await openDiagnostics(resolve(input.diagnosticsDirectory ?? join(config.stateDirectory, 'diagnostics')));
37
+ const diagnosticOwner = await openDiagnostics(resolve(input.diagnosticsDirectory ?? join(config.stateDirectory, 'diagnostics')), { onConflict: 'readonly' });
40
38
  const { diagnostics } = diagnosticOwner;
39
+ if (diagnosticOwner.mode === 'read-only')
40
+ console.warn('oneagents-acp diagnostics are read-only because another instance owns the storage');
41
41
  let closeA2A;
42
42
  const processRequests = input.a2a?.workbench ? createWorkbenchProcessClient(input.a2a.workbench) : undefined;
43
43
  const adapter = new AcpAdapter(ctx, config, diagnostics, processRequests);
@@ -116,7 +116,6 @@ export async function apply(ctx, input = {}) {
116
116
  });
117
117
  if (input.a2a) {
118
118
  const review = await ReviewHandBack.open(join(home, 'plugins', '1agents-acp', 'review.secret'), input.a2a.workbench);
119
- ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: WORKBENCH_UI_PATH, handler: workbenchHandler(ctx, { workbench: input.a2a.workbench, host: () => review.host }) }));
120
119
  ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: REVIEW_SUBMIT_PATH, handler: review.handler }));
121
120
  ctx.effect(() => ctx.tools.register(defineTool({
122
121
  name: SUBMIT_TOOL, description: SUBMIT_DESCRIPTION,
@@ -6,7 +6,9 @@ const leases = new Map();
6
6
  export function resolveServiceOptions(input) {
7
7
  const result = {
8
8
  serviceUrl: input.serviceUrl ?? 'http://127.0.0.1:36812',
9
- serviceMode: input.serviceMode ?? 'auto',
9
+ // The ACP daemon is a shared local service. Host plugins connect to it by default;
10
+ // per-host child ownership remains available only through the explicit `auto` mode.
11
+ serviceMode: input.serviceMode ?? 'external',
10
12
  serviceStartupTimeoutMs: input.serviceStartupTimeoutMs ?? 15_000,
11
13
  serviceShutdownTimeoutMs: input.serviceShutdownTimeoutMs ?? 5_000,
12
14
  };
File without changes
@@ -1,18 +0,0 @@
1
- /**
2
- * The gateway's task workbench page, served by DSH at the same path so the page needs no change. DSH's own
3
- * browser login stands in for the workbench login: every API call must be admitted as the owner, and the
4
- * plugin forwards it to the gateway's bearer API with a token the browser never sees.
5
- */
6
- import type { IncomingMessage, ServerResponse } from 'node:http';
7
- import type { Context } from '@deepseek-ai/cordis';
8
- import type { A2AHostControls } from './a2a.js';
9
- export interface WorkbenchProxyOptions {
10
- /** Gateway origin, bearer token and page relay secret (the same as a2a.workbench). */
11
- workbench?: {
12
- url: string;
13
- token?: string;
14
- pageRelaySecret?: string;
15
- };
16
- host: () => A2AHostControls | undefined;
17
- }
18
- export declare function workbenchHandler(ctx: Context, options: WorkbenchProxyOptions): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
@@ -1,91 +0,0 @@
1
- import { WORKBENCH_UI_PATH, isAgentRequest, serveWorkbenchPage } from '@1agents/acp-service/a2a';
2
- import { inspectSession } from './a2a-executor.js';
3
- const API = `${WORKBENCH_UI_PATH}/api`;
4
- const BODY_LIMIT = 1024 * 1024;
5
- const PASSED_HEADERS = ['content-type', 'content-disposition', 'content-security-policy', 'x-content-type-options', 'cache-control'];
6
- function json(res, status, body) {
7
- res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
8
- res.end(JSON.stringify(body));
9
- }
10
- async function bounded(req) {
11
- const chunks = [];
12
- let size = 0;
13
- for await (const chunk of req) {
14
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
15
- size += buffer.length;
16
- if (size > BODY_LIMIT)
17
- throw new Error('Request body too large');
18
- chunks.push(buffer);
19
- }
20
- return Buffer.concat(chunks);
21
- }
22
- export function workbenchHandler(ctx, options) {
23
- const gateway = options.workbench ? new URL(options.workbench.url).origin : undefined;
24
- return async (req, res) => {
25
- const url = new URL(req.url ?? '/', 'http://localhost');
26
- if (url.pathname !== API && !url.pathname.startsWith(`${API}/`))
27
- return serveWorkbenchPage(req, res, url.pathname, { frameAncestors: "'self'" });
28
- const admission = ctx.connection.admit(req);
29
- if ('rejection' in admission)
30
- return json(res, admission.rejection, { error: admission.rejection === 401 ? 'login_required' : 'forbidden' });
31
- // Hosts with delegated principals admit non-owners too; earlier hosts admit only the owner's browser.
32
- const principal = admission.peer.principal;
33
- if (principal && principal.kind !== 'owner')
34
- return json(res, 403, { error: 'forbidden' });
35
- // The reviewer is the person in the browser, never an agent or tool reusing the cookie.
36
- if (isAgentRequest(req))
37
- return json(res, 403, { error: 'browser_action_required' });
38
- if (req.method !== 'GET' && req.method !== 'HEAD' && req.headers['sec-fetch-site'] !== 'same-origin')
39
- return json(res, 403, { error: 'browser_action_required' });
40
- const route = url.pathname.slice(API.length);
41
- if (route === '/session')
42
- return json(res, 200, { authenticated: true, loginRequired: false });
43
- // The gateway records only the A2A task ID; this host knows which of its sessions ran it.
44
- const task = /^\/dsh\/tasks\/([^/]+)$/.exec(route);
45
- if (task) {
46
- if (req.method !== 'GET')
47
- return json(res, 405, { error: 'Method not allowed' });
48
- const taskId = decodeURIComponent(task[1]);
49
- if (taskId.length > 256)
50
- return json(res, 400, { error: 'Invalid task id' });
51
- const host = options.host(), sessionId = host?.taskSession(taskId);
52
- const available = sessionId !== undefined && await inspectSession(ctx, sessionId).then(found => found != null, () => false);
53
- if (!available)
54
- return json(res, 200, { available: false });
55
- const current = host.sessionTask(sessionId);
56
- return json(res, 200, { available, sessionId, ...(current ? { task: current } : {}) });
57
- }
58
- if (!gateway)
59
- return json(res, 503, { error: 'workbench_not_configured', message: '未配置 a2a.workbench,无法连接任务网关。' });
60
- // As on the gateway page, only the execution host opens process requests.
61
- if (req.method === 'POST' && /^\/tasks\/[^/]+\/process-requests$/.test(route))
62
- return json(res, 403, { error: 'browser_action_required' });
63
- let body;
64
- try {
65
- body = req.method === 'GET' || req.method === 'HEAD' ? undefined : await bounded(req);
66
- }
67
- catch {
68
- return json(res, 413, { error: 'Request body too large' });
69
- }
70
- // The relay secret tells the gateway this request comes from the person on this page, so it may publish and decide reviews.
71
- const headers = { ...(options.workbench.token?.trim() ? { Authorization: `Bearer ${options.workbench.token}` } : {}),
72
- ...(options.workbench.pageRelaySecret ? { 'X-Workbench-Page-Relay': options.workbench.pageRelaySecret } : {}),
73
- ...(body ? { 'Content-Type': String(req.headers['content-type'] ?? 'application/json') } : {}) };
74
- let response;
75
- try {
76
- response = await fetch(new URL(`/workbench${route}${url.search}`, gateway), { method: req.method, headers, ...(body ? { body: new Uint8Array(body) } : {}),
77
- redirect: 'error', signal: AbortSignal.timeout(60_000) });
78
- }
79
- catch {
80
- return json(res, 502, { error: 'gateway_unreachable', message: '任务网关不可达。' });
81
- }
82
- const passed = {};
83
- for (const name of PASSED_HEADERS) {
84
- const value = response.headers.get(name);
85
- if (value)
86
- passed[name] = value;
87
- }
88
- res.writeHead(response.status, passed);
89
- res.end(Buffer.from(await response.arrayBuffer()));
90
- };
91
- }