@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,19 @@
1
+ /**
2
+ * What the model sees of an MCP tool (S5-5 spec §5.2): a control-stripped,
3
+ * 2 KiB-capped description prefixed with its server, and an input schema that
4
+ * must be a JSON object of type "object" (`$schema` removed, missing
5
+ * `properties` added) within 32 KiB. A schema the provider rejects for other
6
+ * reasons is not contained here.
7
+ */
8
+ import type { JSONSchema } from "@nathapp/nax-agent";
9
+ export declare const MCP_DESCRIPTION_BYTES = 2048;
10
+ export declare const MCP_SCHEMA_BYTES = 32768;
11
+ export type ShapedSchema = {
12
+ readonly ok: true;
13
+ readonly schema: JSONSchema;
14
+ } | {
15
+ readonly ok: false;
16
+ readonly reason: string;
17
+ };
18
+ export declare function shapeDescription(server: string, description: string): string;
19
+ export declare function shapeSchema(schema: unknown): ShapedSchema;
@@ -0,0 +1,20 @@
1
+ import { capBytes, isRecord, stripControl, stripInvisible } from "#src/client/text";
2
+ export const MCP_DESCRIPTION_BYTES = 2048;
3
+ export const MCP_SCHEMA_BYTES = 32_768;
4
+ export function shapeDescription(server, description) {
5
+ const text = stripInvisible(stripControl(description)).trim();
6
+ return capBytes(text === "" ? `[${server}]` : `[${server}] ${text}`, MCP_DESCRIPTION_BYTES);
7
+ }
8
+ export function shapeSchema(schema) {
9
+ if (!isRecord(schema))
10
+ return { ok: false, reason: "input schema is not an object" };
11
+ if (schema.type !== "object")
12
+ return { ok: false, reason: 'input schema type must be "object"' };
13
+ if (schema.properties !== undefined && !isRecord(schema.properties))
14
+ return { ok: false, reason: "input schema properties must be an object" };
15
+ const { $schema: _dropped, ...rest } = schema;
16
+ const shaped = { ...rest, properties: schema.properties ?? {} };
17
+ if (Buffer.byteLength(JSON.stringify(shaped), "utf8") > MCP_SCHEMA_BYTES)
18
+ return { ok: false, reason: `input schema is larger than ${MCP_SCHEMA_BYTES} bytes` };
19
+ return { ok: true, schema: shaped };
20
+ }
@@ -0,0 +1,31 @@
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
+ readonly mcpConnectTimeoutSeconds?: number;
15
+ }
16
+ export interface NaxConfigSubset {
17
+ readonly tiers: readonly TierModel[];
18
+ readonly catalogOverrides: readonly Readonly<Record<string, unknown>>[];
19
+ readonly auth: CredentialAuthConfig;
20
+ readonly agentServer: AgentServerSection;
21
+ }
22
+ export interface LoadedNaxConfig {
23
+ readonly config: NaxConfigSubset;
24
+ readonly warning?: string;
25
+ }
26
+ export declare const MODES: readonly ["none", "read", "ask", "full"];
27
+ export declare const BASH_APPROVALS: readonly ["gated", "escalate", "raw"];
28
+ export declare const EMPTY_NAX_CONFIG: NaxConfigSubset;
29
+ export declare function loadNaxConfig(configDir: string, readFile: ReadTextFile): Promise<LoadedNaxConfig>;
30
+ /** Credentials read from `configDir` with the auth block re-read per call, as nax does (M-3). */
31
+ export declare function credentialsFor(configDir: string, readFile: ReadTextFile): CredentialsConfig;
@@ -0,0 +1,139 @@
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
+ mcpConnectTimeoutSeconds: z.number().int().min(1).max(300).optional(),
47
+ })
48
+ .optional(),
49
+ });
50
+ const DEFAULT_AUTH = { source: "file", onChange: "warn" };
51
+ export const EMPTY_NAX_CONFIG = {
52
+ tiers: [],
53
+ catalogOverrides: [],
54
+ auth: DEFAULT_AUTH,
55
+ agentServer: {},
56
+ };
57
+ function errorCode(error) {
58
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
59
+ ? error.code
60
+ : undefined;
61
+ }
62
+ function message(error) {
63
+ return error instanceof Error ? error.message : String(error);
64
+ }
65
+ function tiersFrom(native) {
66
+ const tiers = [];
67
+ for (const tier of TIERS) {
68
+ const raw = native?.[tier];
69
+ if (raw === undefined)
70
+ continue;
71
+ const entry = ModelEntrySchema.safeParse(raw);
72
+ if (!entry.success)
73
+ return { tiers: [], issue: `models.native.${tier}: ${entry.error.issues[0]?.message}` };
74
+ const value = entry.data;
75
+ tiers.push(typeof value === "string"
76
+ ? { tier, model: value }
77
+ : {
78
+ tier,
79
+ model: value.model,
80
+ ...(value.contextWindow !== undefined ? { contextWindow: value.contextWindow } : {}),
81
+ });
82
+ }
83
+ return { tiers };
84
+ }
85
+ function authFrom(auth) {
86
+ if (auth === undefined)
87
+ return DEFAULT_AUTH;
88
+ return {
89
+ source: auth.source,
90
+ onChange: auth.onChange,
91
+ ...(auth.exec !== undefined ? { exec: { command: auth.exec.command, timeoutMs: auth.exec.timeoutMs } } : {}),
92
+ };
93
+ }
94
+ function fallback(path, reason) {
95
+ return { config: EMPTY_NAX_CONFIG, warning: `ignoring ${path}: ${reason}; using built-in defaults` };
96
+ }
97
+ export async function loadNaxConfig(configDir, readFile) {
98
+ const path = join(configDir, "config.json");
99
+ let text;
100
+ try {
101
+ text = await readFile(path, "utf8");
102
+ }
103
+ catch (error) {
104
+ if (errorCode(error) === "ENOENT")
105
+ return { config: EMPTY_NAX_CONFIG };
106
+ return fallback(path, message(error));
107
+ }
108
+ let json;
109
+ try {
110
+ json = JSON.parse(text);
111
+ }
112
+ catch {
113
+ // Not the parser's message: on Node it quotes the offending text, which may hold a key.
114
+ return fallback(path, "invalid JSON");
115
+ }
116
+ const parsed = SubsetSchema.safeParse(json);
117
+ if (!parsed.success) {
118
+ const issue = parsed.error.issues[0];
119
+ return fallback(path, `${issue?.path.join(".")}: ${issue?.message}`);
120
+ }
121
+ const { tiers, issue } = tiersFrom(parsed.data.models?.native);
122
+ if (issue !== undefined)
123
+ return fallback(path, issue);
124
+ return {
125
+ config: {
126
+ tiers,
127
+ catalogOverrides: parsed.data.agent?.native?.catalogOverrides ?? [],
128
+ auth: authFrom(parsed.data.auth),
129
+ agentServer: parsed.data.agentServer ?? {},
130
+ },
131
+ };
132
+ }
133
+ /** Credentials read from `configDir` with the auth block re-read per call, as nax does (M-3). */
134
+ export function credentialsFor(configDir, readFile) {
135
+ return {
136
+ configDir: () => configDir,
137
+ readAuthConfig: async () => (await loadNaxConfig(configDir, readFile)).config.auth,
138
+ };
139
+ }
@@ -0,0 +1,38 @@
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 EmbedderTool, 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
+ readonly tools: readonly EmbedderTool[];
16
+ }
17
+ export interface OpenedSession {
18
+ readonly session: AgentSession;
19
+ /** The stored document read before opening; null for a session never prompted. */
20
+ readonly doc: TranscriptDoc | null;
21
+ }
22
+ export type OpenSession = (request: OpenSessionRequest) => Promise<OpenedSession>;
23
+ /** Entries nax's own schema would reject are dropped here, with one warning (M-17). */
24
+ export declare function catalogOverridesFrom(raw: readonly unknown[], logger: AgentLogger): NativeCatalogOverrides;
25
+ export interface NativeOpenDeps {
26
+ readonly transcripts: TranscriptStore;
27
+ readonly catalogOverrides: NativeCatalogOverrides;
28
+ readonly turnTimeoutSeconds: number;
29
+ readonly create?: (options: CreateAgentSessionOptions) => Promise<AgentSession>;
30
+ readonly resume?: (sessionId: string, options: CreateAgentSessionOptions) => Promise<AgentSession>;
31
+ readonly backend?: (options: NativeBackendOptions) => SessionBackend;
32
+ }
33
+ /**
34
+ * Resume when the store holds the session's document, create when it does not:
35
+ * a session never prompted has none (M-21). History is kept across a model
36
+ * change (M-19).
37
+ */
38
+ export declare function nativeOpenSession(deps: NativeOpenDeps): OpenSession;
@@ -0,0 +1,56 @@
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
+ ...(request.tools.length > 0 ? { tools: request.tools } : {}),
50
+ transcriptStore: deps.transcripts,
51
+ turnTimeoutSeconds: deps.turnTimeoutSeconds,
52
+ };
53
+ const session = doc === null ? await create(options) : await resume(request.sessionId, options);
54
+ return { session, doc };
55
+ };
56
+ }
@@ -0,0 +1,30 @@
1
+ import type { AgentSessionProfile } from "@nathapp/nax-agent";
2
+ import type { CliFlags } from "#src/server/cli";
3
+ import { type BashApproval, type NaxConfigSubset, type TierModel } from "#src/server/nax-config";
4
+ export type Env = Readonly<Record<string, string | undefined>>;
5
+ /** S5-5b: the per-server MCP connect timeout, in seconds (1-300). */
6
+ export declare const MCP_CONNECT_TIMEOUT_SECONDS = 30;
7
+ export interface ServerOptions {
8
+ readonly configDir: string;
9
+ readonly sessionsDir: string;
10
+ readonly defaultModel?: string;
11
+ readonly defaultMode: AgentSessionProfile;
12
+ readonly bashApproval: BashApproval;
13
+ readonly tiers: readonly TierModel[];
14
+ readonly catalogOverrides: readonly Readonly<Record<string, unknown>>[];
15
+ readonly mcpConnectTimeoutSeconds: number;
16
+ }
17
+ export type OptionsResult = {
18
+ readonly ok: true;
19
+ readonly options: ServerOptions;
20
+ } | {
21
+ readonly ok: false;
22
+ readonly message: string;
23
+ };
24
+ export declare function resolveConfigDir(flags: CliFlags, env: Env, home: string): string;
25
+ export declare function resolveServerOptions(input: {
26
+ readonly flags: CliFlags;
27
+ readonly env: Env;
28
+ readonly file: NaxConfigSubset;
29
+ readonly configDir: string;
30
+ }): OptionsResult;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Option resolution for the ACP server (S5 spec §6.1): flag > env > config file >
3
+ * built-in default. Config dir: master plan M-5.
4
+ */
5
+ import { join } from "node:path";
6
+ import { BASH_APPROVALS, MODES } from "#src/server/nax-config";
7
+ /** S5-5b: the per-server MCP connect timeout, in seconds (1-300). */
8
+ export const MCP_CONNECT_TIMEOUT_SECONDS = 30;
9
+ function firstSet(...candidates) {
10
+ return candidates.find((c) => c !== undefined && c.value !== "");
11
+ }
12
+ function from(value, source) {
13
+ return value === undefined ? undefined : { value, source };
14
+ }
15
+ export function resolveConfigDir(flags, env, home) {
16
+ return (firstSet(from(flags.configDir, "--config-dir"), from(env.NAX_AGENT_CONFIG_DIR, "NAX_AGENT_CONFIG_DIR"), from(env.NAX_GLOBAL_CONFIG_DIR, "NAX_GLOBAL_CONFIG_DIR"))?.value ?? join(home, ".nax"));
17
+ }
18
+ function pickEnum(label, allowed, chosen, fallbackValue) {
19
+ if (chosen === undefined)
20
+ return { ok: true, value: fallbackValue };
21
+ const match = allowed.find((a) => a === chosen.value);
22
+ if (match !== undefined)
23
+ return { ok: true, value: match };
24
+ return {
25
+ ok: false,
26
+ message: `invalid ${label} "${chosen.value}" (from ${chosen.source}); expected one of ${allowed.join(", ")}`,
27
+ };
28
+ }
29
+ function pickSeconds(chosen, fallbackValue) {
30
+ if (chosen === undefined)
31
+ return { ok: true, value: fallbackValue };
32
+ const value = Number(chosen.value);
33
+ if (Number.isInteger(value) && value >= 1 && value <= 300)
34
+ return { ok: true, value };
35
+ return {
36
+ ok: false,
37
+ message: `invalid mcp connect timeout "${chosen.value}" (from ${chosen.source}); expected whole seconds 1-300`,
38
+ };
39
+ }
40
+ export function resolveServerOptions(input) {
41
+ const { flags, env, file, configDir } = input;
42
+ const mode = pickEnum("mode", MODES, firstSet(from(flags.mode, "--mode"), from(env.NAX_AGENT_MODE, "NAX_AGENT_MODE"), from(file.agentServer.defaultMode, "config.json agentServer.defaultMode")), "ask");
43
+ if (!mode.ok)
44
+ return mode;
45
+ const bash = pickEnum("bash approval", BASH_APPROVALS, firstSet(from(flags.bashApproval, "--bash-approval"), from(env.NAX_AGENT_BASH_APPROVAL, "NAX_AGENT_BASH_APPROVAL"), from(file.agentServer.bashApproval, "config.json agentServer.bashApproval")), "gated");
46
+ if (!bash.ok)
47
+ return bash;
48
+ if (mode.value === "ask" && bash.value !== "gated") {
49
+ return {
50
+ ok: false,
51
+ message: `bash approval "${bash.value}" cannot be used with mode "ask"; ask requires gated`,
52
+ };
53
+ }
54
+ const mcpTimeout = pickSeconds(firstSet(from(flags.mcpConnectTimeout, "--mcp-connect-timeout"), from(env.NAX_AGENT_MCP_CONNECT_TIMEOUT, "NAX_AGENT_MCP_CONNECT_TIMEOUT"), from(file.agentServer.mcpConnectTimeoutSeconds?.toString(), "config.json agentServer.mcpConnectTimeoutSeconds")), MCP_CONNECT_TIMEOUT_SECONDS);
55
+ if (!mcpTimeout.ok)
56
+ return mcpTimeout;
57
+ const sessionsDir = firstSet(from(flags.sessionsDir, "--sessions-dir"), from(env.NAX_AGENT_SESSIONS_DIR, "NAX_AGENT_SESSIONS_DIR"), from(file.agentServer.sessionsDir, "config.json agentServer.sessionsDir"))?.value ?? join(configDir, ".agent-server", "sessions");
58
+ const defaultModel = firstSet(from(flags.model, "--model"), from(env.NAX_AGENT_MODEL, "NAX_AGENT_MODEL"), from(file.tiers.find((t) => t.tier === "balanced")?.model, "config.json models.native.balanced"))?.value;
59
+ return {
60
+ ok: true,
61
+ options: {
62
+ configDir,
63
+ sessionsDir,
64
+ ...(defaultModel !== undefined ? { defaultModel } : {}),
65
+ defaultMode: mode.value,
66
+ bashApproval: bash.value,
67
+ tiers: file.tiers,
68
+ catalogOverrides: file.catalogOverrides,
69
+ mcpConnectTimeoutSeconds: mcpTimeout.value,
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Approval round trips (S5 spec §4.3). A human approval becomes a
3
+ * `session/request_permission`, and the chosen option is passed to `answer()`.
4
+ * allow_always and reject_always are remembered for the session's life (M-12).
5
+ * Execute tools are keyed on the command plus its subcommand (`git status`,
6
+ * `npm test`) when the second word is a plain word, else on the command alone
7
+ * (`ls`, `ls -la`), so "always allow git status" never approves `git push`.
8
+ * Never remembered: no command; a first or second word that is not plain
9
+ * (quotes, escapes, globs, expansions, an environment assignment), which must
10
+ * not widen the key; a masked command (its visible words are not the real
11
+ * command); a wrapper or interpreter, whose first word says nothing about what
12
+ * runs. A remembered allow covers only a simple command: one with shell
13
+ * metacharacters (chaining, substitution, redirection) is asked again. A
14
+ * remembered reject applies to its key regardless. When S3 settles a request
15
+ * itself (timeout, cancel), the client request is aborted and a late reply is
16
+ * ignored. A failed client request is a deny (M-13).
17
+ */
18
+ import type { PermissionOption, ToolCallUpdate } from "@agentclientprotocol/sdk";
19
+ import type { AgentLogger, AnswerReply, AnswerStatus, SessionEvent } from "@nathapp/nax-agent";
20
+ import { type ClientPort } from "#src/server/client-port";
21
+ export type Decision = "allow" | "deny";
22
+ export type ApprovalEvent = Extract<SessionEvent, {
23
+ type: "approval_requested";
24
+ }>;
25
+ export type Answer = (requestId: string, reply: AnswerReply) => AnswerStatus;
26
+ export declare const PERMISSION_OPTIONS: readonly PermissionOption[];
27
+ export interface PermissionBroker {
28
+ /** Starts the round trip for one human approval; never blocks the caller. */
29
+ request(event: ApprovalEvent, toolCall: ToolCallUpdate | undefined): void;
30
+ /** S3 resolved the request itself: stop waiting for the client. */
31
+ settled(requestId: string): void;
32
+ /** Cancel or turn end: stop waiting on every open request. */
33
+ abortAll(): void;
34
+ /** Resolves when every round trip started so far has finished. */
35
+ drain(): Promise<void>;
36
+ }
37
+ export interface PermissionBrokerDeps {
38
+ readonly port: ClientPort;
39
+ readonly answer: Answer;
40
+ readonly memory: Map<string, Decision>;
41
+ readonly logger: AgentLogger;
42
+ }
43
+ export declare function memoryKey(event: ApprovalEvent): string | undefined;
44
+ export declare function createPermissionBroker(deps: PermissionBrokerDeps): PermissionBroker;
@@ -0,0 +1,157 @@
1
+ import { stripControl, stripInvisible } from "#src/client/text";
2
+ import { untilAborted } from "#src/server/client-port";
3
+ import { messageOf } from "#src/server/errors";
4
+ import { displayLine, toolKind } from "#src/server/translate/tool-kind";
5
+ export const PERMISSION_OPTIONS = [
6
+ { optionId: "allow_once", name: "Allow", kind: "allow_once" },
7
+ { optionId: "allow_always", name: "Always allow", kind: "allow_always" },
8
+ { optionId: "reject_once", name: "Reject", kind: "reject_once" },
9
+ { optionId: "reject_always", name: "Always reject", kind: "reject_always" },
10
+ ];
11
+ const DENY = { decision: "deny", remember: false };
12
+ /** Chaining, pipes, substitution, subshells, redirection and line breaks. */
13
+ const SHELL_METACHARACTERS = /[;&|`$()<>\n\r]/;
14
+ /** First words that run another command or arbitrary code. */
15
+ const WRAPPERS = new Set([
16
+ "sh",
17
+ "bash",
18
+ "zsh",
19
+ "dash",
20
+ "ksh",
21
+ "fish",
22
+ "env",
23
+ "xargs",
24
+ "sudo",
25
+ "doas",
26
+ "su",
27
+ "command",
28
+ "builtin",
29
+ "eval",
30
+ "exec",
31
+ "source",
32
+ ".",
33
+ "nohup",
34
+ "time",
35
+ "timeout",
36
+ "nice",
37
+ "ionice",
38
+ "stdbuf",
39
+ "watch",
40
+ "find",
41
+ "node",
42
+ "bun",
43
+ "deno",
44
+ "npx",
45
+ "bunx",
46
+ "pnpx",
47
+ "python",
48
+ "python3",
49
+ "perl",
50
+ "ruby",
51
+ "php",
52
+ "uv",
53
+ "uvx",
54
+ ]);
55
+ /** A plain command name or path: no quotes, escapes, globs or expansions the shell would rewrite. */
56
+ const PLAIN_WORD = /^[A-Za-z0-9._/-]+$/;
57
+ /** The masking prefix S3 puts in place of a secret in a shown command. */
58
+ const MASK_MARKER = "[REDACTED";
59
+ export function memoryKey(event) {
60
+ if (toolKind(event.tool) !== "execute")
61
+ return event.tool;
62
+ const command = event.command ?? "";
63
+ if (command.includes(MASK_MARKER))
64
+ return undefined;
65
+ const [first = "", second] = command.trim().split(/\s+/);
66
+ if (!PLAIN_WORD.test(first))
67
+ return undefined;
68
+ const name = first.slice(first.lastIndexOf("/") + 1).toLowerCase();
69
+ if (name === "" || WRAPPERS.has(name))
70
+ return undefined;
71
+ if (second === undefined || second.startsWith("-"))
72
+ return `${event.tool}:${first}`;
73
+ return PLAIN_WORD.test(second) ? `${event.tool}:${first} ${second}` : undefined;
74
+ }
75
+ /** Whether a remembered decision may answer this request without asking. */
76
+ function memoryApplies(event, decision) {
77
+ if (decision === "deny" || toolKind(event.tool) !== "execute")
78
+ return true;
79
+ return !SHELL_METACHARACTERS.test(event.command ?? "");
80
+ }
81
+ function choice(response) {
82
+ const { outcome } = response;
83
+ if (outcome.outcome !== "selected")
84
+ return DENY;
85
+ switch (PERMISSION_OPTIONS.find((option) => option.optionId === outcome.optionId)?.kind) {
86
+ case "allow_once":
87
+ return { decision: "allow", remember: false };
88
+ case "allow_always":
89
+ return { decision: "allow", remember: true };
90
+ case "reject_always":
91
+ return { decision: "deny", remember: true };
92
+ default:
93
+ return DENY;
94
+ }
95
+ }
96
+ function fallbackToolCall(event) {
97
+ return {
98
+ toolCallId: event.callId ?? event.requestId,
99
+ title: displayLine(event.summary),
100
+ kind: toolKind(event.tool),
101
+ status: "pending",
102
+ ...(event.command !== undefined ? { rawInput: { command: stripInvisible(stripControl(event.command)) } } : {}),
103
+ };
104
+ }
105
+ export function createPermissionBroker(deps) {
106
+ const open = new Map();
107
+ const running = new Set();
108
+ async function roundTrip(event, toolCall, key) {
109
+ const controller = new AbortController();
110
+ open.set(event.requestId, controller);
111
+ let reply;
112
+ try {
113
+ const ask = { toolCall, options: PERMISSION_OPTIONS };
114
+ reply = choice(await untilAborted(deps.port.requestPermission(ask, controller.signal), controller.signal));
115
+ }
116
+ catch (error) {
117
+ if (controller.signal.aborted)
118
+ return;
119
+ deps.logger.warn("permissions", "permission request failed; denying", { error: messageOf(error) });
120
+ reply = DENY;
121
+ }
122
+ finally {
123
+ open.delete(event.requestId);
124
+ }
125
+ if (controller.signal.aborted)
126
+ return;
127
+ if (reply.remember && key !== undefined)
128
+ deps.memory.set(key, reply.decision);
129
+ deps.answer(event.requestId, { decision: reply.decision });
130
+ }
131
+ return {
132
+ request(event, toolCall) {
133
+ const key = memoryKey(event);
134
+ const remembered = key === undefined ? undefined : deps.memory.get(key);
135
+ if (remembered !== undefined && memoryApplies(event, remembered)) {
136
+ deps.answer(event.requestId, { decision: remembered });
137
+ return;
138
+ }
139
+ // Never rejects: a throwing answer() or logger must not become an unhandled rejection.
140
+ const trip = roundTrip(event, toolCall ?? fallbackToolCall(event), key).catch((error) => {
141
+ deps.logger.warn("permissions", "permission round trip failed", { error: messageOf(error) });
142
+ });
143
+ running.add(trip);
144
+ void trip.finally(() => running.delete(trip));
145
+ },
146
+ settled(requestId) {
147
+ open.get(requestId)?.abort();
148
+ },
149
+ abortAll() {
150
+ for (const controller of open.values())
151
+ controller.abort();
152
+ },
153
+ async drain() {
154
+ await Promise.all([...running]);
155
+ },
156
+ };
157
+ }
@@ -0,0 +1,15 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { type MainDeps } from "#src/server/main";
3
+ import type { Env } from "#src/server/options";
4
+ export interface ProcessLike {
5
+ readonly argv: readonly string[];
6
+ readonly env: Env;
7
+ readonly stdin: Readable & {
8
+ readonly isTTY?: boolean;
9
+ };
10
+ readonly stdout: Writable;
11
+ readonly stderr: Writable;
12
+ once(event: "SIGINT" | "SIGTERM", listener: () => void): unknown;
13
+ }
14
+ export declare function mainDepsFrom(proc: ProcessLike): MainDeps;
15
+ export declare function runCli(proc: ProcessLike): Promise<number>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Adapts a real process to `MainDeps` (master plan M-2): the published bin is a
3
+ * three-line file that calls `runCli(process)`.
4
+ */
5
+ import { readFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { main } from "#src/server/main";
8
+ export function mainDepsFrom(proc) {
9
+ return {
10
+ argv: proc.argv.slice(2),
11
+ env: proc.env,
12
+ homedir: homedir(),
13
+ stdin: proc.stdin,
14
+ stdout: proc.stdout,
15
+ writeErr: (text) => {
16
+ proc.stderr.write(text);
17
+ },
18
+ readFile: (path, encoding) => readFile(path, encoding),
19
+ onSignal: (handler) => {
20
+ proc.once("SIGINT", handler);
21
+ proc.once("SIGTERM", handler);
22
+ },
23
+ isTTY: proc.stdin.isTTY === true,
24
+ };
25
+ }
26
+ export function runCli(proc) {
27
+ return main(mainDepsFrom(proc));
28
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * ACP prompt content as the one text message S3's `send()` takes (S5 spec §3.2):
3
+ * text verbatim; an embedded text resource as a fenced block headed by its URI;
4
+ * a resource link as its URI. Image, audio and binary content are not
5
+ * advertised and are rejected.
6
+ */
7
+ import type { ContentBlock } from "@agentclientprotocol/sdk";
8
+ export declare function flattenPrompt(blocks: readonly ContentBlock[]): string;