@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
@@ -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,36 @@
1
+ import { type AuthInteraction, type ProviderModel } from "@nathapp/nax-agent";
2
+ import { type ReadTextFile } from "#src/server/nax-config";
3
+ export interface ModelPorts {
4
+ /** The provider's catalog models, sorted by id. */
5
+ listModels(provider: string): Promise<readonly ProviderModel[]>;
6
+ }
7
+ export declare const NAX_AGENT_MODELS: ModelPorts;
8
+ /**
9
+ * Writes `text` to `path`, creating the directory (0700) and, if absent, the file (0600).
10
+ * Atomic: a temp file in the same directory (flag "wx", the existing file's mode), synced,
11
+ * then renamed over the target. A symlinked config.json keeps its link: the target is replaced.
12
+ */
13
+ export type ConfigWriter = (path: string, text: string) => Promise<void>;
14
+ export declare const NODE_CONFIG_WRITER: ConfigWriter;
15
+ export type MergeResult = {
16
+ readonly ok: true;
17
+ readonly text: string;
18
+ } | {
19
+ readonly ok: false;
20
+ readonly reason: string;
21
+ };
22
+ /** `existing` (config.json text, or undefined when absent) with models.native.balanced set to `model`. */
23
+ export declare function mergeBalancedModel(existing: string | undefined, model: string): MergeResult;
24
+ export interface OfferInput {
25
+ readonly provider: string;
26
+ readonly configDir: string;
27
+ readonly isTTY: boolean;
28
+ /** A model is already chosen by --model or NAX_AGENT_MODEL. */
29
+ readonly pinned: boolean;
30
+ readonly interaction: AuthInteraction;
31
+ readonly out: (line: string) => void;
32
+ readonly models: ModelPorts;
33
+ readonly readFile: ReadTextFile;
34
+ readonly write: ConfigWriter;
35
+ }
36
+ export declare function offerDefaultModel(input: OfferInput): Promise<void>;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Login-first onboarding (#2414): after `nax-agent login <provider>`, when no
3
+ * default model is configured, offer to write `models.native.balanced` into the
4
+ * config dir's `config.json`. It merges into the existing document, creates the
5
+ * file 0600 when absent, and never touches the credentials file. A document it
6
+ * cannot merge into safely (malformed, or `models` of the wrong shape) is left
7
+ * unchanged and the one-line instruction is printed instead.
8
+ */
9
+ import { mkdir, open, realpath, rename, rm, stat } from "node:fs/promises";
10
+ import { dirname, join } from "node:path";
11
+ import { listProviderModels, PromptCancelledError, redactSecrets, } from "@nathapp/nax-agent";
12
+ import { messageOf } from "#src/server/errors";
13
+ import { loadNaxConfig } from "#src/server/nax-config";
14
+ export const NAX_AGENT_MODELS = { listModels: (provider) => listProviderModels(provider) };
15
+ function codeOf(error) {
16
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
17
+ ? error.code
18
+ : undefined;
19
+ }
20
+ async function existingTarget(path) {
21
+ try {
22
+ const target = await realpath(path);
23
+ return { target, mode: (await stat(target)).mode & 0o777 };
24
+ }
25
+ catch (error) {
26
+ if (codeOf(error) === "ENOENT")
27
+ return { target: path, mode: 0o600 };
28
+ throw error;
29
+ }
30
+ }
31
+ export const NODE_CONFIG_WRITER = async (path, text) => {
32
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
33
+ const { target, mode } = await existingTarget(path);
34
+ const temp = `${target}.${process.pid}.tmp`;
35
+ try {
36
+ const handle = await open(temp, "wx", mode);
37
+ try {
38
+ await handle.chmod(mode); // the umask must not narrow an existing file's mode
39
+ await handle.writeFile(text);
40
+ await handle.sync();
41
+ }
42
+ finally {
43
+ await handle.close();
44
+ }
45
+ await rename(temp, target);
46
+ }
47
+ catch (error) {
48
+ await rm(temp, { force: true });
49
+ throw error;
50
+ }
51
+ };
52
+ function isRecord(value) {
53
+ return typeof value === "object" && value !== null && !Array.isArray(value);
54
+ }
55
+ /** `existing` (config.json text, or undefined when absent) with models.native.balanced set to `model`. */
56
+ export function mergeBalancedModel(existing, model) {
57
+ let root = {};
58
+ if (existing !== undefined) {
59
+ try {
60
+ root = JSON.parse(existing);
61
+ }
62
+ catch {
63
+ return { ok: false, reason: "it is not valid JSON" };
64
+ }
65
+ }
66
+ if (!isRecord(root))
67
+ return { ok: false, reason: "it is not a JSON object" };
68
+ if (root.models !== undefined && !isRecord(root.models))
69
+ return { ok: false, reason: '"models" is not an object' };
70
+ const models = isRecord(root.models) ? root.models : {};
71
+ if (models.native !== undefined && !isRecord(models.native)) {
72
+ return { ok: false, reason: '"models.native" is not an object' };
73
+ }
74
+ const native = isRecord(models.native) ? models.native : {};
75
+ const merged = { ...root, models: { ...models, native: { ...native, balanced: model } } };
76
+ return { ok: true, text: `${JSON.stringify(merged, null, 2)}\n` };
77
+ }
78
+ const SKIP = "skip";
79
+ const MODEL_PREFIX = "model:";
80
+ function instruction(provider, path) {
81
+ return `No default model is set: set models.native.balanced to "${provider}/<model>" in ${path} (or NAX_AGENT_MODEL), then retry in your editor.`;
82
+ }
83
+ async function readExisting(path, readFile) {
84
+ try {
85
+ return await readFile(path, "utf8");
86
+ }
87
+ catch (error) {
88
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
89
+ return undefined;
90
+ throw error;
91
+ }
92
+ }
93
+ async function pickModel(input, models) {
94
+ if (models.length === 0)
95
+ return undefined;
96
+ try {
97
+ const answer = await input.interaction.prompt({
98
+ type: "select",
99
+ message: "Pick the default model for new threads (models.native.balanced)",
100
+ options: [
101
+ ...models.map((m) => ({
102
+ id: `${MODEL_PREFIX}${m.id}`,
103
+ label: m.id,
104
+ description: `${m.contextWindow} token window`,
105
+ })),
106
+ { id: SKIP, label: "Skip", description: "set models.native.balanced yourself" },
107
+ ],
108
+ });
109
+ return answer.startsWith(MODEL_PREFIX) ? `${input.provider}/${answer.slice(MODEL_PREFIX.length)}` : undefined;
110
+ }
111
+ catch (error) {
112
+ if (error instanceof PromptCancelledError)
113
+ return undefined;
114
+ throw error;
115
+ }
116
+ }
117
+ async function listModels(input) {
118
+ try {
119
+ return await input.models.listModels(input.provider);
120
+ }
121
+ catch (error) {
122
+ input.out(`Could not list ${input.provider} models: ${redactSecrets(messageOf(error))}`);
123
+ return [];
124
+ }
125
+ }
126
+ export async function offerDefaultModel(input) {
127
+ if (input.pinned)
128
+ return;
129
+ const path = join(input.configDir, "config.json");
130
+ const loaded = await loadNaxConfig(input.configDir, input.readFile);
131
+ if (loaded.warning === undefined && loaded.config.tiers.some((t) => t.tier === "balanced"))
132
+ return;
133
+ if (loaded.warning !== undefined) {
134
+ input.out(`${path} was left unchanged (${loaded.warning}).`);
135
+ input.out(instruction(input.provider, path));
136
+ return;
137
+ }
138
+ const based = await readExisting(path, input.readFile);
139
+ const model = input.isTTY ? await pickModel(input, await listModels(input)) : undefined;
140
+ if (model === undefined) {
141
+ input.out(instruction(input.provider, path));
142
+ return;
143
+ }
144
+ const merged = mergeBalancedModel(based, model);
145
+ if (!merged.ok) {
146
+ input.out(`${path} was left unchanged (${merged.reason}).`);
147
+ input.out(instruction(input.provider, path));
148
+ return;
149
+ }
150
+ // The pick can take a while; another writer may have changed the file meanwhile.
151
+ if ((await readExisting(path, input.readFile)) !== based) {
152
+ input.out(`${path} changed while picking; left unchanged.`);
153
+ input.out(instruction(input.provider, path));
154
+ return;
155
+ }
156
+ await input.write(path, merged.text);
157
+ input.out(`Set models.native.balanced to ${model} in ${path}. Retry in your editor.`);
158
+ }
@@ -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,20 @@
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
+ /** After a successful login: offers to set a default model (#2414). A failure here never fails the login. */
15
+ readonly offerModel?: (provider: string) => Promise<void>;
16
+ }
17
+ export declare function runLoginCommand(input: {
18
+ readonly provider: string;
19
+ readonly method?: AuthMethod;
20
+ }, deps: LoginDeps): Promise<number>;
@@ -0,0 +1,38 @@
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
+ async function offerAfterLogin(provider, deps) {
13
+ try {
14
+ await deps.offerModel?.(provider);
15
+ }
16
+ catch (error) {
17
+ deps.err(`nax-agent: could not set a default model: ${redactSecrets(messageOf(error))}`);
18
+ }
19
+ }
20
+ export async function runLoginCommand(input, deps) {
21
+ if (!deps.isTTY) {
22
+ deps.err(`nax-agent login needs an interactive terminal. Without one, set the provider's environment variable ` +
23
+ `(for example ${envName(input.provider)}); nax-agent reads it when nothing is stored.`);
24
+ return 1;
25
+ }
26
+ try {
27
+ const result = await deps.auth.runLogin(input.provider, deps.auth.interaction(deps.out), input.method);
28
+ deps.out(`Signed in to ${result.providerId} (method: ${result.method}, credential: ${result.kind})`);
29
+ await offerAfterLogin(result.providerId, deps);
30
+ return 0;
31
+ }
32
+ catch (error) {
33
+ if (error instanceof AuthCancelledError || error instanceof PromptCancelledError)
34
+ return 130;
35
+ deps.err(`nax-agent: ${redactSecrets(messageOf(error))}`);
36
+ return 1;
37
+ }
38
+ }
@@ -0,0 +1,24 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { type AuthPorts } from "#src/server/auth";
3
+ import { type ConfigWriter, type ModelPorts } from "#src/server/default-model";
4
+ import { type ReadTextFile } from "#src/server/nax-config";
5
+ import { type Env } from "#src/server/options";
6
+ export interface MainDeps {
7
+ readonly argv: readonly string[];
8
+ readonly env: Env;
9
+ readonly homedir: string;
10
+ readonly stdin: Readable;
11
+ readonly stdout: Writable;
12
+ readonly writeErr: (text: string) => void;
13
+ readonly readFile: ReadTextFile;
14
+ readonly onSignal: (handler: () => void) => void;
15
+ /** stdin is an interactive terminal (login needs one). */
16
+ readonly isTTY: boolean;
17
+ /** nax-agent's auth API; tests inject a fake. Defaults to the real one. */
18
+ readonly auth?: AuthPorts;
19
+ /** The catalog behind the default-model pick after login; tests inject a fake. */
20
+ readonly models?: ModelPorts;
21
+ /** Writes config.json after login; tests inject a fake. */
22
+ readonly writeConfig?: ConfigWriter;
23
+ }
24
+ export declare function main(deps: MainDeps): Promise<number>;