@zvada/agent-server 0.3.12 → 0.3.14

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.
@@ -1,3 +1,5 @@
1
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
1
3
  import { Readable, Writable } from "node:stream";
2
4
  import type {
3
5
  AgentApp,
@@ -12,6 +14,7 @@ import type {
12
14
  LifecycleEvent,
13
15
  PermissionMode,
14
16
  PermissionOutcome,
17
+ TokenUsage,
15
18
  } from "../../protocol/index.ts";
16
19
  import { AcpUpdateTranslator, fromAcpMcpServers, fromPromptBlocks } from "./translate.ts";
17
20
 
@@ -27,11 +30,35 @@ export interface AcpBindingOptions {
27
30
  permissionMode?: PermissionMode;
28
31
  name?: string;
29
32
  version?: string;
33
+ /**
34
+ * Where to record each session's native id so `session/resume` works after
35
+ * this process restarts. Absent: sessions resume only within the process.
36
+ */
37
+ sessionDir?: string;
30
38
  }
31
39
 
32
40
  interface BoundSession {
33
41
  cwd: string;
34
42
  mcpServers?: ReturnType<typeof fromAcpMcpServers>;
43
+ /** Native conversation to continue on the next prompt (restored sessions). */
44
+ resumeSessionId?: string;
45
+ }
46
+
47
+ /** Session ids become file names; accept only what this binding mints. */
48
+ const SESSION_ID = /^[\w-]{1,128}$/;
49
+
50
+ /** The engine's disjoint token buckets as ACP's (still unstable) turn usage. */
51
+ function toAcpUsage(usage: TokenUsage): NonNullable<PromptResponse["usage"]> {
52
+ const read = usage.cache?.read ?? 0;
53
+ const write = usage.cache?.write ?? 0;
54
+ return {
55
+ totalTokens: usage.input + usage.output + read + write,
56
+ inputTokens: usage.input,
57
+ outputTokens: usage.output,
58
+ ...(usage.reasoning !== undefined && { thoughtTokens: usage.reasoning }),
59
+ cachedReadTokens: read,
60
+ cachedWriteTokens: write,
61
+ };
35
62
  }
36
63
 
37
64
  /**
@@ -41,8 +68,9 @@ interface BoundSession {
41
68
  * integration. `session/prompt` runs one engine turn; LifecycleEvents stream
42
69
  * out as `session/update`; engine-brokered permissions become
43
70
  * `session/request_permission` round-trips (identical option vocabulary).
44
- * Resume is within-process: an ACP sessionId stays valid for the binding's
45
- * lifetime (cross-process resume needs host persistence — not offered yet).
71
+ * An ACP sessionId stays valid for the binding's lifetime; with `sessionDir`
72
+ * its native conversation is recorded, so `session/resume` also works after a
73
+ * restart.
46
74
  */
47
75
  export async function createAcpAgentApp(options: AcpBindingOptions): Promise<AgentApp> {
48
76
  const acp = await import("@agentclientprotocol/sdk");
@@ -59,6 +87,37 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
59
87
  }
60
88
  };
61
89
 
90
+ const recordPath = (sessionId: string): string | undefined =>
91
+ options.sessionDir && SESSION_ID.test(sessionId)
92
+ ? join(options.sessionDir, `${sessionId}.json`)
93
+ : undefined;
94
+ const remember = async (sessionId: string, nativeSessionId: string): Promise<void> => {
95
+ const path = recordPath(sessionId);
96
+ if (!path || !options.sessionDir) return;
97
+ // Write then rename: a crash mid-write must not leave a torn record.
98
+ const draft = `${path}.${process.pid}.tmp`;
99
+ try {
100
+ await mkdir(options.sessionDir, { recursive: true, mode: 0o700 });
101
+ await writeFile(draft, JSON.stringify({ harness, nativeSessionId }), { mode: 0o600 });
102
+ await rename(draft, path);
103
+ } catch {
104
+ // Best effort: without the record the session resumes only in-process.
105
+ await rm(draft, { force: true }).catch(() => {});
106
+ }
107
+ };
108
+ const recall = async (sessionId: string): Promise<string | undefined> => {
109
+ const path = recordPath(sessionId);
110
+ if (!path) return undefined;
111
+ try {
112
+ const record = JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
113
+ return record.harness === harness && typeof record.nativeSessionId === "string"
114
+ ? record.nativeSessionId
115
+ : undefined;
116
+ } catch {
117
+ return undefined;
118
+ }
119
+ };
120
+
62
121
  const requireSession = (sessionId: string): BoundSession => {
63
122
  const session = sessions.get(sessionId);
64
123
  if (!session) throw acp.RequestError.resourceNotFound(sessionId);
@@ -72,6 +131,8 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
72
131
  agentInfo: { name: options.name ?? "agent-server", version: options.version ?? "0.0.0" },
73
132
  agentCapabilities: {
74
133
  promptCapabilities: { image: true },
134
+ // Clients send HTTP/SSE servers only to agents that advertise them.
135
+ ...(harness === "claude-code" && { mcpCapabilities: { http: true, sse: true } }),
75
136
  sessionCapabilities: { resume: {}, close: {} },
76
137
  },
77
138
  authMethods: [],
@@ -85,9 +146,15 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
85
146
  });
86
147
  return { sessionId };
87
148
  })
88
- .onRequest("session/resume", (ctx) => {
89
- const session = requireSession(ctx.params.sessionId);
149
+ .onRequest("session/resume", async (ctx) => {
90
150
  checkMcpSupport(ctx.params.mcpServers);
151
+ let session = sessions.get(ctx.params.sessionId);
152
+ if (!session) {
153
+ const resumeSessionId = await recall(ctx.params.sessionId);
154
+ if (!resumeSessionId) throw acp.RequestError.resourceNotFound(ctx.params.sessionId);
155
+ session = { cwd: ctx.params.cwd, resumeSessionId };
156
+ sessions.set(ctx.params.sessionId, session);
157
+ }
91
158
  session.cwd = ctx.params.cwd;
92
159
  if (ctx.params.mcpServers) session.mcpServers = fromAcpMcpServers(ctx.params.mcpServers);
93
160
  return {};
@@ -152,10 +219,16 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
152
219
  model: options.model,
153
220
  permissionMode: options.permissionMode ?? "default",
154
221
  mcpServers: session.mcpServers,
222
+ resumeSessionId: session.resumeSessionId,
155
223
  },
156
224
  },
157
225
  sink,
158
226
  );
227
+ if (summary.nativeSessionId) {
228
+ session.resumeSessionId = undefined;
229
+ await remember(ctx.params.sessionId, summary.nativeSessionId);
230
+ }
231
+ const usage = toAcpUsage(summary.usage);
159
232
  // ACP v1's StopReason set is closed and has no `error` member. Map our
160
233
  // open stopReason onto it: `error` reports as an ended turn with the
161
234
  // failure in `_meta` (an ACP client must see a stop, not a JSON-RPC
@@ -170,6 +243,7 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
170
243
  if (summary.stopReason === "error") {
171
244
  return {
172
245
  stopReason: "end_turn",
246
+ usage,
173
247
  _meta: {
174
248
  "zvada.dev/error": summary.error ?? { category: "internal", message: "turn failed" },
175
249
  },
@@ -179,6 +253,7 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
179
253
  stopReason: (acpStopReasons.has(summary.stopReason)
180
254
  ? summary.stopReason
181
255
  : "end_turn") as PromptResponse["stopReason"],
256
+ usage,
182
257
  };
183
258
  });
184
259
  }
package/src/server/bin.ts CHANGED
@@ -11,6 +11,8 @@
11
11
  // agent-server install # prefetch the pinned agent CLIs
12
12
  //
13
13
  // All logs go to stderr; stdout is reserved for the wire in stdio mode.
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
14
16
  import pkg from "../../package.json" with { type: "json" };
15
17
  import {
16
18
  KNOWN_ACP_AGENTS,
@@ -61,7 +63,8 @@ function usage(exitCode: number): never {
61
63
  " --version, --help",
62
64
  "",
63
65
  "env: CLAUDE_CLI_PATH / CODEX_CLI_PATH (explicit binaries),",
64
- " AGENT_SERVER_PROVISION, AGENT_SERVER_CACHE_DIR, AGENT_SERVER_NPM_REGISTRY",
66
+ " AGENT_SERVER_PROVISION, AGENT_SERVER_CACHE_DIR, AGENT_SERVER_NPM_REGISTRY,",
67
+ " AGENT_SERVER_ACP_SESSION_DIR (--acp: where resumable session ids are kept)",
65
68
  ].join("\n"),
66
69
  );
67
70
  process.exit(exitCode);
@@ -176,7 +179,18 @@ if (args.mode === "acp") {
176
179
  // Speak ACP v1 on stdio: this process IS the agent (Zed-spawnable).
177
180
  const { serveAcpStdio } = await import("./acp/binding.ts");
178
181
  const frontedHarness = harnesses?.[0] ?? "claude-code";
179
- const connection = await serveAcpStdio({ runtime, harness: frontedHarness, version: VERSION });
182
+ const connection = await serveAcpStdio({
183
+ runtime,
184
+ harness: frontedHarness,
185
+ version: VERSION,
186
+ sessionDir:
187
+ process.env.AGENT_SERVER_ACP_SESSION_DIR ??
188
+ join(
189
+ process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"),
190
+ "agent-server",
191
+ "acp-sessions",
192
+ ),
193
+ });
180
194
  console.error(`agent-server ${VERSION} speaking ACP v1 on stdio (harness: ${frontedHarness})`);
181
195
  shutdown = () => void runtime.shutdown().then(() => process.exit(0));
182
196
  // Client hung up — shut down cleanly (mirrors the stdio wire transport).