@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.
- package/CHANGELOG.md +16 -0
- package/README.md +86 -4
- package/bin/nax-agent.js +4 -0
- package/dist/client/elicitation.d.ts +4 -2
- package/dist/client/elicitation.js +14 -1
- package/dist/client/errors.d.ts +1 -1
- package/dist/client/errors.js +2 -2
- package/dist/client/open.js +17 -3
- package/dist/server/auth.d.ts +45 -0
- package/dist/server/auth.js +87 -0
- package/dist/server/capabilities.d.ts +7 -0
- package/dist/server/capabilities.js +19 -0
- package/dist/server/cli.d.ts +26 -0
- package/dist/server/cli.js +87 -0
- package/dist/server/client-port.d.ts +39 -0
- package/dist/server/client-port.js +49 -0
- package/dist/server/connection.d.ts +22 -0
- package/dist/server/connection.js +56 -0
- package/dist/server/errors.d.ts +21 -0
- package/dist/server/errors.js +70 -0
- package/dist/server/index.d.ts +4 -3
- package/dist/server/index.js +6 -1
- package/dist/server/logger.d.ts +7 -0
- package/dist/server/logger.js +25 -0
- package/dist/server/login.d.ts +18 -0
- package/dist/server/login.js +29 -0
- package/dist/server/main.d.ts +19 -0
- package/dist/server/main.js +120 -0
- package/dist/server/nax-config.d.ts +30 -0
- package/dist/server/nax-config.js +138 -0
- package/dist/server/open-session.d.ts +37 -0
- package/dist/server/open-session.js +55 -0
- package/dist/server/options.d.ts +27 -0
- package/dist/server/options.js +55 -0
- package/dist/server/permissions.d.ts +44 -0
- package/dist/server/permissions.js +157 -0
- package/dist/server/process-entry.d.ts +15 -0
- package/dist/server/process-entry.js +28 -0
- package/dist/server/prompt.d.ts +8 -0
- package/dist/server/prompt.js +29 -0
- package/dist/server/questions.d.ts +33 -0
- package/dist/server/questions.js +79 -0
- package/dist/server/registry-open.d.ts +33 -0
- package/dist/server/registry-open.js +62 -0
- package/dist/server/registry.d.ts +64 -0
- package/dist/server/registry.js +262 -0
- package/dist/server/server-session.d.ts +43 -0
- package/dist/server/server-session.js +221 -0
- package/dist/server/session-config.d.ts +27 -0
- package/dist/server/session-config.js +93 -0
- package/dist/server/storage.d.ts +49 -0
- package/dist/server/storage.js +191 -0
- package/dist/server/translate/diff.d.ts +30 -0
- package/dist/server/translate/diff.js +81 -0
- package/dist/server/translate/events.d.ts +37 -0
- package/dist/server/translate/events.js +126 -0
- package/dist/server/translate/notice.d.ts +10 -0
- package/dist/server/translate/notice.js +14 -0
- package/dist/server/translate/replay.d.ts +11 -0
- package/dist/server/translate/replay.js +53 -0
- package/dist/server/translate/stop.d.ts +22 -0
- package/dist/server/translate/stop.js +48 -0
- package/dist/server/translate/tool-kind.d.ts +9 -0
- package/dist/server/translate/tool-kind.js +67 -0
- package/dist/server/version.d.ts +1 -0
- package/dist/server/version.js +17 -0
- package/package.json +5 -2
|
@@ -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
|
+
}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@nathapp/nax-agent-acp/server`:
|
|
3
|
-
*
|
|
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";
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1,6 @@
|
|
|
1
|
-
|
|
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>;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `nax-agent` entry point as a function of its environment (S5 spec §6.1), so
|
|
3
|
+
* the unit suite covers it without spawning a process. Exit codes: 0 clean stop,
|
|
4
|
+
* 1 connection failure, 2 usage or option error.
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { configureCredentials, createFileTranscriptStore, setAgentLogger } from "@nathapp/nax-agent";
|
|
8
|
+
import { loadServerAuth, NAX_AGENT_AUTH } from "#src/server/auth";
|
|
9
|
+
import { parseCli, USAGE } from "#src/server/cli";
|
|
10
|
+
import { buildAgentApp, serveStdio } from "#src/server/connection";
|
|
11
|
+
import { stderrLogger } from "#src/server/logger";
|
|
12
|
+
import { runLoginCommand } from "#src/server/login";
|
|
13
|
+
import { credentialsFor, loadNaxConfig } from "#src/server/nax-config";
|
|
14
|
+
import { catalogOverridesFrom, nativeOpenSession } from "#src/server/open-session";
|
|
15
|
+
import { resolveConfigDir, resolveServerOptions } from "#src/server/options";
|
|
16
|
+
import { createSessionRegistry } from "#src/server/registry";
|
|
17
|
+
import { TURN_TIMEOUT_SECONDS } from "#src/server/server-session";
|
|
18
|
+
import { createSessionStorage } from "#src/server/storage";
|
|
19
|
+
import { fsReadOldText } from "#src/server/translate/diff";
|
|
20
|
+
import { packageVersion } from "#src/server/version";
|
|
21
|
+
export async function main(deps) {
|
|
22
|
+
const command = parseCli(deps.argv);
|
|
23
|
+
switch (command.kind) {
|
|
24
|
+
case "help":
|
|
25
|
+
deps.stdout.write(`${USAGE}\n`);
|
|
26
|
+
return 0;
|
|
27
|
+
case "version":
|
|
28
|
+
deps.stdout.write(`${packageVersion()}\n`);
|
|
29
|
+
return 0;
|
|
30
|
+
case "usage-error":
|
|
31
|
+
deps.writeErr(`nax-agent: ${command.message}\n\n${USAGE}\n`);
|
|
32
|
+
return 2;
|
|
33
|
+
case "login":
|
|
34
|
+
return login(command, deps);
|
|
35
|
+
case "acp":
|
|
36
|
+
return serveAcp(command.flags, deps);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function login(command, deps) {
|
|
40
|
+
// warn, not info: info lines would land in the middle of the interactive prompts.
|
|
41
|
+
setAgentLogger(stderrLogger(deps.env.NAX_AGENT_LOG === "debug" ? "debug" : "warn", deps.writeErr));
|
|
42
|
+
const configDir = resolveConfigDir(command.flags, deps.env, deps.homedir);
|
|
43
|
+
configureCredentials(credentialsFor(configDir, deps.readFile));
|
|
44
|
+
return runLoginCommand({ provider: command.provider, ...(command.method !== undefined ? { method: command.method } : {}) }, {
|
|
45
|
+
isTTY: deps.isTTY,
|
|
46
|
+
out: (line) => deps.stdout.write(`${line}\n`),
|
|
47
|
+
err: (line) => deps.writeErr(`${line}\n`),
|
|
48
|
+
auth: deps.auth ?? NAX_AGENT_AUTH,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async function serveAcp(flags, deps) {
|
|
52
|
+
const logger = stderrLogger(deps.env.NAX_AGENT_LOG === "debug" ? "debug" : "info", deps.writeErr);
|
|
53
|
+
setAgentLogger(logger);
|
|
54
|
+
const configDir = resolveConfigDir(flags, deps.env, deps.homedir);
|
|
55
|
+
const loaded = await loadNaxConfig(configDir, deps.readFile);
|
|
56
|
+
if (loaded.warning !== undefined)
|
|
57
|
+
logger.warn("config", loaded.warning);
|
|
58
|
+
const resolved = resolveServerOptions({ flags, env: deps.env, file: loaded.config, configDir });
|
|
59
|
+
if (!resolved.ok) {
|
|
60
|
+
deps.writeErr(`nax-agent: ${resolved.message}\n`);
|
|
61
|
+
return 2;
|
|
62
|
+
}
|
|
63
|
+
configureCredentials(credentialsFor(configDir, deps.readFile));
|
|
64
|
+
const overrides = catalogOverridesFrom(resolved.options.catalogOverrides, logger);
|
|
65
|
+
const auth = await loadServerAuth({
|
|
66
|
+
options: resolved.options,
|
|
67
|
+
overrides,
|
|
68
|
+
ports: deps.auth ?? NAX_AGENT_AUTH,
|
|
69
|
+
logger,
|
|
70
|
+
});
|
|
71
|
+
const transcripts = createFileTranscriptStore(resolved.options.sessionsDir);
|
|
72
|
+
const storage = createSessionStorage({
|
|
73
|
+
dir: resolved.options.sessionsDir,
|
|
74
|
+
pid: process.pid,
|
|
75
|
+
now: () => new Date(),
|
|
76
|
+
logger,
|
|
77
|
+
});
|
|
78
|
+
const registry = createSessionRegistry({
|
|
79
|
+
options: resolved.options,
|
|
80
|
+
openSession: nativeOpenSession({
|
|
81
|
+
transcripts,
|
|
82
|
+
catalogOverrides: overrides,
|
|
83
|
+
turnTimeoutSeconds: TURN_TIMEOUT_SECONDS,
|
|
84
|
+
}),
|
|
85
|
+
storage,
|
|
86
|
+
transcripts,
|
|
87
|
+
newId: randomUUID,
|
|
88
|
+
now: () => new Date(),
|
|
89
|
+
readOldText: fsReadOldText(),
|
|
90
|
+
logger,
|
|
91
|
+
turnTimeoutSeconds: TURN_TIMEOUT_SECONDS,
|
|
92
|
+
ensureCredentials: (model) => auth.ensureCredentials(model),
|
|
93
|
+
});
|
|
94
|
+
const connection = serveStdio(buildAgentApp({ version: packageVersion(), registry, logger, auth }), deps);
|
|
95
|
+
const stop = () => connection.close();
|
|
96
|
+
deps.onSignal(stop);
|
|
97
|
+
deps.stdin.once("end", stop);
|
|
98
|
+
logger.info("server", "nax-agent ACP server started", { configDir, sessionsDir: resolved.options.sessionsDir });
|
|
99
|
+
// Scalars only: catalog overrides can carry provider headers (API keys).
|
|
100
|
+
const { defaultModel, defaultMode, bashApproval, tiers, catalogOverrides } = resolved.options;
|
|
101
|
+
logger.debug("server", "resolved options", {
|
|
102
|
+
defaultModel,
|
|
103
|
+
defaultMode,
|
|
104
|
+
bashApproval,
|
|
105
|
+
tiers: tiers.map((t) => `${t.tier}=${t.model}`),
|
|
106
|
+
catalogOverrides: catalogOverrides.length,
|
|
107
|
+
});
|
|
108
|
+
try {
|
|
109
|
+
await connection.closed;
|
|
110
|
+
return 0;
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
logger.error("server", "connection failed", { error: error instanceof Error ? error.message : String(error) });
|
|
114
|
+
return 1;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
// S5-2 shutdown (M-16): no running turn outlives its client.
|
|
118
|
+
await registry.closeAll();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { AgentSessionProfile, CredentialAuthConfig, CredentialsConfig } from "@nathapp/nax-agent";
|
|
2
|
+
export type ReadTextFile = (path: string, encoding: "utf8") => Promise<string>;
|
|
3
|
+
export type BashApproval = "gated" | "escalate" | "raw";
|
|
4
|
+
export declare const TIERS: readonly ["fast", "balanced", "powerful"];
|
|
5
|
+
export interface TierModel {
|
|
6
|
+
readonly tier: (typeof TIERS)[number];
|
|
7
|
+
readonly model: string;
|
|
8
|
+
readonly contextWindow?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface AgentServerSection {
|
|
11
|
+
readonly defaultMode?: AgentSessionProfile;
|
|
12
|
+
readonly bashApproval?: BashApproval;
|
|
13
|
+
readonly sessionsDir?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface NaxConfigSubset {
|
|
16
|
+
readonly tiers: readonly TierModel[];
|
|
17
|
+
readonly catalogOverrides: readonly Readonly<Record<string, unknown>>[];
|
|
18
|
+
readonly auth: CredentialAuthConfig;
|
|
19
|
+
readonly agentServer: AgentServerSection;
|
|
20
|
+
}
|
|
21
|
+
export interface LoadedNaxConfig {
|
|
22
|
+
readonly config: NaxConfigSubset;
|
|
23
|
+
readonly warning?: string;
|
|
24
|
+
}
|
|
25
|
+
export declare const MODES: readonly ["none", "read", "ask", "full"];
|
|
26
|
+
export declare const BASH_APPROVALS: readonly ["gated", "escalate", "raw"];
|
|
27
|
+
export declare const EMPTY_NAX_CONFIG: NaxConfigSubset;
|
|
28
|
+
export declare function loadNaxConfig(configDir: string, readFile: ReadTextFile): Promise<LoadedNaxConfig>;
|
|
29
|
+
/** Credentials read from `configDir` with the auth block re-read per call, as nax does (M-3). */
|
|
30
|
+
export declare function credentialsFor(configDir: string, readFile: ReadTextFile): CredentialsConfig;
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The subset of nax's global `config.json` the ACP server reads (S5 spec §6.2,
|
|
3
|
+
* master plan M-3). It is a local reader, not nax's config loader: nax-agent-acp
|
|
4
|
+
* does not depend on nax. Any problem falls back to the defaults with one
|
|
5
|
+
* warning; the server still starts.
|
|
6
|
+
*/
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
export const TIERS = ["fast", "balanced", "powerful"];
|
|
10
|
+
export const MODES = ["none", "read", "ask", "full"];
|
|
11
|
+
export const BASH_APPROVALS = ["gated", "escalate", "raw"];
|
|
12
|
+
const ModelEntrySchema = z.union([
|
|
13
|
+
z.string().min(1),
|
|
14
|
+
z.object({ model: z.string().min(1), contextWindow: z.number().int().positive().optional() }),
|
|
15
|
+
]);
|
|
16
|
+
/** nax's AuthConfigSchema (packages/nax/src/config/schemas-auth.ts), same defaults. */
|
|
17
|
+
const AuthSchema = z
|
|
18
|
+
.object({
|
|
19
|
+
source: z.enum(["file", "exec"]).default("file"),
|
|
20
|
+
exec: z
|
|
21
|
+
.object({
|
|
22
|
+
command: z.array(z.string().min(1)).min(1),
|
|
23
|
+
timeoutMs: z.number().int().min(1000).max(60000).default(10000),
|
|
24
|
+
})
|
|
25
|
+
.optional(),
|
|
26
|
+
onChange: z.enum(["warn", "refuse"]).default("warn"),
|
|
27
|
+
})
|
|
28
|
+
.superRefine((auth, ctx) => {
|
|
29
|
+
if (auth.source === "exec" && auth.exec === undefined) {
|
|
30
|
+
ctx.addIssue({ code: "custom", path: ["exec"], message: 'exec is required when auth.source is "exec"' });
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
const SubsetSchema = z.object({
|
|
34
|
+
models: z.object({ native: z.record(z.string(), z.unknown()).optional() }).optional(),
|
|
35
|
+
agent: z
|
|
36
|
+
.object({
|
|
37
|
+
native: z.object({ catalogOverrides: z.array(z.record(z.string(), z.unknown())).optional() }).optional(),
|
|
38
|
+
})
|
|
39
|
+
.optional(),
|
|
40
|
+
auth: AuthSchema.optional(),
|
|
41
|
+
agentServer: z
|
|
42
|
+
.object({
|
|
43
|
+
defaultMode: z.enum(MODES).optional(),
|
|
44
|
+
bashApproval: z.enum(BASH_APPROVALS).optional(),
|
|
45
|
+
sessionsDir: z.string().min(1).optional(),
|
|
46
|
+
})
|
|
47
|
+
.optional(),
|
|
48
|
+
});
|
|
49
|
+
const DEFAULT_AUTH = { source: "file", onChange: "warn" };
|
|
50
|
+
export const EMPTY_NAX_CONFIG = {
|
|
51
|
+
tiers: [],
|
|
52
|
+
catalogOverrides: [],
|
|
53
|
+
auth: DEFAULT_AUTH,
|
|
54
|
+
agentServer: {},
|
|
55
|
+
};
|
|
56
|
+
function errorCode(error) {
|
|
57
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
|
|
58
|
+
? error.code
|
|
59
|
+
: undefined;
|
|
60
|
+
}
|
|
61
|
+
function message(error) {
|
|
62
|
+
return error instanceof Error ? error.message : String(error);
|
|
63
|
+
}
|
|
64
|
+
function tiersFrom(native) {
|
|
65
|
+
const tiers = [];
|
|
66
|
+
for (const tier of TIERS) {
|
|
67
|
+
const raw = native?.[tier];
|
|
68
|
+
if (raw === undefined)
|
|
69
|
+
continue;
|
|
70
|
+
const entry = ModelEntrySchema.safeParse(raw);
|
|
71
|
+
if (!entry.success)
|
|
72
|
+
return { tiers: [], issue: `models.native.${tier}: ${entry.error.issues[0]?.message}` };
|
|
73
|
+
const value = entry.data;
|
|
74
|
+
tiers.push(typeof value === "string"
|
|
75
|
+
? { tier, model: value }
|
|
76
|
+
: {
|
|
77
|
+
tier,
|
|
78
|
+
model: value.model,
|
|
79
|
+
...(value.contextWindow !== undefined ? { contextWindow: value.contextWindow } : {}),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
return { tiers };
|
|
83
|
+
}
|
|
84
|
+
function authFrom(auth) {
|
|
85
|
+
if (auth === undefined)
|
|
86
|
+
return DEFAULT_AUTH;
|
|
87
|
+
return {
|
|
88
|
+
source: auth.source,
|
|
89
|
+
onChange: auth.onChange,
|
|
90
|
+
...(auth.exec !== undefined ? { exec: { command: auth.exec.command, timeoutMs: auth.exec.timeoutMs } } : {}),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function fallback(path, reason) {
|
|
94
|
+
return { config: EMPTY_NAX_CONFIG, warning: `ignoring ${path}: ${reason}; using built-in defaults` };
|
|
95
|
+
}
|
|
96
|
+
export async function loadNaxConfig(configDir, readFile) {
|
|
97
|
+
const path = join(configDir, "config.json");
|
|
98
|
+
let text;
|
|
99
|
+
try {
|
|
100
|
+
text = await readFile(path, "utf8");
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (errorCode(error) === "ENOENT")
|
|
104
|
+
return { config: EMPTY_NAX_CONFIG };
|
|
105
|
+
return fallback(path, message(error));
|
|
106
|
+
}
|
|
107
|
+
let json;
|
|
108
|
+
try {
|
|
109
|
+
json = JSON.parse(text);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
// Not the parser's message: on Node it quotes the offending text, which may hold a key.
|
|
113
|
+
return fallback(path, "invalid JSON");
|
|
114
|
+
}
|
|
115
|
+
const parsed = SubsetSchema.safeParse(json);
|
|
116
|
+
if (!parsed.success) {
|
|
117
|
+
const issue = parsed.error.issues[0];
|
|
118
|
+
return fallback(path, `${issue?.path.join(".")}: ${issue?.message}`);
|
|
119
|
+
}
|
|
120
|
+
const { tiers, issue } = tiersFrom(parsed.data.models?.native);
|
|
121
|
+
if (issue !== undefined)
|
|
122
|
+
return fallback(path, issue);
|
|
123
|
+
return {
|
|
124
|
+
config: {
|
|
125
|
+
tiers,
|
|
126
|
+
catalogOverrides: parsed.data.agent?.native?.catalogOverrides ?? [],
|
|
127
|
+
auth: authFrom(parsed.data.auth),
|
|
128
|
+
agentServer: parsed.data.agentServer ?? {},
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** Credentials read from `configDir` with the auth block re-read per call, as nax does (M-3). */
|
|
133
|
+
export function credentialsFor(configDir, readFile) {
|
|
134
|
+
return {
|
|
135
|
+
configDir: () => configDir,
|
|
136
|
+
readAuthConfig: async () => (await loadNaxConfig(configDir, readFile)).config.auth,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opens the S3 session behind an ACP session (S5 spec §5.3 session/new): the
|
|
3
|
+
* native backend with the session's model and bash approval, and a transcript
|
|
4
|
+
* store, resuming a stored session or creating a new one (S5-3 M-21). The
|
|
5
|
+
* facade factories are injectable for tests.
|
|
6
|
+
*/
|
|
7
|
+
import { type AgentLogger, type AgentSession, type AgentSessionProfile, type CreateAgentSessionOptions, type NativeBackendOptions, type NativeCatalogOverrides, type SessionBackend, type TranscriptDoc, type TranscriptStore } from "@nathapp/nax-agent";
|
|
8
|
+
import type { BashApproval } from "#src/server/nax-config";
|
|
9
|
+
export interface OpenSessionRequest {
|
|
10
|
+
readonly sessionId: string;
|
|
11
|
+
readonly cwd: string;
|
|
12
|
+
readonly model: string;
|
|
13
|
+
readonly profile: AgentSessionProfile;
|
|
14
|
+
readonly bashApproval: BashApproval;
|
|
15
|
+
}
|
|
16
|
+
export interface OpenedSession {
|
|
17
|
+
readonly session: AgentSession;
|
|
18
|
+
/** The stored document read before opening; null for a session never prompted. */
|
|
19
|
+
readonly doc: TranscriptDoc | null;
|
|
20
|
+
}
|
|
21
|
+
export type OpenSession = (request: OpenSessionRequest) => Promise<OpenedSession>;
|
|
22
|
+
/** Entries nax's own schema would reject are dropped here, with one warning (M-17). */
|
|
23
|
+
export declare function catalogOverridesFrom(raw: readonly unknown[], logger: AgentLogger): NativeCatalogOverrides;
|
|
24
|
+
export interface NativeOpenDeps {
|
|
25
|
+
readonly transcripts: TranscriptStore;
|
|
26
|
+
readonly catalogOverrides: NativeCatalogOverrides;
|
|
27
|
+
readonly turnTimeoutSeconds: number;
|
|
28
|
+
readonly create?: (options: CreateAgentSessionOptions) => Promise<AgentSession>;
|
|
29
|
+
readonly resume?: (sessionId: string, options: CreateAgentSessionOptions) => Promise<AgentSession>;
|
|
30
|
+
readonly backend?: (options: NativeBackendOptions) => SessionBackend;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Resume when the store holds the session's document, create when it does not:
|
|
34
|
+
* a session never prompted has none (M-21). History is kept across a model
|
|
35
|
+
* change (M-19).
|
|
36
|
+
*/
|
|
37
|
+
export declare function nativeOpenSession(deps: NativeOpenDeps): OpenSession;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opens the S3 session behind an ACP session (S5 spec §5.3 session/new): the
|
|
3
|
+
* native backend with the session's model and bash approval, and a transcript
|
|
4
|
+
* store, resuming a stored session or creating a new one (S5-3 M-21). The
|
|
5
|
+
* facade factories are injectable for tests.
|
|
6
|
+
*/
|
|
7
|
+
import { createAgentSession, nativeBackend, resumeAgentSession, } from "@nathapp/nax-agent";
|
|
8
|
+
function isCatalogOverride(value) {
|
|
9
|
+
return (typeof value === "object" &&
|
|
10
|
+
value !== null &&
|
|
11
|
+
"provider" in value &&
|
|
12
|
+
typeof value.provider === "string" &&
|
|
13
|
+
"models" in value &&
|
|
14
|
+
Array.isArray(value.models));
|
|
15
|
+
}
|
|
16
|
+
/** Entries nax's own schema would reject are dropped here, with one warning (M-17). */
|
|
17
|
+
export function catalogOverridesFrom(raw, logger) {
|
|
18
|
+
const kept = raw.filter(isCatalogOverride);
|
|
19
|
+
if (kept.length < raw.length) {
|
|
20
|
+
logger.warn("config", "ignoring agent.native.catalogOverrides entries without provider and models", {
|
|
21
|
+
dropped: raw.length - kept.length,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
return kept;
|
|
25
|
+
}
|
|
26
|
+
/** nax-agent accepts bashApproval only where Bash is offered (M-22). */
|
|
27
|
+
const TOOL_PROFILES = new Set(["ask", "full"]);
|
|
28
|
+
/**
|
|
29
|
+
* Resume when the store holds the session's document, create when it does not:
|
|
30
|
+
* a session never prompted has none (M-21). History is kept across a model
|
|
31
|
+
* change (M-19).
|
|
32
|
+
*/
|
|
33
|
+
export function nativeOpenSession(deps) {
|
|
34
|
+
const create = deps.create ?? createAgentSession;
|
|
35
|
+
const resume = deps.resume ?? resumeAgentSession;
|
|
36
|
+
const backend = deps.backend ?? nativeBackend;
|
|
37
|
+
return async (request) => {
|
|
38
|
+
const doc = await deps.transcripts.load(request.sessionId);
|
|
39
|
+
const options = {
|
|
40
|
+
backend: backend({
|
|
41
|
+
model: request.model,
|
|
42
|
+
carryHistoryAcrossModels: true,
|
|
43
|
+
...(TOOL_PROFILES.has(request.profile) ? { bashApproval: request.bashApproval } : {}),
|
|
44
|
+
...(deps.catalogOverrides.length > 0 ? { catalogOverrides: deps.catalogOverrides } : {}),
|
|
45
|
+
}),
|
|
46
|
+
sessionId: request.sessionId,
|
|
47
|
+
profile: request.profile,
|
|
48
|
+
...(request.profile !== "none" ? { workdir: request.cwd } : {}),
|
|
49
|
+
transcriptStore: deps.transcripts,
|
|
50
|
+
turnTimeoutSeconds: deps.turnTimeoutSeconds,
|
|
51
|
+
};
|
|
52
|
+
const session = doc === null ? await create(options) : await resume(request.sessionId, options);
|
|
53
|
+
return { session, doc };
|
|
54
|
+
};
|
|
55
|
+
}
|