@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
package/CHANGELOG.md CHANGED
@@ -3,6 +3,22 @@
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.84.0] - 2026-10-09
7
+
8
+ - 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).
9
+
10
+ ### Added
11
+
12
+ - `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).
13
+ - Streamed text, thinking, tool calls with diffs, usage and compaction updates; transcript replay (S5-1).
14
+ - `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).
15
+ - 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).
16
+ - `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).
17
+
18
+ ### Changed
19
+
20
+ - 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).
21
+
6
22
  ## [0.3.1] - 2026-10-07
7
23
 
8
24
  ### 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,86 @@ 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`:
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
+ 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.
293
+ - **Model:** switch it from the thread's model picker; the conversation is kept.
294
+ - **Persistence:** threads are saved and can be reopened after a restart.
295
+
296
+ ### acpx (headless)
297
+
298
+ Add an agent to `~/.acpx/config.json`:
299
+
300
+ ```json
301
+ { "agents": { "nax-agent": { "argv": ["nax-agent", "acp"] } } }
302
+ ```
303
+
304
+ ```sh
305
+ acpx nax-agent sessions new # once per directory: creates the session
306
+ acpx --approve-all nax-agent "add a test for parseCli" # prompts the session
307
+ acpx nax-agent "now run it" # continues the same session
308
+ acpx nax-agent sessions # list sessions
309
+ acpx nax-agent exec "what does this repo do" # one-shot, no saved session
310
+ ```
311
+
312
+ acpx refuses a prompt until `sessions new` has created a session for the directory. A missing credential
313
+ shows up at `sessions new` as an authentication-required error.
314
+
315
+ Questions from the agent need a client with form elicitation. A client without it (acpx) gets a notice,
316
+ and the agent is told to proceed on its best judgement.
317
+
318
+ ### Not supported yet
319
+
320
+ - MCP servers sent by the client are ignored, with a notice.
321
+ - No image or audio prompts.
322
+ - 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,45 @@
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
+ readonly overridden: ReadonlySet<string>;
24
+ readonly loginProviders: readonly string[];
25
+ }): AcpAuthMethod[];
26
+ export interface ServerAuth {
27
+ readonly methods: readonly AcpAuthMethod[];
28
+ /** Spec §6.3, M-29/M-31. */
29
+ authenticate(methodId: string): Promise<AuthenticateResponse>;
30
+ /** M-30: throws auth_required when the model's provider has no credential. */
31
+ ensureCredentials(model: string): Promise<void>;
32
+ }
33
+ export declare function createServerAuth(deps: {
34
+ readonly methods: readonly AcpAuthMethod[];
35
+ readonly overridden: ReadonlySet<string>;
36
+ readonly missing: AuthPorts["providersWithoutCredentials"];
37
+ }): ServerAuth;
38
+ /** No login methods and no checks: the default for an app built without auth. */
39
+ export declare const NO_SERVER_AUTH: ServerAuth;
40
+ export declare function loadServerAuth(input: {
41
+ readonly options: ServerOptions;
42
+ readonly overrides: NativeCatalogOverrides;
43
+ readonly ports: AuthPorts;
44
+ readonly logger: AgentLogger;
45
+ }): 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 providers = [...new Set(input.models.map(providerOf).filter((p) => p !== undefined))].filter((p) => loginable.has(p) && !input.overridden.has(p));
19
+ return providers.map((p) => ({
20
+ id: `${METHOD_PREFIX}${p}`,
21
+ name: `Log in to ${p}`,
22
+ type: "terminal",
23
+ args: ["login", p],
24
+ }));
25
+ }
26
+ export function createServerAuth(deps) {
27
+ const check = async (provider) => {
28
+ let missing;
29
+ try {
30
+ missing = await deps.missing([provider]);
31
+ }
32
+ catch (error) {
33
+ if (error instanceof NaxError && isAuthFailureCode(error.code)) {
34
+ throw authRequired(redactSecrets(error.message), { provider, code: error.code });
35
+ }
36
+ throw error;
37
+ }
38
+ if (missing.includes(provider))
39
+ throw authRequired(`no credentials for provider "${provider}"`, { provider });
40
+ };
41
+ return {
42
+ methods: deps.methods,
43
+ async authenticate(methodId) {
44
+ const method = deps.methods.find((m) => m.id === methodId);
45
+ if (method === undefined) {
46
+ const ids = deps.methods.map((m) => m.id).join(", ");
47
+ throw invalidParams(`unknown auth method "${methodId}"; expected one of: ${ids === "" ? "(none)" : ids}`);
48
+ }
49
+ await check(methodId.slice(METHOD_PREFIX.length));
50
+ return {};
51
+ },
52
+ async ensureCredentials(model) {
53
+ const provider = providerOf(model);
54
+ if (provider === undefined || deps.overridden.has(provider))
55
+ return;
56
+ await check(provider);
57
+ },
58
+ };
59
+ }
60
+ /** No login methods and no checks: the default for an app built without auth. */
61
+ export const NO_SERVER_AUTH = createServerAuth({
62
+ methods: [],
63
+ overridden: new Set(),
64
+ missing: async () => [],
65
+ });
66
+ export async function loadServerAuth(input) {
67
+ const { options, ports, logger } = input;
68
+ const overridden = new Set(input.overrides.map((o) => o.provider));
69
+ let loginProviders = [];
70
+ try {
71
+ loginProviders = await ports.loginProviderIds();
72
+ }
73
+ catch (error) {
74
+ logger.warn("auth", "could not list login providers; no login methods advertised", {
75
+ error: redactSecrets(messageOf(error)),
76
+ });
77
+ }
78
+ const models = [
79
+ ...options.tiers.map((t) => t.model),
80
+ ...(options.defaultModel !== undefined ? [options.defaultModel] : []),
81
+ ];
82
+ return createServerAuth({
83
+ methods: terminalAuthMethods({ models, overridden, loginProviders }),
84
+ overridden,
85
+ missing: (ids) => ports.providersWithoutCredentials(ids),
86
+ });
87
+ }
@@ -0,0 +1,7 @@
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.
5
+ */
6
+ import { type AuthMethod, type InitializeResponse } from "@agentclientprotocol/sdk";
7
+ export declare function initializeResponse(version: string, authMethods?: readonly AuthMethod[]): InitializeResponse;
@@ -0,0 +1,19 @@
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.
5
+ */
6
+ import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
7
+ export function initializeResponse(version, authMethods = []) {
8
+ return {
9
+ protocolVersion: PROTOCOL_VERSION,
10
+ agentCapabilities: {
11
+ loadSession: true,
12
+ promptCapabilities: { image: false, audio: false, embeddedContext: true },
13
+ sessionCapabilities: { list: {}, resume: {}, close: {}, delete: {} },
14
+ },
15
+ // S5-4 advertises terminal login methods to clients that declared `auth.terminal`.
16
+ authMethods: [...authMethods],
17
+ agentInfo: { name: "nax-agent", title: "nax-agent", version },
18
+ };
19
+ }
@@ -0,0 +1,26 @@
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
+ }
9
+ export type CliCommand = {
10
+ readonly kind: "acp";
11
+ readonly flags: CliFlags;
12
+ } | {
13
+ readonly kind: "login";
14
+ readonly provider: string;
15
+ readonly method?: AuthMethod;
16
+ readonly flags: CliFlags;
17
+ } | {
18
+ readonly kind: "version";
19
+ } | {
20
+ readonly kind: "help";
21
+ } | {
22
+ readonly kind: "usage-error";
23
+ readonly message: string;
24
+ };
25
+ export declare const USAGE: string;
26
+ export declare function parseCli(argv: readonly string[]): CliCommand;
@@ -0,0 +1,87 @@
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
+ " --method <api-key|oauth> login method (login only; default: ask)",
20
+ " --version print the version",
21
+ " --help print this help",
22
+ "",
23
+ "Each option can also be set as NAX_AGENT_<OPTION>, for example NAX_AGENT_MODEL.",
24
+ ].join("\n");
25
+ const OPTIONS = {
26
+ "config-dir": { type: "string" },
27
+ "sessions-dir": { type: "string" },
28
+ model: { type: "string" },
29
+ mode: { type: "string" },
30
+ "bash-approval": { type: "string" },
31
+ method: { type: "string" },
32
+ version: { type: "boolean" },
33
+ help: { type: "boolean" },
34
+ };
35
+ function flag(key, value) {
36
+ return (value === undefined ? {} : { [key]: value });
37
+ }
38
+ function parse(argv) {
39
+ return parseArgs({ args: [...argv], options: OPTIONS, allowPositionals: true, strict: true });
40
+ }
41
+ const LOGIN_METHODS = ["api-key", "oauth"];
42
+ function flagsOf(values) {
43
+ return {
44
+ ...flag("configDir", values["config-dir"]),
45
+ ...flag("sessionsDir", values["sessions-dir"]),
46
+ ...flag("model", values.model),
47
+ ...flag("mode", values.mode),
48
+ ...flag("bashApproval", values["bash-approval"]),
49
+ };
50
+ }
51
+ function loginCommand(words, method, flags) {
52
+ const [, provider, ...extra] = words;
53
+ if (provider === undefined || extra.length > 0) {
54
+ return { kind: "usage-error", message: "login takes one provider: nax-agent login <provider>" };
55
+ }
56
+ if (method === undefined)
57
+ return { kind: "login", provider, flags };
58
+ const known = LOGIN_METHODS.find((m) => m === method);
59
+ if (known === undefined) {
60
+ return { kind: "usage-error", message: `invalid --method "${method}"; expected api-key or oauth` };
61
+ }
62
+ return { kind: "login", provider, method: known, flags };
63
+ }
64
+ export function parseCli(argv) {
65
+ let parsed;
66
+ try {
67
+ parsed = parse(argv);
68
+ }
69
+ catch (error) {
70
+ return { kind: "usage-error", message: error instanceof Error ? error.message : String(error) };
71
+ }
72
+ const { values, positionals } = parsed;
73
+ if (values.help === true)
74
+ return { kind: "help" };
75
+ if (values.version === true)
76
+ return { kind: "version" };
77
+ const flags = flagsOf(values);
78
+ // An editor's terminal login appends `login <provider>` to the server invocation (M-34).
79
+ const words = positionals[0] === "acp" ? positionals.slice(1) : positionals;
80
+ if (words[0] === "login")
81
+ return loginCommand(words, values.method, flags);
82
+ if (words.length > 0)
83
+ return { kind: "usage-error", message: `unknown command: ${positionals.join(" ")}` };
84
+ if (values.method !== undefined)
85
+ return { kind: "usage-error", message: "--method is only valid with login" };
86
+ return { kind: "acp", flags };
87
+ }
@@ -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>;
@@ -0,0 +1,49 @@
1
+ export const NO_CLIENT_FEATURES = {
2
+ updates: { notices: false, compaction: false },
3
+ elicitation: false,
4
+ terminalAuth: false,
5
+ };
6
+ const present = (value) => value !== undefined && value !== null;
7
+ export function clientFeatures(caps) {
8
+ return {
9
+ updates: { notices: present(caps?.session?.notices), compaction: present(caps?.session?.compaction) },
10
+ elicitation: present(caps?.elicitation?.form),
11
+ terminalAuth: caps?.auth?.terminal === true,
12
+ };
13
+ }
14
+ export function clientPort(context, sessionId, features) {
15
+ return {
16
+ features,
17
+ update: (update) => context.notify("session/update", { sessionId, update }),
18
+ requestPermission: (ask, signal) => context.request("session/request_permission", { sessionId, toolCall: ask.toolCall, options: [...ask.options] }, { cancellationSignal: signal }),
19
+ elicit: (form, signal) => {
20
+ const request = {
21
+ sessionId,
22
+ mode: "form",
23
+ message: form.message,
24
+ requestedSchema: form.requestedSchema,
25
+ };
26
+ return context.request("elicitation/create", request, { cancellationSignal: signal });
27
+ },
28
+ };
29
+ }
30
+ /**
31
+ * The work's result, or a rejection as soon as `signal` aborts. SDK cancellation
32
+ * is cooperative (the request promise waits for the peer), so a client that never
33
+ * answers would otherwise hold the turn.
34
+ */
35
+ export function untilAborted(work, signal) {
36
+ if (signal.aborted)
37
+ return Promise.reject(signal.reason);
38
+ return new Promise((resolve, reject) => {
39
+ const onAbort = () => reject(signal.reason);
40
+ signal.addEventListener("abort", onAbort, { once: true });
41
+ work.then((value) => {
42
+ signal.removeEventListener("abort", onAbort);
43
+ resolve(value);
44
+ }, (error) => {
45
+ signal.removeEventListener("abort", onAbort);
46
+ reject(error);
47
+ });
48
+ });
49
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The ACP agent app and its stdio transport (S5 spec §3.1). Uses the SDK's
3
+ * `agent()` builder, not the deprecated AgentSideConnection. The client's
4
+ * optional features are read once, at `initialize`. Every request handler runs
5
+ * under `guard` (spec §7): one failure never stops the connection.
6
+ */
7
+ import { Readable, Writable } from "node:stream";
8
+ import { type AgentApp, type AgentConnection } from "@agentclientprotocol/sdk";
9
+ import type { AgentLogger } from "@nathapp/nax-agent";
10
+ import { type ServerAuth } from "#src/server/auth";
11
+ import type { SessionRegistry } from "#src/server/registry";
12
+ export interface AppDeps {
13
+ readonly version: string;
14
+ readonly registry: SessionRegistry;
15
+ readonly logger: AgentLogger;
16
+ readonly auth?: ServerAuth;
17
+ }
18
+ export declare function buildAgentApp(deps: AppDeps): AgentApp;
19
+ export declare function serveStdio(app: AgentApp, io: {
20
+ readonly stdin: Readable;
21
+ readonly stdout: Writable;
22
+ }): AgentConnection;