@nathapp/nax-agent-acp 0.3.0 → 0.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +117 -22
  3. package/bin/nax-agent.js +4 -0
  4. package/dist/client/backend.js +11 -2
  5. package/dist/client/capabilities.d.ts +9 -3
  6. package/dist/client/capabilities.js +26 -5
  7. package/dist/client/elicitation.d.ts +4 -2
  8. package/dist/client/elicitation.js +14 -1
  9. package/dist/client/errors.d.ts +9 -1
  10. package/dist/client/errors.js +19 -2
  11. package/dist/client/events.d.ts +5 -1
  12. package/dist/client/events.js +31 -2
  13. package/dist/client/index.d.ts +2 -1
  14. package/dist/client/index.js +1 -0
  15. package/dist/client/launchable.d.ts +4 -0
  16. package/dist/client/launchable.js +17 -0
  17. package/dist/client/open.js +75 -13
  18. package/dist/client/options.d.ts +11 -0
  19. package/dist/client/options.js +17 -3
  20. package/dist/client/permissions.d.ts +2 -2
  21. package/dist/client/pre-approval.d.ts +5 -13
  22. package/dist/client/pre-approval.js +3 -10
  23. package/dist/client/registry.d.ts +15 -2
  24. package/dist/client/registry.js +22 -2
  25. package/dist/client/tool-calls.js +0 -4
  26. package/dist/client/tool-events.d.ts +8 -1
  27. package/dist/client/tool-events.js +39 -6
  28. package/dist/client/turn.js +28 -8
  29. package/dist/server/auth.d.ts +45 -0
  30. package/dist/server/auth.js +87 -0
  31. package/dist/server/capabilities.d.ts +7 -0
  32. package/dist/server/capabilities.js +19 -0
  33. package/dist/server/cli.d.ts +26 -0
  34. package/dist/server/cli.js +87 -0
  35. package/dist/server/client-port.d.ts +39 -0
  36. package/dist/server/client-port.js +49 -0
  37. package/dist/server/connection.d.ts +22 -0
  38. package/dist/server/connection.js +56 -0
  39. package/dist/server/errors.d.ts +21 -0
  40. package/dist/server/errors.js +70 -0
  41. package/dist/server/index.d.ts +4 -3
  42. package/dist/server/index.js +6 -1
  43. package/dist/server/logger.d.ts +7 -0
  44. package/dist/server/logger.js +25 -0
  45. package/dist/server/login.d.ts +18 -0
  46. package/dist/server/login.js +29 -0
  47. package/dist/server/main.d.ts +19 -0
  48. package/dist/server/main.js +120 -0
  49. package/dist/server/nax-config.d.ts +30 -0
  50. package/dist/server/nax-config.js +138 -0
  51. package/dist/server/open-session.d.ts +37 -0
  52. package/dist/server/open-session.js +55 -0
  53. package/dist/server/options.d.ts +27 -0
  54. package/dist/server/options.js +55 -0
  55. package/dist/server/permissions.d.ts +44 -0
  56. package/dist/server/permissions.js +157 -0
  57. package/dist/server/process-entry.d.ts +15 -0
  58. package/dist/server/process-entry.js +28 -0
  59. package/dist/server/prompt.d.ts +8 -0
  60. package/dist/server/prompt.js +29 -0
  61. package/dist/server/questions.d.ts +33 -0
  62. package/dist/server/questions.js +79 -0
  63. package/dist/server/registry-open.d.ts +33 -0
  64. package/dist/server/registry-open.js +62 -0
  65. package/dist/server/registry.d.ts +64 -0
  66. package/dist/server/registry.js +262 -0
  67. package/dist/server/server-session.d.ts +43 -0
  68. package/dist/server/server-session.js +221 -0
  69. package/dist/server/session-config.d.ts +27 -0
  70. package/dist/server/session-config.js +93 -0
  71. package/dist/server/storage.d.ts +49 -0
  72. package/dist/server/storage.js +191 -0
  73. package/dist/server/translate/diff.d.ts +30 -0
  74. package/dist/server/translate/diff.js +81 -0
  75. package/dist/server/translate/events.d.ts +37 -0
  76. package/dist/server/translate/events.js +126 -0
  77. package/dist/server/translate/notice.d.ts +10 -0
  78. package/dist/server/translate/notice.js +14 -0
  79. package/dist/server/translate/replay.d.ts +11 -0
  80. package/dist/server/translate/replay.js +53 -0
  81. package/dist/server/translate/stop.d.ts +22 -0
  82. package/dist/server/translate/stop.js +48 -0
  83. package/dist/server/translate/tool-kind.d.ts +9 -0
  84. package/dist/server/translate/tool-kind.js +67 -0
  85. package/dist/server/version.d.ts +1 -0
  86. package/dist/server/version.js +17 -0
  87. package/package.json +6 -3
@@ -0,0 +1,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;
@@ -0,0 +1,56 @@
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 { agent, ndJsonStream } from "@agentclientprotocol/sdk";
9
+ import { NO_SERVER_AUTH } from "#src/server/auth";
10
+ import { initializeResponse } from "#src/server/capabilities";
11
+ import { clientFeatures, clientPort, NO_CLIENT_FEATURES } from "#src/server/client-port";
12
+ import { guard } from "#src/server/errors";
13
+ export function buildAgentApp(deps) {
14
+ const auth = deps.auth ?? NO_SERVER_AUTH;
15
+ let features = NO_CLIENT_FEATURES;
16
+ return agent({ name: "nax-agent" })
17
+ .onRequest("initialize", (ctx) => {
18
+ features = clientFeatures(ctx.params.clientCapabilities);
19
+ return initializeResponse(deps.version, features.terminalAuth ? auth.methods : []);
20
+ })
21
+ .onRequest("authenticate", (ctx) => guard(deps.logger, () => auth.authenticate(ctx.params.methodId)))
22
+ .onRequest("session/new", (ctx) => guard(deps.logger, () => deps.registry.create({
23
+ cwd: ctx.params.cwd,
24
+ mcpServers: ctx.params.mcpServers,
25
+ port: (sessionId) => clientPort(ctx.client, sessionId, features),
26
+ })))
27
+ .onRequest("session/load", (ctx) => guard(deps.logger, () => deps.registry.load(ctx.params.sessionId, {
28
+ cwd: ctx.params.cwd,
29
+ mcpServers: ctx.params.mcpServers,
30
+ port: (sessionId) => clientPort(ctx.client, sessionId, features),
31
+ })))
32
+ .onRequest("session/resume", (ctx) => guard(deps.logger, () => deps.registry.resume(ctx.params.sessionId, {
33
+ cwd: ctx.params.cwd,
34
+ mcpServers: ctx.params.mcpServers ?? [],
35
+ port: (sessionId) => clientPort(ctx.client, sessionId, features),
36
+ })))
37
+ .onRequest("session/list", (ctx) => guard(deps.logger, () => deps.registry.list(ctx.params)))
38
+ .onRequest("session/close", (ctx) => guard(deps.logger, () => deps.registry.close(ctx.params.sessionId)))
39
+ .onRequest("session/delete", (ctx) => guard(deps.logger, () => deps.registry.delete(ctx.params.sessionId)))
40
+ .onRequest("session/set_mode", (ctx) => guard(deps.logger, () => deps.registry.setMode(ctx.params.sessionId, ctx.params.modeId)))
41
+ .onRequest("session/set_config_option", (ctx) => guard(deps.logger, async () => ({
42
+ configOptions: await deps.registry.setConfigOption(ctx.params.sessionId, ctx.params.configId, ctx.params.value),
43
+ })))
44
+ .onRequest("session/prompt", (ctx) => guard(deps.logger, () => deps.registry.get(ctx.params.sessionId).prompt(ctx.params.prompt)))
45
+ .onNotification("session/cancel", (ctx) => {
46
+ const session = deps.registry.find(ctx.params.sessionId);
47
+ if (session === undefined) {
48
+ deps.logger.debug("session", "cancel for an unknown session ignored", { sessionId: ctx.params.sessionId });
49
+ return;
50
+ }
51
+ session.cancel();
52
+ });
53
+ }
54
+ export function serveStdio(app, io) {
55
+ return app.connect(ndJsonStream(Writable.toWeb(io.stdout), Readable.toWeb(io.stdin)));
56
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Failures as SDK RequestErrors at the protocol edge (S5 spec §7). Facade errors
3
+ * with a protocol meaning map to it; anything else is logged with its stack and
4
+ * reaches the client as its message only, secrets redacted (a provider error can
5
+ * echo a key). One request's failure never stops the process.
6
+ */
7
+ import { RequestError } from "@agentclientprotocol/sdk";
8
+ import { type AgentLogger } from "@nathapp/nax-agent";
9
+ export declare const TURN_IN_PROGRESS = "turn in progress";
10
+ export declare function turnInProgress(): RequestError;
11
+ export declare function unknownSession(sessionId: string): RequestError;
12
+ export declare function invalidParams(message: string): RequestError;
13
+ export declare function messageOf(error: unknown): string;
14
+ /** Turn and open failures that mean "log in again" (S5-4 M-32). */
15
+ export declare const CREDENTIAL_FAILURE_CODES: ReadonlySet<string>;
16
+ export declare function isAuthFailureCode(code: string): boolean;
17
+ export declare function loginHint(provider?: string): string;
18
+ /** `auth_required` (-32000): editors offer the advertised login methods on it (spec §6.3). */
19
+ export declare function authRequired(message: string, data: Readonly<Record<string, unknown>>): RequestError;
20
+ export declare function toRequestError(error: unknown, logger: AgentLogger): RequestError;
21
+ export declare function guard<T>(logger: AgentLogger, work: () => Promise<T>): Promise<T>;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Failures as SDK RequestErrors at the protocol edge (S5 spec §7). Facade errors
3
+ * with a protocol meaning map to it; anything else is logged with its stack and
4
+ * reaches the client as its message only, secrets redacted (a provider error can
5
+ * echo a key). One request's failure never stops the process.
6
+ */
7
+ import { RequestError } from "@agentclientprotocol/sdk";
8
+ import { AgentSessionError, NaxError, redactSecrets } from "@nathapp/nax-agent";
9
+ export const TURN_IN_PROGRESS = "turn in progress";
10
+ export function turnInProgress() {
11
+ return RequestError.invalidRequest(undefined, TURN_IN_PROGRESS);
12
+ }
13
+ export function unknownSession(sessionId) {
14
+ return RequestError.resourceNotFound(sessionId);
15
+ }
16
+ export function invalidParams(message) {
17
+ return RequestError.invalidParams(undefined, message);
18
+ }
19
+ export function messageOf(error) {
20
+ return error instanceof Error ? error.message : String(error);
21
+ }
22
+ /** Turn and open failures that mean "log in again" (S5-4 M-32). */
23
+ export const CREDENTIAL_FAILURE_CODES = new Set([
24
+ "fail-auth",
25
+ "CREDENTIAL_HELPER_FAILED",
26
+ "CREDENTIAL_HELPER_INVALID",
27
+ "CREDENTIAL_CHANGED",
28
+ "CREDENTIAL_FILE_UNREADABLE",
29
+ "CREDENTIALS_NOT_CONFIGURED",
30
+ ]);
31
+ export function isAuthFailureCode(code) {
32
+ return CREDENTIAL_FAILURE_CODES.has(code);
33
+ }
34
+ export function loginHint(provider) {
35
+ const name = provider ?? "<provider>";
36
+ return `Log in with \`nax-agent login ${name}\` (or \`nax auth login ${name}\`), then retry.`;
37
+ }
38
+ /** `auth_required` (-32000): editors offer the advertised login methods on it (spec §6.3). */
39
+ export function authRequired(message, data) {
40
+ const provider = typeof data.provider === "string" ? data.provider : undefined;
41
+ // A redacted NaxError message may already end in "."; never print "..".
42
+ return RequestError.authRequired(data, `${message.replace(/\.+$/, "")}. ${loginHint(provider)}`);
43
+ }
44
+ export function toRequestError(error, logger) {
45
+ if (error instanceof RequestError)
46
+ return error;
47
+ if (error instanceof AgentSessionError) {
48
+ if (error.code === "AGENT_SESSION_INVALID_OPTIONS")
49
+ return invalidParams(error.message);
50
+ if (error.code === "AGENT_SESSION_BUSY")
51
+ return turnInProgress();
52
+ }
53
+ if (error instanceof NaxError && isAuthFailureCode(error.code)) {
54
+ return authRequired(redactSecrets(error.message), { code: error.code });
55
+ }
56
+ const message = redactSecrets(messageOf(error));
57
+ logger.error("server", "request failed", {
58
+ error: message,
59
+ ...(error instanceof Error && error.stack !== undefined ? { stack: redactSecrets(error.stack) } : {}),
60
+ });
61
+ return RequestError.internalError(undefined, message);
62
+ }
63
+ export async function guard(logger, work) {
64
+ try {
65
+ return await work();
66
+ }
67
+ catch (error) {
68
+ throw toRequestError(error, logger);
69
+ }
70
+ }
@@ -1,5 +1,6 @@
1
1
  /**
2
- * `@nathapp/nax-agent-acp/server`: reserved for the ACP server (S5).
3
- * Intentionally empty in S4.
2
+ * `@nathapp/nax-agent-acp/server`: the nax-agent ACP server (S5). `runCli(process)`
3
+ * is what the `nax-agent` bin runs; `main(deps)` runs it on any streams.
4
4
  */
5
- export {};
5
+ export { type MainDeps, main } from "#src/server/main";
6
+ export { type ProcessLike, runCli } from "#src/server/process-entry";
@@ -1 +1,6 @@
1
- export {};
1
+ /**
2
+ * `@nathapp/nax-agent-acp/server`: the nax-agent ACP server (S5). `runCli(process)`
3
+ * is what the `nax-agent` bin runs; `main(deps)` runs it on any streams.
4
+ */
5
+ export { main } from "#src/server/main";
6
+ export { runCli } from "#src/server/process-entry";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The server's logger (S5 spec §6.4): JSON lines on stderr, never stdout, which
3
+ * carries ACP frames only. A log call never throws.
4
+ */
5
+ import type { AgentLogger } from "@nathapp/nax-agent";
6
+ export type LogLevel = "warn" | "info" | "debug";
7
+ export declare function stderrLogger(level: LogLevel, write: (text: string) => void): AgentLogger;
@@ -0,0 +1,25 @@
1
+ const RANK = { error: 0, warn: 1, info: 2, debug: 3 };
2
+ function line(level, stage, message, data) {
3
+ const base = { level, stage, message };
4
+ if (data === undefined)
5
+ return `${JSON.stringify(base)}\n`;
6
+ try {
7
+ return `${JSON.stringify({ ...base, data })}\n`;
8
+ }
9
+ catch {
10
+ return `${JSON.stringify({ ...base, data: "[unserialisable]" })}\n`;
11
+ }
12
+ }
13
+ export function stderrLogger(level, write) {
14
+ const at = (severity) => (stage, message, data) => {
15
+ if (RANK[severity] > RANK[level])
16
+ return;
17
+ try {
18
+ write(line(severity, stage, message, data));
19
+ }
20
+ catch {
21
+ // A broken stderr must not take the server down.
22
+ }
23
+ };
24
+ return { error: at("error"), warn: at("warn"), info: at("info"), debug: at("debug") };
25
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `nax-agent login <provider>` (S5 spec §6.1, S5-4): an interactive login on
3
+ * the terminal, writing to the same credential store as `nax auth login`. An
4
+ * editor's terminal auth runs this; exit 0 tells it the login succeeded.
5
+ * Exit codes: 0 signed in, 1 failure or no terminal, 130 cancelled.
6
+ */
7
+ import { type AuthMethod } from "@nathapp/nax-agent";
8
+ import type { AuthPorts } from "#src/server/auth";
9
+ export interface LoginDeps {
10
+ readonly isTTY: boolean;
11
+ readonly out: (line: string) => void;
12
+ readonly err: (line: string) => void;
13
+ readonly auth: Pick<AuthPorts, "runLogin" | "interaction">;
14
+ }
15
+ export declare function runLoginCommand(input: {
16
+ readonly provider: string;
17
+ readonly method?: AuthMethod;
18
+ }, deps: LoginDeps): Promise<number>;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `nax-agent login <provider>` (S5 spec §6.1, S5-4): an interactive login on
3
+ * the terminal, writing to the same credential store as `nax auth login`. An
4
+ * editor's terminal auth runs this; exit 0 tells it the login succeeded.
5
+ * Exit codes: 0 signed in, 1 failure or no terminal, 130 cancelled.
6
+ */
7
+ import { AuthCancelledError, PromptCancelledError, redactSecrets } from "@nathapp/nax-agent";
8
+ import { messageOf } from "#src/server/errors";
9
+ function envName(provider) {
10
+ return `${provider.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_API_KEY`;
11
+ }
12
+ export async function runLoginCommand(input, deps) {
13
+ if (!deps.isTTY) {
14
+ deps.err(`nax-agent login needs an interactive terminal. Without one, set the provider's environment variable ` +
15
+ `(for example ${envName(input.provider)}); nax-agent reads it when nothing is stored.`);
16
+ return 1;
17
+ }
18
+ try {
19
+ const result = await deps.auth.runLogin(input.provider, deps.auth.interaction(deps.out), input.method);
20
+ deps.out(`Signed in to ${result.providerId} (method: ${result.method}, credential: ${result.kind})`);
21
+ return 0;
22
+ }
23
+ catch (error) {
24
+ if (error instanceof AuthCancelledError || error instanceof PromptCancelledError)
25
+ return 130;
26
+ deps.err(`nax-agent: ${redactSecrets(messageOf(error))}`);
27
+ return 1;
28
+ }
29
+ }
@@ -0,0 +1,19 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { type AuthPorts } from "#src/server/auth";
3
+ import { type ReadTextFile } from "#src/server/nax-config";
4
+ import { type Env } from "#src/server/options";
5
+ export interface MainDeps {
6
+ readonly argv: readonly string[];
7
+ readonly env: Env;
8
+ readonly homedir: string;
9
+ readonly stdin: Readable;
10
+ readonly stdout: Writable;
11
+ readonly writeErr: (text: string) => void;
12
+ readonly readFile: ReadTextFile;
13
+ readonly onSignal: (handler: () => void) => void;
14
+ /** stdin is an interactive terminal (login needs one). */
15
+ readonly isTTY: boolean;
16
+ /** nax-agent's auth API; tests inject a fake. Defaults to the real one. */
17
+ readonly auth?: AuthPorts;
18
+ }
19
+ export declare function main(deps: MainDeps): Promise<number>;