@nathapp/nax-agent-acp 0.3.1 → 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 (67) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +86 -4
  3. package/bin/nax-agent.js +4 -0
  4. package/dist/client/elicitation.d.ts +4 -2
  5. package/dist/client/elicitation.js +14 -1
  6. package/dist/client/errors.d.ts +1 -1
  7. package/dist/client/errors.js +2 -2
  8. package/dist/client/open.js +17 -3
  9. package/dist/server/auth.d.ts +45 -0
  10. package/dist/server/auth.js +87 -0
  11. package/dist/server/capabilities.d.ts +7 -0
  12. package/dist/server/capabilities.js +19 -0
  13. package/dist/server/cli.d.ts +26 -0
  14. package/dist/server/cli.js +87 -0
  15. package/dist/server/client-port.d.ts +39 -0
  16. package/dist/server/client-port.js +49 -0
  17. package/dist/server/connection.d.ts +22 -0
  18. package/dist/server/connection.js +56 -0
  19. package/dist/server/errors.d.ts +21 -0
  20. package/dist/server/errors.js +70 -0
  21. package/dist/server/index.d.ts +4 -3
  22. package/dist/server/index.js +6 -1
  23. package/dist/server/logger.d.ts +7 -0
  24. package/dist/server/logger.js +25 -0
  25. package/dist/server/login.d.ts +18 -0
  26. package/dist/server/login.js +29 -0
  27. package/dist/server/main.d.ts +19 -0
  28. package/dist/server/main.js +120 -0
  29. package/dist/server/nax-config.d.ts +30 -0
  30. package/dist/server/nax-config.js +138 -0
  31. package/dist/server/open-session.d.ts +37 -0
  32. package/dist/server/open-session.js +55 -0
  33. package/dist/server/options.d.ts +27 -0
  34. package/dist/server/options.js +55 -0
  35. package/dist/server/permissions.d.ts +44 -0
  36. package/dist/server/permissions.js +157 -0
  37. package/dist/server/process-entry.d.ts +15 -0
  38. package/dist/server/process-entry.js +28 -0
  39. package/dist/server/prompt.d.ts +8 -0
  40. package/dist/server/prompt.js +29 -0
  41. package/dist/server/questions.d.ts +33 -0
  42. package/dist/server/questions.js +79 -0
  43. package/dist/server/registry-open.d.ts +33 -0
  44. package/dist/server/registry-open.js +62 -0
  45. package/dist/server/registry.d.ts +64 -0
  46. package/dist/server/registry.js +262 -0
  47. package/dist/server/server-session.d.ts +43 -0
  48. package/dist/server/server-session.js +221 -0
  49. package/dist/server/session-config.d.ts +27 -0
  50. package/dist/server/session-config.js +93 -0
  51. package/dist/server/storage.d.ts +49 -0
  52. package/dist/server/storage.js +191 -0
  53. package/dist/server/translate/diff.d.ts +30 -0
  54. package/dist/server/translate/diff.js +81 -0
  55. package/dist/server/translate/events.d.ts +37 -0
  56. package/dist/server/translate/events.js +126 -0
  57. package/dist/server/translate/notice.d.ts +10 -0
  58. package/dist/server/translate/notice.js +14 -0
  59. package/dist/server/translate/replay.d.ts +11 -0
  60. package/dist/server/translate/replay.js +53 -0
  61. package/dist/server/translate/stop.d.ts +22 -0
  62. package/dist/server/translate/stop.js +48 -0
  63. package/dist/server/translate/tool-kind.d.ts +9 -0
  64. package/dist/server/translate/tool-kind.js +67 -0
  65. package/dist/server/version.d.ts +1 -0
  66. package/dist/server/version.js +17 -0
  67. package/package.json +5 -2
@@ -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;
@@ -0,0 +1,221 @@
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 { RequestError } from "@agentclientprotocol/sdk";
10
+ import { messageOf, turnInProgress } from "#src/server/errors";
11
+ import { createPermissionBroker } from "#src/server/permissions";
12
+ import { flattenPrompt } from "#src/server/prompt";
13
+ import { createQuestionBroker } from "#src/server/questions";
14
+ import { createEventTranslator } from "#src/server/translate/events";
15
+ import { promptOutcome } from "#src/server/translate/stop";
16
+ /** S3's default turn limit, passed explicitly so the timeout notice names it (M-15). */
17
+ export const TURN_TIMEOUT_SECONDS = 3600;
18
+ /** The answer when a cancel arrived before the S3 turn started: nothing ran. */
19
+ const CANCELLED_BEFORE_SEND = {
20
+ kind: "response",
21
+ response: { stopReason: "cancelled", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 } },
22
+ notices: [],
23
+ };
24
+ function react(event, turn, translator) {
25
+ switch (event.type) {
26
+ case "approval_requested":
27
+ if (event.answerable !== false) {
28
+ turn.permissions.request(event, event.callId === undefined ? undefined : translator.toolCallFor(event.callId));
29
+ }
30
+ return;
31
+ case "approval_resolved":
32
+ turn.permissions.settled(event.requestId);
33
+ return;
34
+ case "question":
35
+ turn.questions.ask(event);
36
+ return;
37
+ default:
38
+ return;
39
+ }
40
+ }
41
+ /** Sends updates in order; on the first failure, cancels the turn and drops the rest. */
42
+ function createDelivery(deps, agentOf) {
43
+ let broken;
44
+ return {
45
+ failure: () => broken,
46
+ async deliver(update) {
47
+ if (broken !== undefined)
48
+ return;
49
+ try {
50
+ await deps.port.update(update);
51
+ }
52
+ catch (error) {
53
+ broken = error;
54
+ deps.logger.warn("session", "client stopped accepting updates; cancelling the turn", {
55
+ sessionId: deps.session.id,
56
+ error: messageOf(error),
57
+ });
58
+ agentOf().cancel("client connection failed");
59
+ }
60
+ },
61
+ };
62
+ }
63
+ /** One event: its updates, its round trips, and at turn_end the prompt outcome. */
64
+ async function forwardEvent(event, ctx) {
65
+ for (const update of await ctx.translator.translate(event))
66
+ await ctx.delivery.deliver(update);
67
+ react(event, ctx.turn, ctx.translator);
68
+ if (event.type !== "turn_end")
69
+ return undefined;
70
+ const outcome = promptOutcome(event, ctx.deps.turnTimeoutSeconds, ctx.deps.port.features.updates.notices);
71
+ if (outcome.kind === "response")
72
+ for (const notice of outcome.notices)
73
+ await ctx.delivery.deliver(notice);
74
+ return outcome;
75
+ }
76
+ export function createServerSession(deps) {
77
+ const memory = new Map();
78
+ let queued = [];
79
+ let costUsd = 0;
80
+ let running = false;
81
+ /** A cancel before send() claimed the S3 turn, where AgentSession.cancel() is a no-op. */
82
+ let cancelBeforeSend = false;
83
+ let turn;
84
+ let agent = deps.session;
85
+ let contextWindow = deps.contextWindow;
86
+ function stopWaiting() {
87
+ turn?.permissions.abortAll();
88
+ turn?.questions.abortAll();
89
+ }
90
+ async function reportTurnEnd(message) {
91
+ if (deps.onTurnEnd === undefined)
92
+ return;
93
+ try {
94
+ await deps.onTurnEnd(message);
95
+ }
96
+ catch (error) {
97
+ deps.logger.warn("session", "turn bookkeeping failed", { sessionId: deps.session.id, error: messageOf(error) });
98
+ }
99
+ }
100
+ async function runTurn(message) {
101
+ const delivery = createDelivery(deps, () => agent);
102
+ const answer = agent.answer.bind(agent);
103
+ const translator = createEventTranslator({
104
+ cwd: deps.cwd,
105
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
106
+ readOldText: deps.readOldText,
107
+ clientUpdates: deps.port.features.updates,
108
+ priorCostUsd: costUsd,
109
+ });
110
+ const current = {
111
+ permissions: createPermissionBroker({ port: deps.port, answer, memory, logger: deps.logger }),
112
+ questions: createQuestionBroker({
113
+ port: deps.port,
114
+ deliver: delivery.deliver,
115
+ answer,
116
+ logger: deps.logger,
117
+ ...(deps.now !== undefined ? { now: deps.now } : {}),
118
+ }),
119
+ };
120
+ turn = current;
121
+ const ctx = { deps, translator, turn: current, delivery };
122
+ let outcome;
123
+ try {
124
+ const pending = queued;
125
+ queued = [];
126
+ for (const update of pending)
127
+ await delivery.deliver(update);
128
+ if (cancelBeforeSend) {
129
+ outcome = CANCELLED_BEFORE_SEND;
130
+ }
131
+ else if (delivery.failure() === undefined) {
132
+ for await (const event of agent.send(message))
133
+ outcome = (await forwardEvent(event, ctx)) ?? outcome;
134
+ }
135
+ }
136
+ finally {
137
+ current.permissions.abortAll();
138
+ current.questions.abortAll();
139
+ await Promise.all([current.permissions.drain(), current.questions.drain()]);
140
+ costUsd = translator.costUsd();
141
+ turn = undefined;
142
+ }
143
+ const broken = delivery.failure();
144
+ if (broken !== undefined) {
145
+ throw RequestError.internalError(undefined, `could not send a session update: ${messageOf(broken)}`);
146
+ }
147
+ return outcome;
148
+ }
149
+ return {
150
+ id: deps.session.id,
151
+ get running() {
152
+ return running;
153
+ },
154
+ queueNotice(update) {
155
+ queued = [...queued, update];
156
+ },
157
+ async prompt(blocks) {
158
+ if (running)
159
+ throw turnInProgress();
160
+ const message = flattenPrompt(blocks);
161
+ running = true;
162
+ cancelBeforeSend = false;
163
+ let outcome;
164
+ try {
165
+ outcome = await runTurn(message);
166
+ }
167
+ finally {
168
+ // Still "running" while the turn is recorded, so a switchTo cannot
169
+ // slip in and write metadata from before this turn's title/updatedAt.
170
+ await reportTurnEnd(message);
171
+ running = false;
172
+ }
173
+ if (outcome === undefined)
174
+ throw RequestError.internalError(undefined, "the turn ended without a turn_end event");
175
+ if (outcome.kind === "error")
176
+ throw outcome.error;
177
+ return outcome.response;
178
+ },
179
+ async switchTo(open, restore) {
180
+ if (running)
181
+ throw turnInProgress();
182
+ running = true;
183
+ try {
184
+ stopWaiting();
185
+ await agent.close();
186
+ try {
187
+ const next = await open();
188
+ agent = next.session;
189
+ contextWindow = next.contextWindow;
190
+ }
191
+ catch (error) {
192
+ try {
193
+ const back = await restore();
194
+ agent = back.session;
195
+ contextWindow = back.contextWindow;
196
+ }
197
+ catch (restoreError) {
198
+ deps.logger.error("session", "could not reopen the session after a failed switch", {
199
+ sessionId: deps.session.id,
200
+ error: messageOf(restoreError),
201
+ });
202
+ }
203
+ throw error;
204
+ }
205
+ }
206
+ finally {
207
+ running = false;
208
+ }
209
+ },
210
+ cancel() {
211
+ if (running)
212
+ cancelBeforeSend = true;
213
+ agent.cancel("cancelled by the client");
214
+ stopWaiting();
215
+ },
216
+ async close() {
217
+ stopWaiting();
218
+ await agent.close();
219
+ },
220
+ };
221
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * What an ACP session exposes about its settings (S5 spec §5.2, §5.3): the four
3
+ * modes (S3 profiles), and two select config options, the model (the configured
4
+ * tiers plus the current model) and the bash approval mode. Changes are
5
+ * validated here; applying them is the registry's close-and-reopen (§3.3).
6
+ */
7
+ import type { SessionConfigOption, SessionMode, SessionModeState } from "@agentclientprotocol/sdk";
8
+ import type { AgentSessionProfile } from "@nathapp/nax-agent";
9
+ import { type BashApproval, type TierModel } from "#src/server/nax-config";
10
+ export interface SessionSettings {
11
+ readonly mode: AgentSessionProfile;
12
+ readonly model: string;
13
+ readonly bashApproval: BashApproval;
14
+ }
15
+ export declare const MODEL_OPTION = "model";
16
+ export declare const BASH_OPTION = "bashApproval";
17
+ export declare const SESSION_MODES: readonly SessionMode[];
18
+ export declare function sameSettings(a: SessionSettings, b: SessionSettings): boolean;
19
+ export declare function modeState(settings: SessionSettings): SessionModeState;
20
+ export declare function modelChoices(settings: SessionSettings, tiers: readonly TierModel[]): readonly {
21
+ value: string;
22
+ name: string;
23
+ description: string;
24
+ }[];
25
+ export declare function configOptions(settings: SessionSettings, tiers: readonly TierModel[]): SessionConfigOption[];
26
+ export declare function applyModeChange(settings: SessionSettings, modeId: string): SessionSettings;
27
+ export declare function applyConfigChange(settings: SessionSettings, configId: string, value: unknown, tiers: readonly TierModel[]): SessionSettings;
@@ -0,0 +1,93 @@
1
+ import { invalidParams } from "#src/server/errors";
2
+ import { BASH_APPROVALS, MODES } from "#src/server/nax-config";
3
+ export const MODEL_OPTION = "model";
4
+ export const BASH_OPTION = "bashApproval";
5
+ export const SESSION_MODES = [
6
+ { id: "none", name: "Chat", description: "Chat only: no workspace tools." },
7
+ { id: "read", name: "Read only", description: "Reads and searches the workspace; changes nothing." },
8
+ { id: "ask", name: "Ask", description: "Asks before every edit and command." },
9
+ { id: "full", name: "Full access", description: "Edits files and runs commands without asking, inside the sandbox." },
10
+ ];
11
+ const BASH_CHOICES = [
12
+ {
13
+ value: "gated",
14
+ name: "Gated",
15
+ description: "Commands are checked against the rules; one the checks cannot judge is refused.",
16
+ },
17
+ {
18
+ value: "escalate",
19
+ name: "Escalate",
20
+ description: "Like gated, but a command the checks cannot judge asks you instead.",
21
+ },
22
+ {
23
+ value: "raw",
24
+ name: "Raw",
25
+ description: "Commands run as written, without per-command checks (mode Full only).",
26
+ },
27
+ ];
28
+ export function sameSettings(a, b) {
29
+ return a.mode === b.mode && a.model === b.model && a.bashApproval === b.bashApproval;
30
+ }
31
+ export function modeState(settings) {
32
+ return { currentModeId: settings.mode, availableModes: [...SESSION_MODES] };
33
+ }
34
+ export function modelChoices(settings, tiers) {
35
+ const seen = new Set();
36
+ const choices = [];
37
+ for (const tier of tiers) {
38
+ if (seen.has(tier.model))
39
+ continue;
40
+ seen.add(tier.model);
41
+ choices.push({ value: tier.model, name: tier.tier, description: tier.model });
42
+ }
43
+ if (!seen.has(settings.model)) {
44
+ choices.push({ value: settings.model, name: settings.model, description: "current model" });
45
+ }
46
+ return choices;
47
+ }
48
+ export function configOptions(settings, tiers) {
49
+ return [
50
+ {
51
+ id: MODEL_OPTION,
52
+ name: "Model",
53
+ category: "model",
54
+ type: "select",
55
+ currentValue: settings.model,
56
+ options: [...modelChoices(settings, tiers)],
57
+ },
58
+ {
59
+ id: BASH_OPTION,
60
+ name: "Bash approval",
61
+ type: "select",
62
+ currentValue: settings.bashApproval,
63
+ options: [...BASH_CHOICES],
64
+ },
65
+ ];
66
+ }
67
+ export function applyModeChange(settings, modeId) {
68
+ const mode = MODES.find((m) => m === modeId);
69
+ if (mode === undefined)
70
+ throw invalidParams(`unknown mode "${modeId}"; expected one of ${MODES.join(", ")}`);
71
+ // Ask runs every command past a person, which needs gated (M-23).
72
+ return { ...settings, mode, bashApproval: mode === "ask" ? "gated" : settings.bashApproval };
73
+ }
74
+ export function applyConfigChange(settings, configId, value, tiers) {
75
+ if (typeof value !== "string")
76
+ throw invalidParams(`config option "${configId}" takes a string value`);
77
+ if (configId === MODEL_OPTION) {
78
+ const valid = modelChoices(settings, tiers).map((choice) => choice.value);
79
+ if (!valid.includes(value))
80
+ throw invalidParams(`unknown model "${value}"; valid models: ${valid.join(", ")}`);
81
+ return { ...settings, model: value };
82
+ }
83
+ if (configId === BASH_OPTION) {
84
+ const bash = BASH_APPROVALS.find((b) => b === value);
85
+ if (bash === undefined)
86
+ throw invalidParams(`unknown bash approval "${value}"; expected one of ${BASH_APPROVALS.join(", ")}`);
87
+ if (settings.mode === "ask" && bash !== "gated") {
88
+ throw invalidParams('mode "ask" requires bash approval "gated"');
89
+ }
90
+ return { ...settings, bashApproval: bash };
91
+ }
92
+ throw invalidParams(`unknown config option "${configId}"`);
93
+ }