@nathapp/nax-agent-acp 0.84.0 → 0.85.1

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 (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +54 -4
  3. package/dist/server/auth.d.ts +2 -0
  4. package/dist/server/auth.js +6 -6
  5. package/dist/server/capabilities.d.ts +2 -1
  6. package/dist/server/capabilities.js +3 -1
  7. package/dist/server/cli.d.ts +1 -0
  8. package/dist/server/cli.js +3 -0
  9. package/dist/server/default-model.d.ts +36 -0
  10. package/dist/server/default-model.js +158 -0
  11. package/dist/server/login.d.ts +2 -0
  12. package/dist/server/login.js +9 -0
  13. package/dist/server/main.d.ts +5 -0
  14. package/dist/server/main.js +36 -3
  15. package/dist/server/mcp/connect.d.ts +38 -0
  16. package/dist/server/mcp/connect.js +95 -0
  17. package/dist/server/mcp/naming.d.ts +12 -0
  18. package/dist/server/mcp/naming.js +43 -0
  19. package/dist/server/mcp/notices.d.ts +8 -0
  20. package/dist/server/mcp/notices.js +19 -0
  21. package/dist/server/mcp/parse.d.ts +24 -0
  22. package/dist/server/mcp/parse.js +107 -0
  23. package/dist/server/mcp/secrets.d.ts +4 -0
  24. package/dist/server/mcp/secrets.js +44 -0
  25. package/dist/server/mcp/session-tools.d.ts +37 -0
  26. package/dist/server/mcp/session-tools.js +70 -0
  27. package/dist/server/mcp/tool-shape.d.ts +19 -0
  28. package/dist/server/mcp/tool-shape.js +20 -0
  29. package/dist/server/nax-config.d.ts +6 -1
  30. package/dist/server/nax-config.js +41 -1
  31. package/dist/server/open-session.d.ts +5 -2
  32. package/dist/server/open-session.js +2 -0
  33. package/dist/server/options.d.ts +6 -1
  34. package/dist/server/options.js +19 -1
  35. package/dist/server/questions.js +13 -2
  36. package/dist/server/registry-open.d.ts +1 -2
  37. package/dist/server/registry-open.js +8 -10
  38. package/dist/server/registry.d.ts +18 -3
  39. package/dist/server/registry.js +116 -45
  40. package/dist/server/server-session.d.ts +2 -0
  41. package/dist/server/server-session.js +1 -0
  42. package/dist/server/session-config.d.ts +4 -2
  43. package/dist/server/session-config.js +11 -0
  44. package/dist/server/translate/events.d.ts +2 -0
  45. package/dist/server/translate/events.js +1 -1
  46. package/dist/server/translate/replay.d.ts +1 -1
  47. package/dist/server/translate/replay.js +6 -6
  48. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -3,6 +3,27 @@
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.85.1] - 2026-10-10
7
+
8
+ ### Added
9
+
10
+ - The server honours `execution.compaction` from `~/.nax/config.json` and passes it to the native backend. An invalid value is handled like any other invalid section of the file: one warning on stderr and the built-in defaults (#2427).
11
+
12
+ ### Changed
13
+
14
+ - Behaviour change, from `@nathapp/nax-agent`: editor threads now compact their history by default (see its changelog), so a long thread no longer ends `errored` at the context window. Each compaction adds one billed summary call. Set `execution.compaction.enabled` to `false` in `config.json` for the old behaviour (#2427).
15
+
16
+ ## [0.85.0] - 2026-10-09
17
+
18
+ ### Added
19
+
20
+ - The mode is a session config option (category `mode`), so editors that render config options show a mode picker; `modes` and `session/set_mode` still work (#2422).
21
+ - Login-first onboarding (#2414): with no model configured, `initialize` advertises terminal login for every loginable provider and `session/new` returns `auth_required`. `nax-agent login <provider>` then offers to write `models.native.balanced` into `config.json` from the provider's catalog models. A server with no model re-reads `config.json` on `session/new`, so the retry needs no restart.
22
+
23
+ ### Changed
24
+
25
+ - The notice that MCP tools are off in `read` and `none` mode, also sent when the mode is switched, reads as one sentence when the client has no notice support (#2422).
26
+
6
27
  ## [0.84.0] - 2026-10-09
7
28
 
8
29
  - Versioning: released in lockstep with `@nathapp/nax`, `@nathapp/nax-ai` and the other agent package at one shared version, starting at 0.84.0 (previously 0.3.x).
package/README.md CHANGED
@@ -4,7 +4,7 @@ ACP (Agent Client Protocol) backend for `@nathapp/nax-agent` sessions. It lets t
4
4
  nax-agent session API (`createAgentSession`, `send()`, `answer()`, `cancel()`, `close()`)
5
5
  drive external coding agents such as Claude Code over ACP.
6
6
 
7
- **Status: 0.4.0.** `./client`: `acpBackend()` drives external ACP agents (Claude Code and others) as
7
+ **Status:** released in lockstep with `@nathapp/nax` (see CHANGELOG.md). `./client`: `acpBackend()` drives external ACP agents (Claude Code and others) as
8
8
  nax-agent sessions. `./server` and the `nax-agent` binary: nax-agent's own native coding agent as an
9
9
  ACP server for editors (Zed) and headless clients (acpx). See "The nax-agent ACP server" below.
10
10
 
@@ -252,6 +252,7 @@ It reads `~/.nax/config.json`, the same file nax uses:
252
252
  - `models.native.balanced` is the default model. `fast`, `balanced` and `powerful` are the models offered in the editor.
253
253
  - `auth` controls where credentials come from.
254
254
  - An optional `agentServer` block sets `defaultMode`, `bashApproval` and `sessionsDir`.
255
+ - `execution.compaction` (`enabled`, `compactAtPercent`, `keepRecentPercent`) is honoured, with the same meaning as in nax. Editor threads compact their history by default when it nears the model's context window, and a context overflow is compacted and retried once; set `{ "enabled": false }` to turn it off. A value nax would reject (for example `compactAtPercent` outside 50-99) is treated like any other invalid section: the server logs a warning to stderr and uses its built-in defaults. Changes need a restart.
255
256
 
256
257
  Flags (`--model`, `--mode`, `--bash-approval`, `--config-dir`, `--sessions-dir`) and `NAX_AGENT_<OPTION>`
257
258
  environment variables override the file. Sessions are stored under `~/.nax/.agent-server/sessions/`.
@@ -273,7 +274,7 @@ turn. Editors that support terminal auth then offer "Log in to <provider>", whic
273
274
 
274
275
  ### Zed
275
276
 
276
- In Zed's `settings.json`:
277
+ In Zed's `settings.json` (`~/.config/zed/settings.json`; `zed: open settings` from the command palette):
277
278
 
278
279
  ```json
279
280
  {
@@ -288,8 +289,32 @@ In Zed's `settings.json`:
288
289
  }
289
290
  ```
290
291
 
292
+ Zed started from the Dock or Finder does not see your shell's `PATH`. If `node` comes from a version
293
+ manager such as nvm, `nax-agent` fails to start there (its script runs `#!/usr/bin/env node`). Use
294
+ absolute paths instead, from `which node` and the global install's `bin/nax-agent.js`:
295
+
296
+ ```json
297
+ "command": "/Users/you/.nvm/versions/node/v22.22.2/bin/node",
298
+ "args": ["/path/to/node_modules/@nathapp/nax-agent-acp/bin/nax-agent.js", "acp"]
299
+ ```
300
+
301
+ First run with an empty `~/.nax` (no model configured): the thread fails with `auth_required`, and Zed offers
302
+ "Log in to <provider>" for every provider that supports login. That runs `nax-agent login <provider>`; after
303
+ the credential is stored it lists the provider's catalog models and writes your pick as
304
+ `models.native.balanced` in `config.json` (in `--config-dir` / `NAX_AGENT_CONFIG_DIR` if set). The write is
305
+ atomic and keeps the file's mode (0600 for a new file; the credentials file is not touched). It re-serialises
306
+ `config.json` as 2-space JSON: every other key is kept, but any custom formatting is not. Without a terminal,
307
+ when `config.json` is malformed, or when it changed while you were picking, nothing is written and the command
308
+ prints the line to add.
309
+
310
+ Then retry in the editor. A server that started with no model re-reads `config.json` on the next new thread, so
311
+ no restart is needed. That retry re-reads only the model and tiers (`models.native`); changes to catalog
312
+ overrides, `auth` or `agentServer` need a restart. A model set with `--model` or
313
+ `"env": { "NAX_AGENT_MODEL": "<provider>/<model>" }` always wins over the file, and then login does not offer
314
+ one. If `config.json` cannot be used, the `auth_required` message says why.
315
+
291
316
  Open the agent panel and start a "nax-agent" thread.
292
- - **Modes:** `ask` (default) asks before each edit or command, `full` runs without asking, `read` is read-only, and `none` has no tools.
317
+ - **Modes:** the thread's mode picker (a session config option of category `mode`; `modes` and `session/set_mode` still work for other clients) switches between `ask` (default), which asks before each edit or command, `full`, which runs without asking, `read`, which is read-only, and `none`, which has no tools.
293
318
  - **Model:** switch it from the thread's model picker; the conversation is kept.
294
319
  - **Persistence:** threads are saved and can be reopened after a restart.
295
320
 
@@ -315,8 +340,33 @@ shows up at `sessions new` as an authentication-required error.
315
340
  Questions from the agent need a client with form elicitation. A client without it (acpx) gets a notice,
316
341
  and the agent is told to proceed on its best judgement.
317
342
 
343
+ ### MCP servers
344
+
345
+ Clients can pass MCP servers with `session/new`, `session/load` and `session/resume`
346
+ (Zed passes its context servers). nax-agent connects them and offers their tools to the
347
+ model as `<server>__<tool>`.
348
+
349
+ - **Transports:** stdio and streamable HTTP. SSE and ACP-tunnelled servers are skipped with a notice.
350
+ - **Approval:** `ask` asks before every MCP tool call ("Always allow" is remembered per tool
351
+ for the session); `full` runs them without asking; `read` and `none` do not offer them
352
+ (the servers stay connected, so switching back to `ask` or `full` brings the tools back).
353
+ - **Startup:** servers connect in parallel when the session opens, each within
354
+ `--mcp-connect-timeout` seconds (default 30; `NAX_AGENT_MCP_CONNECT_TIMEOUT`,
355
+ `agentServer.mcpConnectTimeoutSeconds`). A server that fails is skipped; the session
356
+ opens anyway and a notice names it, with the end of its stderr.
357
+ - **Limits:** 20 servers and 200 MCP tools per session. Tool schemas must be JSON objects of
358
+ type `object` within 32 KiB; a server whose schemas the model provider rejects can still
359
+ fail turns, so remove it.
360
+ - **Not saved:** MCP servers are never written to the session files; a reopened session
361
+ connects to the servers the client sends at that time. A server that exits mid-session is
362
+ reported once; reopen the session to reconnect it.
363
+ - **Large results:** the model sees at most 40 KB of a tool result; the full text is written
364
+ to the session's scratchpad.
365
+ - **Secrets:** values of env vars whose names contain `KEY`, `TOKEN`, `SECRET` or `PASSWORD`
366
+ (any case), every HTTP header value and an HTTP URL's password and query values are scrubbed
367
+ from notices and tool results. Values shorter than 8 characters are not scrubbed by value.
368
+
318
369
  ### Not supported yet
319
370
 
320
- - MCP servers sent by the client are ignored, with a notice.
321
371
  - No image or audio prompts.
322
372
  - No logout or provider management over ACP. Use `nax auth list` / `nax auth rm`.
@@ -20,6 +20,8 @@ export declare function providerOf(model: string): string | undefined;
20
20
  /** Terminal login methods (spec §6.3, M-33): loginable, non-override providers, in order. */
21
21
  export declare function terminalAuthMethods(input: {
22
22
  readonly models: readonly string[];
23
+ /** Providers named directly, after those of `models`. */
24
+ readonly providers?: readonly string[];
23
25
  readonly overridden: ReadonlySet<string>;
24
26
  readonly loginProviders: readonly string[];
25
27
  }): AcpAuthMethod[];
@@ -15,7 +15,8 @@ export function providerOf(model) {
15
15
  /** Terminal login methods (spec §6.3, M-33): loginable, non-override providers, in order. */
16
16
  export function terminalAuthMethods(input) {
17
17
  const loginable = new Set(input.loginProviders);
18
- const providers = [...new Set(input.models.map(providerOf).filter((p) => p !== undefined))].filter((p) => loginable.has(p) && !input.overridden.has(p));
18
+ const named = [...input.models.map(providerOf), ...(input.providers ?? [])];
19
+ const providers = [...new Set(named.filter((p) => p !== undefined))].filter((p) => loginable.has(p) && !input.overridden.has(p));
19
20
  return providers.map((p) => ({
20
21
  id: `${METHOD_PREFIX}${p}`,
21
22
  name: `Log in to ${p}`,
@@ -75,12 +76,11 @@ export async function loadServerAuth(input) {
75
76
  error: redactSecrets(messageOf(error)),
76
77
  });
77
78
  }
78
- const models = [
79
- ...options.tiers.map((t) => t.model),
80
- ...(options.defaultModel !== undefined ? [options.defaultModel] : []),
81
- ];
79
+ // No model configured: a first-time user has nothing to derive a provider from, so every one is offered (#2414).
80
+ const noModel = options.defaultModel === undefined;
81
+ const models = noModel ? [] : [...options.tiers.map((t) => t.model), options.defaultModel];
82
82
  return createServerAuth({
83
- methods: terminalAuthMethods({ models, overridden, loginProviders }),
83
+ methods: terminalAuthMethods({ models, providers: noModel ? loginProviders : [], overridden, loginProviders }),
84
84
  overridden,
85
85
  missing: (ids) => ports.providersWithoutCredentials(ids),
86
86
  });
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The `initialize` response (S5 spec §5.2). Each slice advertises a capability in
3
3
  * the same change that implements it (master plan Review Focus); S5-3 advertises
4
- * load, list, resume, close and delete.
4
+ * load, list, resume, close and delete; S5-5 advertises MCP http; stdio is always
5
+ * supported.
5
6
  */
6
7
  import { type AuthMethod, type InitializeResponse } from "@agentclientprotocol/sdk";
7
8
  export declare function initializeResponse(version: string, authMethods?: readonly AuthMethod[]): InitializeResponse;
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The `initialize` response (S5 spec §5.2). Each slice advertises a capability in
3
3
  * the same change that implements it (master plan Review Focus); S5-3 advertises
4
- * load, list, resume, close and delete.
4
+ * load, list, resume, close and delete; S5-5 advertises MCP http; stdio is always
5
+ * supported.
5
6
  */
6
7
  import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
7
8
  export function initializeResponse(version, authMethods = []) {
@@ -11,6 +12,7 @@ export function initializeResponse(version, authMethods = []) {
11
12
  loadSession: true,
12
13
  promptCapabilities: { image: false, audio: false, embeddedContext: true },
13
14
  sessionCapabilities: { list: {}, resume: {}, close: {}, delete: {} },
15
+ mcpCapabilities: { http: true, sse: false },
14
16
  },
15
17
  // S5-4 advertises terminal login methods to clients that declared `auth.terminal`.
16
18
  authMethods: [...authMethods],
@@ -5,6 +5,7 @@ export interface CliFlags {
5
5
  readonly model?: string;
6
6
  readonly mode?: string;
7
7
  readonly bashApproval?: string;
8
+ readonly mcpConnectTimeout?: string;
8
9
  }
9
10
  export type CliCommand = {
10
11
  readonly kind: "acp";
@@ -16,6 +16,7 @@ export const USAGE = [
16
16
  " --model <provider/model[effort]> default model for new sessions",
17
17
  " --mode <none|read|ask|full> default mode for new sessions (default ask)",
18
18
  " --bash-approval <gated|escalate|raw> default bash approval (default gated)",
19
+ " --mcp-connect-timeout <seconds> per-server MCP connect timeout, 1-300 (default 30)",
19
20
  " --method <api-key|oauth> login method (login only; default: ask)",
20
21
  " --version print the version",
21
22
  " --help print this help",
@@ -28,6 +29,7 @@ const OPTIONS = {
28
29
  model: { type: "string" },
29
30
  mode: { type: "string" },
30
31
  "bash-approval": { type: "string" },
32
+ "mcp-connect-timeout": { type: "string" },
31
33
  method: { type: "string" },
32
34
  version: { type: "boolean" },
33
35
  help: { type: "boolean" },
@@ -46,6 +48,7 @@ function flagsOf(values) {
46
48
  ...flag("model", values.model),
47
49
  ...flag("mode", values.mode),
48
50
  ...flag("bashApproval", values["bash-approval"]),
51
+ ...flag("mcpConnectTimeout", values["mcp-connect-timeout"]),
49
52
  };
50
53
  }
51
54
  function loginCommand(words, method, flags) {
@@ -0,0 +1,36 @@
1
+ import { type AuthInteraction, type ProviderModel } from "@nathapp/nax-agent";
2
+ import { type ReadTextFile } from "#src/server/nax-config";
3
+ export interface ModelPorts {
4
+ /** The provider's catalog models, sorted by id. */
5
+ listModels(provider: string): Promise<readonly ProviderModel[]>;
6
+ }
7
+ export declare const NAX_AGENT_MODELS: ModelPorts;
8
+ /**
9
+ * Writes `text` to `path`, creating the directory (0700) and, if absent, the file (0600).
10
+ * Atomic: a temp file in the same directory (flag "wx", the existing file's mode), synced,
11
+ * then renamed over the target. A symlinked config.json keeps its link: the target is replaced.
12
+ */
13
+ export type ConfigWriter = (path: string, text: string) => Promise<void>;
14
+ export declare const NODE_CONFIG_WRITER: ConfigWriter;
15
+ export type MergeResult = {
16
+ readonly ok: true;
17
+ readonly text: string;
18
+ } | {
19
+ readonly ok: false;
20
+ readonly reason: string;
21
+ };
22
+ /** `existing` (config.json text, or undefined when absent) with models.native.balanced set to `model`. */
23
+ export declare function mergeBalancedModel(existing: string | undefined, model: string): MergeResult;
24
+ export interface OfferInput {
25
+ readonly provider: string;
26
+ readonly configDir: string;
27
+ readonly isTTY: boolean;
28
+ /** A model is already chosen by --model or NAX_AGENT_MODEL. */
29
+ readonly pinned: boolean;
30
+ readonly interaction: AuthInteraction;
31
+ readonly out: (line: string) => void;
32
+ readonly models: ModelPorts;
33
+ readonly readFile: ReadTextFile;
34
+ readonly write: ConfigWriter;
35
+ }
36
+ export declare function offerDefaultModel(input: OfferInput): Promise<void>;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Login-first onboarding (#2414): after `nax-agent login <provider>`, when no
3
+ * default model is configured, offer to write `models.native.balanced` into the
4
+ * config dir's `config.json`. It merges into the existing document, creates the
5
+ * file 0600 when absent, and never touches the credentials file. A document it
6
+ * cannot merge into safely (malformed, or `models` of the wrong shape) is left
7
+ * unchanged and the one-line instruction is printed instead.
8
+ */
9
+ import { mkdir, open, realpath, rename, rm, stat } from "node:fs/promises";
10
+ import { dirname, join } from "node:path";
11
+ import { listProviderModels, PromptCancelledError, redactSecrets, } from "@nathapp/nax-agent";
12
+ import { messageOf } from "#src/server/errors";
13
+ import { loadNaxConfig } from "#src/server/nax-config";
14
+ export const NAX_AGENT_MODELS = { listModels: (provider) => listProviderModels(provider) };
15
+ function codeOf(error) {
16
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
17
+ ? error.code
18
+ : undefined;
19
+ }
20
+ async function existingTarget(path) {
21
+ try {
22
+ const target = await realpath(path);
23
+ return { target, mode: (await stat(target)).mode & 0o777 };
24
+ }
25
+ catch (error) {
26
+ if (codeOf(error) === "ENOENT")
27
+ return { target: path, mode: 0o600 };
28
+ throw error;
29
+ }
30
+ }
31
+ export const NODE_CONFIG_WRITER = async (path, text) => {
32
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
33
+ const { target, mode } = await existingTarget(path);
34
+ const temp = `${target}.${process.pid}.tmp`;
35
+ try {
36
+ const handle = await open(temp, "wx", mode);
37
+ try {
38
+ await handle.chmod(mode); // the umask must not narrow an existing file's mode
39
+ await handle.writeFile(text);
40
+ await handle.sync();
41
+ }
42
+ finally {
43
+ await handle.close();
44
+ }
45
+ await rename(temp, target);
46
+ }
47
+ catch (error) {
48
+ await rm(temp, { force: true });
49
+ throw error;
50
+ }
51
+ };
52
+ function isRecord(value) {
53
+ return typeof value === "object" && value !== null && !Array.isArray(value);
54
+ }
55
+ /** `existing` (config.json text, or undefined when absent) with models.native.balanced set to `model`. */
56
+ export function mergeBalancedModel(existing, model) {
57
+ let root = {};
58
+ if (existing !== undefined) {
59
+ try {
60
+ root = JSON.parse(existing);
61
+ }
62
+ catch {
63
+ return { ok: false, reason: "it is not valid JSON" };
64
+ }
65
+ }
66
+ if (!isRecord(root))
67
+ return { ok: false, reason: "it is not a JSON object" };
68
+ if (root.models !== undefined && !isRecord(root.models))
69
+ return { ok: false, reason: '"models" is not an object' };
70
+ const models = isRecord(root.models) ? root.models : {};
71
+ if (models.native !== undefined && !isRecord(models.native)) {
72
+ return { ok: false, reason: '"models.native" is not an object' };
73
+ }
74
+ const native = isRecord(models.native) ? models.native : {};
75
+ const merged = { ...root, models: { ...models, native: { ...native, balanced: model } } };
76
+ return { ok: true, text: `${JSON.stringify(merged, null, 2)}\n` };
77
+ }
78
+ const SKIP = "skip";
79
+ const MODEL_PREFIX = "model:";
80
+ function instruction(provider, path) {
81
+ return `No default model is set: set models.native.balanced to "${provider}/<model>" in ${path} (or NAX_AGENT_MODEL), then retry in your editor.`;
82
+ }
83
+ async function readExisting(path, readFile) {
84
+ try {
85
+ return await readFile(path, "utf8");
86
+ }
87
+ catch (error) {
88
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
89
+ return undefined;
90
+ throw error;
91
+ }
92
+ }
93
+ async function pickModel(input, models) {
94
+ if (models.length === 0)
95
+ return undefined;
96
+ try {
97
+ const answer = await input.interaction.prompt({
98
+ type: "select",
99
+ message: "Pick the default model for new threads (models.native.balanced)",
100
+ options: [
101
+ ...models.map((m) => ({
102
+ id: `${MODEL_PREFIX}${m.id}`,
103
+ label: m.id,
104
+ description: `${m.contextWindow} token window`,
105
+ })),
106
+ { id: SKIP, label: "Skip", description: "set models.native.balanced yourself" },
107
+ ],
108
+ });
109
+ return answer.startsWith(MODEL_PREFIX) ? `${input.provider}/${answer.slice(MODEL_PREFIX.length)}` : undefined;
110
+ }
111
+ catch (error) {
112
+ if (error instanceof PromptCancelledError)
113
+ return undefined;
114
+ throw error;
115
+ }
116
+ }
117
+ async function listModels(input) {
118
+ try {
119
+ return await input.models.listModels(input.provider);
120
+ }
121
+ catch (error) {
122
+ input.out(`Could not list ${input.provider} models: ${redactSecrets(messageOf(error))}`);
123
+ return [];
124
+ }
125
+ }
126
+ export async function offerDefaultModel(input) {
127
+ if (input.pinned)
128
+ return;
129
+ const path = join(input.configDir, "config.json");
130
+ const loaded = await loadNaxConfig(input.configDir, input.readFile);
131
+ if (loaded.warning === undefined && loaded.config.tiers.some((t) => t.tier === "balanced"))
132
+ return;
133
+ if (loaded.warning !== undefined) {
134
+ input.out(`${path} was left unchanged (${loaded.warning}).`);
135
+ input.out(instruction(input.provider, path));
136
+ return;
137
+ }
138
+ const based = await readExisting(path, input.readFile);
139
+ const model = input.isTTY ? await pickModel(input, await listModels(input)) : undefined;
140
+ if (model === undefined) {
141
+ input.out(instruction(input.provider, path));
142
+ return;
143
+ }
144
+ const merged = mergeBalancedModel(based, model);
145
+ if (!merged.ok) {
146
+ input.out(`${path} was left unchanged (${merged.reason}).`);
147
+ input.out(instruction(input.provider, path));
148
+ return;
149
+ }
150
+ // The pick can take a while; another writer may have changed the file meanwhile.
151
+ if ((await readExisting(path, input.readFile)) !== based) {
152
+ input.out(`${path} changed while picking; left unchanged.`);
153
+ input.out(instruction(input.provider, path));
154
+ return;
155
+ }
156
+ await input.write(path, merged.text);
157
+ input.out(`Set models.native.balanced to ${model} in ${path}. Retry in your editor.`);
158
+ }
@@ -11,6 +11,8 @@ export interface LoginDeps {
11
11
  readonly out: (line: string) => void;
12
12
  readonly err: (line: string) => void;
13
13
  readonly auth: Pick<AuthPorts, "runLogin" | "interaction">;
14
+ /** After a successful login: offers to set a default model (#2414). A failure here never fails the login. */
15
+ readonly offerModel?: (provider: string) => Promise<void>;
14
16
  }
15
17
  export declare function runLoginCommand(input: {
16
18
  readonly provider: string;
@@ -9,6 +9,14 @@ import { messageOf } from "#src/server/errors";
9
9
  function envName(provider) {
10
10
  return `${provider.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_API_KEY`;
11
11
  }
12
+ async function offerAfterLogin(provider, deps) {
13
+ try {
14
+ await deps.offerModel?.(provider);
15
+ }
16
+ catch (error) {
17
+ deps.err(`nax-agent: could not set a default model: ${redactSecrets(messageOf(error))}`);
18
+ }
19
+ }
12
20
  export async function runLoginCommand(input, deps) {
13
21
  if (!deps.isTTY) {
14
22
  deps.err(`nax-agent login needs an interactive terminal. Without one, set the provider's environment variable ` +
@@ -18,6 +26,7 @@ export async function runLoginCommand(input, deps) {
18
26
  try {
19
27
  const result = await deps.auth.runLogin(input.provider, deps.auth.interaction(deps.out), input.method);
20
28
  deps.out(`Signed in to ${result.providerId} (method: ${result.method}, credential: ${result.kind})`);
29
+ await offerAfterLogin(result.providerId, deps);
21
30
  return 0;
22
31
  }
23
32
  catch (error) {
@@ -1,5 +1,6 @@
1
1
  import type { Readable, Writable } from "node:stream";
2
2
  import { type AuthPorts } from "#src/server/auth";
3
+ import { type ConfigWriter, type ModelPorts } from "#src/server/default-model";
3
4
  import { type ReadTextFile } from "#src/server/nax-config";
4
5
  import { type Env } from "#src/server/options";
5
6
  export interface MainDeps {
@@ -15,5 +16,9 @@ export interface MainDeps {
15
16
  readonly isTTY: boolean;
16
17
  /** nax-agent's auth API; tests inject a fake. Defaults to the real one. */
17
18
  readonly auth?: AuthPorts;
19
+ /** The catalog behind the default-model pick after login; tests inject a fake. */
20
+ readonly models?: ModelPorts;
21
+ /** Writes config.json after login; tests inject a fake. */
22
+ readonly writeConfig?: ConfigWriter;
18
23
  }
19
24
  export declare function main(deps: MainDeps): Promise<number>;
@@ -4,12 +4,15 @@
4
4
  * 1 connection failure, 2 usage or option error.
5
5
  */
6
6
  import { randomUUID } from "node:crypto";
7
- import { configureCredentials, createFileTranscriptStore, setAgentLogger } from "@nathapp/nax-agent";
7
+ import { configureCredentials, createFileTranscriptStore, redactSecrets, setAgentLogger } from "@nathapp/nax-agent";
8
+ import { connectMcp } from "@nathapp/nax-agent/mcp";
8
9
  import { loadServerAuth, NAX_AGENT_AUTH } from "#src/server/auth";
9
10
  import { parseCli, USAGE } from "#src/server/cli";
10
11
  import { buildAgentApp, serveStdio } from "#src/server/connection";
12
+ import { NAX_AGENT_MODELS, NODE_CONFIG_WRITER, offerDefaultModel, } from "#src/server/default-model";
11
13
  import { stderrLogger } from "#src/server/logger";
12
14
  import { runLoginCommand } from "#src/server/login";
15
+ import { createMcpConnector } from "#src/server/mcp/connect";
13
16
  import { credentialsFor, loadNaxConfig } from "#src/server/nax-config";
14
17
  import { catalogOverridesFrom, nativeOpenSession } from "#src/server/open-session";
15
18
  import { resolveConfigDir, resolveServerOptions } from "#src/server/options";
@@ -41,11 +44,24 @@ async function login(command, deps) {
41
44
  setAgentLogger(stderrLogger(deps.env.NAX_AGENT_LOG === "debug" ? "debug" : "warn", deps.writeErr));
42
45
  const configDir = resolveConfigDir(command.flags, deps.env, deps.homedir);
43
46
  configureCredentials(credentialsFor(configDir, deps.readFile));
47
+ const auth = deps.auth ?? NAX_AGENT_AUTH;
48
+ const pinned = [command.flags.model, deps.env.NAX_AGENT_MODEL].some((m) => m !== undefined && m !== "");
44
49
  return runLoginCommand({ provider: command.provider, ...(command.method !== undefined ? { method: command.method } : {}) }, {
45
50
  isTTY: deps.isTTY,
46
51
  out: (line) => deps.stdout.write(`${line}\n`),
47
52
  err: (line) => deps.writeErr(`${line}\n`),
48
- auth: deps.auth ?? NAX_AGENT_AUTH,
53
+ auth,
54
+ offerModel: (provider) => offerDefaultModel({
55
+ provider,
56
+ configDir,
57
+ isTTY: deps.isTTY,
58
+ pinned,
59
+ interaction: auth.interaction((line) => deps.stdout.write(`${line}\n`)),
60
+ out: (line) => deps.stdout.write(`${line}\n`),
61
+ models: deps.models ?? NAX_AGENT_MODELS,
62
+ readFile: deps.readFile,
63
+ write: deps.writeConfig ?? NODE_CONFIG_WRITER,
64
+ }),
49
65
  });
50
66
  }
51
67
  async function serveAcp(flags, deps) {
@@ -81,6 +97,7 @@ async function serveAcp(flags, deps) {
81
97
  transcripts,
82
98
  catalogOverrides: overrides,
83
99
  turnTimeoutSeconds: TURN_TIMEOUT_SECONDS,
100
+ ...(resolved.options.compaction !== undefined ? { compaction: resolved.options.compaction } : {}),
84
101
  }),
85
102
  storage,
86
103
  transcripts,
@@ -90,6 +107,21 @@ async function serveAcp(flags, deps) {
90
107
  logger,
91
108
  turnTimeoutSeconds: TURN_TIMEOUT_SECONDS,
92
109
  ensureCredentials: (model) => auth.ensureCredentials(model),
110
+ reloadOptions: async () => {
111
+ const reloaded = await loadNaxConfig(configDir, deps.readFile);
112
+ const again = resolveServerOptions({ flags, env: deps.env, file: reloaded.config, configDir });
113
+ const problem = reloaded.warning ?? (again.ok ? undefined : again.message);
114
+ if (problem === undefined)
115
+ return again.ok ? { options: again.options } : {};
116
+ // Config paths and option names only, never file contents.
117
+ logger.warn("config", redactSecrets(problem));
118
+ return { ...(again.ok ? { options: again.options } : {}), problem: redactSecrets(problem) };
119
+ },
120
+ connectMcp: createMcpConnector({
121
+ connect: connectMcp,
122
+ timeoutMs: resolved.options.mcpConnectTimeoutSeconds * 1000,
123
+ clientVersion: packageVersion(),
124
+ }),
93
125
  });
94
126
  const connection = serveStdio(buildAgentApp({ version: packageVersion(), registry, logger, auth }), deps);
95
127
  const stop = () => connection.close();
@@ -97,13 +129,14 @@ async function serveAcp(flags, deps) {
97
129
  deps.stdin.once("end", stop);
98
130
  logger.info("server", "nax-agent ACP server started", { configDir, sessionsDir: resolved.options.sessionsDir });
99
131
  // Scalars only: catalog overrides can carry provider headers (API keys).
100
- const { defaultModel, defaultMode, bashApproval, tiers, catalogOverrides } = resolved.options;
132
+ const { defaultModel, defaultMode, bashApproval, tiers, catalogOverrides, mcpConnectTimeoutSeconds } = resolved.options;
101
133
  logger.debug("server", "resolved options", {
102
134
  defaultModel,
103
135
  defaultMode,
104
136
  bashApproval,
105
137
  tiers: tiers.map((t) => `${t.tier}=${t.model}`),
106
138
  catalogOverrides: catalogOverrides.length,
139
+ mcpConnectTimeoutSeconds,
107
140
  });
108
141
  try {
109
142
  await connection.closed;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Connects one ACP session's MCP servers (S5-5 spec §4.1, §5.1-§5.3): all in
3
+ * parallel through the shared layer, each bounded by the connect timeout; a
4
+ * failure skips that server with a scrubbed notice line (stderr tail included).
5
+ * Tools are taken server by server in list order up to MCP_MAX_TOOLS, shaped
6
+ * and named. If the signal aborts (shutdown), everything connected is closed.
7
+ */
8
+ import type { connectMcp, McpToolInfo } from "@nathapp/nax-agent/mcp";
9
+ import { type NamedTool, type ToolRef } from "#src/server/mcp/naming";
10
+ import { type ParsedServers } from "#src/server/mcp/parse";
11
+ import { type Scrub } from "#src/server/mcp/secrets";
12
+ import { type BridgedTool, type McpSessionTools } from "#src/server/mcp/session-tools";
13
+ export declare const MCP_MAX_TOOLS = 200;
14
+ export interface SessionMcp {
15
+ readonly tools: McpSessionTools;
16
+ readonly noticeLines: readonly string[];
17
+ readonly scrub: Scrub;
18
+ }
19
+ export interface ConnectSessionMcpInput {
20
+ readonly parsed: ParsedServers;
21
+ readonly cwd: string;
22
+ readonly signal: AbortSignal;
23
+ readonly onDisconnect: (server: string, reason: string) => void;
24
+ }
25
+ export type ConnectSessionMcp = (input: ConnectSessionMcpInput) => Promise<SessionMcp>;
26
+ export interface McpConnectorDeps {
27
+ readonly connect: typeof connectMcp;
28
+ readonly timeoutMs: number;
29
+ readonly clientVersion: string;
30
+ readonly closeGraceMs?: number;
31
+ }
32
+ export declare const connectNothing: ConnectSessionMcp;
33
+ export interface Candidate extends ToolRef {
34
+ readonly info: McpToolInfo;
35
+ }
36
+ /** Names a candidate into what the model sees; candidates without matching info are skipped. */
37
+ export declare function bridgeTools(candidates: readonly Candidate[], named: readonly NamedTool[]): BridgedTool[];
38
+ export declare function createMcpConnector(deps: McpConnectorDeps): ConnectSessionMcp;