@nathapp/nax-agent-acp 0.91.6 → 0.91.7-canary.2

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.91.7-canary.2] - 2026-10-26
7
+
8
+ - No changes in this package. Released in lockstep with the other nax packages.
9
+
10
+ ## [0.91.7-canary.1] - 2026-10-24
11
+
12
+ - No changes in this package. Released in lockstep with the other nax packages.
13
+
6
14
  ## [0.91.6] - 2026-10-24
7
15
 
8
16
  - No changes in this package. Released in lockstep with the other nax packages.
@@ -6,11 +6,11 @@
6
6
  */
7
7
  import { Readable, Writable } from "node:stream";
8
8
  import { agent, ndJsonStream } from "@agentclientprotocol/sdk";
9
+ import { SESSION_ID_PATTERN } from "@nathapp/nax-agent";
9
10
  import { NO_SERVER_AUTH } from "#src/server/auth";
10
11
  import { initializeResponse } from "#src/server/capabilities";
11
12
  import { clientFeatures, clientPort, NO_CLIENT_FEATURES } from "#src/server/client-port";
12
13
  import { guard, invalidParams } from "#src/server/errors";
13
- import { SESSION_ID_PATTERN } from "#src/server/storage";
14
14
  function validatedSessionId(sessionId) {
15
15
  if (!SESSION_ID_PATTERN.test(sessionId))
16
16
  throw invalidParams("invalid session id");
@@ -53,6 +53,12 @@ export function toRequestError(error, logger) {
53
53
  if (error instanceof NaxError && isAuthFailureCode(error.code)) {
54
54
  return authRequired(redactSecrets(error.message), { code: error.code });
55
55
  }
56
+ if (error instanceof NaxError) {
57
+ if (error.code === "SESSION_LOCKED")
58
+ return RequestError.invalidRequest(undefined, error.message);
59
+ if (error.code === "SESSION_LIST_CURSOR_INVALID")
60
+ return invalidParams(error.message);
61
+ }
56
62
  const message = redactSecrets(messageOf(error));
57
63
  logger.error("server", "request failed", {
58
64
  error: message,
@@ -4,7 +4,7 @@
4
4
  * 1 connection failure, 2 usage or option error.
5
5
  */
6
6
  import { randomUUID } from "node:crypto";
7
- import { configureCredentials, createFileTranscriptStore, redactSecrets, setAgentLogger } from "@nathapp/nax-agent";
7
+ import { configureCredentials, createFileTranscriptStore, createSessionStorage, redactSecrets, setAgentLogger, } from "@nathapp/nax-agent";
8
8
  import { connectMcp } from "@nathapp/nax-agent/mcp";
9
9
  import { loadServerAuth, NAX_AGENT_AUTH } from "#src/server/auth";
10
10
  import { parseCli, USAGE } from "#src/server/cli";
@@ -18,7 +18,6 @@ import { catalogOverridesFrom, nativeOpenSession } from "#src/server/open-sessio
18
18
  import { resolveConfigDir, resolveServerOptions } from "#src/server/options";
19
19
  import { createSessionRegistry } from "#src/server/registry";
20
20
  import { TURN_TIMEOUT_SECONDS } from "#src/server/server-session";
21
- import { createSessionStorage } from "#src/server/storage";
22
21
  import { fsReadOldText } from "#src/server/translate/diff";
23
22
  import { packageVersion } from "#src/server/version";
24
23
  export async function main(deps) {
@@ -5,10 +5,10 @@
5
5
  * warning; the server still starts.
6
6
  */
7
7
  import { join } from "node:path";
8
- import { nativeBackend, } from "@nathapp/nax-agent";
8
+ import { nativeBackend, SESSION_META_MODES, } from "@nathapp/nax-agent";
9
9
  import { z } from "zod";
10
10
  export const TIERS = ["fast", "balanced", "powerful"];
11
- export const MODES = ["none", "read", "ask", "full"];
11
+ export const MODES = SESSION_META_MODES;
12
12
  export const BASH_APPROVALS = ["gated", "escalate", "raw"];
13
13
  const ModelEntrySchema = z.union([
14
14
  z.string().min(1),
@@ -3,6 +3,7 @@
3
3
  * built-in default. Config dir: master plan M-5.
4
4
  */
5
5
  import { join } from "node:path";
6
+ import { defaultSessionsDir } from "@nathapp/nax-agent";
6
7
  import { BASH_APPROVALS, MODES, } from "#src/server/nax-config";
7
8
  /** S5-5b: the per-server MCP connect timeout, in seconds (1-300). */
8
9
  export const MCP_CONNECT_TIMEOUT_SECONDS = 30;
@@ -54,7 +55,7 @@ export function resolveServerOptions(input) {
54
55
  const mcpTimeout = pickSeconds(firstSet(from(flags.mcpConnectTimeout, "--mcp-connect-timeout"), from(env.NAX_AGENT_MCP_CONNECT_TIMEOUT, "NAX_AGENT_MCP_CONNECT_TIMEOUT"), from(file.agentServer.mcpConnectTimeoutSeconds?.toString(), "config.json agentServer.mcpConnectTimeoutSeconds")), MCP_CONNECT_TIMEOUT_SECONDS);
55
56
  if (!mcpTimeout.ok)
56
57
  return mcpTimeout;
57
- const sessionsDir = firstSet(from(flags.sessionsDir, "--sessions-dir"), from(env.NAX_AGENT_SESSIONS_DIR, "NAX_AGENT_SESSIONS_DIR"), from(file.agentServer.sessionsDir, "config.json agentServer.sessionsDir"))?.value ?? join(configDir, ".agent-server", "sessions");
58
+ const sessionsDir = firstSet(from(flags.sessionsDir, "--sessions-dir"), from(env.NAX_AGENT_SESSIONS_DIR, "NAX_AGENT_SESSIONS_DIR"), from(file.agentServer.sessionsDir, "config.json agentServer.sessionsDir"))?.value ?? defaultSessionsDir(configDir);
58
59
  const defaultModel = firstSet(from(flags.model, "--model"), from(env.NAX_AGENT_MODEL, "NAX_AGENT_MODEL"), from(file.tiers.find((t) => t.tier === "balanced")?.model, "config.json models.native.balanced"))?.value;
59
60
  return {
60
61
  ok: true,
@@ -20,7 +20,7 @@
20
20
  * ignored. A failed client request is a deny (M-13).
21
21
  */
22
22
  import type { PermissionOption, ToolCallUpdate } from "@agentclientprotocol/sdk";
23
- import type { AgentLogger, AnswerReply, AnswerStatus, SessionEvent } from "@nathapp/nax-agent";
23
+ import { type AgentLogger, type AnswerReply, type AnswerStatus, type SessionEvent } from "@nathapp/nax-agent";
24
24
  import { type ClientPort } from "#src/server/client-port";
25
25
  export type Decision = "allow" | "deny";
26
26
  export type ApprovalEvent = Extract<SessionEvent, {
@@ -44,5 +44,4 @@ export interface PermissionBrokerDeps {
44
44
  readonly memory: Map<string, Decision>;
45
45
  readonly logger: AgentLogger;
46
46
  }
47
- export declare function memoryKey(event: ApprovalEvent): string | undefined;
48
47
  export declare function createPermissionBroker(deps: PermissionBrokerDeps): PermissionBroker;
@@ -1,3 +1,4 @@
1
+ import { approvalMemoryApplies, approvalMemoryKey, } from "@nathapp/nax-agent";
1
2
  import { stripControl, stripInvisible } from "#src/client/text";
2
3
  import { untilAborted } from "#src/server/client-port";
3
4
  import { messageOf } from "#src/server/errors";
@@ -9,83 +10,6 @@ export const PERMISSION_OPTIONS = [
9
10
  { optionId: "reject_always", name: "Always reject", kind: "reject_always" },
10
11
  ];
11
12
  const DENY = { decision: "deny", remember: false };
12
- /** Chaining, pipes, substitution, subshells, redirection and line breaks. */
13
- const SHELL_METACHARACTERS = /[;&|`$()<>\n\r]/;
14
- /** First words that run another command or arbitrary code. */
15
- const WRAPPERS = new Set([
16
- "sh",
17
- "bash",
18
- "zsh",
19
- "dash",
20
- "ksh",
21
- "fish",
22
- "env",
23
- "xargs",
24
- "sudo",
25
- "doas",
26
- "su",
27
- "command",
28
- "builtin",
29
- "eval",
30
- "exec",
31
- "source",
32
- ".",
33
- "nohup",
34
- "time",
35
- "timeout",
36
- "nice",
37
- "ionice",
38
- "stdbuf",
39
- "watch",
40
- "find",
41
- "node",
42
- "bun",
43
- "deno",
44
- "npx",
45
- "bunx",
46
- "pnpx",
47
- "python",
48
- "python3",
49
- "perl",
50
- "ruby",
51
- "php",
52
- "uv",
53
- "uvx",
54
- ]);
55
- /** A plain command name or path: no quotes, escapes, globs or expansions the shell would rewrite. */
56
- const PLAIN_WORD = /^[A-Za-z0-9._/-]+$/;
57
- /** The masking prefix S3 puts in place of a secret in a shown command. */
58
- const MASK_MARKER = "[REDACTED";
59
- export function memoryKey(event) {
60
- if (toolKind(event.tool) !== "execute")
61
- return event.tool;
62
- const command = event.command ?? "";
63
- if (command.includes(MASK_MARKER))
64
- return undefined;
65
- const [first = "", second] = command.trim().split(/\s+/);
66
- if (!PLAIN_WORD.test(first))
67
- return undefined;
68
- const name = first.slice(first.lastIndexOf("/") + 1).toLowerCase();
69
- if (name === "" || WRAPPERS.has(name))
70
- return undefined;
71
- if (second === undefined)
72
- return `${event.tool}:${first}`;
73
- // A flag can change what the command does (`rm -f`, `git -C repo`): remembering the bare command would
74
- // approve every later invocation of it, so a flag second word is never remembered (nax#2553).
75
- if (second.startsWith("-"))
76
- return undefined;
77
- return PLAIN_WORD.test(second) ? `${event.tool}:${first} ${second}` : undefined;
78
- }
79
- /** Whether a remembered decision may answer this request without asking. */
80
- function memoryApplies(event, decision) {
81
- if (decision === "deny" || toolKind(event.tool) !== "execute")
82
- return true;
83
- const command = event.command ?? "";
84
- if (SHELL_METACHARACTERS.test(command))
85
- return false;
86
- const rest = command.trim().split(/\s+/).slice(2);
87
- return rest.every((word) => PLAIN_WORD.test(word) && !word.startsWith("-"));
88
- }
89
13
  function choice(response) {
90
14
  const { outcome } = response;
91
15
  if (outcome.outcome !== "selected")
@@ -138,9 +62,9 @@ export function createPermissionBroker(deps) {
138
62
  }
139
63
  return {
140
64
  request(event, toolCall) {
141
- const key = memoryKey(event);
65
+ const key = approvalMemoryKey(event);
142
66
  const remembered = key === undefined ? undefined : deps.memory.get(key);
143
- if (remembered !== undefined && memoryApplies(event, remembered)) {
67
+ if (remembered !== undefined && approvalMemoryApplies(event, remembered)) {
144
68
  deps.answer(event.requestId, { decision: remembered });
145
69
  return;
146
70
  }
@@ -1,11 +1,10 @@
1
1
  /** Bounded registry shutdown and ownership cleanup. */
2
- import type { AgentLogger } from "@nathapp/nax-agent";
2
+ import type { AgentLogger, SessionMeta } from "@nathapp/nax-agent";
3
3
  import type { ClientPort } from "#src/server/client-port";
4
4
  import type { McpSessionTools } from "#src/server/mcp/session-tools";
5
5
  import type { OpenedSession } from "#src/server/open-session";
6
6
  import type { Entry, RegistryDeps } from "#src/server/registry";
7
7
  import { type ServerSession } from "#src/server/server-session";
8
- import type { SessionMeta } from "#src/server/storage";
9
8
  export declare function closeEntries({ open, entries, wait, logger, }: {
10
9
  readonly open: readonly (readonly [string, Entry])[];
11
10
  readonly entries: Map<string, Entry>;
@@ -5,13 +5,12 @@
5
5
  * in. Load replays the stored transcript (and warns when the last turn was
6
6
  * interrupted); resume reopens without replay.
7
7
  */
8
- import type { AgentLogger, TranscriptStore } from "@nathapp/nax-agent";
8
+ import type { AgentLogger, SessionMeta, SessionStorage, TranscriptStore } from "@nathapp/nax-agent";
9
9
  import type { ClientPort } from "#src/server/client-port";
10
10
  import type { OpenedSession } from "#src/server/open-session";
11
11
  import type { Entry, OpenInput, SessionState } from "#src/server/registry";
12
12
  import type { ServerSession } from "#src/server/server-session";
13
13
  import type { SessionSettings } from "#src/server/session-config";
14
- import type { SessionMeta, SessionStorage } from "#src/server/storage";
15
14
  export interface ReopenDeps {
16
15
  readonly entries: Map<string, Entry>;
17
16
  readonly storage: SessionStorage;
@@ -1,4 +1,5 @@
1
1
  import { type ListSessionsResponse, type SessionConfigOption, type SessionModeState } from "@agentclientprotocol/sdk";
2
+ import type { SessionMeta, SessionStorage } from "@nathapp/nax-agent";
2
3
  import { type AgentLogger, type TranscriptStore } from "@nathapp/nax-agent";
3
4
  import type { ClientPort } from "#src/server/client-port";
4
5
  import { type ConnectSessionMcp } from "#src/server/mcp/connect";
@@ -6,7 +7,6 @@ import type { McpSessionTools } from "#src/server/mcp/session-tools";
6
7
  import type { OpenSession } from "#src/server/open-session";
7
8
  import type { ServerOptions } from "#src/server/options";
8
9
  import type { ServerSession } from "#src/server/server-session";
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";
@@ -265,7 +265,13 @@ export function createSessionRegistry(deps) {
265
265
  },
266
266
  load: (sessionId, input) => reopen(sessionId, input, true),
267
267
  resume: (sessionId, input) => reopen(sessionId, input, false),
268
- list: (query) => deps.storage.list(query),
268
+ async list(query) {
269
+ const page = await deps.storage.list(query);
270
+ return {
271
+ sessions: page.sessions.map(({ sessionId, cwd, title, updatedAt }) => ({ sessionId, cwd, title, updatedAt })),
272
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
273
+ };
274
+ },
269
275
  get: (sessionId) => entryOf(sessionId).server,
270
276
  find: (sessionId) => entries.get(sessionId)?.server,
271
277
  async close(sessionId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nax-agent-acp",
3
- "version": "0.91.6",
3
+ "version": "0.91.7-canary.2",
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.91.6"
52
+ "@nathapp/nax-agent": "^0.91.7-canary.2"
53
53
  },
54
54
  "publishConfig": {
55
55
  "access": "public",
56
56
  "registry": "https://registry.npmjs.org/",
57
57
  "provenance": true,
58
- "tag": "latest"
58
+ "tag": "canary"
59
59
  }
60
60
  }
@@ -1,6 +0,0 @@
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;
@@ -1,85 +0,0 @@
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
- }
@@ -1,10 +0,0 @@
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>;
@@ -1,164 +0,0 @@
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,52 +0,0 @@
1
- import type { ListSessionsResponse } from "@agentclientprotocol/sdk";
2
- import { type AgentLogger } from "@nathapp/nax-agent";
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;
6
- export declare const LIST_PAGE_SIZE = 50;
7
- declare const MetaSchema: z.ZodObject<{
8
- schemaVersion: z.ZodLiteral<1>;
9
- sessionId: z.ZodString;
10
- cwd: z.ZodString;
11
- mode: z.ZodEnum<{
12
- ask: "ask";
13
- full: "full";
14
- none: "none";
15
- read: "read";
16
- }>;
17
- model: z.ZodString;
18
- bashApproval: z.ZodEnum<{
19
- escalate: "escalate";
20
- gated: "gated";
21
- raw: "raw";
22
- }>;
23
- title: z.ZodNullable<z.ZodString>;
24
- createdAt: z.ZodString;
25
- updatedAt: z.ZodNullable<z.ZodString>;
26
- costUsd: z.ZodOptional<z.ZodNumber>;
27
- }, z.core.$strip>;
28
- export type SessionMeta = Readonly<z.infer<typeof MetaSchema>>;
29
- export interface SessionStorage {
30
- readonly dir: string;
31
- readMeta(sessionId: string): Promise<SessionMeta | null>;
32
- writeMeta(meta: SessionMeta): Promise<void>;
33
- hasMeta(sessionId: string): Promise<boolean>;
34
- removeMeta(sessionId: string): Promise<void>;
35
- /** Resolves to the release function; refuses with invalid_request when another live process holds it. */
36
- acquireLock(sessionId: string): Promise<() => Promise<void>>;
37
- list(query: {
38
- readonly cwd?: string | null;
39
- readonly cursor?: string | null;
40
- }): Promise<ListSessionsResponse>;
41
- }
42
- export interface StorageDeps {
43
- readonly dir: string;
44
- readonly pid: number;
45
- readonly now: () => Date;
46
- readonly logger: AgentLogger;
47
- readonly setInterval?: (callback: () => void, ms: number) => ReturnType<typeof setInterval>;
48
- readonly isAlive?: (pid: number) => boolean;
49
- }
50
- /** Signal 0 checks existence only. EPERM means the process exists under another user. */
51
- export declare function processAlive(pid: number): boolean;
52
- export declare function createSessionStorage(deps: StorageDeps): SessionStorage;
@@ -1,157 +0,0 @@
1
- /**
2
- * Session files beside the S3 transcript (S5 spec §5.1): `<id>.session.json`
3
- * metadata, written as a temp file then renamed, and `<id>.lock`, created
4
- * exclusively. Nonce-owned locks use heartbeats to detect stale live pids;
5
- * legacy locks remain pid-based. Listing scans the metadata files.
6
- * Files that cannot be read are never rewritten or deleted here.
7
- */
8
- import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
9
- import { join } from "node:path";
10
- import { NaxError } from "@nathapp/nax-agent";
11
- import { z } from "zod";
12
- import { invalidParams, messageOf } from "#src/server/errors";
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}$/;
17
- export const LIST_PAGE_SIZE = 50;
18
- const META_SUFFIX = ".session.json";
19
- const MetaSchema = z.object({
20
- schemaVersion: z.literal(1),
21
- sessionId: z.string().min(1),
22
- cwd: z.string().min(1),
23
- mode: z.enum(MODES),
24
- model: z.string().min(1),
25
- bashApproval: z.enum(BASH_APPROVALS),
26
- title: z.string().nullable(),
27
- createdAt: z.string(),
28
- updatedAt: z.string().nullable(),
29
- costUsd: z.number().optional(),
30
- });
31
- function codeOf(error) {
32
- return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
33
- ? error.code
34
- : undefined;
35
- }
36
- /** Signal 0 checks existence only. EPERM means the process exists under another user. */
37
- export function processAlive(pid) {
38
- try {
39
- process.kill(pid, 0);
40
- return true;
41
- }
42
- catch (error) {
43
- return codeOf(error) === "EPERM";
44
- }
45
- }
46
- function unreadable(sessionId, reason) {
47
- return new NaxError(`session metadata for "${sessionId}" is unreadable: ${reason}`, "SESSION_META_UNREADABLE", {
48
- stage: "agent-server",
49
- sessionId,
50
- });
51
- }
52
- function encodeCursor(offset) {
53
- return Buffer.from(String(offset), "utf8").toString("base64");
54
- }
55
- function decodeCursor(cursor) {
56
- if (cursor === undefined || cursor === null || cursor === "")
57
- return 0;
58
- const text = Buffer.from(cursor, "base64").toString("utf8");
59
- const offset = Number(text);
60
- if (!/^\d+$/.test(text) || !Number.isSafeInteger(offset))
61
- throw invalidParams("invalid cursor");
62
- return offset;
63
- }
64
- const sortKey = (meta) => meta.updatedAt ?? meta.createdAt;
65
- function infoOf(meta) {
66
- return { sessionId: meta.sessionId, cwd: meta.cwd, title: meta.title, updatedAt: sortKey(meta) };
67
- }
68
- export function createSessionStorage(deps) {
69
- const isAlive = deps.isAlive ?? processAlive;
70
- const metaPath = (id) => join(deps.dir, `${id}${META_SUFFIX}`);
71
- const lockPath = (id) => join(deps.dir, `${id}.lock`);
72
- async function readMeta(sessionId) {
73
- let text;
74
- try {
75
- text = await readFile(metaPath(sessionId), "utf8");
76
- }
77
- catch (error) {
78
- if (codeOf(error) === "ENOENT")
79
- return null;
80
- throw unreadable(sessionId, messageOf(error));
81
- }
82
- let json;
83
- try {
84
- json = JSON.parse(text);
85
- }
86
- catch {
87
- throw unreadable(sessionId, "invalid JSON");
88
- }
89
- const version = typeof json === "object" && json !== null && "schemaVersion" in json ? json.schemaVersion : undefined;
90
- if (version !== 1)
91
- throw unreadable(sessionId, `schemaVersion ${String(version)}; this build reads 1`);
92
- const parsed = MetaSchema.safeParse(json);
93
- if (!parsed.success)
94
- throw unreadable(sessionId, parsed.error.issues[0]?.message ?? "bad shape");
95
- return parsed.data;
96
- }
97
- async function acquireLock(sessionId) {
98
- await mkdir(deps.dir, { recursive: true });
99
- return acquireSessionLock(lockPath(sessionId), deps, isAlive);
100
- }
101
- async function list(query) {
102
- const offset = decodeCursor(query.cursor);
103
- let names;
104
- try {
105
- names = await readdir(deps.dir);
106
- }
107
- catch (error) {
108
- if (codeOf(error) === "ENOENT")
109
- return { sessions: [] };
110
- throw error;
111
- }
112
- const metas = [];
113
- for (const name of names.filter((n) => n.endsWith(META_SUFFIX))) {
114
- try {
115
- const meta = await readMeta(name.slice(0, -META_SUFFIX.length));
116
- if (meta !== null)
117
- metas.push(meta);
118
- }
119
- catch (error) {
120
- deps.logger.warn("session", "skipping unreadable session metadata", { file: name, error: messageOf(error) });
121
- }
122
- }
123
- const matching = metas
124
- .filter((meta) => query.cwd === undefined || query.cwd === null || meta.cwd === query.cwd)
125
- .sort((a, b) => sortKey(b).localeCompare(sortKey(a)));
126
- const end = offset + LIST_PAGE_SIZE;
127
- return {
128
- sessions: matching.slice(offset, end).map(infoOf),
129
- ...(end < matching.length ? { nextCursor: encodeCursor(end) } : {}),
130
- };
131
- }
132
- return {
133
- dir: deps.dir,
134
- readMeta,
135
- async writeMeta(meta) {
136
- await mkdir(deps.dir, { recursive: true });
137
- const path = metaPath(meta.sessionId);
138
- const temp = `${path}.${deps.pid}.tmp`;
139
- await writeFile(temp, `${JSON.stringify(meta, null, 2)}\n`);
140
- await rename(temp, path);
141
- },
142
- async hasMeta(sessionId) {
143
- try {
144
- await stat(metaPath(sessionId));
145
- return true;
146
- }
147
- catch {
148
- return false;
149
- }
150
- },
151
- async removeMeta(sessionId) {
152
- await rm(metaPath(sessionId), { force: true });
153
- },
154
- acquireLock,
155
- list,
156
- };
157
- }