@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.
- package/CHANGELOG.md +27 -0
- package/README.md +135 -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 +47 -0
- package/dist/server/auth.js +87 -0
- package/dist/server/capabilities.d.ts +8 -0
- package/dist/server/capabilities.js +21 -0
- package/dist/server/cli.d.ts +27 -0
- package/dist/server/cli.js +90 -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/default-model.d.ts +36 -0
- package/dist/server/default-model.js +158 -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 +20 -0
- package/dist/server/login.js +38 -0
- package/dist/server/main.d.ts +24 -0
- package/dist/server/main.js +152 -0
- package/dist/server/mcp/connect.d.ts +38 -0
- package/dist/server/mcp/connect.js +95 -0
- package/dist/server/mcp/naming.d.ts +12 -0
- package/dist/server/mcp/naming.js +43 -0
- package/dist/server/mcp/notices.d.ts +8 -0
- package/dist/server/mcp/notices.js +19 -0
- package/dist/server/mcp/parse.d.ts +24 -0
- package/dist/server/mcp/parse.js +107 -0
- package/dist/server/mcp/secrets.d.ts +4 -0
- package/dist/server/mcp/secrets.js +44 -0
- package/dist/server/mcp/session-tools.d.ts +37 -0
- package/dist/server/mcp/session-tools.js +70 -0
- package/dist/server/mcp/tool-shape.d.ts +19 -0
- package/dist/server/mcp/tool-shape.js +20 -0
- package/dist/server/nax-config.d.ts +31 -0
- package/dist/server/nax-config.js +139 -0
- package/dist/server/open-session.d.ts +38 -0
- package/dist/server/open-session.js +56 -0
- package/dist/server/options.d.ts +30 -0
- package/dist/server/options.js +72 -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 +90 -0
- package/dist/server/registry-open.d.ts +32 -0
- package/dist/server/registry-open.js +60 -0
- package/dist/server/registry.d.ts +79 -0
- package/dist/server/registry.js +333 -0
- package/dist/server/server-session.d.ts +45 -0
- package/dist/server/server-session.js +222 -0
- package/dist/server/session-config.d.ts +29 -0
- package/dist/server/session-config.js +104 -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 +39 -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,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,90 @@
|
|
|
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
|
+
const MAX_TIMER_DELAY = 2_147_483_647;
|
|
26
|
+
function armExpiry(expiresAt, now, onExpire) {
|
|
27
|
+
let timer;
|
|
28
|
+
const arm = () => {
|
|
29
|
+
const delta = Date.parse(expiresAt) - now();
|
|
30
|
+
const remaining = delta > 0 ? delta : 0;
|
|
31
|
+
timer = remaining > MAX_TIMER_DELAY ? setTimeout(arm, MAX_TIMER_DELAY) : setTimeout(onExpire, remaining);
|
|
32
|
+
};
|
|
33
|
+
arm();
|
|
34
|
+
return () => clearTimeout(timer);
|
|
35
|
+
}
|
|
36
|
+
export function createQuestionBroker(deps) {
|
|
37
|
+
const now = deps.now ?? Date.now;
|
|
38
|
+
const open = new Set();
|
|
39
|
+
const running = new Set();
|
|
40
|
+
const notices = deps.port.features.updates.notices;
|
|
41
|
+
async function elicit(event) {
|
|
42
|
+
const controller = new AbortController();
|
|
43
|
+
open.add(controller);
|
|
44
|
+
const clearExpiry = armExpiry(event.expiresAt, now, () => controller.abort());
|
|
45
|
+
let text;
|
|
46
|
+
try {
|
|
47
|
+
text = answerText(await untilAborted(deps.port.elicit(formFor(event.text), controller.signal), controller.signal));
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (controller.signal.aborted)
|
|
51
|
+
return;
|
|
52
|
+
deps.logger.warn("questions", "elicitation failed; answering without the user", { error: messageOf(error) });
|
|
53
|
+
text = NO_ANSWER_TEXT;
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
clearExpiry();
|
|
57
|
+
open.delete(controller);
|
|
58
|
+
}
|
|
59
|
+
deps.answer(event.requestId, { text });
|
|
60
|
+
}
|
|
61
|
+
async function handle(event) {
|
|
62
|
+
if (event.answerable === false) {
|
|
63
|
+
await deps.deliver(announce(notices, "info", "The agent noted a question", event.text));
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (deps.port.features.elicitation) {
|
|
67
|
+
await elicit(event);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
await deps.deliver(announce(notices, "warning", "The agent asked a question", event.text));
|
|
71
|
+
deps.answer(event.requestId, { text: NO_ANSWER_TEXT });
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
ask(event) {
|
|
75
|
+
// Never rejects: a throwing answer() or delivery must not become an unhandled rejection.
|
|
76
|
+
const work = handle(event).catch((error) => {
|
|
77
|
+
deps.logger.warn("questions", "question handling failed", { error: messageOf(error) });
|
|
78
|
+
});
|
|
79
|
+
running.add(work);
|
|
80
|
+
void work.finally(() => running.delete(work));
|
|
81
|
+
},
|
|
82
|
+
abortAll() {
|
|
83
|
+
for (const controller of open)
|
|
84
|
+
controller.abort();
|
|
85
|
+
},
|
|
86
|
+
async drain() {
|
|
87
|
+
await Promise.all([...running]);
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
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, mcpServers: readonly unknown[]) => 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 interruptedNotice: string;
|
|
27
|
+
}
|
|
28
|
+
export interface Reopener {
|
|
29
|
+
reopen(sessionId: string, input: OpenInput, replay: boolean): Promise<SessionState>;
|
|
30
|
+
}
|
|
31
|
+
export declare const settingsOf: (meta: SessionMeta) => SessionSettings;
|
|
32
|
+
export declare function createReopen(deps: ReopenDeps): Reopener;
|
|
@@ -0,0 +1,60 @@
|
|
|
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, titleFor) {
|
|
11
|
+
for (const update of replayTranscript(messages, cwd, titleFor))
|
|
12
|
+
await port.update(update);
|
|
13
|
+
}
|
|
14
|
+
async function replayOpened(port, sessionId, opened, cwd) {
|
|
15
|
+
await replayTo(port, opened.doc?.messages ?? [], cwd, (name) => deps.entries.get(sessionId)?.mcp.titleFor(name));
|
|
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 { opened } = await deps.openEntry(meta, port, input.mcpServers);
|
|
23
|
+
if (replay) {
|
|
24
|
+
try {
|
|
25
|
+
await replayOpened(port, sessionId, 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
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
async reopen(sessionId, input, replay) {
|
|
38
|
+
const open = deps.entries.get(sessionId);
|
|
39
|
+
if (open !== undefined) {
|
|
40
|
+
// An already-open session keeps its connection and ignores input.mcpServers (§4.4).
|
|
41
|
+
if (replay) {
|
|
42
|
+
await replayTo(open.port, (await deps.transcripts.load(sessionId))?.messages ?? [], open.meta.cwd, (name) => open.mcp.titleFor(name));
|
|
43
|
+
}
|
|
44
|
+
return deps.stateOf(settingsOf(open.meta));
|
|
45
|
+
}
|
|
46
|
+
const meta = await deps.storage.readMeta(sessionId);
|
|
47
|
+
if (meta === null)
|
|
48
|
+
throw unknownSession(sessionId);
|
|
49
|
+
if (input.cwd !== meta.cwd) {
|
|
50
|
+
deps.logger.debug("session", "reopening in the stored cwd", {
|
|
51
|
+
sessionId,
|
|
52
|
+
requested: input.cwd,
|
|
53
|
+
stored: meta.cwd,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
await openAndReplay(sessionId, meta, input, replay);
|
|
57
|
+
return deps.stateOf(settingsOf(meta));
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { type ListSessionsResponse, type SessionConfigOption, type SessionModeState } from "@agentclientprotocol/sdk";
|
|
2
|
+
import { type AgentLogger, type TranscriptStore } from "@nathapp/nax-agent";
|
|
3
|
+
import type { ClientPort } from "#src/server/client-port";
|
|
4
|
+
import { type ConnectSessionMcp } from "#src/server/mcp/connect";
|
|
5
|
+
import type { McpSessionTools } from "#src/server/mcp/session-tools";
|
|
6
|
+
import type { OpenSession } from "#src/server/open-session";
|
|
7
|
+
import type { ServerOptions } from "#src/server/options";
|
|
8
|
+
import { type ServerSession } from "#src/server/server-session";
|
|
9
|
+
import type { SessionMeta, SessionStorage } from "#src/server/storage";
|
|
10
|
+
import type { ReadOldText } from "#src/server/translate/diff";
|
|
11
|
+
export declare const NO_MODEL_MESSAGE = "no model configured: log in to pick one, or set models.native.balanced in config.json / NAX_AGENT_MODEL";
|
|
12
|
+
export declare const INTERRUPTED_NOTICE = "The previous turn was interrupted";
|
|
13
|
+
export declare const SHUTTING_DOWN = "server is shutting down";
|
|
14
|
+
export declare const SHUTDOWN_WAIT_MS = 5000;
|
|
15
|
+
export declare const TITLE_MAX = 80;
|
|
16
|
+
/** What re-reading the options found: the options, or why there are none (a short, redacted reason). */
|
|
17
|
+
export interface ReloadedOptions {
|
|
18
|
+
readonly options?: ServerOptions;
|
|
19
|
+
readonly problem?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface SessionState {
|
|
22
|
+
readonly modes: SessionModeState;
|
|
23
|
+
readonly configOptions: SessionConfigOption[];
|
|
24
|
+
}
|
|
25
|
+
export interface OpenInput {
|
|
26
|
+
readonly cwd: string;
|
|
27
|
+
readonly mcpServers: readonly unknown[];
|
|
28
|
+
readonly port: (sessionId: string) => ClientPort;
|
|
29
|
+
}
|
|
30
|
+
export interface SessionRegistry {
|
|
31
|
+
create(input: OpenInput): Promise<{
|
|
32
|
+
readonly sessionId: string;
|
|
33
|
+
} & SessionState>;
|
|
34
|
+
load(sessionId: string, input: OpenInput): Promise<SessionState>;
|
|
35
|
+
resume(sessionId: string, input: OpenInput): Promise<SessionState>;
|
|
36
|
+
list(query: {
|
|
37
|
+
readonly cwd?: string | null;
|
|
38
|
+
readonly cursor?: string | null;
|
|
39
|
+
}): Promise<ListSessionsResponse>;
|
|
40
|
+
get(sessionId: string): ServerSession;
|
|
41
|
+
find(sessionId: string): ServerSession | undefined;
|
|
42
|
+
close(sessionId: string): Promise<void>;
|
|
43
|
+
delete(sessionId: string): Promise<void>;
|
|
44
|
+
setMode(sessionId: string, modeId: string): Promise<void>;
|
|
45
|
+
setConfigOption(sessionId: string, configId: string, value: unknown): Promise<SessionConfigOption[]>;
|
|
46
|
+
closeAll(): Promise<void>;
|
|
47
|
+
}
|
|
48
|
+
export interface RegistryDeps {
|
|
49
|
+
readonly options: ServerOptions;
|
|
50
|
+
readonly openSession: OpenSession;
|
|
51
|
+
readonly storage: SessionStorage;
|
|
52
|
+
readonly transcripts: TranscriptStore;
|
|
53
|
+
readonly newId: () => string;
|
|
54
|
+
readonly now: () => Date;
|
|
55
|
+
readonly readOldText: ReadOldText;
|
|
56
|
+
readonly logger: AgentLogger;
|
|
57
|
+
readonly turnTimeoutSeconds: number;
|
|
58
|
+
readonly shutdownWaitMs?: number;
|
|
59
|
+
/** S5-4 M-30: refuses (auth_required) when the model's provider has no credential. */
|
|
60
|
+
readonly ensureCredentials?: (model: string) => Promise<void>;
|
|
61
|
+
/** S5-5: connects a session's client-supplied MCP servers. Default: connects nothing (plan M-38). */
|
|
62
|
+
readonly connectMcp?: ConnectSessionMcp;
|
|
63
|
+
/**
|
|
64
|
+
* Re-resolves the options (flags and env still win over the config file). Called by
|
|
65
|
+
* session/new when no model is configured, so a model written by `nax-agent login`
|
|
66
|
+
* takes effect without restarting the server (#2414).
|
|
67
|
+
*/
|
|
68
|
+
readonly reloadOptions?: () => Promise<ReloadedOptions>;
|
|
69
|
+
}
|
|
70
|
+
export interface Entry {
|
|
71
|
+
readonly server: ServerSession;
|
|
72
|
+
readonly port: ClientPort;
|
|
73
|
+
readonly meta: SessionMeta;
|
|
74
|
+
readonly release: () => Promise<void>;
|
|
75
|
+
readonly mcp: McpSessionTools;
|
|
76
|
+
}
|
|
77
|
+
/** One line, no control or invisible characters, at most TITLE_MAX code points. */
|
|
78
|
+
export declare function titleOf(prompt: string): string;
|
|
79
|
+
export declare function createSessionRegistry(deps: RegistryDeps): SessionRegistry;
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP session id -> open session, backed by files (S5 spec §5.1, §5.3). Opening
|
|
3
|
+
* (new, load, resume) takes the session's lock, then reopens the S3 session;
|
|
4
|
+
* close releases the lock and keeps the files; delete removes them. Mode and
|
|
5
|
+
* config changes are a close-and-reopen (§3.3) that rolls back on failure and
|
|
6
|
+
* writes metadata only on success. closeAll is the shutdown (§5.5).
|
|
7
|
+
*/
|
|
8
|
+
import { isAbsolute } from "node:path";
|
|
9
|
+
import { RequestError, } from "@agentclientprotocol/sdk";
|
|
10
|
+
import { redactSecrets } from "@nathapp/nax-agent";
|
|
11
|
+
import { stripControl, stripInvisible } from "#src/client/text";
|
|
12
|
+
import { authRequired, invalidParams, messageOf, turnInProgress, unknownSession } from "#src/server/errors";
|
|
13
|
+
import { connectNothing } from "#src/server/mcp/connect";
|
|
14
|
+
import { disconnectNotice, modeNotice, openNotice } from "#src/server/mcp/notices";
|
|
15
|
+
import { NO_SERVERS, parseMcpServers } from "#src/server/mcp/parse";
|
|
16
|
+
import { mcpSecrets, scrubber } from "#src/server/mcp/secrets";
|
|
17
|
+
import { createReopen, settingsOf } from "#src/server/registry-open";
|
|
18
|
+
import { createServerSession } from "#src/server/server-session";
|
|
19
|
+
import { applyConfigChange, applyModeChange, configOptions, modeState, sameSettings, } from "#src/server/session-config";
|
|
20
|
+
export const NO_MODEL_MESSAGE = "no model configured: log in to pick one, or set models.native.balanced in config.json / NAX_AGENT_MODEL";
|
|
21
|
+
export const INTERRUPTED_NOTICE = "The previous turn was interrupted";
|
|
22
|
+
export const SHUTTING_DOWN = "server is shutting down";
|
|
23
|
+
export const SHUTDOWN_WAIT_MS = 5000;
|
|
24
|
+
export const TITLE_MAX = 80;
|
|
25
|
+
/** One line, no control or invisible characters, at most TITLE_MAX code points. */
|
|
26
|
+
export function titleOf(prompt) {
|
|
27
|
+
return Array.from(stripInvisible(stripControl(prompt)).replace(/\s+/g, " ").trim())
|
|
28
|
+
.slice(0, TITLE_MAX)
|
|
29
|
+
.join("");
|
|
30
|
+
}
|
|
31
|
+
function waitAtMost(ms) {
|
|
32
|
+
let timer;
|
|
33
|
+
const done = new Promise((resolve) => {
|
|
34
|
+
timer = setTimeout(() => resolve("timeout"), ms);
|
|
35
|
+
});
|
|
36
|
+
return { done, cancel: () => clearTimeout(timer) };
|
|
37
|
+
}
|
|
38
|
+
export function createSessionRegistry(deps) {
|
|
39
|
+
const entries = new Map();
|
|
40
|
+
let options = deps.options;
|
|
41
|
+
const connectMcp = deps.connectMcp ?? connectNothing;
|
|
42
|
+
const shutdown = new AbortController();
|
|
43
|
+
let closing = false;
|
|
44
|
+
const contextWindowFor = (model) => options.tiers.find((tier) => tier.model === model)?.contextWindow;
|
|
45
|
+
const stateOf = (settings) => ({
|
|
46
|
+
modes: modeState(settings),
|
|
47
|
+
configOptions: configOptions(settings, options.tiers),
|
|
48
|
+
});
|
|
49
|
+
function entryOf(sessionId) {
|
|
50
|
+
const entry = entries.get(sessionId);
|
|
51
|
+
if (entry === undefined)
|
|
52
|
+
throw unknownSession(sessionId);
|
|
53
|
+
return entry;
|
|
54
|
+
}
|
|
55
|
+
async function recordTurn(sessionId, prompt) {
|
|
56
|
+
const entry = entries.get(sessionId);
|
|
57
|
+
if (entry === undefined)
|
|
58
|
+
return;
|
|
59
|
+
const meta = {
|
|
60
|
+
...entry.meta,
|
|
61
|
+
title: entry.meta.title ?? (titleOf(prompt) || null),
|
|
62
|
+
updatedAt: deps.now().toISOString(),
|
|
63
|
+
};
|
|
64
|
+
entries.set(sessionId, { ...entry, meta });
|
|
65
|
+
await deps.storage.writeMeta(meta);
|
|
66
|
+
}
|
|
67
|
+
async function target(sessionId, cwd, settings, tools) {
|
|
68
|
+
const opened = await deps.openSession({
|
|
69
|
+
sessionId,
|
|
70
|
+
cwd,
|
|
71
|
+
model: settings.model,
|
|
72
|
+
profile: settings.mode,
|
|
73
|
+
bashApproval: settings.bashApproval,
|
|
74
|
+
tools,
|
|
75
|
+
});
|
|
76
|
+
const contextWindow = contextWindowFor(settings.model);
|
|
77
|
+
return { session: opened.session, ...(contextWindow !== undefined ? { contextWindow } : {}) };
|
|
78
|
+
}
|
|
79
|
+
function startMcp(parsed, meta, port) {
|
|
80
|
+
// Built before connecting: a disconnect fired before connectMcp resolves must still be scrubbed.
|
|
81
|
+
const scrub = scrubber(mcpSecrets(parsed.servers));
|
|
82
|
+
return connectMcp({
|
|
83
|
+
parsed,
|
|
84
|
+
cwd: meta.cwd,
|
|
85
|
+
signal: shutdown.signal,
|
|
86
|
+
onDisconnect: (server, reason) => {
|
|
87
|
+
port.update(disconnectNotice(port.features.updates.notices, server, reason, scrub)).catch((error) => {
|
|
88
|
+
deps.logger.warn("session", "MCP disconnect notice failed", {
|
|
89
|
+
sessionId: meta.sessionId,
|
|
90
|
+
error: messageOf(error),
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
function queueMcpNotices(server, port, mcp, mode) {
|
|
97
|
+
const notices = port.features.updates.notices;
|
|
98
|
+
const open = openNotice(notices, mcp.noticeLines, mcp.scrub);
|
|
99
|
+
if (open !== undefined)
|
|
100
|
+
server.queueNotice(open);
|
|
101
|
+
if (mcp.tools.connectedCount > 0 && !mcp.tools.offersTools(mode))
|
|
102
|
+
server.queueNotice(modeNotice(notices, mode));
|
|
103
|
+
}
|
|
104
|
+
/** Parses MCP servers, takes the lock, connects MCP, opens the S3 session, registers it. Everything is undone on failure. */
|
|
105
|
+
async function openEntry(meta, port, mcpServers) {
|
|
106
|
+
if (closing)
|
|
107
|
+
throw RequestError.internalError(undefined, SHUTTING_DOWN);
|
|
108
|
+
const parsed = mcpServers.length === 0 ? NO_SERVERS : parseMcpServers(mcpServers);
|
|
109
|
+
await deps.ensureCredentials?.(meta.model);
|
|
110
|
+
const release = await deps.storage.acquireLock(meta.sessionId);
|
|
111
|
+
let mcp;
|
|
112
|
+
let opened;
|
|
113
|
+
try {
|
|
114
|
+
mcp = await startMcp(parsed, meta, port);
|
|
115
|
+
if (closing)
|
|
116
|
+
throw RequestError.internalError(undefined, SHUTTING_DOWN); // shutdown during connect
|
|
117
|
+
const settings = settingsOf(meta);
|
|
118
|
+
opened = await deps.openSession({
|
|
119
|
+
sessionId: meta.sessionId,
|
|
120
|
+
cwd: meta.cwd,
|
|
121
|
+
model: settings.model,
|
|
122
|
+
profile: settings.mode,
|
|
123
|
+
bashApproval: settings.bashApproval,
|
|
124
|
+
tools: mcp.tools.embedderTools(settings.mode),
|
|
125
|
+
});
|
|
126
|
+
if (closing) {
|
|
127
|
+
// Shutdown started while this open was in flight (M-26).
|
|
128
|
+
await opened.session.close().catch(() => undefined);
|
|
129
|
+
opened = undefined; // already closed; the catch must not close it twice
|
|
130
|
+
throw RequestError.internalError(undefined, SHUTTING_DOWN);
|
|
131
|
+
}
|
|
132
|
+
const server = createEntryServer(meta, port, opened, mcp.tools);
|
|
133
|
+
queueMcpNotices(server, port, mcp, settings.mode);
|
|
134
|
+
entries.set(meta.sessionId, { server, port, meta, release, mcp: mcp.tools });
|
|
135
|
+
return { server, opened };
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
// If the facade session opened but a later step threw, do not orphan it.
|
|
139
|
+
await opened?.session.close().catch(() => undefined);
|
|
140
|
+
await mcp?.tools.closeAll();
|
|
141
|
+
await release();
|
|
142
|
+
throw closing ? RequestError.internalError(undefined, SHUTTING_DOWN) : error;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function createEntryServer(meta, port, opened, mcp) {
|
|
146
|
+
const contextWindow = contextWindowFor(meta.model);
|
|
147
|
+
return createServerSession({
|
|
148
|
+
session: opened.session,
|
|
149
|
+
port,
|
|
150
|
+
cwd: meta.cwd,
|
|
151
|
+
...(contextWindow !== undefined ? { contextWindow } : {}),
|
|
152
|
+
readOldText: deps.readOldText,
|
|
153
|
+
logger: deps.logger,
|
|
154
|
+
turnTimeoutSeconds: deps.turnTimeoutSeconds,
|
|
155
|
+
onTurnEnd: (prompt) => recordTurn(meta.sessionId, prompt),
|
|
156
|
+
titleFor: (name) => mcp.titleFor(name),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
async function closeEntry(sessionId, entry) {
|
|
160
|
+
entries.delete(sessionId);
|
|
161
|
+
try {
|
|
162
|
+
await entry.server.close();
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
await entry.mcp.closeAll();
|
|
166
|
+
await entry.release();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const reopen = createReopen({
|
|
170
|
+
entries,
|
|
171
|
+
storage: deps.storage,
|
|
172
|
+
transcripts: deps.transcripts,
|
|
173
|
+
logger: deps.logger,
|
|
174
|
+
openEntry,
|
|
175
|
+
closeEntry,
|
|
176
|
+
stateOf,
|
|
177
|
+
interruptedNotice: INTERRUPTED_NOTICE,
|
|
178
|
+
}).reopen;
|
|
179
|
+
/** Close-and-reopen with `next` (§3.3). Metadata is written only after the reopen succeeds. */
|
|
180
|
+
async function switchTo(sessionId, entry, next) {
|
|
181
|
+
const from = settingsOf(entry.meta);
|
|
182
|
+
// A busy session answers "turn in progress" first, as ServerSession.switchTo would.
|
|
183
|
+
if (entry.server.running)
|
|
184
|
+
throw turnInProgress();
|
|
185
|
+
// Before the live session is closed, so a refused model changes nothing (final review I6).
|
|
186
|
+
if (next.model !== from.model)
|
|
187
|
+
await deps.ensureCredentials?.(next.model);
|
|
188
|
+
await entry.server.switchTo(() => target(sessionId, entry.meta.cwd, next, entry.mcp.embedderTools(next.mode)), () => target(sessionId, entry.meta.cwd, from, entry.mcp.embedderTools(from.mode)));
|
|
189
|
+
const meta = { ...entry.meta, mode: next.mode, model: next.model, bashApproval: next.bashApproval };
|
|
190
|
+
entries.set(sessionId, { ...entry, meta });
|
|
191
|
+
await deps.storage.writeMeta(meta);
|
|
192
|
+
if (next.mode !== from.mode && entry.mcp.connectedCount > 0 && !entry.mcp.offersTools(next.mode))
|
|
193
|
+
await entry.port.update(modeNotice(entry.port.features.updates.notices, next.mode));
|
|
194
|
+
}
|
|
195
|
+
async function announceConfig(entry, settings) {
|
|
196
|
+
await entry.port.update({
|
|
197
|
+
sessionUpdate: "config_option_update",
|
|
198
|
+
configOptions: configOptions(settings, options.tiers),
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* The one path for set_mode and set_config_option: reopen when anything changed,
|
|
203
|
+
* then announce. `current_mode_update` follows every set_mode and any mode
|
|
204
|
+
* change; `config_option_update` follows every change (M-25).
|
|
205
|
+
*/
|
|
206
|
+
async function applySettings(sessionId, entry, next, alwaysAnnounceMode) {
|
|
207
|
+
const from = settingsOf(entry.meta);
|
|
208
|
+
const changed = !sameSettings(from, next);
|
|
209
|
+
if (changed)
|
|
210
|
+
await switchTo(sessionId, entry, next);
|
|
211
|
+
if (alwaysAnnounceMode || next.mode !== from.mode) {
|
|
212
|
+
await entry.port.update({ sessionUpdate: "current_mode_update", currentModeId: next.mode });
|
|
213
|
+
}
|
|
214
|
+
if (changed)
|
|
215
|
+
await announceConfig(entry, next);
|
|
216
|
+
}
|
|
217
|
+
/** The default model, re-read from the config when none was configured at startup. */
|
|
218
|
+
async function reloadDefaultModel() {
|
|
219
|
+
let problem;
|
|
220
|
+
let fresh;
|
|
221
|
+
try {
|
|
222
|
+
({ options: fresh, problem } = (await deps.reloadOptions?.()) ?? {});
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
problem = redactSecrets(messageOf(error));
|
|
226
|
+
deps.logger.warn("config", "could not re-read the options", { error: problem });
|
|
227
|
+
}
|
|
228
|
+
if (fresh?.defaultModel === undefined) {
|
|
229
|
+
const reason = problem === undefined ? "" : `; config.json could not be used: ${problem}`;
|
|
230
|
+
throw authRequired(`${NO_MODEL_MESSAGE}${reason}`, {});
|
|
231
|
+
}
|
|
232
|
+
options = { ...options, defaultModel: fresh.defaultModel, tiers: fresh.tiers };
|
|
233
|
+
return fresh.defaultModel;
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
async create(input) {
|
|
237
|
+
if (!isAbsolute(input.cwd))
|
|
238
|
+
throw invalidParams(`cwd must be an absolute path: ${input.cwd}`);
|
|
239
|
+
const model = options.defaultModel ?? (await reloadDefaultModel());
|
|
240
|
+
const sessionId = deps.newId();
|
|
241
|
+
const meta = {
|
|
242
|
+
schemaVersion: 1,
|
|
243
|
+
sessionId,
|
|
244
|
+
cwd: input.cwd,
|
|
245
|
+
mode: options.defaultMode,
|
|
246
|
+
model,
|
|
247
|
+
bashApproval: options.bashApproval,
|
|
248
|
+
title: null,
|
|
249
|
+
createdAt: deps.now().toISOString(),
|
|
250
|
+
updatedAt: null,
|
|
251
|
+
};
|
|
252
|
+
const port = input.port(sessionId);
|
|
253
|
+
await openEntry(meta, port, input.mcpServers);
|
|
254
|
+
try {
|
|
255
|
+
await deps.storage.writeMeta(meta);
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
const entry = entries.get(sessionId);
|
|
259
|
+
if (entry !== undefined)
|
|
260
|
+
await closeEntry(sessionId, entry);
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
if (closing) {
|
|
264
|
+
// Shutdown started while this create's metadata write was in flight (M-26).
|
|
265
|
+
// closeAll has already cleared the map and closed the entry (releasing its
|
|
266
|
+
// lock), but the write it raced landed after the clear; remove it so no
|
|
267
|
+
// phantom session survives shutdown, then refuse.
|
|
268
|
+
const raced = entries.get(sessionId);
|
|
269
|
+
if (raced !== undefined)
|
|
270
|
+
await closeEntry(sessionId, raced);
|
|
271
|
+
await deps.storage.removeMeta(sessionId);
|
|
272
|
+
throw RequestError.internalError(undefined, SHUTTING_DOWN);
|
|
273
|
+
}
|
|
274
|
+
deps.logger.info("session", "session opened", { sessionId, cwd: input.cwd, model, mode: meta.mode });
|
|
275
|
+
return { sessionId, ...stateOf(settingsOf(meta)) };
|
|
276
|
+
},
|
|
277
|
+
load: (sessionId, input) => reopen(sessionId, input, true),
|
|
278
|
+
resume: (sessionId, input) => reopen(sessionId, input, false),
|
|
279
|
+
list: (query) => deps.storage.list(query),
|
|
280
|
+
get: (sessionId) => entryOf(sessionId).server,
|
|
281
|
+
find: (sessionId) => entries.get(sessionId)?.server,
|
|
282
|
+
async close(sessionId) {
|
|
283
|
+
await closeEntry(sessionId, entryOf(sessionId));
|
|
284
|
+
},
|
|
285
|
+
async delete(sessionId) {
|
|
286
|
+
const entry = entries.get(sessionId);
|
|
287
|
+
if (entry !== undefined)
|
|
288
|
+
await closeEntry(sessionId, entry);
|
|
289
|
+
else if (!(await deps.storage.hasMeta(sessionId)))
|
|
290
|
+
throw unknownSession(sessionId);
|
|
291
|
+
const release = await deps.storage.acquireLock(sessionId);
|
|
292
|
+
try {
|
|
293
|
+
await deps.transcripts.delete(sessionId);
|
|
294
|
+
await deps.storage.removeMeta(sessionId);
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
await release();
|
|
298
|
+
}
|
|
299
|
+
},
|
|
300
|
+
async setMode(sessionId, modeId) {
|
|
301
|
+
const entry = entryOf(sessionId);
|
|
302
|
+
const next = applyModeChange(settingsOf(entry.meta), modeId);
|
|
303
|
+
await applySettings(sessionId, entry, next, true);
|
|
304
|
+
},
|
|
305
|
+
async setConfigOption(sessionId, configId, value) {
|
|
306
|
+
const entry = entryOf(sessionId);
|
|
307
|
+
const next = applyConfigChange(settingsOf(entry.meta), configId, value, options.tiers);
|
|
308
|
+
await applySettings(sessionId, entry, next, false);
|
|
309
|
+
return configOptions(next, options.tiers);
|
|
310
|
+
},
|
|
311
|
+
async closeAll() {
|
|
312
|
+
closing = true;
|
|
313
|
+
shutdown.abort();
|
|
314
|
+
const open = [...entries.entries()];
|
|
315
|
+
entries.clear();
|
|
316
|
+
const wait = deps.shutdownWaitMs ?? SHUTDOWN_WAIT_MS;
|
|
317
|
+
await Promise.all(open.map(async ([sessionId, entry]) => {
|
|
318
|
+
entry.server.cancel();
|
|
319
|
+
const limit = waitAtMost(wait);
|
|
320
|
+
const closed = entry.server.close().then(() => "closed", (error) => {
|
|
321
|
+
deps.logger.warn("session", "session close failed", { sessionId, error: messageOf(error) });
|
|
322
|
+
return "closed";
|
|
323
|
+
});
|
|
324
|
+
const outcome = await Promise.race([closed, limit.done]);
|
|
325
|
+
limit.cancel();
|
|
326
|
+
if (outcome === "timeout")
|
|
327
|
+
deps.logger.warn("session", "session did not close in time", { sessionId, waitMs: wait });
|
|
328
|
+
await entry.mcp.closeAll();
|
|
329
|
+
await entry.release();
|
|
330
|
+
}));
|
|
331
|
+
},
|
|
332
|
+
};
|
|
333
|
+
}
|