@nathapp/nax-agent-acp 0.3.1 → 0.85.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 (83) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +135 -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 +47 -0
  10. package/dist/server/auth.js +87 -0
  11. package/dist/server/capabilities.d.ts +8 -0
  12. package/dist/server/capabilities.js +21 -0
  13. package/dist/server/cli.d.ts +27 -0
  14. package/dist/server/cli.js +90 -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/default-model.d.ts +36 -0
  20. package/dist/server/default-model.js +158 -0
  21. package/dist/server/errors.d.ts +21 -0
  22. package/dist/server/errors.js +70 -0
  23. package/dist/server/index.d.ts +4 -3
  24. package/dist/server/index.js +6 -1
  25. package/dist/server/logger.d.ts +7 -0
  26. package/dist/server/logger.js +25 -0
  27. package/dist/server/login.d.ts +20 -0
  28. package/dist/server/login.js +38 -0
  29. package/dist/server/main.d.ts +24 -0
  30. package/dist/server/main.js +152 -0
  31. package/dist/server/mcp/connect.d.ts +38 -0
  32. package/dist/server/mcp/connect.js +95 -0
  33. package/dist/server/mcp/naming.d.ts +12 -0
  34. package/dist/server/mcp/naming.js +43 -0
  35. package/dist/server/mcp/notices.d.ts +8 -0
  36. package/dist/server/mcp/notices.js +19 -0
  37. package/dist/server/mcp/parse.d.ts +24 -0
  38. package/dist/server/mcp/parse.js +107 -0
  39. package/dist/server/mcp/secrets.d.ts +4 -0
  40. package/dist/server/mcp/secrets.js +44 -0
  41. package/dist/server/mcp/session-tools.d.ts +37 -0
  42. package/dist/server/mcp/session-tools.js +70 -0
  43. package/dist/server/mcp/tool-shape.d.ts +19 -0
  44. package/dist/server/mcp/tool-shape.js +20 -0
  45. package/dist/server/nax-config.d.ts +31 -0
  46. package/dist/server/nax-config.js +139 -0
  47. package/dist/server/open-session.d.ts +38 -0
  48. package/dist/server/open-session.js +56 -0
  49. package/dist/server/options.d.ts +30 -0
  50. package/dist/server/options.js +72 -0
  51. package/dist/server/permissions.d.ts +44 -0
  52. package/dist/server/permissions.js +157 -0
  53. package/dist/server/process-entry.d.ts +15 -0
  54. package/dist/server/process-entry.js +28 -0
  55. package/dist/server/prompt.d.ts +8 -0
  56. package/dist/server/prompt.js +29 -0
  57. package/dist/server/questions.d.ts +33 -0
  58. package/dist/server/questions.js +90 -0
  59. package/dist/server/registry-open.d.ts +32 -0
  60. package/dist/server/registry-open.js +60 -0
  61. package/dist/server/registry.d.ts +79 -0
  62. package/dist/server/registry.js +333 -0
  63. package/dist/server/server-session.d.ts +45 -0
  64. package/dist/server/server-session.js +222 -0
  65. package/dist/server/session-config.d.ts +29 -0
  66. package/dist/server/session-config.js +104 -0
  67. package/dist/server/storage.d.ts +49 -0
  68. package/dist/server/storage.js +191 -0
  69. package/dist/server/translate/diff.d.ts +30 -0
  70. package/dist/server/translate/diff.js +81 -0
  71. package/dist/server/translate/events.d.ts +39 -0
  72. package/dist/server/translate/events.js +126 -0
  73. package/dist/server/translate/notice.d.ts +10 -0
  74. package/dist/server/translate/notice.js +14 -0
  75. package/dist/server/translate/replay.d.ts +11 -0
  76. package/dist/server/translate/replay.js +53 -0
  77. package/dist/server/translate/stop.d.ts +22 -0
  78. package/dist/server/translate/stop.js +48 -0
  79. package/dist/server/translate/tool-kind.d.ts +9 -0
  80. package/dist/server/translate/tool-kind.js +67 -0
  81. package/dist/server/version.d.ts +1 -0
  82. package/dist/server/version.js +17 -0
  83. package/package.json +5 -2
package/CHANGELOG.md CHANGED
@@ -3,6 +3,33 @@
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.0] - 2026-10-09
7
+
8
+ ### Added
9
+
10
+ - 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).
11
+ - 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.
12
+
13
+ ### Changed
14
+
15
+ - 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).
16
+
17
+ ## [0.84.0] - 2026-10-09
18
+
19
+ - 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).
20
+
21
+ ### Added
22
+
23
+ - `nax-agent` binary and the `./server` entry (`main`, `runCli`): an ACP server on stdio over nax-agent's native agent. It reads `~/.nax` (models, auth, optional `agentServer` block) and logs to stderr only (S5-0).
24
+ - Streamed text, thinking, tool calls with diffs, usage and compaction updates; transcript replay (S5-1).
25
+ - `session/new`, `session/prompt`, `session/cancel`; permission requests with per-session always-allow (keyed on command and subcommand); questions via form elicitation, or a canned answer for clients without it (S5-2).
26
+ - File-backed sessions: `session/load` (with replay), `resume`, `list`, `close`, `delete`, `set_mode`, `set_config_option` (model, bash approval). A model switch keeps the conversation (S5-3).
27
+ - `nax-agent login <provider>`, terminal `authMethods` for clients that declare `auth.terminal`, `authenticate`, and `auth_required` for missing or rejected credentials, checked before a session opens (S5-4).
28
+
29
+ ### Changed
30
+
31
+ - A model the agent does not offer verbatim still fails the open with `AGENT_SESSION_CAPABILITY_UNSUPPORTED`; the error now lists the model ids the agent does offer (message and `context.offered`, at most 50, cleaned like other agent text).
32
+
6
33
  ## [0.3.1] - 2026-10-07
7
34
 
8
35
  ### Added
package/README.md CHANGED
@@ -4,10 +4,9 @@ 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: pre-release (0.3.0, not yet published).** `acpBackend()` serves sessions
8
- under all four profiles, with thinking, tool and usage events, questions from the
9
- agent, embedder tools on Claude, resume across processes and reconnect after a
10
- crash. `./server` is reserved for a later ACP server.
7
+ **Status: 0.4.0.** `./client`: `acpBackend()` drives external ACP agents (Claude Code and others) as
8
+ nax-agent sessions. `./server` and the `nax-agent` binary: nax-agent's own native coding agent as an
9
+ ACP server for editors (Zed) and headless clients (acpx). See "The nax-agent ACP server" below.
11
10
 
12
11
  ```ts
13
12
  import { createAgentSession, createMemoryTranscriptStore } from "@nathapp/nax-agent";
@@ -238,3 +237,135 @@ and `read` forms are not offered, and one that arrives anyway is declined.
238
237
  and later fields are not asked. `answer()` on that question returns `"cancelled"`.
239
238
  - **Question text comes from the agent.** Control characters are stripped, your
240
239
  secrets scrubbed, and it is capped at 4 KiB.
240
+
241
+ ## The nax-agent ACP server
242
+
243
+ `nax-agent` is an ACP server on stdio. It runs nax-agent's native coding agent: tools run locally
244
+ under nax-agent's profiles and sandbox, and edits reach the editor as diffs.
245
+
246
+ ```sh
247
+ npm install -g @nathapp/nax-agent @nathapp/nax-agent-acp
248
+ nax-agent --version
249
+ ```
250
+
251
+ It reads `~/.nax/config.json`, the same file nax uses:
252
+ - `models.native.balanced` is the default model. `fast`, `balanced` and `powerful` are the models offered in the editor.
253
+ - `auth` controls where credentials come from.
254
+ - An optional `agentServer` block sets `defaultMode`, `bashApproval` and `sessionsDir`.
255
+
256
+ Flags (`--model`, `--mode`, `--bash-approval`, `--config-dir`, `--sessions-dir`) and `NAX_AGENT_<OPTION>`
257
+ environment variables override the file. Sessions are stored under `~/.nax/.agent-server/sessions/`.
258
+
259
+ ### Credentials
260
+
261
+ Log in once on a terminal. The credential lands in `~/.nax`, shared with `nax auth login`:
262
+
263
+ ```sh
264
+ nax-agent login anthropic # asks for a method; --method api-key|oauth to choose
265
+ ```
266
+
267
+ A provider's environment variable (for example `ANTHROPIC_API_KEY`) also works when nothing is stored.
268
+
269
+ Before opening a session, the server checks for a credential for the session model's provider. A missing
270
+ one fails the request with `auth_required` before anything is billed, and so does a rejected one during a
271
+ turn. Editors that support terminal auth then offer "Log in to <provider>", which runs
272
+ `nax-agent login <provider>` in a terminal.
273
+
274
+ ### Zed
275
+
276
+ In Zed's `settings.json` (`~/.config/zed/settings.json`; `zed: open settings` from the command palette):
277
+
278
+ ```json
279
+ {
280
+ "agent_servers": {
281
+ "nax-agent": {
282
+ "type": "custom",
283
+ "command": "nax-agent",
284
+ "args": ["acp"],
285
+ "env": {}
286
+ }
287
+ }
288
+ }
289
+ ```
290
+
291
+ Zed started from the Dock or Finder does not see your shell's `PATH`. If `node` comes from a version
292
+ manager such as nvm, `nax-agent` fails to start there (its script runs `#!/usr/bin/env node`). Use
293
+ absolute paths instead, from `which node` and the global install's `bin/nax-agent.js`:
294
+
295
+ ```json
296
+ "command": "/Users/you/.nvm/versions/node/v22.22.2/bin/node",
297
+ "args": ["/path/to/node_modules/@nathapp/nax-agent-acp/bin/nax-agent.js", "acp"]
298
+ ```
299
+
300
+ First run with an empty `~/.nax` (no model configured): the thread fails with `auth_required`, and Zed offers
301
+ "Log in to <provider>" for every provider that supports login. That runs `nax-agent login <provider>`; after
302
+ the credential is stored it lists the provider's catalog models and writes your pick as
303
+ `models.native.balanced` in `config.json` (in `--config-dir` / `NAX_AGENT_CONFIG_DIR` if set). The write is
304
+ atomic and keeps the file's mode (0600 for a new file; the credentials file is not touched). It re-serialises
305
+ `config.json` as 2-space JSON: every other key is kept, but any custom formatting is not. Without a terminal,
306
+ when `config.json` is malformed, or when it changed while you were picking, nothing is written and the command
307
+ prints the line to add.
308
+
309
+ Then retry in the editor. A server that started with no model re-reads `config.json` on the next new thread, so
310
+ no restart is needed. That retry re-reads only the model and tiers (`models.native`); changes to catalog
311
+ overrides, `auth` or `agentServer` need a restart. A model set with `--model` or
312
+ `"env": { "NAX_AGENT_MODEL": "<provider>/<model>" }` always wins over the file, and then login does not offer
313
+ one. If `config.json` cannot be used, the `auth_required` message says why.
314
+
315
+ Open the agent panel and start a "nax-agent" thread.
316
+ - **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.
317
+ - **Model:** switch it from the thread's model picker; the conversation is kept.
318
+ - **Persistence:** threads are saved and can be reopened after a restart.
319
+
320
+ ### acpx (headless)
321
+
322
+ Add an agent to `~/.acpx/config.json`:
323
+
324
+ ```json
325
+ { "agents": { "nax-agent": { "argv": ["nax-agent", "acp"] } } }
326
+ ```
327
+
328
+ ```sh
329
+ acpx nax-agent sessions new # once per directory: creates the session
330
+ acpx --approve-all nax-agent "add a test for parseCli" # prompts the session
331
+ acpx nax-agent "now run it" # continues the same session
332
+ acpx nax-agent sessions # list sessions
333
+ acpx nax-agent exec "what does this repo do" # one-shot, no saved session
334
+ ```
335
+
336
+ acpx refuses a prompt until `sessions new` has created a session for the directory. A missing credential
337
+ shows up at `sessions new` as an authentication-required error.
338
+
339
+ Questions from the agent need a client with form elicitation. A client without it (acpx) gets a notice,
340
+ and the agent is told to proceed on its best judgement.
341
+
342
+ ### MCP servers
343
+
344
+ Clients can pass MCP servers with `session/new`, `session/load` and `session/resume`
345
+ (Zed passes its context servers). nax-agent connects them and offers their tools to the
346
+ model as `<server>__<tool>`.
347
+
348
+ - **Transports:** stdio and streamable HTTP. SSE and ACP-tunnelled servers are skipped with a notice.
349
+ - **Approval:** `ask` asks before every MCP tool call ("Always allow" is remembered per tool
350
+ for the session); `full` runs them without asking; `read` and `none` do not offer them
351
+ (the servers stay connected, so switching back to `ask` or `full` brings the tools back).
352
+ - **Startup:** servers connect in parallel when the session opens, each within
353
+ `--mcp-connect-timeout` seconds (default 30; `NAX_AGENT_MCP_CONNECT_TIMEOUT`,
354
+ `agentServer.mcpConnectTimeoutSeconds`). A server that fails is skipped; the session
355
+ opens anyway and a notice names it, with the end of its stderr.
356
+ - **Limits:** 20 servers and 200 MCP tools per session. Tool schemas must be JSON objects of
357
+ type `object` within 32 KiB; a server whose schemas the model provider rejects can still
358
+ fail turns, so remove it.
359
+ - **Not saved:** MCP servers are never written to the session files; a reopened session
360
+ connects to the servers the client sends at that time. A server that exits mid-session is
361
+ reported once; reopen the session to reconnect it.
362
+ - **Large results:** the model sees at most 40 KB of a tool result; the full text is written
363
+ to the session's scratchpad.
364
+ - **Secrets:** values of env vars whose names contain `KEY`, `TOKEN`, `SECRET` or `PASSWORD`
365
+ (any case), every HTTP header value and an HTTP URL's password and query values are scrubbed
366
+ from notices and tool results. Values shorter than 8 characters are not scrubbed by value.
367
+
368
+ ### Not supported yet
369
+
370
+ - No image or audio prompts.
371
+ - No logout or provider management over ACP. Use `nax auth list` / `nax auth rm`.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from "../dist/server/index.js";
3
+
4
+ process.exitCode = await runCli(process);
@@ -12,8 +12,10 @@
12
12
  * companion (Claude's AskUserQuestion "Other" box): not asked on its own; a reply
13
13
  * naming no choice becomes its value. Any other field type, a malformed or oversized
14
14
  * choice list, too many fields, or a non-form request declines the form unasked;
15
- * a reply naming no choice without a companion, or an empty reply to a required
16
- * field, declines after asking. Each decline is noted with noteQuestion. No reply
15
+ * a reply naming no choice without a companion, a reply naming no choice to a
16
+ * REQUIRED select (its companion only adds to a choice — filling it alone would
17
+ * omit the required key), or an empty reply to a required field, declines after
18
+ * asking. Each decline is noted with noteQuestion. No reply
17
19
  * (deadline, cancel, turn end, process exit) cancels. Question text is agent data:
18
20
  * control and invisible characters stripped, secrets scrubbed, capped.
19
21
  */
@@ -90,8 +90,21 @@ function parseForm(request) {
90
90
  ? { ok: true, fields: withCompanions(fields) }
91
91
  : REFUSED;
92
92
  }
93
+ /**
94
+ * The companion offer, only where a typed answer would be accepted: a required
95
+ * select must name a choice (filling only `<key>_custom` would omit the required
96
+ * key), so a required single-select gets no offer and a required multi-select
97
+ * gets one only beside a choice.
98
+ */
99
+ function ownAnswerHint(field) {
100
+ if (field.companion === undefined)
101
+ return "";
102
+ if (!field.required)
103
+ return ", or type your own answer";
104
+ return field.kind === "multi" ? "; you may add your own after at least one choice" : "";
105
+ }
93
106
  function instruction(field) {
94
- const own = field.companion === undefined ? "" : ", or type your own answer";
107
+ const own = ownAnswerHint(field);
95
108
  const skip = field.required ? "" : " Leave empty to skip.";
96
109
  if (field.kind === "single")
97
110
  return `Reply with one number or choice${own}.${skip}`;
@@ -17,7 +17,7 @@ export declare const ACP_STOP_CODES: Readonly<{
17
17
  export type AcpStopCode = (typeof ACP_STOP_CODES)[keyof typeof ACP_STOP_CODES];
18
18
  /** Agent text made safe for an error: control characters stripped (except \n, \t), secrets redacted, capped. */
19
19
  export declare function agentTextExcerpt(text: string, secrets: readonly string[]): string;
20
- export declare function capabilityUnsupported(capability: string, reason: string): AgentSessionError;
20
+ export declare function capabilityUnsupported(capability: string, reason: string, details?: Readonly<Record<string, unknown>>): AgentSessionError;
21
21
  export declare function backendUnavailable(reason: string, details?: Readonly<Record<string, unknown>>): AgentSessionError;
22
22
  export declare function closedDuringOpen(sessionId: string): AgentSessionError;
23
23
  /** The session cannot run another turn: closed, or its agent is gone and cannot be reconnected (§6.3 step 5). */
@@ -30,8 +30,8 @@ export const ACP_STOP_CODES = Object.freeze({
30
30
  export function agentTextExcerpt(text, secrets) {
31
31
  return capBytes(redactSecrets(scrubSecrets(stripControl(text), secrets)), EXCERPT_BYTES);
32
32
  }
33
- export function capabilityUnsupported(capability, reason) {
34
- return new AgentSessionError(`The ACP agent cannot meet the "${capability}" requirement: ${reason}`, "AGENT_SESSION_CAPABILITY_UNSUPPORTED", { capability });
33
+ export function capabilityUnsupported(capability, reason, details = {}) {
34
+ return new AgentSessionError(`The ACP agent cannot meet the "${capability}" requirement: ${reason}`, "AGENT_SESSION_CAPABILITY_UNSUPPORTED", { ...details, capability });
35
35
  }
36
36
  export function backendUnavailable(reason, details = {}) {
37
37
  return new AgentSessionError(`The ACP agent is unavailable: ${reason}`, "AGENT_SESSION_BACKEND_UNAVAILABLE", {
@@ -13,13 +13,14 @@
13
13
  */
14
14
  import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
15
15
  import { getLogger, NaxError, } from "@nathapp/nax-agent";
16
- import { buildCapabilityRecord, effortOptionId, modeFor, modelOptionId, offersValue, readOnlyFor, unmetRequirement, } from "#src/client/capabilities";
16
+ import { buildCapabilityRecord, effortOptionId, modeFor, modelOptionId, offersValue, readOnlyFor, selectValues, unmetRequirement, } from "#src/client/capabilities";
17
17
  import { openConnection } from "#src/client/connection";
18
18
  import { backendUnavailable, capabilityUnsupported, closedDuringOpen, EXCERPT_BYTES, openRequestError, rpcErrorOf, } from "#src/client/errors";
19
19
  import { agentGoneError, pickCandidate } from "#src/client/launch";
20
20
  import { claudeSessionMeta } from "#src/client/pre-approval";
21
21
  import { race } from "#src/client/race";
22
22
  import { isUsableSessionId, restoreSession, } from "#src/client/resume";
23
+ import { cleanLabel } from "#src/client/text";
23
24
  function chooseLaunch(options) {
24
25
  if (options.launch.kind === "explicit")
25
26
  return options.launch.candidate;
@@ -162,13 +163,26 @@ async function applyMode(o, sessionId, offered) {
162
163
  const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }));
163
164
  return set.configOptions ?? offered;
164
165
  }
166
+ /** At most this many offered ids, each cleaned and capped, go into a model refusal (agent-supplied text). */
167
+ const MAX_OFFERED_MODELS = 50;
168
+ const MAX_MODEL_ID_CHARS = 100;
169
+ function offeredModels(offered, secrets) {
170
+ return offered
171
+ .filter((option) => option.category === "model")
172
+ .flatMap((option) => selectValues(option))
173
+ .slice(0, MAX_OFFERED_MODELS)
174
+ .map((id) => cleanLabel(id, secrets, MAX_MODEL_ID_CHARS) ?? "")
175
+ .filter((id) => id !== "");
176
+ }
165
177
  async function applyModel(o, sessionId, offered) {
166
178
  const model = o.options.model;
167
179
  if (model === undefined)
168
180
  return offered;
169
181
  const configId = modelOptionId(offered, model);
170
- if (configId === undefined)
171
- throw capabilityUnsupported("model", `the agent offers no model option "${model}"`);
182
+ if (configId === undefined) {
183
+ const ids = offeredModels(offered, o.options.secrets);
184
+ throw capabilityUnsupported("model", `the agent offers no model option "${model}"; offered: ${ids.length === 0 ? "(none)" : ids.join(", ")}`, { offered: ids });
185
+ }
172
186
  const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
173
187
  return set.configOptions ?? offered;
174
188
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Credentials for the ACP server (S5 spec §6.3, S5-4): the nax-agent auth API
3
+ * behind one port, so the server and `login` are testable without a store.
4
+ */
5
+ import type { AuthMethod as AcpAuthMethod, AuthenticateResponse } from "@agentclientprotocol/sdk";
6
+ import { type AgentLogger, type AuthInteraction, type AuthMethod, type AuthResult, type NativeCatalogOverrides } from "@nathapp/nax-agent";
7
+ import type { ServerOptions } from "#src/server/options";
8
+ export interface AuthPorts {
9
+ /** Providers `runLogin` can serve (M-33). */
10
+ loginProviderIds(): Promise<readonly string[]>;
11
+ /** Of these providers, those with neither a stored nor an ambient credential (M-29). */
12
+ providersWithoutCredentials(providerIds: readonly string[]): Promise<readonly string[]>;
13
+ runLogin(providerId: string, interaction: AuthInteraction, method?: AuthMethod): Promise<AuthResult>;
14
+ /** The terminal login UI, writing its lines through `log`. */
15
+ interaction(log: (line: string) => void): AuthInteraction;
16
+ }
17
+ export declare const NAX_AGENT_AUTH: AuthPorts;
18
+ /** The provider prefix of a native model id, or undefined when it has none (never guessed). */
19
+ export declare function providerOf(model: string): string | undefined;
20
+ /** Terminal login methods (spec §6.3, M-33): loginable, non-override providers, in order. */
21
+ export declare function terminalAuthMethods(input: {
22
+ readonly models: readonly string[];
23
+ /** Providers named directly, after those of `models`. */
24
+ readonly providers?: readonly string[];
25
+ readonly overridden: ReadonlySet<string>;
26
+ readonly loginProviders: readonly string[];
27
+ }): AcpAuthMethod[];
28
+ export interface ServerAuth {
29
+ readonly methods: readonly AcpAuthMethod[];
30
+ /** Spec §6.3, M-29/M-31. */
31
+ authenticate(methodId: string): Promise<AuthenticateResponse>;
32
+ /** M-30: throws auth_required when the model's provider has no credential. */
33
+ ensureCredentials(model: string): Promise<void>;
34
+ }
35
+ export declare function createServerAuth(deps: {
36
+ readonly methods: readonly AcpAuthMethod[];
37
+ readonly overridden: ReadonlySet<string>;
38
+ readonly missing: AuthPorts["providersWithoutCredentials"];
39
+ }): ServerAuth;
40
+ /** No login methods and no checks: the default for an app built without auth. */
41
+ export declare const NO_SERVER_AUTH: ServerAuth;
42
+ export declare function loadServerAuth(input: {
43
+ readonly options: ServerOptions;
44
+ readonly overrides: NativeCatalogOverrides;
45
+ readonly ports: AuthPorts;
46
+ readonly logger: AgentLogger;
47
+ }): Promise<ServerAuth>;
@@ -0,0 +1,87 @@
1
+ import { createTerminalAuthInteraction, loginProviderIds, NaxError, providersWithoutCredentials, redactSecrets, runLogin, } from "@nathapp/nax-agent";
2
+ import { authRequired, invalidParams, isAuthFailureCode, messageOf } from "#src/server/errors";
3
+ export const NAX_AGENT_AUTH = {
4
+ loginProviderIds,
5
+ providersWithoutCredentials,
6
+ runLogin,
7
+ interaction: (log) => createTerminalAuthInteraction({ log }),
8
+ };
9
+ const METHOD_PREFIX = "login-";
10
+ /** The provider prefix of a native model id, or undefined when it has none (never guessed). */
11
+ export function providerOf(model) {
12
+ const slash = model.indexOf("/");
13
+ return slash > 0 ? model.slice(0, slash) : undefined;
14
+ }
15
+ /** Terminal login methods (spec §6.3, M-33): loginable, non-override providers, in order. */
16
+ export function terminalAuthMethods(input) {
17
+ const loginable = new Set(input.loginProviders);
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));
20
+ return providers.map((p) => ({
21
+ id: `${METHOD_PREFIX}${p}`,
22
+ name: `Log in to ${p}`,
23
+ type: "terminal",
24
+ args: ["login", p],
25
+ }));
26
+ }
27
+ export function createServerAuth(deps) {
28
+ const check = async (provider) => {
29
+ let missing;
30
+ try {
31
+ missing = await deps.missing([provider]);
32
+ }
33
+ catch (error) {
34
+ if (error instanceof NaxError && isAuthFailureCode(error.code)) {
35
+ throw authRequired(redactSecrets(error.message), { provider, code: error.code });
36
+ }
37
+ throw error;
38
+ }
39
+ if (missing.includes(provider))
40
+ throw authRequired(`no credentials for provider "${provider}"`, { provider });
41
+ };
42
+ return {
43
+ methods: deps.methods,
44
+ async authenticate(methodId) {
45
+ const method = deps.methods.find((m) => m.id === methodId);
46
+ if (method === undefined) {
47
+ const ids = deps.methods.map((m) => m.id).join(", ");
48
+ throw invalidParams(`unknown auth method "${methodId}"; expected one of: ${ids === "" ? "(none)" : ids}`);
49
+ }
50
+ await check(methodId.slice(METHOD_PREFIX.length));
51
+ return {};
52
+ },
53
+ async ensureCredentials(model) {
54
+ const provider = providerOf(model);
55
+ if (provider === undefined || deps.overridden.has(provider))
56
+ return;
57
+ await check(provider);
58
+ },
59
+ };
60
+ }
61
+ /** No login methods and no checks: the default for an app built without auth. */
62
+ export const NO_SERVER_AUTH = createServerAuth({
63
+ methods: [],
64
+ overridden: new Set(),
65
+ missing: async () => [],
66
+ });
67
+ export async function loadServerAuth(input) {
68
+ const { options, ports, logger } = input;
69
+ const overridden = new Set(input.overrides.map((o) => o.provider));
70
+ let loginProviders = [];
71
+ try {
72
+ loginProviders = await ports.loginProviderIds();
73
+ }
74
+ catch (error) {
75
+ logger.warn("auth", "could not list login providers; no login methods advertised", {
76
+ error: redactSecrets(messageOf(error)),
77
+ });
78
+ }
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
+ return createServerAuth({
83
+ methods: terminalAuthMethods({ models, providers: noModel ? loginProviders : [], overridden, loginProviders }),
84
+ overridden,
85
+ missing: (ids) => ports.providersWithoutCredentials(ids),
86
+ });
87
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The `initialize` response (S5 spec §5.2). Each slice advertises a capability in
3
+ * the same change that implements it (master plan Review Focus); S5-3 advertises
4
+ * load, list, resume, close and delete; S5-5 advertises MCP http; stdio is always
5
+ * supported.
6
+ */
7
+ import { type AuthMethod, type InitializeResponse } from "@agentclientprotocol/sdk";
8
+ export declare function initializeResponse(version: string, authMethods?: readonly AuthMethod[]): InitializeResponse;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The `initialize` response (S5 spec §5.2). Each slice advertises a capability in
3
+ * the same change that implements it (master plan Review Focus); S5-3 advertises
4
+ * load, list, resume, close and delete; S5-5 advertises MCP http; stdio is always
5
+ * supported.
6
+ */
7
+ import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
8
+ export function initializeResponse(version, authMethods = []) {
9
+ return {
10
+ protocolVersion: PROTOCOL_VERSION,
11
+ agentCapabilities: {
12
+ loadSession: true,
13
+ promptCapabilities: { image: false, audio: false, embeddedContext: true },
14
+ sessionCapabilities: { list: {}, resume: {}, close: {}, delete: {} },
15
+ mcpCapabilities: { http: true, sse: false },
16
+ },
17
+ // S5-4 advertises terminal login methods to clients that declared `auth.terminal`.
18
+ authMethods: [...authMethods],
19
+ agentInfo: { name: "nax-agent", title: "nax-agent", version },
20
+ };
21
+ }
@@ -0,0 +1,27 @@
1
+ import type { AuthMethod } from "@nathapp/nax-agent";
2
+ export interface CliFlags {
3
+ readonly configDir?: string;
4
+ readonly sessionsDir?: string;
5
+ readonly model?: string;
6
+ readonly mode?: string;
7
+ readonly bashApproval?: string;
8
+ readonly mcpConnectTimeout?: string;
9
+ }
10
+ export type CliCommand = {
11
+ readonly kind: "acp";
12
+ readonly flags: CliFlags;
13
+ } | {
14
+ readonly kind: "login";
15
+ readonly provider: string;
16
+ readonly method?: AuthMethod;
17
+ readonly flags: CliFlags;
18
+ } | {
19
+ readonly kind: "version";
20
+ } | {
21
+ readonly kind: "help";
22
+ } | {
23
+ readonly kind: "usage-error";
24
+ readonly message: string;
25
+ };
26
+ export declare const USAGE: string;
27
+ export declare function parseCli(argv: readonly string[]): CliCommand;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The `nax-agent` command line (S5 spec §6.1). S5-0 knows the ACP server only;
3
+ * `login <provider>` (S5-4).
4
+ */
5
+ import { parseArgs } from "node:util";
6
+ export const USAGE = [
7
+ "Usage: nax-agent [acp] [options]",
8
+ " nax-agent login <provider> [--method api-key|oauth] [--config-dir <dir>]",
9
+ "",
10
+ "Runs the nax-agent ACP server on stdio, or logs in to a model provider",
11
+ "(the credential is stored in <config-dir>, shared with `nax auth login`).",
12
+ "",
13
+ "Options:",
14
+ " --config-dir <dir> nax config directory (default ~/.nax)",
15
+ " --sessions-dir <dir> session storage (default <config-dir>/.agent-server/sessions)",
16
+ " --model <provider/model[effort]> default model for new sessions",
17
+ " --mode <none|read|ask|full> default mode for new sessions (default ask)",
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)",
20
+ " --method <api-key|oauth> login method (login only; default: ask)",
21
+ " --version print the version",
22
+ " --help print this help",
23
+ "",
24
+ "Each option can also be set as NAX_AGENT_<OPTION>, for example NAX_AGENT_MODEL.",
25
+ ].join("\n");
26
+ const OPTIONS = {
27
+ "config-dir": { type: "string" },
28
+ "sessions-dir": { type: "string" },
29
+ model: { type: "string" },
30
+ mode: { type: "string" },
31
+ "bash-approval": { type: "string" },
32
+ "mcp-connect-timeout": { type: "string" },
33
+ method: { type: "string" },
34
+ version: { type: "boolean" },
35
+ help: { type: "boolean" },
36
+ };
37
+ function flag(key, value) {
38
+ return (value === undefined ? {} : { [key]: value });
39
+ }
40
+ function parse(argv) {
41
+ return parseArgs({ args: [...argv], options: OPTIONS, allowPositionals: true, strict: true });
42
+ }
43
+ const LOGIN_METHODS = ["api-key", "oauth"];
44
+ function flagsOf(values) {
45
+ return {
46
+ ...flag("configDir", values["config-dir"]),
47
+ ...flag("sessionsDir", values["sessions-dir"]),
48
+ ...flag("model", values.model),
49
+ ...flag("mode", values.mode),
50
+ ...flag("bashApproval", values["bash-approval"]),
51
+ ...flag("mcpConnectTimeout", values["mcp-connect-timeout"]),
52
+ };
53
+ }
54
+ function loginCommand(words, method, flags) {
55
+ const [, provider, ...extra] = words;
56
+ if (provider === undefined || extra.length > 0) {
57
+ return { kind: "usage-error", message: "login takes one provider: nax-agent login <provider>" };
58
+ }
59
+ if (method === undefined)
60
+ return { kind: "login", provider, flags };
61
+ const known = LOGIN_METHODS.find((m) => m === method);
62
+ if (known === undefined) {
63
+ return { kind: "usage-error", message: `invalid --method "${method}"; expected api-key or oauth` };
64
+ }
65
+ return { kind: "login", provider, method: known, flags };
66
+ }
67
+ export function parseCli(argv) {
68
+ let parsed;
69
+ try {
70
+ parsed = parse(argv);
71
+ }
72
+ catch (error) {
73
+ return { kind: "usage-error", message: error instanceof Error ? error.message : String(error) };
74
+ }
75
+ const { values, positionals } = parsed;
76
+ if (values.help === true)
77
+ return { kind: "help" };
78
+ if (values.version === true)
79
+ return { kind: "version" };
80
+ const flags = flagsOf(values);
81
+ // An editor's terminal login appends `login <provider>` to the server invocation (M-34).
82
+ const words = positionals[0] === "acp" ? positionals.slice(1) : positionals;
83
+ if (words[0] === "login")
84
+ return loginCommand(words, values.method, flags);
85
+ if (words.length > 0)
86
+ return { kind: "usage-error", message: `unknown command: ${positionals.join(" ")}` };
87
+ if (values.method !== undefined)
88
+ return { kind: "usage-error", message: "--method is only valid with login" };
89
+ return { kind: "acp", flags };
90
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * What a server session needs from its client (S5 spec §4.3): session updates,
3
+ * permission requests and form elicitations, plus the optional features the
4
+ * client declared in `initialize`. Sessions and brokers depend on this port,
5
+ * not on the SDK connection.
6
+ */
7
+ import type { AgentContext, ClientCapabilities, CreateElicitationResponse, ElicitationSchema, PermissionOption, RequestPermissionResponse, SessionUpdate, ToolCallUpdate } from "@agentclientprotocol/sdk";
8
+ import type { ClientUpdates } from "#src/server/translate/events";
9
+ export interface ClientFeatures {
10
+ readonly updates: ClientUpdates;
11
+ /** The client declared form elicitation (`clientCapabilities.elicitation.form`). */
12
+ readonly elicitation: boolean;
13
+ /** The client runs terminal auth methods (`clientCapabilities.auth.terminal: true`, S5-4). */
14
+ readonly terminalAuth: boolean;
15
+ }
16
+ export declare const NO_CLIENT_FEATURES: ClientFeatures;
17
+ export declare function clientFeatures(caps: ClientCapabilities | undefined): ClientFeatures;
18
+ export interface PermissionAsk {
19
+ readonly toolCall: ToolCallUpdate;
20
+ readonly options: readonly PermissionOption[];
21
+ }
22
+ export interface ElicitationForm {
23
+ readonly message: string;
24
+ readonly requestedSchema: ElicitationSchema;
25
+ }
26
+ export interface ClientPort {
27
+ readonly features: ClientFeatures;
28
+ update(update: SessionUpdate): Promise<void>;
29
+ /** Aborting `signal` sends `$/cancel_request`; callers stop waiting with `untilAborted`. */
30
+ requestPermission(ask: PermissionAsk, signal: AbortSignal): Promise<RequestPermissionResponse>;
31
+ elicit(form: ElicitationForm, signal: AbortSignal): Promise<CreateElicitationResponse>;
32
+ }
33
+ export declare function clientPort(context: AgentContext, sessionId: string, features: ClientFeatures): ClientPort;
34
+ /**
35
+ * The work's result, or a rejection as soon as `signal` aborts. SDK cancellation
36
+ * is cooperative (the request promise waits for the peer), so a client that never
37
+ * answers would otherwise hold the turn.
38
+ */
39
+ export declare function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T>;