@nathapp/nax-agent-acp 0.3.0 → 0.84.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.
Files changed (87) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +117 -22
  3. package/bin/nax-agent.js +4 -0
  4. package/dist/client/backend.js +11 -2
  5. package/dist/client/capabilities.d.ts +9 -3
  6. package/dist/client/capabilities.js +26 -5
  7. package/dist/client/elicitation.d.ts +4 -2
  8. package/dist/client/elicitation.js +14 -1
  9. package/dist/client/errors.d.ts +9 -1
  10. package/dist/client/errors.js +19 -2
  11. package/dist/client/events.d.ts +5 -1
  12. package/dist/client/events.js +31 -2
  13. package/dist/client/index.d.ts +2 -1
  14. package/dist/client/index.js +1 -0
  15. package/dist/client/launchable.d.ts +4 -0
  16. package/dist/client/launchable.js +17 -0
  17. package/dist/client/open.js +75 -13
  18. package/dist/client/options.d.ts +11 -0
  19. package/dist/client/options.js +17 -3
  20. package/dist/client/permissions.d.ts +2 -2
  21. package/dist/client/pre-approval.d.ts +5 -13
  22. package/dist/client/pre-approval.js +3 -10
  23. package/dist/client/registry.d.ts +15 -2
  24. package/dist/client/registry.js +22 -2
  25. package/dist/client/tool-calls.js +0 -4
  26. package/dist/client/tool-events.d.ts +8 -1
  27. package/dist/client/tool-events.js +39 -6
  28. package/dist/client/turn.js +28 -8
  29. package/dist/server/auth.d.ts +45 -0
  30. package/dist/server/auth.js +87 -0
  31. package/dist/server/capabilities.d.ts +7 -0
  32. package/dist/server/capabilities.js +19 -0
  33. package/dist/server/cli.d.ts +26 -0
  34. package/dist/server/cli.js +87 -0
  35. package/dist/server/client-port.d.ts +39 -0
  36. package/dist/server/client-port.js +49 -0
  37. package/dist/server/connection.d.ts +22 -0
  38. package/dist/server/connection.js +56 -0
  39. package/dist/server/errors.d.ts +21 -0
  40. package/dist/server/errors.js +70 -0
  41. package/dist/server/index.d.ts +4 -3
  42. package/dist/server/index.js +6 -1
  43. package/dist/server/logger.d.ts +7 -0
  44. package/dist/server/logger.js +25 -0
  45. package/dist/server/login.d.ts +18 -0
  46. package/dist/server/login.js +29 -0
  47. package/dist/server/main.d.ts +19 -0
  48. package/dist/server/main.js +120 -0
  49. package/dist/server/nax-config.d.ts +30 -0
  50. package/dist/server/nax-config.js +138 -0
  51. package/dist/server/open-session.d.ts +37 -0
  52. package/dist/server/open-session.js +55 -0
  53. package/dist/server/options.d.ts +27 -0
  54. package/dist/server/options.js +55 -0
  55. package/dist/server/permissions.d.ts +44 -0
  56. package/dist/server/permissions.js +157 -0
  57. package/dist/server/process-entry.d.ts +15 -0
  58. package/dist/server/process-entry.js +28 -0
  59. package/dist/server/prompt.d.ts +8 -0
  60. package/dist/server/prompt.js +29 -0
  61. package/dist/server/questions.d.ts +33 -0
  62. package/dist/server/questions.js +79 -0
  63. package/dist/server/registry-open.d.ts +33 -0
  64. package/dist/server/registry-open.js +62 -0
  65. package/dist/server/registry.d.ts +64 -0
  66. package/dist/server/registry.js +262 -0
  67. package/dist/server/server-session.d.ts +43 -0
  68. package/dist/server/server-session.js +221 -0
  69. package/dist/server/session-config.d.ts +27 -0
  70. package/dist/server/session-config.js +93 -0
  71. package/dist/server/storage.d.ts +49 -0
  72. package/dist/server/storage.js +191 -0
  73. package/dist/server/translate/diff.d.ts +30 -0
  74. package/dist/server/translate/diff.js +81 -0
  75. package/dist/server/translate/events.d.ts +37 -0
  76. package/dist/server/translate/events.js +126 -0
  77. package/dist/server/translate/notice.d.ts +10 -0
  78. package/dist/server/translate/notice.js +14 -0
  79. package/dist/server/translate/replay.d.ts +11 -0
  80. package/dist/server/translate/replay.js +53 -0
  81. package/dist/server/translate/stop.d.ts +22 -0
  82. package/dist/server/translate/stop.js +48 -0
  83. package/dist/server/translate/tool-kind.d.ts +9 -0
  84. package/dist/server/translate/tool-kind.js +67 -0
  85. package/dist/server/version.d.ts +1 -0
  86. package/dist/server/version.js +17 -0
  87. package/package.json +6 -3
@@ -0,0 +1,15 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { type MainDeps } from "#src/server/main";
3
+ import type { Env } from "#src/server/options";
4
+ export interface ProcessLike {
5
+ readonly argv: readonly string[];
6
+ readonly env: Env;
7
+ readonly stdin: Readable & {
8
+ readonly isTTY?: boolean;
9
+ };
10
+ readonly stdout: Writable;
11
+ readonly stderr: Writable;
12
+ once(event: "SIGINT" | "SIGTERM", listener: () => void): unknown;
13
+ }
14
+ export declare function mainDepsFrom(proc: ProcessLike): MainDeps;
15
+ export declare function runCli(proc: ProcessLike): Promise<number>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Adapts a real process to `MainDeps` (master plan M-2): the published bin is a
3
+ * three-line file that calls `runCli(process)`.
4
+ */
5
+ import { readFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { main } from "#src/server/main";
8
+ export function mainDepsFrom(proc) {
9
+ return {
10
+ argv: proc.argv.slice(2),
11
+ env: proc.env,
12
+ homedir: homedir(),
13
+ stdin: proc.stdin,
14
+ stdout: proc.stdout,
15
+ writeErr: (text) => {
16
+ proc.stderr.write(text);
17
+ },
18
+ readFile: (path, encoding) => readFile(path, encoding),
19
+ onSignal: (handler) => {
20
+ proc.once("SIGINT", handler);
21
+ proc.once("SIGTERM", handler);
22
+ },
23
+ isTTY: proc.stdin.isTTY === true,
24
+ };
25
+ }
26
+ export function runCli(proc) {
27
+ return main(mainDepsFrom(proc));
28
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * ACP prompt content as the one text message S3's `send()` takes (S5 spec §3.2):
3
+ * text verbatim; an embedded text resource as a fenced block headed by its URI;
4
+ * a resource link as its URI. Image, audio and binary content are not
5
+ * advertised and are rejected.
6
+ */
7
+ import type { ContentBlock } from "@agentclientprotocol/sdk";
8
+ export declare function flattenPrompt(blocks: readonly ContentBlock[]): string;
@@ -0,0 +1,29 @@
1
+ import { invalidParams } from "#src/server/errors";
2
+ function fenceFor(text) {
3
+ const longest = Math.max(0, ...Array.from(text.matchAll(/`+/g), (run) => run[0].length));
4
+ return "`".repeat(Math.max(3, longest + 1));
5
+ }
6
+ function blockText(block) {
7
+ switch (block.type) {
8
+ case "text":
9
+ return block.text;
10
+ case "resource_link":
11
+ return block.uri;
12
+ case "resource": {
13
+ const { resource } = block;
14
+ if (!("text" in resource))
15
+ throw invalidParams(`binary embedded resource ${resource.uri} is not supported`);
16
+ const fence = fenceFor(resource.text);
17
+ return `${resource.uri}\n${fence}\n${resource.text}\n${fence}`;
18
+ }
19
+ case "image":
20
+ case "audio":
21
+ throw invalidParams(`${block.type} prompt content is not supported`);
22
+ }
23
+ }
24
+ export function flattenPrompt(blocks) {
25
+ const parts = blocks.map(blockText).filter((part) => part !== "");
26
+ if (parts.length === 0)
27
+ throw invalidParams("the prompt has no text");
28
+ return parts.join("\n\n");
29
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Questions (S5 spec §4.3). With form elicitation: one required free-text field,
3
+ * the accepted text is the answer, anything else is the declined text. Without
4
+ * it: the question is shown and answered at once with the no-answer text, so a
5
+ * headless client never leaves the agent waiting. The open elicitation is aborted
6
+ * at the question's expiresAt (M-14). An unanswerable question (M-1) is shown
7
+ * only.
8
+ */
9
+ import type { SessionUpdate } from "@agentclientprotocol/sdk";
10
+ import type { AgentLogger, SessionEvent } from "@nathapp/nax-agent";
11
+ import { type ClientPort } from "#src/server/client-port";
12
+ import type { Answer } from "#src/server/permissions";
13
+ export declare const ANSWER_FIELD = "answer";
14
+ export declare const DECLINED_TEXT = "The user declined to answer.";
15
+ export declare const NO_ANSWER_TEXT = "No answer available: this client cannot answer questions. Proceed with your best judgement.";
16
+ export type QuestionEvent = Extract<SessionEvent, {
17
+ type: "question";
18
+ }>;
19
+ export interface QuestionBroker {
20
+ /** Starts handling one question; never blocks the caller. */
21
+ ask(event: QuestionEvent): void;
22
+ abortAll(): void;
23
+ drain(): Promise<void>;
24
+ }
25
+ export interface QuestionBrokerDeps {
26
+ readonly port: ClientPort;
27
+ /** The session's delivery (it handles a broken connection). */
28
+ readonly deliver: (update: SessionUpdate) => Promise<void>;
29
+ readonly answer: Answer;
30
+ readonly logger: AgentLogger;
31
+ readonly now?: () => number;
32
+ }
33
+ export declare function createQuestionBroker(deps: QuestionBrokerDeps): QuestionBroker;
@@ -0,0 +1,79 @@
1
+ import { untilAborted } from "#src/server/client-port";
2
+ import { messageOf } from "#src/server/errors";
3
+ import { announce } from "#src/server/translate/notice";
4
+ export const ANSWER_FIELD = "answer";
5
+ export const DECLINED_TEXT = "The user declined to answer.";
6
+ export const NO_ANSWER_TEXT = "No answer available: this client cannot answer questions. Proceed with your best judgement.";
7
+ function formFor(text) {
8
+ return {
9
+ message: text,
10
+ requestedSchema: {
11
+ type: "object",
12
+ properties: { [ANSWER_FIELD]: { type: "string", title: "Answer" } },
13
+ required: [ANSWER_FIELD],
14
+ },
15
+ };
16
+ }
17
+ function answerText(response) {
18
+ if (response.action !== "accept")
19
+ return DECLINED_TEXT;
20
+ // The response union has an open `action: string` member, so read content defensively.
21
+ const content = "content" in response ? response.content : undefined;
22
+ const value = typeof content === "object" && content !== null ? Reflect.get(content, ANSWER_FIELD) : undefined;
23
+ return typeof value === "string" && value.trim() !== "" ? value : DECLINED_TEXT;
24
+ }
25
+ export function createQuestionBroker(deps) {
26
+ const now = deps.now ?? Date.now;
27
+ const open = new Set();
28
+ const running = new Set();
29
+ const notices = deps.port.features.updates.notices;
30
+ async function elicit(event) {
31
+ const controller = new AbortController();
32
+ open.add(controller);
33
+ const expiry = setTimeout(() => controller.abort(), Math.max(0, Date.parse(event.expiresAt) - now()));
34
+ let text;
35
+ try {
36
+ text = answerText(await untilAborted(deps.port.elicit(formFor(event.text), controller.signal), controller.signal));
37
+ }
38
+ catch (error) {
39
+ if (controller.signal.aborted)
40
+ return;
41
+ deps.logger.warn("questions", "elicitation failed; answering without the user", { error: messageOf(error) });
42
+ text = NO_ANSWER_TEXT;
43
+ }
44
+ finally {
45
+ clearTimeout(expiry);
46
+ open.delete(controller);
47
+ }
48
+ deps.answer(event.requestId, { text });
49
+ }
50
+ async function handle(event) {
51
+ if (event.answerable === false) {
52
+ await deps.deliver(announce(notices, "info", "The agent noted a question", event.text));
53
+ return;
54
+ }
55
+ if (deps.port.features.elicitation) {
56
+ await elicit(event);
57
+ return;
58
+ }
59
+ await deps.deliver(announce(notices, "warning", "The agent asked a question", event.text));
60
+ deps.answer(event.requestId, { text: NO_ANSWER_TEXT });
61
+ }
62
+ return {
63
+ ask(event) {
64
+ // Never rejects: a throwing answer() or delivery must not become an unhandled rejection.
65
+ const work = handle(event).catch((error) => {
66
+ deps.logger.warn("questions", "question handling failed", { error: messageOf(error) });
67
+ });
68
+ running.add(work);
69
+ void work.finally(() => running.delete(work));
70
+ },
71
+ abortAll() {
72
+ for (const controller of open)
73
+ controller.abort();
74
+ },
75
+ async drain() {
76
+ await Promise.all([...running]);
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Reopening a stored session for session/load and session/resume (S5 spec §5.3,
3
+ * §5.4). Extracted from registry.ts so neither module grows past the complexity
4
+ * limit; registry.ts owns the entry and lock lifecycle and passes its internals
5
+ * in. Load replays the stored transcript (and warns when the last turn was
6
+ * interrupted); resume reopens without replay.
7
+ */
8
+ import type { AgentLogger, TranscriptStore } from "@nathapp/nax-agent";
9
+ import type { ClientPort } from "#src/server/client-port";
10
+ import type { OpenedSession } from "#src/server/open-session";
11
+ import type { Entry, OpenInput, SessionState } from "#src/server/registry";
12
+ import type { ServerSession } from "#src/server/server-session";
13
+ import type { SessionSettings } from "#src/server/session-config";
14
+ import type { SessionMeta, SessionStorage } from "#src/server/storage";
15
+ export interface ReopenDeps {
16
+ readonly entries: Map<string, Entry>;
17
+ readonly storage: SessionStorage;
18
+ readonly transcripts: TranscriptStore;
19
+ readonly logger: AgentLogger;
20
+ readonly openEntry: (meta: SessionMeta, port: ClientPort) => Promise<{
21
+ readonly server: ServerSession;
22
+ readonly opened: OpenedSession;
23
+ }>;
24
+ readonly closeEntry: (sessionId: string, entry: Entry) => Promise<void>;
25
+ readonly stateOf: (settings: SessionSettings) => SessionState;
26
+ readonly mcpNotice: string;
27
+ readonly interruptedNotice: string;
28
+ }
29
+ export interface Reopener {
30
+ reopen(sessionId: string, input: OpenInput, replay: boolean): Promise<SessionState>;
31
+ }
32
+ export declare const settingsOf: (meta: SessionMeta) => SessionSettings;
33
+ export declare function createReopen(deps: ReopenDeps): Reopener;
@@ -0,0 +1,62 @@
1
+ import { unknownSession } from "#src/server/errors";
2
+ import { announce } from "#src/server/translate/notice";
3
+ import { replayTranscript } from "#src/server/translate/replay";
4
+ export const settingsOf = (meta) => ({
5
+ mode: meta.mode,
6
+ model: meta.model,
7
+ bashApproval: meta.bashApproval,
8
+ });
9
+ export function createReopen(deps) {
10
+ async function replayTo(port, messages, cwd) {
11
+ for (const update of replayTranscript(messages, cwd))
12
+ await port.update(update);
13
+ }
14
+ async function replayOpened(port, opened, cwd) {
15
+ await replayTo(port, opened.doc?.messages ?? [], cwd);
16
+ if (opened.session.lastTurn?.status === "interrupted") {
17
+ await port.update(announce(port.features.updates.notices, "warning", deps.interruptedNotice));
18
+ }
19
+ }
20
+ async function openAndReplay(sessionId, meta, input, replay) {
21
+ const port = input.port(sessionId);
22
+ const { server, opened } = await deps.openEntry(meta, port);
23
+ if (replay) {
24
+ try {
25
+ await replayOpened(port, opened, meta.cwd);
26
+ }
27
+ catch (error) {
28
+ // The client did not get its history: do not leave the session open and locked.
29
+ const entry = deps.entries.get(sessionId);
30
+ if (entry !== undefined)
31
+ await deps.closeEntry(sessionId, entry);
32
+ throw error;
33
+ }
34
+ }
35
+ if (input.mcpServers.length > 0) {
36
+ server.queueNotice(announce(port.features.updates.notices, "warning", deps.mcpNotice));
37
+ }
38
+ }
39
+ return {
40
+ async reopen(sessionId, input, replay) {
41
+ const open = deps.entries.get(sessionId);
42
+ if (open !== undefined) {
43
+ if (replay) {
44
+ await replayTo(open.port, (await deps.transcripts.load(sessionId))?.messages ?? [], open.meta.cwd);
45
+ }
46
+ return deps.stateOf(settingsOf(open.meta));
47
+ }
48
+ const meta = await deps.storage.readMeta(sessionId);
49
+ if (meta === null)
50
+ throw unknownSession(sessionId);
51
+ if (input.cwd !== meta.cwd) {
52
+ deps.logger.debug("session", "reopening in the stored cwd", {
53
+ sessionId,
54
+ requested: input.cwd,
55
+ stored: meta.cwd,
56
+ });
57
+ }
58
+ await openAndReplay(sessionId, meta, input, replay);
59
+ return deps.stateOf(settingsOf(meta));
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,64 @@
1
+ import { type ListSessionsResponse, type SessionConfigOption, type SessionModeState } from "@agentclientprotocol/sdk";
2
+ import type { AgentLogger, TranscriptStore } from "@nathapp/nax-agent";
3
+ import type { ClientPort } from "#src/server/client-port";
4
+ import type { OpenSession } from "#src/server/open-session";
5
+ import type { ServerOptions } from "#src/server/options";
6
+ import { type ServerSession } from "#src/server/server-session";
7
+ import type { SessionMeta, SessionStorage } from "#src/server/storage";
8
+ import type { ReadOldText } from "#src/server/translate/diff";
9
+ export declare const NO_MODEL_MESSAGE = "no model configured: set models.native.balanced or --model";
10
+ export declare const MCP_NOTICE = "MCP servers are not supported yet; ignored";
11
+ export declare const INTERRUPTED_NOTICE = "The previous turn was interrupted";
12
+ export declare const SHUTTING_DOWN = "server is shutting down";
13
+ export declare const SHUTDOWN_WAIT_MS = 5000;
14
+ export declare const TITLE_MAX = 80;
15
+ export interface SessionState {
16
+ readonly modes: SessionModeState;
17
+ readonly configOptions: SessionConfigOption[];
18
+ }
19
+ export interface OpenInput {
20
+ readonly cwd: string;
21
+ readonly mcpServers: readonly unknown[];
22
+ readonly port: (sessionId: string) => ClientPort;
23
+ }
24
+ export interface SessionRegistry {
25
+ create(input: OpenInput): Promise<{
26
+ readonly sessionId: string;
27
+ } & SessionState>;
28
+ load(sessionId: string, input: OpenInput): Promise<SessionState>;
29
+ resume(sessionId: string, input: OpenInput): Promise<SessionState>;
30
+ list(query: {
31
+ readonly cwd?: string | null;
32
+ readonly cursor?: string | null;
33
+ }): Promise<ListSessionsResponse>;
34
+ get(sessionId: string): ServerSession;
35
+ find(sessionId: string): ServerSession | undefined;
36
+ close(sessionId: string): Promise<void>;
37
+ delete(sessionId: string): Promise<void>;
38
+ setMode(sessionId: string, modeId: string): Promise<void>;
39
+ setConfigOption(sessionId: string, configId: string, value: unknown): Promise<SessionConfigOption[]>;
40
+ closeAll(): Promise<void>;
41
+ }
42
+ export interface RegistryDeps {
43
+ readonly options: ServerOptions;
44
+ readonly openSession: OpenSession;
45
+ readonly storage: SessionStorage;
46
+ readonly transcripts: TranscriptStore;
47
+ readonly newId: () => string;
48
+ readonly now: () => Date;
49
+ readonly readOldText: ReadOldText;
50
+ readonly logger: AgentLogger;
51
+ readonly turnTimeoutSeconds: number;
52
+ readonly shutdownWaitMs?: number;
53
+ /** S5-4 M-30: refuses (auth_required) when the model's provider has no credential. */
54
+ readonly ensureCredentials?: (model: string) => Promise<void>;
55
+ }
56
+ export interface Entry {
57
+ readonly server: ServerSession;
58
+ readonly port: ClientPort;
59
+ readonly meta: SessionMeta;
60
+ readonly release: () => Promise<void>;
61
+ }
62
+ /** One line, no control or invisible characters, at most TITLE_MAX code points. */
63
+ export declare function titleOf(prompt: string): string;
64
+ export declare function createSessionRegistry(deps: RegistryDeps): SessionRegistry;
@@ -0,0 +1,262 @@
1
+ /**
2
+ * ACP session id -> open session, backed by files (S5 spec §5.1, §5.3). Opening
3
+ * (new, load, resume) takes the session's lock, then reopens the S3 session;
4
+ * close releases the lock and keeps the files; delete removes them. Mode and
5
+ * config changes are a close-and-reopen (§3.3) that rolls back on failure and
6
+ * writes metadata only on success. closeAll is the shutdown (§5.5).
7
+ */
8
+ import { isAbsolute } from "node:path";
9
+ import { RequestError, } from "@agentclientprotocol/sdk";
10
+ import { stripControl, stripInvisible } from "#src/client/text";
11
+ import { invalidParams, messageOf, turnInProgress, unknownSession } from "#src/server/errors";
12
+ import { createReopen, settingsOf } from "#src/server/registry-open";
13
+ import { createServerSession } from "#src/server/server-session";
14
+ import { applyConfigChange, applyModeChange, configOptions, modeState, sameSettings, } from "#src/server/session-config";
15
+ import { announce } from "#src/server/translate/notice";
16
+ export const NO_MODEL_MESSAGE = "no model configured: set models.native.balanced or --model";
17
+ export const MCP_NOTICE = "MCP servers are not supported yet; ignored";
18
+ export const INTERRUPTED_NOTICE = "The previous turn was interrupted";
19
+ export const SHUTTING_DOWN = "server is shutting down";
20
+ export const SHUTDOWN_WAIT_MS = 5000;
21
+ export const TITLE_MAX = 80;
22
+ /** One line, no control or invisible characters, at most TITLE_MAX code points. */
23
+ export function titleOf(prompt) {
24
+ return Array.from(stripInvisible(stripControl(prompt)).replace(/\s+/g, " ").trim())
25
+ .slice(0, TITLE_MAX)
26
+ .join("");
27
+ }
28
+ function waitAtMost(ms) {
29
+ let timer;
30
+ const done = new Promise((resolve) => {
31
+ timer = setTimeout(() => resolve("timeout"), ms);
32
+ });
33
+ return { done, cancel: () => clearTimeout(timer) };
34
+ }
35
+ export function createSessionRegistry(deps) {
36
+ const entries = new Map();
37
+ const { options } = deps;
38
+ let closing = false;
39
+ const contextWindowFor = (model) => options.tiers.find((tier) => tier.model === model)?.contextWindow;
40
+ const stateOf = (settings) => ({
41
+ modes: modeState(settings),
42
+ configOptions: configOptions(settings, options.tiers),
43
+ });
44
+ function entryOf(sessionId) {
45
+ const entry = entries.get(sessionId);
46
+ if (entry === undefined)
47
+ throw unknownSession(sessionId);
48
+ return entry;
49
+ }
50
+ async function recordTurn(sessionId, prompt) {
51
+ const entry = entries.get(sessionId);
52
+ if (entry === undefined)
53
+ return;
54
+ const meta = {
55
+ ...entry.meta,
56
+ title: entry.meta.title ?? (titleOf(prompt) || null),
57
+ updatedAt: deps.now().toISOString(),
58
+ };
59
+ entries.set(sessionId, { ...entry, meta });
60
+ await deps.storage.writeMeta(meta);
61
+ }
62
+ async function target(sessionId, cwd, settings) {
63
+ const opened = await deps.openSession({
64
+ sessionId,
65
+ cwd,
66
+ model: settings.model,
67
+ profile: settings.mode,
68
+ bashApproval: settings.bashApproval,
69
+ });
70
+ const contextWindow = contextWindowFor(settings.model);
71
+ return { session: opened.session, ...(contextWindow !== undefined ? { contextWindow } : {}) };
72
+ }
73
+ /** Takes the lock, opens the S3 session, registers it. The lock is released if anything fails. */
74
+ async function openEntry(meta, port) {
75
+ if (closing)
76
+ throw RequestError.internalError(undefined, SHUTTING_DOWN);
77
+ await deps.ensureCredentials?.(meta.model);
78
+ const release = await deps.storage.acquireLock(meta.sessionId);
79
+ try {
80
+ const settings = settingsOf(meta);
81
+ const opened = await deps.openSession({
82
+ sessionId: meta.sessionId,
83
+ cwd: meta.cwd,
84
+ model: settings.model,
85
+ profile: settings.mode,
86
+ bashApproval: settings.bashApproval,
87
+ });
88
+ if (closing) {
89
+ // Shutdown started while this open was in flight: closeAll has already
90
+ // cleared the map, so nothing would close this session or its lock (M-26).
91
+ await opened.session.close().catch(() => undefined);
92
+ throw RequestError.internalError(undefined, SHUTTING_DOWN);
93
+ }
94
+ const contextWindow = contextWindowFor(settings.model);
95
+ const server = createServerSession({
96
+ session: opened.session,
97
+ port,
98
+ cwd: meta.cwd,
99
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
100
+ readOldText: deps.readOldText,
101
+ logger: deps.logger,
102
+ turnTimeoutSeconds: deps.turnTimeoutSeconds,
103
+ onTurnEnd: (prompt) => recordTurn(meta.sessionId, prompt),
104
+ });
105
+ entries.set(meta.sessionId, { server, port, meta, release });
106
+ return { server, opened };
107
+ }
108
+ catch (error) {
109
+ await release();
110
+ throw error;
111
+ }
112
+ }
113
+ async function closeEntry(sessionId, entry) {
114
+ entries.delete(sessionId);
115
+ try {
116
+ await entry.server.close();
117
+ }
118
+ finally {
119
+ await entry.release();
120
+ }
121
+ }
122
+ const reopen = createReopen({
123
+ entries,
124
+ storage: deps.storage,
125
+ transcripts: deps.transcripts,
126
+ logger: deps.logger,
127
+ openEntry,
128
+ closeEntry,
129
+ stateOf,
130
+ mcpNotice: MCP_NOTICE,
131
+ interruptedNotice: INTERRUPTED_NOTICE,
132
+ }).reopen;
133
+ /** Close-and-reopen with `next` (§3.3). Metadata is written only after the reopen succeeds. */
134
+ async function switchTo(sessionId, entry, next) {
135
+ const from = settingsOf(entry.meta);
136
+ // A busy session answers "turn in progress" first, as ServerSession.switchTo would.
137
+ if (entry.server.running)
138
+ throw turnInProgress();
139
+ // Before the live session is closed, so a refused model changes nothing (final review I6).
140
+ if (next.model !== from.model)
141
+ await deps.ensureCredentials?.(next.model);
142
+ await entry.server.switchTo(() => target(sessionId, entry.meta.cwd, next), () => target(sessionId, entry.meta.cwd, from));
143
+ const meta = { ...entry.meta, mode: next.mode, model: next.model, bashApproval: next.bashApproval };
144
+ entries.set(sessionId, { ...entry, meta });
145
+ await deps.storage.writeMeta(meta);
146
+ }
147
+ async function announceConfig(entry, settings) {
148
+ await entry.port.update({
149
+ sessionUpdate: "config_option_update",
150
+ configOptions: configOptions(settings, options.tiers),
151
+ });
152
+ }
153
+ return {
154
+ async create(input) {
155
+ if (!isAbsolute(input.cwd))
156
+ throw invalidParams(`cwd must be an absolute path: ${input.cwd}`);
157
+ const model = options.defaultModel;
158
+ if (model === undefined)
159
+ throw invalidParams(NO_MODEL_MESSAGE);
160
+ const sessionId = deps.newId();
161
+ const meta = {
162
+ schemaVersion: 1,
163
+ sessionId,
164
+ cwd: input.cwd,
165
+ mode: options.defaultMode,
166
+ model,
167
+ bashApproval: options.bashApproval,
168
+ title: null,
169
+ createdAt: deps.now().toISOString(),
170
+ updatedAt: null,
171
+ };
172
+ const port = input.port(sessionId);
173
+ const { server } = await openEntry(meta, port);
174
+ try {
175
+ await deps.storage.writeMeta(meta);
176
+ }
177
+ catch (error) {
178
+ const entry = entries.get(sessionId);
179
+ if (entry !== undefined)
180
+ await closeEntry(sessionId, entry);
181
+ throw error;
182
+ }
183
+ if (closing) {
184
+ // Shutdown started while this create's metadata write was in flight (M-26).
185
+ // closeAll has already cleared the map and closed the entry (releasing its
186
+ // lock), but the write it raced landed after the clear; remove it so no
187
+ // phantom session survives shutdown, then refuse.
188
+ const raced = entries.get(sessionId);
189
+ if (raced !== undefined)
190
+ await closeEntry(sessionId, raced);
191
+ await deps.storage.removeMeta(sessionId);
192
+ throw RequestError.internalError(undefined, SHUTTING_DOWN);
193
+ }
194
+ if (input.mcpServers.length > 0)
195
+ server.queueNotice(announce(port.features.updates.notices, "warning", MCP_NOTICE));
196
+ deps.logger.info("session", "session opened", { sessionId, cwd: input.cwd, model, mode: meta.mode });
197
+ return { sessionId, ...stateOf(settingsOf(meta)) };
198
+ },
199
+ load: (sessionId, input) => reopen(sessionId, input, true),
200
+ resume: (sessionId, input) => reopen(sessionId, input, false),
201
+ list: (query) => deps.storage.list(query),
202
+ get: (sessionId) => entryOf(sessionId).server,
203
+ find: (sessionId) => entries.get(sessionId)?.server,
204
+ async close(sessionId) {
205
+ await closeEntry(sessionId, entryOf(sessionId));
206
+ },
207
+ async delete(sessionId) {
208
+ const entry = entries.get(sessionId);
209
+ if (entry !== undefined)
210
+ await closeEntry(sessionId, entry);
211
+ else if (!(await deps.storage.hasMeta(sessionId)))
212
+ throw unknownSession(sessionId);
213
+ const release = await deps.storage.acquireLock(sessionId);
214
+ try {
215
+ await deps.transcripts.delete(sessionId);
216
+ await deps.storage.removeMeta(sessionId);
217
+ }
218
+ finally {
219
+ await release();
220
+ }
221
+ },
222
+ async setMode(sessionId, modeId) {
223
+ const entry = entryOf(sessionId);
224
+ const from = settingsOf(entry.meta);
225
+ const next = applyModeChange(from, modeId);
226
+ if (!sameSettings(from, next))
227
+ await switchTo(sessionId, entry, next);
228
+ await entry.port.update({ sessionUpdate: "current_mode_update", currentModeId: next.mode });
229
+ if (next.bashApproval !== from.bashApproval)
230
+ await announceConfig(entry, next);
231
+ },
232
+ async setConfigOption(sessionId, configId, value) {
233
+ const entry = entryOf(sessionId);
234
+ const from = settingsOf(entry.meta);
235
+ const next = applyConfigChange(from, configId, value, options.tiers);
236
+ if (!sameSettings(from, next)) {
237
+ await switchTo(sessionId, entry, next);
238
+ await announceConfig(entry, next);
239
+ }
240
+ return configOptions(next, options.tiers);
241
+ },
242
+ async closeAll() {
243
+ closing = true;
244
+ const open = [...entries.entries()];
245
+ entries.clear();
246
+ const wait = deps.shutdownWaitMs ?? SHUTDOWN_WAIT_MS;
247
+ await Promise.all(open.map(async ([sessionId, entry]) => {
248
+ entry.server.cancel();
249
+ const limit = waitAtMost(wait);
250
+ const closed = entry.server.close().then(() => "closed", (error) => {
251
+ deps.logger.warn("session", "session close failed", { sessionId, error: messageOf(error) });
252
+ return "closed";
253
+ });
254
+ const outcome = await Promise.race([closed, limit.done]);
255
+ limit.cancel();
256
+ if (outcome === "timeout")
257
+ deps.logger.warn("session", "session did not close in time", { sessionId, waitMs: wait });
258
+ await entry.release();
259
+ }));
260
+ },
261
+ };
262
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * One ACP session over one S3 AgentSession (S5 spec §3.2, §4.3, §4.4). A prompt
3
+ * is one send(): each event goes through the translator to the client, and
4
+ * approvals and questions start client round trips without blocking the stream.
5
+ * If the client stops accepting updates, the turn is cancelled and drained so
6
+ * the S3 turn slot is freed. In memory only (S5-2); S5-3 adds metadata, locks
7
+ * and close-and-resume.
8
+ */
9
+ import { type ContentBlock, type PromptResponse, type SessionUpdate } from "@agentclientprotocol/sdk";
10
+ import type { AgentLogger, AgentSession } from "@nathapp/nax-agent";
11
+ import type { ClientPort } from "#src/server/client-port";
12
+ import type { ReadOldText } from "#src/server/translate/diff";
13
+ /** S3's default turn limit, passed explicitly so the timeout notice names it (M-15). */
14
+ export declare const TURN_TIMEOUT_SECONDS = 3600;
15
+ export interface ServerSessionDeps {
16
+ readonly session: AgentSession;
17
+ readonly port: ClientPort;
18
+ readonly cwd: string;
19
+ readonly contextWindow?: number;
20
+ readonly readOldText: ReadOldText;
21
+ readonly logger: AgentLogger;
22
+ readonly turnTimeoutSeconds: number;
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>;
26
+ }
27
+ /** The S3 session and context window to adopt on a switchTo (spec §3.3). */
28
+ export interface SwitchTarget {
29
+ readonly session: AgentSession;
30
+ readonly contextWindow?: number;
31
+ }
32
+ export interface ServerSession {
33
+ readonly id: string;
34
+ readonly running: boolean;
35
+ /** Delivered as the first updates of the next turn (M-11). */
36
+ queueNotice(update: SessionUpdate): void;
37
+ prompt(blocks: readonly ContentBlock[]): Promise<PromptResponse>;
38
+ /** Close-and-reopen for a mode or config change (spec §3.3); `restore` reopens the old settings when `open` fails. */
39
+ switchTo(open: () => Promise<SwitchTarget>, restore: () => Promise<SwitchTarget>): Promise<void>;
40
+ cancel(): void;
41
+ close(): Promise<void>;
42
+ }
43
+ export declare function createServerSession(deps: ServerSessionDeps): ServerSession;