@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,27 @@
|
|
|
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
|
+
export interface ServerOptions {
|
|
6
|
+
readonly configDir: string;
|
|
7
|
+
readonly sessionsDir: string;
|
|
8
|
+
readonly defaultModel?: string;
|
|
9
|
+
readonly defaultMode: AgentSessionProfile;
|
|
10
|
+
readonly bashApproval: BashApproval;
|
|
11
|
+
readonly tiers: readonly TierModel[];
|
|
12
|
+
readonly catalogOverrides: readonly Readonly<Record<string, unknown>>[];
|
|
13
|
+
}
|
|
14
|
+
export type OptionsResult = {
|
|
15
|
+
readonly ok: true;
|
|
16
|
+
readonly options: ServerOptions;
|
|
17
|
+
} | {
|
|
18
|
+
readonly ok: false;
|
|
19
|
+
readonly message: string;
|
|
20
|
+
};
|
|
21
|
+
export declare function resolveConfigDir(flags: CliFlags, env: Env, home: string): string;
|
|
22
|
+
export declare function resolveServerOptions(input: {
|
|
23
|
+
readonly flags: CliFlags;
|
|
24
|
+
readonly env: Env;
|
|
25
|
+
readonly file: NaxConfigSubset;
|
|
26
|
+
readonly configDir: string;
|
|
27
|
+
}): OptionsResult;
|
|
@@ -0,0 +1,55 @@
|
|
|
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
|
+
function firstSet(...candidates) {
|
|
8
|
+
return candidates.find((c) => c !== undefined && c.value !== "");
|
|
9
|
+
}
|
|
10
|
+
function from(value, source) {
|
|
11
|
+
return value === undefined ? undefined : { value, source };
|
|
12
|
+
}
|
|
13
|
+
export function resolveConfigDir(flags, env, home) {
|
|
14
|
+
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"));
|
|
15
|
+
}
|
|
16
|
+
function pickEnum(label, allowed, chosen, fallbackValue) {
|
|
17
|
+
if (chosen === undefined)
|
|
18
|
+
return { ok: true, value: fallbackValue };
|
|
19
|
+
const match = allowed.find((a) => a === chosen.value);
|
|
20
|
+
if (match !== undefined)
|
|
21
|
+
return { ok: true, value: match };
|
|
22
|
+
return {
|
|
23
|
+
ok: false,
|
|
24
|
+
message: `invalid ${label} "${chosen.value}" (from ${chosen.source}); expected one of ${allowed.join(", ")}`,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function resolveServerOptions(input) {
|
|
28
|
+
const { flags, env, file, configDir } = input;
|
|
29
|
+
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");
|
|
30
|
+
if (!mode.ok)
|
|
31
|
+
return mode;
|
|
32
|
+
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");
|
|
33
|
+
if (!bash.ok)
|
|
34
|
+
return bash;
|
|
35
|
+
if (mode.value === "ask" && bash.value !== "gated") {
|
|
36
|
+
return {
|
|
37
|
+
ok: false,
|
|
38
|
+
message: `bash approval "${bash.value}" cannot be used with mode "ask"; ask requires gated`,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
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");
|
|
42
|
+
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;
|
|
43
|
+
return {
|
|
44
|
+
ok: true,
|
|
45
|
+
options: {
|
|
46
|
+
configDir,
|
|
47
|
+
sessionsDir,
|
|
48
|
+
...(defaultModel !== undefined ? { defaultModel } : {}),
|
|
49
|
+
defaultMode: mode.value,
|
|
50
|
+
bashApproval: bash.value,
|
|
51
|
+
tiers: file.tiers,
|
|
52
|
+
catalogOverrides: file.catalogOverrides,
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -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;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { invalidParams } from "#src/server/errors";
|
|
2
|
+
function fenceFor(text) {
|
|
3
|
+
const longest = Math.max(0, ...Array.from(text.matchAll(/`+/g), (run) => run[0].length));
|
|
4
|
+
return "`".repeat(Math.max(3, longest + 1));
|
|
5
|
+
}
|
|
6
|
+
function blockText(block) {
|
|
7
|
+
switch (block.type) {
|
|
8
|
+
case "text":
|
|
9
|
+
return block.text;
|
|
10
|
+
case "resource_link":
|
|
11
|
+
return block.uri;
|
|
12
|
+
case "resource": {
|
|
13
|
+
const { resource } = block;
|
|
14
|
+
if (!("text" in resource))
|
|
15
|
+
throw invalidParams(`binary embedded resource ${resource.uri} is not supported`);
|
|
16
|
+
const fence = fenceFor(resource.text);
|
|
17
|
+
return `${resource.uri}\n${fence}\n${resource.text}\n${fence}`;
|
|
18
|
+
}
|
|
19
|
+
case "image":
|
|
20
|
+
case "audio":
|
|
21
|
+
throw invalidParams(`${block.type} prompt content is not supported`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function flattenPrompt(blocks) {
|
|
25
|
+
const parts = blocks.map(blockText).filter((part) => part !== "");
|
|
26
|
+
if (parts.length === 0)
|
|
27
|
+
throw invalidParams("the prompt has no text");
|
|
28
|
+
return parts.join("\n\n");
|
|
29
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Questions (S5 spec §4.3). With form elicitation: one required free-text field,
|
|
3
|
+
* the accepted text is the answer, anything else is the declined text. Without
|
|
4
|
+
* it: the question is shown and answered at once with the no-answer text, so a
|
|
5
|
+
* headless client never leaves the agent waiting. The open elicitation is aborted
|
|
6
|
+
* at the question's expiresAt (M-14). An unanswerable question (M-1) is shown
|
|
7
|
+
* only.
|
|
8
|
+
*/
|
|
9
|
+
import type { SessionUpdate } from "@agentclientprotocol/sdk";
|
|
10
|
+
import type { AgentLogger, SessionEvent } from "@nathapp/nax-agent";
|
|
11
|
+
import { type ClientPort } from "#src/server/client-port";
|
|
12
|
+
import type { Answer } from "#src/server/permissions";
|
|
13
|
+
export declare const ANSWER_FIELD = "answer";
|
|
14
|
+
export declare const DECLINED_TEXT = "The user declined to answer.";
|
|
15
|
+
export declare const NO_ANSWER_TEXT = "No answer available: this client cannot answer questions. Proceed with your best judgement.";
|
|
16
|
+
export type QuestionEvent = Extract<SessionEvent, {
|
|
17
|
+
type: "question";
|
|
18
|
+
}>;
|
|
19
|
+
export interface QuestionBroker {
|
|
20
|
+
/** Starts handling one question; never blocks the caller. */
|
|
21
|
+
ask(event: QuestionEvent): void;
|
|
22
|
+
abortAll(): void;
|
|
23
|
+
drain(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
export interface QuestionBrokerDeps {
|
|
26
|
+
readonly port: ClientPort;
|
|
27
|
+
/** The session's delivery (it handles a broken connection). */
|
|
28
|
+
readonly deliver: (update: SessionUpdate) => Promise<void>;
|
|
29
|
+
readonly answer: Answer;
|
|
30
|
+
readonly logger: AgentLogger;
|
|
31
|
+
readonly now?: () => number;
|
|
32
|
+
}
|
|
33
|
+
export declare function createQuestionBroker(deps: QuestionBrokerDeps): QuestionBroker;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { untilAborted } from "#src/server/client-port";
|
|
2
|
+
import { messageOf } from "#src/server/errors";
|
|
3
|
+
import { announce } from "#src/server/translate/notice";
|
|
4
|
+
export const ANSWER_FIELD = "answer";
|
|
5
|
+
export const DECLINED_TEXT = "The user declined to answer.";
|
|
6
|
+
export const NO_ANSWER_TEXT = "No answer available: this client cannot answer questions. Proceed with your best judgement.";
|
|
7
|
+
function formFor(text) {
|
|
8
|
+
return {
|
|
9
|
+
message: text,
|
|
10
|
+
requestedSchema: {
|
|
11
|
+
type: "object",
|
|
12
|
+
properties: { [ANSWER_FIELD]: { type: "string", title: "Answer" } },
|
|
13
|
+
required: [ANSWER_FIELD],
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function answerText(response) {
|
|
18
|
+
if (response.action !== "accept")
|
|
19
|
+
return DECLINED_TEXT;
|
|
20
|
+
// The response union has an open `action: string` member, so read content defensively.
|
|
21
|
+
const content = "content" in response ? response.content : undefined;
|
|
22
|
+
const value = typeof content === "object" && content !== null ? Reflect.get(content, ANSWER_FIELD) : undefined;
|
|
23
|
+
return typeof value === "string" && value.trim() !== "" ? value : DECLINED_TEXT;
|
|
24
|
+
}
|
|
25
|
+
export function createQuestionBroker(deps) {
|
|
26
|
+
const now = deps.now ?? Date.now;
|
|
27
|
+
const open = new Set();
|
|
28
|
+
const running = new Set();
|
|
29
|
+
const notices = deps.port.features.updates.notices;
|
|
30
|
+
async function elicit(event) {
|
|
31
|
+
const controller = new AbortController();
|
|
32
|
+
open.add(controller);
|
|
33
|
+
const expiry = setTimeout(() => controller.abort(), Math.max(0, Date.parse(event.expiresAt) - now()));
|
|
34
|
+
let text;
|
|
35
|
+
try {
|
|
36
|
+
text = answerText(await untilAborted(deps.port.elicit(formFor(event.text), controller.signal), controller.signal));
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (controller.signal.aborted)
|
|
40
|
+
return;
|
|
41
|
+
deps.logger.warn("questions", "elicitation failed; answering without the user", { error: messageOf(error) });
|
|
42
|
+
text = NO_ANSWER_TEXT;
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
clearTimeout(expiry);
|
|
46
|
+
open.delete(controller);
|
|
47
|
+
}
|
|
48
|
+
deps.answer(event.requestId, { text });
|
|
49
|
+
}
|
|
50
|
+
async function handle(event) {
|
|
51
|
+
if (event.answerable === false) {
|
|
52
|
+
await deps.deliver(announce(notices, "info", "The agent noted a question", event.text));
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (deps.port.features.elicitation) {
|
|
56
|
+
await elicit(event);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
await deps.deliver(announce(notices, "warning", "The agent asked a question", event.text));
|
|
60
|
+
deps.answer(event.requestId, { text: NO_ANSWER_TEXT });
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
ask(event) {
|
|
64
|
+
// Never rejects: a throwing answer() or delivery must not become an unhandled rejection.
|
|
65
|
+
const work = handle(event).catch((error) => {
|
|
66
|
+
deps.logger.warn("questions", "question handling failed", { error: messageOf(error) });
|
|
67
|
+
});
|
|
68
|
+
running.add(work);
|
|
69
|
+
void work.finally(() => running.delete(work));
|
|
70
|
+
},
|
|
71
|
+
abortAll() {
|
|
72
|
+
for (const controller of open)
|
|
73
|
+
controller.abort();
|
|
74
|
+
},
|
|
75
|
+
async drain() {
|
|
76
|
+
await Promise.all([...running]);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reopening a stored session for session/load and session/resume (S5 spec §5.3,
|
|
3
|
+
* §5.4). Extracted from registry.ts so neither module grows past the complexity
|
|
4
|
+
* limit; registry.ts owns the entry and lock lifecycle and passes its internals
|
|
5
|
+
* in. Load replays the stored transcript (and warns when the last turn was
|
|
6
|
+
* interrupted); resume reopens without replay.
|
|
7
|
+
*/
|
|
8
|
+
import type { AgentLogger, TranscriptStore } from "@nathapp/nax-agent";
|
|
9
|
+
import type { ClientPort } from "#src/server/client-port";
|
|
10
|
+
import type { OpenedSession } from "#src/server/open-session";
|
|
11
|
+
import type { Entry, OpenInput, SessionState } from "#src/server/registry";
|
|
12
|
+
import type { ServerSession } from "#src/server/server-session";
|
|
13
|
+
import type { SessionSettings } from "#src/server/session-config";
|
|
14
|
+
import type { SessionMeta, SessionStorage } from "#src/server/storage";
|
|
15
|
+
export interface ReopenDeps {
|
|
16
|
+
readonly entries: Map<string, Entry>;
|
|
17
|
+
readonly storage: SessionStorage;
|
|
18
|
+
readonly transcripts: TranscriptStore;
|
|
19
|
+
readonly logger: AgentLogger;
|
|
20
|
+
readonly openEntry: (meta: SessionMeta, port: ClientPort) => Promise<{
|
|
21
|
+
readonly server: ServerSession;
|
|
22
|
+
readonly opened: OpenedSession;
|
|
23
|
+
}>;
|
|
24
|
+
readonly closeEntry: (sessionId: string, entry: Entry) => Promise<void>;
|
|
25
|
+
readonly stateOf: (settings: SessionSettings) => SessionState;
|
|
26
|
+
readonly mcpNotice: string;
|
|
27
|
+
readonly interruptedNotice: string;
|
|
28
|
+
}
|
|
29
|
+
export interface Reopener {
|
|
30
|
+
reopen(sessionId: string, input: OpenInput, replay: boolean): Promise<SessionState>;
|
|
31
|
+
}
|
|
32
|
+
export declare const settingsOf: (meta: SessionMeta) => SessionSettings;
|
|
33
|
+
export declare function createReopen(deps: ReopenDeps): Reopener;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { unknownSession } from "#src/server/errors";
|
|
2
|
+
import { announce } from "#src/server/translate/notice";
|
|
3
|
+
import { replayTranscript } from "#src/server/translate/replay";
|
|
4
|
+
export const settingsOf = (meta) => ({
|
|
5
|
+
mode: meta.mode,
|
|
6
|
+
model: meta.model,
|
|
7
|
+
bashApproval: meta.bashApproval,
|
|
8
|
+
});
|
|
9
|
+
export function createReopen(deps) {
|
|
10
|
+
async function replayTo(port, messages, cwd) {
|
|
11
|
+
for (const update of replayTranscript(messages, cwd))
|
|
12
|
+
await port.update(update);
|
|
13
|
+
}
|
|
14
|
+
async function replayOpened(port, opened, cwd) {
|
|
15
|
+
await replayTo(port, opened.doc?.messages ?? [], cwd);
|
|
16
|
+
if (opened.session.lastTurn?.status === "interrupted") {
|
|
17
|
+
await port.update(announce(port.features.updates.notices, "warning", deps.interruptedNotice));
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function openAndReplay(sessionId, meta, input, replay) {
|
|
21
|
+
const port = input.port(sessionId);
|
|
22
|
+
const { server, opened } = await deps.openEntry(meta, port);
|
|
23
|
+
if (replay) {
|
|
24
|
+
try {
|
|
25
|
+
await replayOpened(port, opened, meta.cwd);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
// The client did not get its history: do not leave the session open and locked.
|
|
29
|
+
const entry = deps.entries.get(sessionId);
|
|
30
|
+
if (entry !== undefined)
|
|
31
|
+
await deps.closeEntry(sessionId, entry);
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (input.mcpServers.length > 0) {
|
|
36
|
+
server.queueNotice(announce(port.features.updates.notices, "warning", deps.mcpNotice));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
async reopen(sessionId, input, replay) {
|
|
41
|
+
const open = deps.entries.get(sessionId);
|
|
42
|
+
if (open !== undefined) {
|
|
43
|
+
if (replay) {
|
|
44
|
+
await replayTo(open.port, (await deps.transcripts.load(sessionId))?.messages ?? [], open.meta.cwd);
|
|
45
|
+
}
|
|
46
|
+
return deps.stateOf(settingsOf(open.meta));
|
|
47
|
+
}
|
|
48
|
+
const meta = await deps.storage.readMeta(sessionId);
|
|
49
|
+
if (meta === null)
|
|
50
|
+
throw unknownSession(sessionId);
|
|
51
|
+
if (input.cwd !== meta.cwd) {
|
|
52
|
+
deps.logger.debug("session", "reopening in the stored cwd", {
|
|
53
|
+
sessionId,
|
|
54
|
+
requested: input.cwd,
|
|
55
|
+
stored: meta.cwd,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
await openAndReplay(sessionId, meta, input, replay);
|
|
59
|
+
return deps.stateOf(settingsOf(meta));
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type ListSessionsResponse, type SessionConfigOption, type SessionModeState } from "@agentclientprotocol/sdk";
|
|
2
|
+
import type { AgentLogger, TranscriptStore } from "@nathapp/nax-agent";
|
|
3
|
+
import type { ClientPort } from "#src/server/client-port";
|
|
4
|
+
import type { OpenSession } from "#src/server/open-session";
|
|
5
|
+
import type { ServerOptions } from "#src/server/options";
|
|
6
|
+
import { type ServerSession } from "#src/server/server-session";
|
|
7
|
+
import type { SessionMeta, SessionStorage } from "#src/server/storage";
|
|
8
|
+
import type { ReadOldText } from "#src/server/translate/diff";
|
|
9
|
+
export declare const NO_MODEL_MESSAGE = "no model configured: set models.native.balanced or --model";
|
|
10
|
+
export declare const MCP_NOTICE = "MCP servers are not supported yet; ignored";
|
|
11
|
+
export declare const INTERRUPTED_NOTICE = "The previous turn was interrupted";
|
|
12
|
+
export declare const SHUTTING_DOWN = "server is shutting down";
|
|
13
|
+
export declare const SHUTDOWN_WAIT_MS = 5000;
|
|
14
|
+
export declare const TITLE_MAX = 80;
|
|
15
|
+
export interface SessionState {
|
|
16
|
+
readonly modes: SessionModeState;
|
|
17
|
+
readonly configOptions: SessionConfigOption[];
|
|
18
|
+
}
|
|
19
|
+
export interface OpenInput {
|
|
20
|
+
readonly cwd: string;
|
|
21
|
+
readonly mcpServers: readonly unknown[];
|
|
22
|
+
readonly port: (sessionId: string) => ClientPort;
|
|
23
|
+
}
|
|
24
|
+
export interface SessionRegistry {
|
|
25
|
+
create(input: OpenInput): Promise<{
|
|
26
|
+
readonly sessionId: string;
|
|
27
|
+
} & SessionState>;
|
|
28
|
+
load(sessionId: string, input: OpenInput): Promise<SessionState>;
|
|
29
|
+
resume(sessionId: string, input: OpenInput): Promise<SessionState>;
|
|
30
|
+
list(query: {
|
|
31
|
+
readonly cwd?: string | null;
|
|
32
|
+
readonly cursor?: string | null;
|
|
33
|
+
}): Promise<ListSessionsResponse>;
|
|
34
|
+
get(sessionId: string): ServerSession;
|
|
35
|
+
find(sessionId: string): ServerSession | undefined;
|
|
36
|
+
close(sessionId: string): Promise<void>;
|
|
37
|
+
delete(sessionId: string): Promise<void>;
|
|
38
|
+
setMode(sessionId: string, modeId: string): Promise<void>;
|
|
39
|
+
setConfigOption(sessionId: string, configId: string, value: unknown): Promise<SessionConfigOption[]>;
|
|
40
|
+
closeAll(): Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
export interface RegistryDeps {
|
|
43
|
+
readonly options: ServerOptions;
|
|
44
|
+
readonly openSession: OpenSession;
|
|
45
|
+
readonly storage: SessionStorage;
|
|
46
|
+
readonly transcripts: TranscriptStore;
|
|
47
|
+
readonly newId: () => string;
|
|
48
|
+
readonly now: () => Date;
|
|
49
|
+
readonly readOldText: ReadOldText;
|
|
50
|
+
readonly logger: AgentLogger;
|
|
51
|
+
readonly turnTimeoutSeconds: number;
|
|
52
|
+
readonly shutdownWaitMs?: number;
|
|
53
|
+
/** S5-4 M-30: refuses (auth_required) when the model's provider has no credential. */
|
|
54
|
+
readonly ensureCredentials?: (model: string) => Promise<void>;
|
|
55
|
+
}
|
|
56
|
+
export interface Entry {
|
|
57
|
+
readonly server: ServerSession;
|
|
58
|
+
readonly port: ClientPort;
|
|
59
|
+
readonly meta: SessionMeta;
|
|
60
|
+
readonly release: () => Promise<void>;
|
|
61
|
+
}
|
|
62
|
+
/** One line, no control or invisible characters, at most TITLE_MAX code points. */
|
|
63
|
+
export declare function titleOf(prompt: string): string;
|
|
64
|
+
export declare function createSessionRegistry(deps: RegistryDeps): SessionRegistry;
|