@nathapp/nax-agent-acp 0.88.0-canary.2 → 0.89.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  All notable changes to `@nathapp/nax-agent-acp` are recorded here. Versions move in
4
4
  step with `@nathapp/nax-agent`.
5
5
 
6
+ ## [0.89.0] - 2026-10-17
7
+
8
+ - No changes in this package. Released in lockstep with the other nax packages.
9
+
10
+ ## [0.88.0] - 2026-10-16
11
+
12
+ - No changes in this package. Released in lockstep with the other nax packages.
13
+
6
14
  ## [0.88.0-canary.2] - 2026-10-15
7
15
 
8
16
  - No changes in this package. Released in lockstep with the other nax packages.
package/README.md CHANGED
@@ -347,8 +347,7 @@ Clients can pass MCP servers with `session/new`, `session/load` and `session/res
347
347
  model as `<server>__<tool>`.
348
348
 
349
349
  - **Transports:** stdio and streamable HTTP. SSE and ACP-tunnelled servers are skipped with a notice.
350
- - **Approval:** `ask` asks before every MCP tool call ("Always allow" is remembered per tool
351
- for the session); `full` runs them without asking; `read` and `none` do not offer them
350
+ - **Approval:** `ask` asks before every MCP tool call; `full` runs them without asking; `read` and `none` do not offer them
352
351
  (the servers stay connected, so switching back to `ask` or `full` brings the tools back).
353
352
  - **Startup:** servers connect in parallel when the session opens, each within
354
353
  `--mcp-connect-timeout` seconds (default 30; `NAX_AGENT_MCP_CONNECT_TIMEOUT`,
@@ -360,8 +359,7 @@ model as `<server>__<tool>`.
360
359
  - **Not saved:** MCP servers are never written to the session files; a reopened session
361
360
  connects to the servers the client sends at that time. A server that exits mid-session is
362
361
  reported once; reopen the session to reconnect it.
363
- - **Large results:** the model sees at most 40 KB of a tool result; the full text is written
364
- to the session's scratchpad.
362
+ - **Large results:** each call reads at most 1 MiB of result text.
365
363
  - **Secrets:** values of env vars whose names contain `KEY`, `TOKEN`, `SECRET` or `PASSWORD`
366
364
  (any case), every HTTP header value and an HTTP URL's password and query values are scrubbed
367
365
  from notices and tool results. Values shorter than 8 characters are not scrubbed by value.
@@ -1,5 +1,6 @@
1
1
  import type { SandboxPolicy } from "@nathapp/nax-agent";
2
2
  export declare const OUTSIDE_WRITE_ROOTS_REASON = "the edit target is outside the sandbox write roots";
3
+ export declare const WRITE_KINDS: ReadonlySet<string>;
3
4
  /** Test seam: the platform decides whether path comparison folds case (darwin and win32 filesystems are case-insensitive by default). */
4
5
  export declare const _editTargetsDeps: {
5
6
  platform: () => string;
@@ -14,6 +14,8 @@ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
14
14
  import { isRecord } from "#src/client/text";
15
15
  export const OUTSIDE_WRITE_ROOTS_REASON = "the edit target is outside the sandbox write roots";
16
16
  const RAW_PATH_KEYS = ["file_path", "notebook_path"];
17
+ const WRITE_PATH_KEYS = [...RAW_PATH_KEYS, "path", "filePath", "old_path", "new_path"];
18
+ export const WRITE_KINDS = new Set(["edit", "delete", "move"]);
17
19
  /** Test seam: the platform decides whether path comparison folds case (darwin and win32 filesystems are case-insensitive by default). */
18
20
  export const _editTargetsDeps = { platform: () => process.platform };
19
21
  export function editTargets(toolCall) {
@@ -23,7 +25,8 @@ export function editTargets(toolCall) {
23
25
  ? toolCall.locations.flatMap((l) => isRecord(l) && typeof l.path === "string" && l.path !== "" ? [l.path] : [])
24
26
  : [];
25
27
  const raw = isRecord(toolCall.rawInput) ? toolCall.rawInput : {};
26
- const fromRaw = RAW_PATH_KEYS.flatMap((k) => (typeof raw[k] === "string" && raw[k] !== "" ? [raw[k]] : []));
28
+ const keys = typeof toolCall.kind === "string" && WRITE_KINDS.has(toolCall.kind) ? WRITE_PATH_KEYS : RAW_PATH_KEYS;
29
+ const fromRaw = keys.flatMap((k) => (typeof raw[k] === "string" && raw[k] !== "" ? [raw[k]] : []));
27
30
  return [...new Set([...fromLocations, ...fromRaw])];
28
31
  }
29
32
  /**
@@ -1,6 +1,10 @@
1
1
  import { type AgentApp, type Stream } from "@agentclientprotocol/sdk";
2
- import { type AgentSessionError, type StderrTail } from "@nathapp/nax-agent";
2
+ import { type AgentSessionError, killProcessGroup, type StderrTail } from "@nathapp/nax-agent";
3
3
  import type { LaunchCandidate } from "#src/client/registry";
4
+ /** Test seam for process-group signalling. */
5
+ export declare const _launchDeps: {
6
+ killProcessGroup: typeof killProcessGroup;
7
+ };
4
8
  export type LaunchTarget = {
5
9
  readonly kind: "stream";
6
10
  readonly stream: Stream;
@@ -24,7 +28,7 @@ export interface LaunchedAgent {
24
28
  readonly exited: Promise<AgentExit>;
25
29
  /** The exit once the process has exited (and its stderr drained), or undefined after `waitMs`. */
26
30
  whenGone(waitMs: number): Promise<AgentExit | undefined>;
27
- /** Closes stdin, SIGTERMs the group, SIGKILLs it after `graceMs`; resolves once exited. */
31
+ /** Closes stdin, SIGTERMs the group, SIGKILLs survivors on leader exit or after `graceMs`; resolves once exited. */
28
32
  terminate(graceMs: number): Promise<void>;
29
33
  /** SIGKILLs the group now. */
30
34
  kill(): void;
@@ -15,6 +15,8 @@ import { agentTextExcerpt, backendUnavailable, EXCERPT_BYTES } from "#src/client
15
15
  import { race } from "#src/client/race";
16
16
  /** How long a transport failure waits for the exit status. */
17
17
  const GONE_WAIT_MS = 1_000;
18
+ /** Test seam for process-group signalling. */
19
+ export const _launchDeps = { killProcessGroup };
18
20
  /** How long, after the exit, the last stderr may take to arrive. */
19
21
  const STDERR_DRAIN_MS = 200;
20
22
  function isExecutableFile(path) {
@@ -96,8 +98,12 @@ function startedLaunch(child, stderr, maxMessageBytes) {
96
98
  gone = true;
97
99
  });
98
100
  const kill = () => {
99
- if (!gone && pid !== undefined)
100
- killProcessGroup(pid, "SIGKILL");
101
+ if (pid === undefined)
102
+ return;
103
+ if (gone)
104
+ _launchDeps.killProcessGroup(pid, "SIGKILL", { singleProcessFallback: false });
105
+ else
106
+ _launchDeps.killProcessGroup(pid, "SIGKILL");
101
107
  };
102
108
  return {
103
109
  target: { kind: "stream", stream },
@@ -113,14 +119,24 @@ function startedLaunch(child, stderr, maxMessageBytes) {
113
119
  return exit.value;
114
120
  },
115
121
  async terminate(graceMs) {
116
- if (!gone && pid !== undefined) {
122
+ if (pid === undefined) {
123
+ await exited;
124
+ return;
125
+ }
126
+ if (!gone)
117
127
  child.stdin.end();
118
- killProcessGroup(pid, "SIGTERM");
119
- const timer = setTimeout(kill, graceMs);
128
+ if (gone)
129
+ _launchDeps.killProcessGroup(pid, "SIGTERM", { singleProcessFallback: false });
130
+ else
131
+ _launchDeps.killProcessGroup(pid, "SIGTERM");
132
+ const timer = setTimeout(kill, graceMs);
133
+ try {
120
134
  await exited;
135
+ kill();
136
+ }
137
+ finally {
121
138
  clearTimeout(timer);
122
139
  }
123
- await exited;
124
140
  },
125
141
  };
126
142
  }
@@ -1,4 +1,4 @@
1
- import { editTargets, firstOutsidePolicy, OUTSIDE_WRITE_ROOTS_REASON } from "#src/client/edit-targets";
1
+ import { editTargets, firstOutsidePolicy, OUTSIDE_WRITE_ROOTS_REASON, WRITE_KINDS } from "#src/client/edit-targets";
2
2
  import { isRecord } from "#src/client/text";
3
3
  import { describeToolCall } from "#src/client/tool-display";
4
4
  export const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
@@ -107,10 +107,12 @@ const READ_ONLY_KINDS = new Set(["read", "search", "think", "fetch", "switch_mod
107
107
  async function decideFull(request, display, offered, auto, ctx) {
108
108
  if (offered.allowOnce === undefined)
109
109
  return denyNoAllowOnce(offered, auto);
110
+ const targets = editTargets(request.toolCall);
111
+ const unknownWrite = ctx.sandbox !== undefined && WRITE_KINDS.has(display.tool) && targets.length === 0;
110
112
  const outside = ctx.sandbox !== undefined && display.tool !== "execute" && !READ_ONLY_KINDS.has(display.tool)
111
- ? await firstOutsidePolicy(editTargets(request.toolCall), ctx.sandbox, ctx.cwd)
113
+ ? await firstOutsidePolicy(targets, ctx.sandbox, ctx.cwd)
112
114
  : undefined;
113
- if (outside !== undefined) {
115
+ if (unknownWrite || outside !== undefined) {
114
116
  auto(OUTSIDE_WRITE_ROOTS_REASON, "deny");
115
117
  return rejectWith(offered);
116
118
  }
@@ -9,7 +9,13 @@ import { agent, ndJsonStream } from "@agentclientprotocol/sdk";
9
9
  import { NO_SERVER_AUTH } from "#src/server/auth";
10
10
  import { initializeResponse } from "#src/server/capabilities";
11
11
  import { clientFeatures, clientPort, NO_CLIENT_FEATURES } from "#src/server/client-port";
12
- import { guard } from "#src/server/errors";
12
+ import { guard, invalidParams } from "#src/server/errors";
13
+ import { SESSION_ID_PATTERN } from "#src/server/storage";
14
+ function validatedSessionId(sessionId) {
15
+ if (!SESSION_ID_PATTERN.test(sessionId))
16
+ throw invalidParams("invalid session id");
17
+ return sessionId;
18
+ }
13
19
  export function buildAgentApp(deps) {
14
20
  const auth = deps.auth ?? NO_SERVER_AUTH;
15
21
  let features = NO_CLIENT_FEATURES;
@@ -24,19 +30,19 @@ export function buildAgentApp(deps) {
24
30
  mcpServers: ctx.params.mcpServers,
25
31
  port: (sessionId) => clientPort(ctx.client, sessionId, features),
26
32
  })))
27
- .onRequest("session/load", (ctx) => guard(deps.logger, () => deps.registry.load(ctx.params.sessionId, {
33
+ .onRequest("session/load", (ctx) => guard(deps.logger, () => deps.registry.load(validatedSessionId(ctx.params.sessionId), {
28
34
  cwd: ctx.params.cwd,
29
35
  mcpServers: ctx.params.mcpServers,
30
36
  port: (sessionId) => clientPort(ctx.client, sessionId, features),
31
37
  })))
32
- .onRequest("session/resume", (ctx) => guard(deps.logger, () => deps.registry.resume(ctx.params.sessionId, {
38
+ .onRequest("session/resume", (ctx) => guard(deps.logger, () => deps.registry.resume(validatedSessionId(ctx.params.sessionId), {
33
39
  cwd: ctx.params.cwd,
34
40
  mcpServers: ctx.params.mcpServers ?? [],
35
41
  port: (sessionId) => clientPort(ctx.client, sessionId, features),
36
42
  })))
37
43
  .onRequest("session/list", (ctx) => guard(deps.logger, () => deps.registry.list(ctx.params)))
38
44
  .onRequest("session/close", (ctx) => guard(deps.logger, () => deps.registry.close(ctx.params.sessionId)))
39
- .onRequest("session/delete", (ctx) => guard(deps.logger, () => deps.registry.delete(ctx.params.sessionId)))
45
+ .onRequest("session/delete", (ctx) => guard(deps.logger, () => deps.registry.delete(validatedSessionId(ctx.params.sessionId))))
40
46
  .onRequest("session/set_mode", (ctx) => guard(deps.logger, () => deps.registry.setMode(ctx.params.sessionId, ctx.params.modeId)))
41
47
  .onRequest("session/set_config_option", (ctx) => guard(deps.logger, async () => ({
42
48
  configOptions: await deps.registry.setConfigOption(ctx.params.sessionId, ctx.params.configId, ctx.params.value),
@@ -0,0 +1,27 @@
1
+ /** Bounded registry shutdown and ownership cleanup. */
2
+ import type { AgentLogger } from "@nathapp/nax-agent";
3
+ import type { ClientPort } from "#src/server/client-port";
4
+ import type { McpSessionTools } from "#src/server/mcp/session-tools";
5
+ import type { OpenedSession } from "#src/server/open-session";
6
+ import type { Entry, RegistryDeps } from "#src/server/registry";
7
+ import { type ServerSession } from "#src/server/server-session";
8
+ import type { SessionMeta } from "#src/server/storage";
9
+ export declare function closeEntries({ open, entries, wait, logger, }: {
10
+ readonly open: readonly (readonly [string, Entry])[];
11
+ readonly entries: Map<string, Entry>;
12
+ readonly wait: number;
13
+ readonly logger: AgentLogger;
14
+ }): Promise<void>;
15
+ export declare function createEntryServer({ meta, port, opened, mcp, deps, contextWindow, recordTurn, }: {
16
+ meta: SessionMeta;
17
+ port: ClientPort;
18
+ opened: OpenedSession;
19
+ mcp: McpSessionTools;
20
+ deps: RegistryDeps;
21
+ contextWindow: number | undefined;
22
+ recordTurn: (id: string, prompt: string, cost: number) => Promise<void>;
23
+ }): ServerSession;
24
+ export declare function closeRegistryEntry(entries: Map<string, Entry>, sessionId: string, entry: Entry): Promise<void>;
25
+ export declare const TITLE_MAX = 80;
26
+ /** One line, no control or invisible characters, at most TITLE_MAX code points. */
27
+ export declare function titleOf(prompt: string): string;
@@ -0,0 +1,96 @@
1
+ import { stripControl, stripInvisible } from "#src/client/text";
2
+ import { messageOf } from "#src/server/errors";
3
+ import { createServerSession } from "#src/server/server-session";
4
+ function waitAtMost(ms) {
5
+ let timer;
6
+ const done = new Promise((resolve) => {
7
+ timer = setTimeout(() => resolve("timeout"), ms);
8
+ });
9
+ return { done, cancel: () => clearTimeout(timer) };
10
+ }
11
+ export async function closeEntries({ open, entries, wait, logger, }) {
12
+ await Promise.all(open.map(async ([sessionId, entry]) => {
13
+ entry.server.cancel();
14
+ const limit = waitAtMost(wait);
15
+ const closed = entry.server.close().then(() => "closed", (error) => {
16
+ logger.warn("session", "session close failed", { sessionId, error: messageOf(error) });
17
+ return "closed";
18
+ });
19
+ const outcome = await Promise.race([closed, limit.done]);
20
+ limit.cancel();
21
+ if (outcome === "timeout")
22
+ logger.warn("session", "session did not close in time", { sessionId, waitMs: wait });
23
+ const cleanup = async () => {
24
+ entries.delete(sessionId);
25
+ try {
26
+ await entry.mcp.closeAll();
27
+ }
28
+ finally {
29
+ await entry.release();
30
+ }
31
+ };
32
+ const deferred = (error) => {
33
+ logger.warn("session", "deferred session cleanup failed", { sessionId, error: messageOf(error) });
34
+ };
35
+ if (outcome === "timeout" && entry.server.running) {
36
+ // Bound shutdown, not ownership: a slow cancelled turn must still be
37
+ // able to persist its cost before another process can resume it.
38
+ void closed.then(cleanup).catch(deferred);
39
+ return;
40
+ }
41
+ // Cleanup is bounded too: a release waiting on a live lock guard keeps
42
+ // ownership in the background instead of hanging shutdown.
43
+ const cleaning = cleanup();
44
+ const cleanupLimit = waitAtMost(wait);
45
+ let settled;
46
+ try {
47
+ settled = await Promise.race([cleaning.then(() => "cleaned"), cleanupLimit.done]);
48
+ }
49
+ finally {
50
+ cleanupLimit.cancel();
51
+ }
52
+ if (settled === "timeout") {
53
+ logger.warn("session", "session cleanup did not finish in time", { sessionId, waitMs: wait });
54
+ cleaning.catch(deferred);
55
+ }
56
+ }));
57
+ }
58
+ export function createEntryServer({ meta, port, opened, mcp, deps, contextWindow, recordTurn, }) {
59
+ return createServerSession({
60
+ session: opened.session,
61
+ port,
62
+ cwd: meta.cwd,
63
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
64
+ readOldText: deps.readOldText,
65
+ logger: deps.logger,
66
+ turnTimeoutSeconds: deps.turnTimeoutSeconds,
67
+ priorCostUsd: meta.costUsd ?? 0,
68
+ onTurnEnd: (prompt, costUsd) => recordTurn(meta.sessionId, prompt, costUsd),
69
+ titleFor: (name) => mcp.titleFor(name),
70
+ });
71
+ }
72
+ export async function closeRegistryEntry(entries, sessionId, entry) {
73
+ try {
74
+ await entry.server.close();
75
+ }
76
+ finally {
77
+ try {
78
+ try {
79
+ await entry.mcp.closeAll();
80
+ }
81
+ finally {
82
+ await entry.release();
83
+ }
84
+ }
85
+ finally {
86
+ entries.delete(sessionId);
87
+ }
88
+ }
89
+ }
90
+ export const TITLE_MAX = 80;
91
+ /** One line, no control or invisible characters, at most TITLE_MAX code points. */
92
+ export function titleOf(prompt) {
93
+ return Array.from(stripInvisible(stripControl(prompt)).replace(/\s+/g, " ").trim())
94
+ .slice(0, TITLE_MAX)
95
+ .join("");
96
+ }
@@ -37,6 +37,8 @@ export function createReopen(deps) {
37
37
  async reopen(sessionId, input, replay) {
38
38
  const open = deps.entries.get(sessionId);
39
39
  if (open !== undefined) {
40
+ if (open.server.isClosed())
41
+ throw unknownSession(sessionId);
40
42
  // An already-open session keeps its connection and ignores input.mcpServers (§4.4).
41
43
  if (replay) {
42
44
  await replayTo(open.port, (await deps.transcripts.load(sessionId))?.messages ?? [], open.meta.cwd, (name) => open.mcp.titleFor(name));
@@ -5,14 +5,14 @@ import { type ConnectSessionMcp } from "#src/server/mcp/connect";
5
5
  import type { McpSessionTools } from "#src/server/mcp/session-tools";
6
6
  import type { OpenSession } from "#src/server/open-session";
7
7
  import type { ServerOptions } from "#src/server/options";
8
- import { type ServerSession } from "#src/server/server-session";
8
+ import type { ServerSession } from "#src/server/server-session";
9
9
  import type { SessionMeta, SessionStorage } from "#src/server/storage";
10
10
  import type { ReadOldText } from "#src/server/translate/diff";
11
11
  export declare const NO_MODEL_MESSAGE = "no model configured: log in to pick one, or set models.native.balanced in config.json / NAX_AGENT_MODEL";
12
12
  export declare const INTERRUPTED_NOTICE = "The previous turn was interrupted";
13
13
  export declare const SHUTTING_DOWN = "server is shutting down";
14
14
  export declare const SHUTDOWN_WAIT_MS = 5000;
15
- export declare const TITLE_MAX = 80;
15
+ export { TITLE_MAX, titleOf } from "#src/server/registry-lifecycle";
16
16
  /** What re-reading the options found: the options, or why there are none (a short, redacted reason). */
17
17
  export interface ReloadedOptions {
18
18
  readonly options?: ServerOptions;
@@ -74,6 +74,4 @@ export interface Entry {
74
74
  readonly release: () => Promise<void>;
75
75
  readonly mcp: McpSessionTools;
76
76
  }
77
- /** One line, no control or invisible characters, at most TITLE_MAX code points. */
78
- export declare function titleOf(prompt: string): string;
79
77
  export declare function createSessionRegistry(deps: RegistryDeps): SessionRegistry;
@@ -8,33 +8,19 @@
8
8
  import { isAbsolute } from "node:path";
9
9
  import { RequestError, } from "@agentclientprotocol/sdk";
10
10
  import { redactSecrets } from "@nathapp/nax-agent";
11
- import { stripControl, stripInvisible } from "#src/client/text";
12
11
  import { authRequired, invalidParams, messageOf, turnInProgress, unknownSession } from "#src/server/errors";
13
12
  import { connectNothing } from "#src/server/mcp/connect";
14
13
  import { disconnectNotice, modeNotice, openNotice } from "#src/server/mcp/notices";
15
14
  import { NO_SERVERS, parseMcpServers } from "#src/server/mcp/parse";
16
15
  import { mcpSecrets, scrubber } from "#src/server/mcp/secrets";
16
+ import { closeEntries, closeRegistryEntry, createEntryServer, titleOf } from "#src/server/registry-lifecycle";
17
17
  import { createReopen, settingsOf } from "#src/server/registry-open";
18
- import { createServerSession } from "#src/server/server-session";
19
18
  import { applyConfigChange, applyModeChange, configOptions, modeState, sameSettings, } from "#src/server/session-config";
20
19
  export const NO_MODEL_MESSAGE = "no model configured: log in to pick one, or set models.native.balanced in config.json / NAX_AGENT_MODEL";
21
20
  export const INTERRUPTED_NOTICE = "The previous turn was interrupted";
22
21
  export const SHUTTING_DOWN = "server is shutting down";
23
22
  export const SHUTDOWN_WAIT_MS = 5000;
24
- export const TITLE_MAX = 80;
25
- /** One line, no control or invisible characters, at most TITLE_MAX code points. */
26
- export function titleOf(prompt) {
27
- return Array.from(stripInvisible(stripControl(prompt)).replace(/\s+/g, " ").trim())
28
- .slice(0, TITLE_MAX)
29
- .join("");
30
- }
31
- function waitAtMost(ms) {
32
- let timer;
33
- const done = new Promise((resolve) => {
34
- timer = setTimeout(() => resolve("timeout"), ms);
35
- });
36
- return { done, cancel: () => clearTimeout(timer) };
37
- }
23
+ export { TITLE_MAX, titleOf } from "#src/server/registry-lifecycle";
38
24
  export function createSessionRegistry(deps) {
39
25
  const entries = new Map();
40
26
  let options = deps.options;
@@ -52,12 +38,13 @@ export function createSessionRegistry(deps) {
52
38
  throw unknownSession(sessionId);
53
39
  return entry;
54
40
  }
55
- async function recordTurn(sessionId, prompt) {
41
+ async function recordTurn(sessionId, prompt, costUsd) {
56
42
  const entry = entries.get(sessionId);
57
43
  if (entry === undefined)
58
44
  return;
59
45
  const meta = {
60
46
  ...entry.meta,
47
+ costUsd,
61
48
  title: entry.meta.title ?? (titleOf(prompt) || null),
62
49
  updatedAt: deps.now().toISOString(),
63
50
  };
@@ -129,7 +116,15 @@ export function createSessionRegistry(deps) {
129
116
  opened = undefined; // already closed; the catch must not close it twice
130
117
  throw RequestError.internalError(undefined, SHUTTING_DOWN);
131
118
  }
132
- const server = createEntryServer(meta, port, opened, mcp.tools);
119
+ const server = createEntryServer({
120
+ meta,
121
+ port,
122
+ opened,
123
+ mcp: mcp.tools,
124
+ deps,
125
+ contextWindow: contextWindowFor(meta.model),
126
+ recordTurn,
127
+ });
133
128
  queueMcpNotices(server, port, mcp, settings.mode);
134
129
  entries.set(meta.sessionId, { server, port, meta, release, mcp: mcp.tools });
135
130
  return { server, opened };
@@ -142,30 +137,7 @@ export function createSessionRegistry(deps) {
142
137
  throw closing ? RequestError.internalError(undefined, SHUTTING_DOWN) : error;
143
138
  }
144
139
  }
145
- function createEntryServer(meta, port, opened, mcp) {
146
- const contextWindow = contextWindowFor(meta.model);
147
- return createServerSession({
148
- session: opened.session,
149
- port,
150
- cwd: meta.cwd,
151
- ...(contextWindow !== undefined ? { contextWindow } : {}),
152
- readOldText: deps.readOldText,
153
- logger: deps.logger,
154
- turnTimeoutSeconds: deps.turnTimeoutSeconds,
155
- onTurnEnd: (prompt) => recordTurn(meta.sessionId, prompt),
156
- titleFor: (name) => mcp.titleFor(name),
157
- });
158
- }
159
- async function closeEntry(sessionId, entry) {
160
- entries.delete(sessionId);
161
- try {
162
- await entry.server.close();
163
- }
164
- finally {
165
- await entry.mcp.closeAll();
166
- await entry.release();
167
- }
168
- }
140
+ const closeEntry = (id, entry) => closeRegistryEntry(entries, id, entry);
169
141
  const reopen = createReopen({
170
142
  entries,
171
143
  storage: deps.storage,
@@ -185,7 +157,20 @@ export function createSessionRegistry(deps) {
185
157
  // Before the live session is closed, so a refused model changes nothing (final review I6).
186
158
  if (next.model !== from.model)
187
159
  await deps.ensureCredentials?.(next.model);
188
- await entry.server.switchTo(() => target(sessionId, entry.meta.cwd, next, entry.mcp.embedderTools(next.mode)), () => target(sessionId, entry.meta.cwd, from, entry.mcp.embedderTools(from.mode)));
160
+ try {
161
+ await entry.server.switchTo(() => target(sessionId, entry.meta.cwd, next, entry.mcp.embedderTools(next.mode)), () => target(sessionId, entry.meta.cwd, from, entry.mcp.embedderTools(from.mode)));
162
+ }
163
+ catch (error) {
164
+ if (entry.server.isClosed()) {
165
+ try {
166
+ await closeEntry(sessionId, entry);
167
+ }
168
+ catch (cleanupError) {
169
+ deps.logger.warn("session", "dead session cleanup failed", { sessionId, error: messageOf(cleanupError) });
170
+ }
171
+ }
172
+ throw error;
173
+ }
189
174
  const meta = { ...entry.meta, mode: next.mode, model: next.model, bashApproval: next.bashApproval };
190
175
  entries.set(sessionId, { ...entry, meta });
191
176
  await deps.storage.writeMeta(meta);
@@ -312,22 +297,8 @@ export function createSessionRegistry(deps) {
312
297
  closing = true;
313
298
  shutdown.abort();
314
299
  const open = [...entries.entries()];
315
- entries.clear();
316
300
  const wait = deps.shutdownWaitMs ?? SHUTDOWN_WAIT_MS;
317
- await Promise.all(open.map(async ([sessionId, entry]) => {
318
- entry.server.cancel();
319
- const limit = waitAtMost(wait);
320
- const closed = entry.server.close().then(() => "closed", (error) => {
321
- deps.logger.warn("session", "session close failed", { sessionId, error: messageOf(error) });
322
- return "closed";
323
- });
324
- const outcome = await Promise.race([closed, limit.done]);
325
- limit.cancel();
326
- if (outcome === "timeout")
327
- deps.logger.warn("session", "session did not close in time", { sessionId, waitMs: wait });
328
- await entry.mcp.closeAll();
329
- await entry.release();
330
- }));
301
+ await closeEntries({ open, entries, wait, logger: deps.logger });
331
302
  },
332
303
  };
333
304
  }
@@ -21,8 +21,9 @@ export interface ServerSessionDeps {
21
21
  readonly logger: AgentLogger;
22
22
  readonly turnTimeoutSeconds: number;
23
23
  readonly now?: () => number;
24
- /** After every prompt that reached send() (S5-3: title and updatedAt). A rejection is logged, never thrown. */
25
- readonly onTurnEnd?: (message: string) => Promise<void>;
24
+ readonly priorCostUsd?: number;
25
+ /** After each turn: title, timestamp and cumulative cost. A rejection is logged, never thrown. */
26
+ readonly onTurnEnd?: (message: string, costUsd: number) => Promise<void>;
26
27
  /** S5-5 (wired in S5-5b Task 10): a display title for an MCP tool call's model name. */
27
28
  readonly titleFor?: (name: string) => string | undefined;
28
29
  }
@@ -39,6 +40,7 @@ export interface ServerSession {
39
40
  prompt(blocks: readonly ContentBlock[]): Promise<PromptResponse>;
40
41
  /** Close-and-reopen for a mode or config change (spec §3.3); `restore` reopens the old settings when `open` fails. */
41
42
  switchTo(open: () => Promise<SwitchTarget>, restore: () => Promise<SwitchTarget>): Promise<void>;
43
+ isClosed(): boolean;
42
44
  cancel(): void;
43
45
  close(): Promise<void>;
44
46
  }
@@ -76,13 +76,16 @@ async function forwardEvent(event, ctx) {
76
76
  export function createServerSession(deps) {
77
77
  const memory = new Map();
78
78
  let queued = [];
79
- let costUsd = 0;
79
+ let costUsd = deps.priorCostUsd ?? 0;
80
+ let closed = false;
80
81
  let running = false;
81
82
  /** A cancel before send() claimed the S3 turn, where AgentSession.cancel() is a no-op. */
82
83
  let cancelBeforeSend = false;
83
84
  let turn;
84
85
  let agent = deps.session;
85
86
  let contextWindow = deps.contextWindow;
87
+ let drained = Promise.resolve();
88
+ let closing;
86
89
  function stopWaiting() {
87
90
  turn?.permissions.abortAll();
88
91
  turn?.questions.abortAll();
@@ -91,7 +94,7 @@ export function createServerSession(deps) {
91
94
  if (deps.onTurnEnd === undefined)
92
95
  return;
93
96
  try {
94
- await deps.onTurnEnd(message);
97
+ await deps.onTurnEnd(message, costUsd);
95
98
  }
96
99
  catch (error) {
97
100
  deps.logger.warn("session", "turn bookkeeping failed", { sessionId: deps.session.id, error: messageOf(error) });
@@ -149,6 +152,7 @@ export function createServerSession(deps) {
149
152
  }
150
153
  return {
151
154
  id: deps.session.id,
155
+ isClosed: () => closed,
152
156
  get running() {
153
157
  return running;
154
158
  },
@@ -158,9 +162,15 @@ export function createServerSession(deps) {
158
162
  async prompt(blocks) {
159
163
  if (running)
160
164
  throw turnInProgress();
165
+ if (closed)
166
+ throw RequestError.invalidRequest(undefined, "session is closed");
161
167
  const message = flattenPrompt(blocks);
162
168
  running = true;
163
169
  cancelBeforeSend = false;
170
+ let finish = () => { };
171
+ drained = new Promise((resolve) => {
172
+ finish = resolve;
173
+ });
164
174
  let outcome;
165
175
  try {
166
176
  outcome = await runTurn(message);
@@ -168,8 +178,13 @@ export function createServerSession(deps) {
168
178
  finally {
169
179
  // Still "running" while the turn is recorded, so a switchTo cannot
170
180
  // slip in and write metadata from before this turn's title/updatedAt.
171
- await reportTurnEnd(message);
172
- running = false;
181
+ try {
182
+ await reportTurnEnd(message);
183
+ }
184
+ finally {
185
+ running = false;
186
+ finish();
187
+ }
173
188
  }
174
189
  if (outcome === undefined)
175
190
  throw RequestError.internalError(undefined, "the turn ended without a turn_end event");
@@ -178,20 +193,33 @@ export function createServerSession(deps) {
178
193
  return outcome.response;
179
194
  },
180
195
  async switchTo(open, restore) {
196
+ if (closed)
197
+ throw RequestError.invalidRequest(undefined, "session is closed");
181
198
  if (running)
182
199
  throw turnInProgress();
183
200
  running = true;
184
201
  try {
185
202
  stopWaiting();
186
- await agent.close();
203
+ closed = true;
204
+ try {
205
+ await agent.close();
206
+ }
207
+ catch (error) {
208
+ deps.logger.warn("session", "session close failed during switch", {
209
+ sessionId: deps.session.id,
210
+ error: messageOf(error),
211
+ });
212
+ }
187
213
  try {
188
214
  const next = await open();
215
+ closed = false;
189
216
  agent = next.session;
190
217
  contextWindow = next.contextWindow;
191
218
  }
192
219
  catch (error) {
193
220
  try {
194
221
  const back = await restore();
222
+ closed = false;
195
223
  agent = back.session;
196
224
  contextWindow = back.contextWindow;
197
225
  }
@@ -214,9 +242,26 @@ export function createServerSession(deps) {
214
242
  agent.cancel("cancelled by the client");
215
243
  stopWaiting();
216
244
  },
217
- async close() {
245
+ close() {
246
+ if (closing !== undefined)
247
+ return closing;
248
+ if (closed)
249
+ return Promise.resolve();
250
+ closed = true; // Refuse new prompts/switches before the first await.
251
+ cancelBeforeSend = true;
252
+ agent.cancel("session is closing");
218
253
  stopWaiting();
219
- await agent.close();
254
+ closing = (async () => {
255
+ try {
256
+ await agent.close();
257
+ }
258
+ finally {
259
+ // AgentSession.close need not await the facade's event delivery or
260
+ // onTurnEnd. Ownership must outlive both, even if close rejects.
261
+ await drained;
262
+ }
263
+ })();
264
+ return closing;
220
265
  },
221
266
  };
222
267
  }
@@ -0,0 +1,6 @@
1
+ import { RequestError } from "@agentclientprotocol/sdk";
2
+ /** Distinguishes retryable mutex contention from mutation and filesystem failures. */
3
+ export declare class SessionLockGuardBusy extends RequestError {
4
+ constructor();
5
+ }
6
+ export declare function withSessionLockGuard(path: string, mutate: () => void): void;
@@ -0,0 +1,85 @@
1
+ /** Short interprocess mutex for lock-file mutations, never stolen from a live process. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdirSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { RequestError } from "@agentclientprotocol/sdk";
5
+ /** Distinguishes retryable mutex contention from mutation and filesystem failures. */
6
+ export class SessionLockGuardBusy extends RequestError {
7
+ constructor() {
8
+ super(-32600, "session in use by another process");
9
+ }
10
+ }
11
+ function codeOf(error) {
12
+ return typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
13
+ }
14
+ function removeMarker(guard, marker) {
15
+ try {
16
+ unlinkSync(`${guard}/${marker}`);
17
+ }
18
+ catch (error) {
19
+ if (codeOf(error) !== "ENOENT")
20
+ throw error;
21
+ }
22
+ try {
23
+ // A contender can replace the now-empty directory. rmdir cannot remove its
24
+ // non-empty replacement; never recursively delete the shared guard path.
25
+ rmdirSync(guard);
26
+ }
27
+ catch (error) {
28
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(String(codeOf(error))))
29
+ throw error;
30
+ }
31
+ }
32
+ function reapDeadGuard(guard) {
33
+ let markers;
34
+ try {
35
+ markers = readdirSync(guard);
36
+ }
37
+ catch (error) {
38
+ if (codeOf(error) === "ENOENT")
39
+ return;
40
+ throw error;
41
+ }
42
+ for (const marker of markers) {
43
+ const pid = /^(\d+)\.[0-9a-f-]+$/.exec(marker)?.[1];
44
+ if (pid === undefined)
45
+ continue; // Unrecognized guards fail closed.
46
+ try {
47
+ process.kill(Number(pid), 0);
48
+ }
49
+ catch (error) {
50
+ // Only proven death permits recovery, never heartbeat age or EPERM.
51
+ // The unique marker path prevents two reapers from deleting a new owner.
52
+ if (codeOf(error) === "ESRCH")
53
+ removeMarker(guard, marker);
54
+ }
55
+ }
56
+ }
57
+ export function withSessionLockGuard(path, mutate) {
58
+ const guard = `${path}.guard`;
59
+ const marker = `${process.pid}.${randomUUID()}`;
60
+ const prepared = `${guard}.${marker}.tmp`;
61
+ mkdirSync(prepared);
62
+ try {
63
+ writeFileSync(`${prepared}/${marker}`, "", { flag: "wx" });
64
+ reapDeadGuard(guard);
65
+ try {
66
+ // Publish an already non-empty directory atomically. rename can replace
67
+ // an empty (released/reaped) guard, but never a live non-empty guard.
68
+ renameSync(prepared, guard);
69
+ }
70
+ catch (error) {
71
+ if (["ENOTEMPTY", "EEXIST"].includes(String(codeOf(error))))
72
+ throw new SessionLockGuardBusy();
73
+ throw error;
74
+ }
75
+ try {
76
+ mutate();
77
+ }
78
+ finally {
79
+ removeMarker(guard, marker);
80
+ }
81
+ }
82
+ finally {
83
+ removeMarker(prepared, marker);
84
+ }
85
+ }
@@ -0,0 +1,10 @@
1
+ import { linkSync, renameSync, rmSync } from "node:fs";
2
+ import type { StorageDeps } from "#src/server/storage";
3
+ export declare const LOCK_HEARTBEAT_MS = 30000;
4
+ export declare const LOCK_STALE_MS = 120000;
5
+ export declare const _lockDeps: {
6
+ rename: typeof renameSync;
7
+ link: typeof linkSync;
8
+ remove: typeof rmSync;
9
+ };
10
+ export declare function acquireSessionLock(path: string, deps: StorageDeps, isAlive: (pid: number) => boolean): () => Promise<void>;
@@ -0,0 +1,164 @@
1
+ /** Local-filesystem ownership protocol. All lock mutations share an exclusive directory guard. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { linkSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { setTimeout as sleep } from "node:timers/promises";
5
+ import { RequestError } from "@agentclientprotocol/sdk";
6
+ import { z } from "zod";
7
+ import { withSessionLockGuard as guarded, SessionLockGuardBusy } from "#src/server/session-lock-guard";
8
+ export const LOCK_HEARTBEAT_MS = 30_000;
9
+ export const LOCK_STALE_MS = 120_000;
10
+ const LockSchema = z.union([
11
+ z.object({
12
+ pid: z.number().int().positive(),
13
+ startedAt: z.string(),
14
+ nonce: z.string(),
15
+ heartbeatAt: z.string().datetime(),
16
+ }),
17
+ z.object({
18
+ pid: z.number().int().positive(),
19
+ startedAt: z.string(),
20
+ nonce: z.undefined(),
21
+ heartbeatAt: z.undefined(),
22
+ }),
23
+ ]);
24
+ export const _lockDeps = { rename: renameSync, link: linkSync, remove: rmSync };
25
+ function codeOf(error) {
26
+ return typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
27
+ }
28
+ function read(path) {
29
+ let text;
30
+ try {
31
+ text = readFileSync(path, "utf8");
32
+ const parsed = LockSchema.safeParse(JSON.parse(text));
33
+ return parsed.success ? { text, body: parsed.data } : { text };
34
+ }
35
+ catch {
36
+ return text === undefined ? {} : { text };
37
+ }
38
+ }
39
+ function same(a, b) {
40
+ if (a.body?.nonce !== undefined)
41
+ return a.body.nonce === b.body?.nonce;
42
+ if (a.body !== undefined)
43
+ return b.body?.nonce === undefined && a.body.pid === b.body?.pid && a.body.startedAt === b.body.startedAt;
44
+ return a.text === b.text;
45
+ }
46
+ const refused = (pid) => RequestError.invalidRequest(undefined, `session in use by ${pid === undefined ? "another process" : `pid ${pid}`}`);
47
+ function create(path, body) {
48
+ const temp = `${path}.${body.nonce}.tmp`;
49
+ try {
50
+ writeFileSync(temp, JSON.stringify(body), { flag: "wx" });
51
+ _lockDeps.link(temp, path);
52
+ return true;
53
+ }
54
+ catch (error) {
55
+ if (codeOf(error) === "EEXIST")
56
+ return false;
57
+ throw error;
58
+ }
59
+ finally {
60
+ rmSync(temp, { force: true });
61
+ }
62
+ }
63
+ function takeover(path, body, deps, isAlive) {
64
+ const old = read(path);
65
+ const holder = old.body;
66
+ const fresh = holder !== undefined &&
67
+ holder.pid !== deps.pid &&
68
+ isAlive(holder.pid) &&
69
+ (holder.heartbeatAt === undefined || deps.now().getTime() - Date.parse(holder.heartbeatAt) <= LOCK_STALE_MS);
70
+ if (fresh)
71
+ throw refused(holder.pid);
72
+ const stale = `${path}.${body.nonce}.stale`;
73
+ try {
74
+ _lockDeps.rename(path, stale);
75
+ }
76
+ catch (error) {
77
+ if (codeOf(error) !== "ENOENT")
78
+ throw error;
79
+ // A failed rename is not permission to overwrite the winner.
80
+ const raced = read(path);
81
+ if (raced.body !== undefined || !create(path, body))
82
+ throw refused(raced.body?.pid);
83
+ return;
84
+ }
85
+ if (!same(old, read(stale))) {
86
+ // Never discard another owner's renamed file if restoration is blocked.
87
+ try {
88
+ _lockDeps.link(stale, path);
89
+ }
90
+ catch (error) {
91
+ if (codeOf(error) !== "EEXIST")
92
+ throw error;
93
+ throw refused();
94
+ }
95
+ rmSync(stale, { force: true });
96
+ throw refused();
97
+ }
98
+ try {
99
+ deps.logger.info("session", "taking over a stale session lock", { pid: holder?.pid });
100
+ if (!create(path, body))
101
+ throw refused();
102
+ }
103
+ finally {
104
+ rmSync(stale, { force: true });
105
+ }
106
+ }
107
+ async function releaseOwnedLock(path, nonce) {
108
+ for (;;) {
109
+ try {
110
+ guarded(path, () => {
111
+ if (read(path).body?.nonce === nonce)
112
+ _lockDeps.remove(path, { force: true });
113
+ });
114
+ return;
115
+ }
116
+ catch (error) {
117
+ if (!(error instanceof SessionLockGuardBusy))
118
+ throw error;
119
+ // Release owns cleanup until it can check the nonce under the guard.
120
+ // Yield to the holder rather than abandoning a fresh lock on contention.
121
+ // Unref'd: a deferred release after bounded shutdown never keeps the process alive.
122
+ await sleep(10, undefined, { ref: false });
123
+ }
124
+ }
125
+ }
126
+ export function acquireSessionLock(path, deps, isAlive) {
127
+ const stamp = deps.now().toISOString();
128
+ const body = { pid: deps.pid, startedAt: stamp, nonce: randomUUID(), heartbeatAt: stamp };
129
+ guarded(path, () => {
130
+ if (!create(path, body))
131
+ takeover(path, body, deps, isAlive);
132
+ });
133
+ const timer = (deps.setInterval ?? setInterval)(() => {
134
+ const temp = `${path}.${body.nonce}.tmp`;
135
+ try {
136
+ guarded(path, () => {
137
+ if (read(path).body?.nonce !== body.nonce) {
138
+ clearInterval(timer);
139
+ return;
140
+ }
141
+ body.heartbeatAt = deps.now().toISOString();
142
+ writeFileSync(temp, JSON.stringify(body));
143
+ _lockDeps.rename(temp, path);
144
+ });
145
+ }
146
+ catch (error) {
147
+ deps.logger.warn("session", "lock heartbeat failed", { path, error: String(error) });
148
+ }
149
+ finally {
150
+ rmSync(temp, { force: true });
151
+ }
152
+ }, LOCK_HEARTBEAT_MS);
153
+ timer.unref();
154
+ return async () => {
155
+ try {
156
+ // The heartbeat stays live while release waits out contention.
157
+ await releaseOwnedLock(path, body.nonce);
158
+ }
159
+ finally {
160
+ // A terminal release failure must let the lock age into stale recovery.
161
+ clearInterval(timer);
162
+ }
163
+ };
164
+ }
@@ -1,6 +1,8 @@
1
- import { type ListSessionsResponse } from "@agentclientprotocol/sdk";
1
+ import type { ListSessionsResponse } from "@agentclientprotocol/sdk";
2
2
  import { type AgentLogger } from "@nathapp/nax-agent";
3
3
  import { z } from "zod";
4
+ export { LOCK_HEARTBEAT_MS, LOCK_STALE_MS } from "#src/server/session-lock";
5
+ export declare const SESSION_ID_PATTERN: RegExp;
4
6
  export declare const LIST_PAGE_SIZE = 50;
5
7
  declare const MetaSchema: z.ZodObject<{
6
8
  schemaVersion: z.ZodLiteral<1>;
@@ -21,6 +23,7 @@ declare const MetaSchema: z.ZodObject<{
21
23
  title: z.ZodNullable<z.ZodString>;
22
24
  createdAt: z.ZodString;
23
25
  updatedAt: z.ZodNullable<z.ZodString>;
26
+ costUsd: z.ZodOptional<z.ZodNumber>;
24
27
  }, z.core.$strip>;
25
28
  export type SessionMeta = Readonly<z.infer<typeof MetaSchema>>;
26
29
  export interface SessionStorage {
@@ -41,9 +44,9 @@ export interface StorageDeps {
41
44
  readonly pid: number;
42
45
  readonly now: () => Date;
43
46
  readonly logger: AgentLogger;
47
+ readonly setInterval?: (callback: () => void, ms: number) => ReturnType<typeof setInterval>;
44
48
  readonly isAlive?: (pid: number) => boolean;
45
49
  }
46
50
  /** Signal 0 checks existence only. EPERM means the process exists under another user. */
47
51
  export declare function processAlive(pid: number): boolean;
48
52
  export declare function createSessionStorage(deps: StorageDeps): SessionStorage;
49
- export {};
@@ -1,17 +1,19 @@
1
1
  /**
2
2
  * Session files beside the S3 transcript (S5 spec §5.1): `<id>.session.json`
3
3
  * metadata, written as a temp file then renamed, and `<id>.lock`, created
4
- * exclusively. A lock whose pid is dead, or that cannot be read, is stale and
5
- * taken over; a live one refuses the open. Listing scans the metadata files.
4
+ * exclusively. Nonce-owned locks use heartbeats to detect stale live pids;
5
+ * legacy locks remain pid-based. Listing scans the metadata files.
6
6
  * Files that cannot be read are never rewritten or deleted here.
7
7
  */
8
8
  import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
9
9
  import { join } from "node:path";
10
- import { RequestError } from "@agentclientprotocol/sdk";
11
10
  import { NaxError } from "@nathapp/nax-agent";
12
11
  import { z } from "zod";
13
12
  import { invalidParams, messageOf } from "#src/server/errors";
14
13
  import { BASH_APPROVALS, MODES } from "#src/server/nax-config";
14
+ import { acquireSessionLock } from "#src/server/session-lock";
15
+ export { LOCK_HEARTBEAT_MS, LOCK_STALE_MS } from "#src/server/session-lock";
16
+ export const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
15
17
  export const LIST_PAGE_SIZE = 50;
16
18
  const META_SUFFIX = ".session.json";
17
19
  const MetaSchema = z.object({
@@ -24,8 +26,8 @@ const MetaSchema = z.object({
24
26
  title: z.string().nullable(),
25
27
  createdAt: z.string(),
26
28
  updatedAt: z.string().nullable(),
29
+ costUsd: z.number().optional(),
27
30
  });
28
- const LockSchema = z.object({ pid: z.number().int().positive(), startedAt: z.string() });
29
31
  function codeOf(error) {
30
32
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
31
33
  ? error.code
@@ -92,45 +94,9 @@ export function createSessionStorage(deps) {
92
94
  throw unreadable(sessionId, parsed.error.issues[0]?.message ?? "bad shape");
93
95
  return parsed.data;
94
96
  }
95
- /** The pid holding the lock, or undefined when the lock cannot be read (stale). */
96
- async function lockHolder(path) {
97
- try {
98
- const parsed = LockSchema.safeParse(JSON.parse(await readFile(path, "utf8")));
99
- return parsed.success ? parsed.data.pid : undefined;
100
- }
101
- catch {
102
- return undefined;
103
- }
104
- }
105
- async function tryLock(path) {
106
- const body = JSON.stringify({ pid: deps.pid, startedAt: deps.now().toISOString() });
107
- try {
108
- await writeFile(path, body, { flag: "wx" });
109
- return true;
110
- }
111
- catch (error) {
112
- if (codeOf(error) === "EEXIST")
113
- return false;
114
- throw error;
115
- }
116
- }
117
97
  async function acquireLock(sessionId) {
118
98
  await mkdir(deps.dir, { recursive: true });
119
- const path = lockPath(sessionId);
120
- const release = async () => {
121
- await rm(path, { force: true });
122
- };
123
- if (await tryLock(path))
124
- return release;
125
- const holder = await lockHolder(path);
126
- if (holder !== undefined && holder !== deps.pid && isAlive(holder)) {
127
- throw RequestError.invalidRequest(undefined, `session in use by pid ${holder}`);
128
- }
129
- deps.logger.info("session", "taking over a stale session lock", { sessionId, pid: holder });
130
- await rm(path, { force: true });
131
- if (await tryLock(path))
132
- return release;
133
- throw RequestError.invalidRequest(undefined, "session in use by another process");
99
+ return acquireSessionLock(lockPath(sessionId), deps, isAlive);
134
100
  }
135
101
  async function list(query) {
136
102
  const offset = decodeCursor(query.cursor);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nax-agent-acp",
3
- "version": "0.88.0-canary.2",
3
+ "version": "0.89.0",
4
4
  "description": "ACP (Agent Client Protocol) backend for @nathapp/nax-agent sessions: drive Claude Code and other ACP agents through the nax-agent session API.",
5
5
  "license": "MIT",
6
6
  "author": "William Khoo",
@@ -49,12 +49,12 @@
49
49
  "zod": "^4.3.6"
50
50
  },
51
51
  "peerDependencies": {
52
- "@nathapp/nax-agent": "^0.88.0-canary.2"
52
+ "@nathapp/nax-agent": "^0.89.0"
53
53
  },
54
54
  "publishConfig": {
55
55
  "access": "public",
56
56
  "registry": "https://registry.npmjs.org/",
57
57
  "provenance": true,
58
- "tag": "canary"
58
+ "tag": "latest"
59
59
  }
60
60
  }