@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,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One ACP session over one S3 AgentSession (S5 spec §3.2, §4.3, §4.4). A prompt
|
|
3
|
+
* is one send(): each event goes through the translator to the client, and
|
|
4
|
+
* approvals and questions start client round trips without blocking the stream.
|
|
5
|
+
* If the client stops accepting updates, the turn is cancelled and drained so
|
|
6
|
+
* the S3 turn slot is freed. In memory only (S5-2); S5-3 adds metadata, locks
|
|
7
|
+
* and close-and-resume.
|
|
8
|
+
*/
|
|
9
|
+
import { type ContentBlock, type PromptResponse, type SessionUpdate } from "@agentclientprotocol/sdk";
|
|
10
|
+
import type { AgentLogger, AgentSession } from "@nathapp/nax-agent";
|
|
11
|
+
import type { ClientPort } from "#src/server/client-port";
|
|
12
|
+
import type { ReadOldText } from "#src/server/translate/diff";
|
|
13
|
+
/** S3's default turn limit, passed explicitly so the timeout notice names it (M-15). */
|
|
14
|
+
export declare const TURN_TIMEOUT_SECONDS = 3600;
|
|
15
|
+
export interface ServerSessionDeps {
|
|
16
|
+
readonly session: AgentSession;
|
|
17
|
+
readonly port: ClientPort;
|
|
18
|
+
readonly cwd: string;
|
|
19
|
+
readonly contextWindow?: number;
|
|
20
|
+
readonly readOldText: ReadOldText;
|
|
21
|
+
readonly logger: AgentLogger;
|
|
22
|
+
readonly turnTimeoutSeconds: number;
|
|
23
|
+
readonly now?: () => number;
|
|
24
|
+
/** After every prompt that reached send() (S5-3: title and updatedAt). A rejection is logged, never thrown. */
|
|
25
|
+
readonly onTurnEnd?: (message: string) => Promise<void>;
|
|
26
|
+
/** S5-5 (wired in S5-5b Task 10): a display title for an MCP tool call's model name. */
|
|
27
|
+
readonly titleFor?: (name: string) => string | undefined;
|
|
28
|
+
}
|
|
29
|
+
/** The S3 session and context window to adopt on a switchTo (spec §3.3). */
|
|
30
|
+
export interface SwitchTarget {
|
|
31
|
+
readonly session: AgentSession;
|
|
32
|
+
readonly contextWindow?: number;
|
|
33
|
+
}
|
|
34
|
+
export interface ServerSession {
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly running: boolean;
|
|
37
|
+
/** Delivered as the first updates of the next turn (M-11). */
|
|
38
|
+
queueNotice(update: SessionUpdate): void;
|
|
39
|
+
prompt(blocks: readonly ContentBlock[]): Promise<PromptResponse>;
|
|
40
|
+
/** Close-and-reopen for a mode or config change (spec §3.3); `restore` reopens the old settings when `open` fails. */
|
|
41
|
+
switchTo(open: () => Promise<SwitchTarget>, restore: () => Promise<SwitchTarget>): Promise<void>;
|
|
42
|
+
cancel(): void;
|
|
43
|
+
close(): Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
export declare function createServerSession(deps: ServerSessionDeps): ServerSession;
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One ACP session over one S3 AgentSession (S5 spec §3.2, §4.3, §4.4). A prompt
|
|
3
|
+
* is one send(): each event goes through the translator to the client, and
|
|
4
|
+
* approvals and questions start client round trips without blocking the stream.
|
|
5
|
+
* If the client stops accepting updates, the turn is cancelled and drained so
|
|
6
|
+
* the S3 turn slot is freed. In memory only (S5-2); S5-3 adds metadata, locks
|
|
7
|
+
* and close-and-resume.
|
|
8
|
+
*/
|
|
9
|
+
import { RequestError } from "@agentclientprotocol/sdk";
|
|
10
|
+
import { messageOf, turnInProgress } from "#src/server/errors";
|
|
11
|
+
import { createPermissionBroker } from "#src/server/permissions";
|
|
12
|
+
import { flattenPrompt } from "#src/server/prompt";
|
|
13
|
+
import { createQuestionBroker } from "#src/server/questions";
|
|
14
|
+
import { createEventTranslator } from "#src/server/translate/events";
|
|
15
|
+
import { promptOutcome } from "#src/server/translate/stop";
|
|
16
|
+
/** S3's default turn limit, passed explicitly so the timeout notice names it (M-15). */
|
|
17
|
+
export const TURN_TIMEOUT_SECONDS = 3600;
|
|
18
|
+
/** The answer when a cancel arrived before the S3 turn started: nothing ran. */
|
|
19
|
+
const CANCELLED_BEFORE_SEND = {
|
|
20
|
+
kind: "response",
|
|
21
|
+
response: { stopReason: "cancelled", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 } },
|
|
22
|
+
notices: [],
|
|
23
|
+
};
|
|
24
|
+
function react(event, turn, translator) {
|
|
25
|
+
switch (event.type) {
|
|
26
|
+
case "approval_requested":
|
|
27
|
+
if (event.answerable !== false) {
|
|
28
|
+
turn.permissions.request(event, event.callId === undefined ? undefined : translator.toolCallFor(event.callId));
|
|
29
|
+
}
|
|
30
|
+
return;
|
|
31
|
+
case "approval_resolved":
|
|
32
|
+
turn.permissions.settled(event.requestId);
|
|
33
|
+
return;
|
|
34
|
+
case "question":
|
|
35
|
+
turn.questions.ask(event);
|
|
36
|
+
return;
|
|
37
|
+
default:
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Sends updates in order; on the first failure, cancels the turn and drops the rest. */
|
|
42
|
+
function createDelivery(deps, agentOf) {
|
|
43
|
+
let broken;
|
|
44
|
+
return {
|
|
45
|
+
failure: () => broken,
|
|
46
|
+
async deliver(update) {
|
|
47
|
+
if (broken !== undefined)
|
|
48
|
+
return;
|
|
49
|
+
try {
|
|
50
|
+
await deps.port.update(update);
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
broken = error;
|
|
54
|
+
deps.logger.warn("session", "client stopped accepting updates; cancelling the turn", {
|
|
55
|
+
sessionId: deps.session.id,
|
|
56
|
+
error: messageOf(error),
|
|
57
|
+
});
|
|
58
|
+
agentOf().cancel("client connection failed");
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** One event: its updates, its round trips, and at turn_end the prompt outcome. */
|
|
64
|
+
async function forwardEvent(event, ctx) {
|
|
65
|
+
for (const update of await ctx.translator.translate(event))
|
|
66
|
+
await ctx.delivery.deliver(update);
|
|
67
|
+
react(event, ctx.turn, ctx.translator);
|
|
68
|
+
if (event.type !== "turn_end")
|
|
69
|
+
return undefined;
|
|
70
|
+
const outcome = promptOutcome(event, ctx.deps.turnTimeoutSeconds, ctx.deps.port.features.updates.notices);
|
|
71
|
+
if (outcome.kind === "response")
|
|
72
|
+
for (const notice of outcome.notices)
|
|
73
|
+
await ctx.delivery.deliver(notice);
|
|
74
|
+
return outcome;
|
|
75
|
+
}
|
|
76
|
+
export function createServerSession(deps) {
|
|
77
|
+
const memory = new Map();
|
|
78
|
+
let queued = [];
|
|
79
|
+
let costUsd = 0;
|
|
80
|
+
let running = false;
|
|
81
|
+
/** A cancel before send() claimed the S3 turn, where AgentSession.cancel() is a no-op. */
|
|
82
|
+
let cancelBeforeSend = false;
|
|
83
|
+
let turn;
|
|
84
|
+
let agent = deps.session;
|
|
85
|
+
let contextWindow = deps.contextWindow;
|
|
86
|
+
function stopWaiting() {
|
|
87
|
+
turn?.permissions.abortAll();
|
|
88
|
+
turn?.questions.abortAll();
|
|
89
|
+
}
|
|
90
|
+
async function reportTurnEnd(message) {
|
|
91
|
+
if (deps.onTurnEnd === undefined)
|
|
92
|
+
return;
|
|
93
|
+
try {
|
|
94
|
+
await deps.onTurnEnd(message);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
deps.logger.warn("session", "turn bookkeeping failed", { sessionId: deps.session.id, error: messageOf(error) });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
async function runTurn(message) {
|
|
101
|
+
const delivery = createDelivery(deps, () => agent);
|
|
102
|
+
const answer = agent.answer.bind(agent);
|
|
103
|
+
const translator = createEventTranslator({
|
|
104
|
+
cwd: deps.cwd,
|
|
105
|
+
...(contextWindow !== undefined ? { contextWindow } : {}),
|
|
106
|
+
readOldText: deps.readOldText,
|
|
107
|
+
clientUpdates: deps.port.features.updates,
|
|
108
|
+
priorCostUsd: costUsd,
|
|
109
|
+
...(deps.titleFor !== undefined ? { titleFor: deps.titleFor } : {}),
|
|
110
|
+
});
|
|
111
|
+
const current = {
|
|
112
|
+
permissions: createPermissionBroker({ port: deps.port, answer, memory, logger: deps.logger }),
|
|
113
|
+
questions: createQuestionBroker({
|
|
114
|
+
port: deps.port,
|
|
115
|
+
deliver: delivery.deliver,
|
|
116
|
+
answer,
|
|
117
|
+
logger: deps.logger,
|
|
118
|
+
...(deps.now !== undefined ? { now: deps.now } : {}),
|
|
119
|
+
}),
|
|
120
|
+
};
|
|
121
|
+
turn = current;
|
|
122
|
+
const ctx = { deps, translator, turn: current, delivery };
|
|
123
|
+
let outcome;
|
|
124
|
+
try {
|
|
125
|
+
const pending = queued;
|
|
126
|
+
queued = [];
|
|
127
|
+
for (const update of pending)
|
|
128
|
+
await delivery.deliver(update);
|
|
129
|
+
if (cancelBeforeSend) {
|
|
130
|
+
outcome = CANCELLED_BEFORE_SEND;
|
|
131
|
+
}
|
|
132
|
+
else if (delivery.failure() === undefined) {
|
|
133
|
+
for await (const event of agent.send(message))
|
|
134
|
+
outcome = (await forwardEvent(event, ctx)) ?? outcome;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
current.permissions.abortAll();
|
|
139
|
+
current.questions.abortAll();
|
|
140
|
+
await Promise.all([current.permissions.drain(), current.questions.drain()]);
|
|
141
|
+
costUsd = translator.costUsd();
|
|
142
|
+
turn = undefined;
|
|
143
|
+
}
|
|
144
|
+
const broken = delivery.failure();
|
|
145
|
+
if (broken !== undefined) {
|
|
146
|
+
throw RequestError.internalError(undefined, `could not send a session update: ${messageOf(broken)}`);
|
|
147
|
+
}
|
|
148
|
+
return outcome;
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
id: deps.session.id,
|
|
152
|
+
get running() {
|
|
153
|
+
return running;
|
|
154
|
+
},
|
|
155
|
+
queueNotice(update) {
|
|
156
|
+
queued = [...queued, update];
|
|
157
|
+
},
|
|
158
|
+
async prompt(blocks) {
|
|
159
|
+
if (running)
|
|
160
|
+
throw turnInProgress();
|
|
161
|
+
const message = flattenPrompt(blocks);
|
|
162
|
+
running = true;
|
|
163
|
+
cancelBeforeSend = false;
|
|
164
|
+
let outcome;
|
|
165
|
+
try {
|
|
166
|
+
outcome = await runTurn(message);
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
// Still "running" while the turn is recorded, so a switchTo cannot
|
|
170
|
+
// slip in and write metadata from before this turn's title/updatedAt.
|
|
171
|
+
await reportTurnEnd(message);
|
|
172
|
+
running = false;
|
|
173
|
+
}
|
|
174
|
+
if (outcome === undefined)
|
|
175
|
+
throw RequestError.internalError(undefined, "the turn ended without a turn_end event");
|
|
176
|
+
if (outcome.kind === "error")
|
|
177
|
+
throw outcome.error;
|
|
178
|
+
return outcome.response;
|
|
179
|
+
},
|
|
180
|
+
async switchTo(open, restore) {
|
|
181
|
+
if (running)
|
|
182
|
+
throw turnInProgress();
|
|
183
|
+
running = true;
|
|
184
|
+
try {
|
|
185
|
+
stopWaiting();
|
|
186
|
+
await agent.close();
|
|
187
|
+
try {
|
|
188
|
+
const next = await open();
|
|
189
|
+
agent = next.session;
|
|
190
|
+
contextWindow = next.contextWindow;
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
try {
|
|
194
|
+
const back = await restore();
|
|
195
|
+
agent = back.session;
|
|
196
|
+
contextWindow = back.contextWindow;
|
|
197
|
+
}
|
|
198
|
+
catch (restoreError) {
|
|
199
|
+
deps.logger.error("session", "could not reopen the session after a failed switch", {
|
|
200
|
+
sessionId: deps.session.id,
|
|
201
|
+
error: messageOf(restoreError),
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
running = false;
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
cancel() {
|
|
212
|
+
if (running)
|
|
213
|
+
cancelBeforeSend = true;
|
|
214
|
+
agent.cancel("cancelled by the client");
|
|
215
|
+
stopWaiting();
|
|
216
|
+
},
|
|
217
|
+
async close() {
|
|
218
|
+
stopWaiting();
|
|
219
|
+
await agent.close();
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an ACP session exposes about its settings (S5 spec §5.2, §5.3): the four
|
|
3
|
+
* modes (S3 profiles), and three select config options (mode, which editors
|
|
4
|
+
* render in place of `modes`; the model (the configured
|
|
5
|
+
* tiers plus the current model); and the bash approval mode). Changes are
|
|
6
|
+
* validated here; applying them is the registry's close-and-reopen (§3.3).
|
|
7
|
+
*/
|
|
8
|
+
import type { SessionConfigOption, SessionMode, SessionModeState } from "@agentclientprotocol/sdk";
|
|
9
|
+
import type { AgentSessionProfile } from "@nathapp/nax-agent";
|
|
10
|
+
import { type BashApproval, type TierModel } from "#src/server/nax-config";
|
|
11
|
+
export interface SessionSettings {
|
|
12
|
+
readonly mode: AgentSessionProfile;
|
|
13
|
+
readonly model: string;
|
|
14
|
+
readonly bashApproval: BashApproval;
|
|
15
|
+
}
|
|
16
|
+
export declare const MODE_OPTION = "mode";
|
|
17
|
+
export declare const MODEL_OPTION = "model";
|
|
18
|
+
export declare const BASH_OPTION = "bashApproval";
|
|
19
|
+
export declare const SESSION_MODES: readonly SessionMode[];
|
|
20
|
+
export declare function sameSettings(a: SessionSettings, b: SessionSettings): boolean;
|
|
21
|
+
export declare function modeState(settings: SessionSettings): SessionModeState;
|
|
22
|
+
export declare function modelChoices(settings: SessionSettings, tiers: readonly TierModel[]): readonly {
|
|
23
|
+
value: string;
|
|
24
|
+
name: string;
|
|
25
|
+
description: string;
|
|
26
|
+
}[];
|
|
27
|
+
export declare function configOptions(settings: SessionSettings, tiers: readonly TierModel[]): SessionConfigOption[];
|
|
28
|
+
export declare function applyModeChange(settings: SessionSettings, modeId: string): SessionSettings;
|
|
29
|
+
export declare function applyConfigChange(settings: SessionSettings, configId: string, value: unknown, tiers: readonly TierModel[]): SessionSettings;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { invalidParams } from "#src/server/errors";
|
|
2
|
+
import { BASH_APPROVALS, MODES } from "#src/server/nax-config";
|
|
3
|
+
export const MODE_OPTION = "mode";
|
|
4
|
+
export const MODEL_OPTION = "model";
|
|
5
|
+
export const BASH_OPTION = "bashApproval";
|
|
6
|
+
export const SESSION_MODES = [
|
|
7
|
+
{ id: "none", name: "Chat", description: "Chat only: no workspace tools." },
|
|
8
|
+
{ id: "read", name: "Read only", description: "Reads and searches the workspace; changes nothing." },
|
|
9
|
+
{ id: "ask", name: "Ask", description: "Asks before every edit and command." },
|
|
10
|
+
{ id: "full", name: "Full access", description: "Edits files and runs commands without asking, inside the sandbox." },
|
|
11
|
+
];
|
|
12
|
+
const BASH_CHOICES = [
|
|
13
|
+
{
|
|
14
|
+
value: "gated",
|
|
15
|
+
name: "Gated",
|
|
16
|
+
description: "Commands are checked against the rules; one the checks cannot judge is refused.",
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
value: "escalate",
|
|
20
|
+
name: "Escalate",
|
|
21
|
+
description: "Like gated, but a command the checks cannot judge asks you instead.",
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
value: "raw",
|
|
25
|
+
name: "Raw",
|
|
26
|
+
description: "Commands run as written, without per-command checks (mode Full only).",
|
|
27
|
+
},
|
|
28
|
+
];
|
|
29
|
+
export function sameSettings(a, b) {
|
|
30
|
+
return a.mode === b.mode && a.model === b.model && a.bashApproval === b.bashApproval;
|
|
31
|
+
}
|
|
32
|
+
export function modeState(settings) {
|
|
33
|
+
return { currentModeId: settings.mode, availableModes: [...SESSION_MODES] };
|
|
34
|
+
}
|
|
35
|
+
export function modelChoices(settings, tiers) {
|
|
36
|
+
const seen = new Set();
|
|
37
|
+
const choices = [];
|
|
38
|
+
for (const tier of tiers) {
|
|
39
|
+
if (seen.has(tier.model))
|
|
40
|
+
continue;
|
|
41
|
+
seen.add(tier.model);
|
|
42
|
+
choices.push({ value: tier.model, name: tier.tier, description: tier.model });
|
|
43
|
+
}
|
|
44
|
+
if (!seen.has(settings.model)) {
|
|
45
|
+
choices.push({ value: settings.model, name: settings.model, description: "current model" });
|
|
46
|
+
}
|
|
47
|
+
return choices;
|
|
48
|
+
}
|
|
49
|
+
export function configOptions(settings, tiers) {
|
|
50
|
+
return [
|
|
51
|
+
{
|
|
52
|
+
id: MODE_OPTION,
|
|
53
|
+
name: "Mode",
|
|
54
|
+
category: "mode",
|
|
55
|
+
type: "select",
|
|
56
|
+
currentValue: settings.mode,
|
|
57
|
+
options: SESSION_MODES.map((m) => ({ value: m.id, name: m.name, description: m.description ?? null })),
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
id: MODEL_OPTION,
|
|
61
|
+
name: "Model",
|
|
62
|
+
category: "model",
|
|
63
|
+
type: "select",
|
|
64
|
+
currentValue: settings.model,
|
|
65
|
+
options: [...modelChoices(settings, tiers)],
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
id: BASH_OPTION,
|
|
69
|
+
name: "Bash approval",
|
|
70
|
+
type: "select",
|
|
71
|
+
currentValue: settings.bashApproval,
|
|
72
|
+
options: [...BASH_CHOICES],
|
|
73
|
+
},
|
|
74
|
+
];
|
|
75
|
+
}
|
|
76
|
+
export function applyModeChange(settings, modeId) {
|
|
77
|
+
const mode = MODES.find((m) => m === modeId);
|
|
78
|
+
if (mode === undefined)
|
|
79
|
+
throw invalidParams(`unknown mode "${modeId}"; expected one of ${MODES.join(", ")}`);
|
|
80
|
+
// Ask runs every command past a person, which needs gated (M-23).
|
|
81
|
+
return { ...settings, mode, bashApproval: mode === "ask" ? "gated" : settings.bashApproval };
|
|
82
|
+
}
|
|
83
|
+
export function applyConfigChange(settings, configId, value, tiers) {
|
|
84
|
+
if (typeof value !== "string")
|
|
85
|
+
throw invalidParams(`config option "${configId}" takes a string value`);
|
|
86
|
+
if (configId === MODE_OPTION)
|
|
87
|
+
return applyModeChange(settings, value);
|
|
88
|
+
if (configId === MODEL_OPTION) {
|
|
89
|
+
const valid = modelChoices(settings, tiers).map((choice) => choice.value);
|
|
90
|
+
if (!valid.includes(value))
|
|
91
|
+
throw invalidParams(`unknown model "${value}"; valid models: ${valid.join(", ")}`);
|
|
92
|
+
return { ...settings, model: value };
|
|
93
|
+
}
|
|
94
|
+
if (configId === BASH_OPTION) {
|
|
95
|
+
const bash = BASH_APPROVALS.find((b) => b === value);
|
|
96
|
+
if (bash === undefined)
|
|
97
|
+
throw invalidParams(`unknown bash approval "${value}"; expected one of ${BASH_APPROVALS.join(", ")}`);
|
|
98
|
+
if (settings.mode === "ask" && bash !== "gated") {
|
|
99
|
+
throw invalidParams('mode "ask" requires bash approval "gated"');
|
|
100
|
+
}
|
|
101
|
+
return { ...settings, bashApproval: bash };
|
|
102
|
+
}
|
|
103
|
+
throw invalidParams(`unknown config option "${configId}"`);
|
|
104
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type ListSessionsResponse } from "@agentclientprotocol/sdk";
|
|
2
|
+
import { type AgentLogger } from "@nathapp/nax-agent";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
export declare const LIST_PAGE_SIZE = 50;
|
|
5
|
+
declare const MetaSchema: z.ZodObject<{
|
|
6
|
+
schemaVersion: z.ZodLiteral<1>;
|
|
7
|
+
sessionId: z.ZodString;
|
|
8
|
+
cwd: z.ZodString;
|
|
9
|
+
mode: z.ZodEnum<{
|
|
10
|
+
ask: "ask";
|
|
11
|
+
full: "full";
|
|
12
|
+
none: "none";
|
|
13
|
+
read: "read";
|
|
14
|
+
}>;
|
|
15
|
+
model: z.ZodString;
|
|
16
|
+
bashApproval: z.ZodEnum<{
|
|
17
|
+
escalate: "escalate";
|
|
18
|
+
gated: "gated";
|
|
19
|
+
raw: "raw";
|
|
20
|
+
}>;
|
|
21
|
+
title: z.ZodNullable<z.ZodString>;
|
|
22
|
+
createdAt: z.ZodString;
|
|
23
|
+
updatedAt: z.ZodNullable<z.ZodString>;
|
|
24
|
+
}, z.core.$strip>;
|
|
25
|
+
export type SessionMeta = Readonly<z.infer<typeof MetaSchema>>;
|
|
26
|
+
export interface SessionStorage {
|
|
27
|
+
readonly dir: string;
|
|
28
|
+
readMeta(sessionId: string): Promise<SessionMeta | null>;
|
|
29
|
+
writeMeta(meta: SessionMeta): Promise<void>;
|
|
30
|
+
hasMeta(sessionId: string): Promise<boolean>;
|
|
31
|
+
removeMeta(sessionId: string): Promise<void>;
|
|
32
|
+
/** Resolves to the release function; refuses with invalid_request when another live process holds it. */
|
|
33
|
+
acquireLock(sessionId: string): Promise<() => Promise<void>>;
|
|
34
|
+
list(query: {
|
|
35
|
+
readonly cwd?: string | null;
|
|
36
|
+
readonly cursor?: string | null;
|
|
37
|
+
}): Promise<ListSessionsResponse>;
|
|
38
|
+
}
|
|
39
|
+
export interface StorageDeps {
|
|
40
|
+
readonly dir: string;
|
|
41
|
+
readonly pid: number;
|
|
42
|
+
readonly now: () => Date;
|
|
43
|
+
readonly logger: AgentLogger;
|
|
44
|
+
readonly isAlive?: (pid: number) => boolean;
|
|
45
|
+
}
|
|
46
|
+
/** Signal 0 checks existence only. EPERM means the process exists under another user. */
|
|
47
|
+
export declare function processAlive(pid: number): boolean;
|
|
48
|
+
export declare function createSessionStorage(deps: StorageDeps): SessionStorage;
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session files beside the S3 transcript (S5 spec §5.1): `<id>.session.json`
|
|
3
|
+
* metadata, written as a temp file then renamed, and `<id>.lock`, created
|
|
4
|
+
* exclusively. A lock whose pid is dead, or that cannot be read, is stale and
|
|
5
|
+
* taken over; a live one refuses the open. Listing scans the metadata files.
|
|
6
|
+
* Files that cannot be read are never rewritten or deleted here.
|
|
7
|
+
*/
|
|
8
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { RequestError } from "@agentclientprotocol/sdk";
|
|
11
|
+
import { NaxError } from "@nathapp/nax-agent";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
import { invalidParams, messageOf } from "#src/server/errors";
|
|
14
|
+
import { BASH_APPROVALS, MODES } from "#src/server/nax-config";
|
|
15
|
+
export const LIST_PAGE_SIZE = 50;
|
|
16
|
+
const META_SUFFIX = ".session.json";
|
|
17
|
+
const MetaSchema = z.object({
|
|
18
|
+
schemaVersion: z.literal(1),
|
|
19
|
+
sessionId: z.string().min(1),
|
|
20
|
+
cwd: z.string().min(1),
|
|
21
|
+
mode: z.enum(MODES),
|
|
22
|
+
model: z.string().min(1),
|
|
23
|
+
bashApproval: z.enum(BASH_APPROVALS),
|
|
24
|
+
title: z.string().nullable(),
|
|
25
|
+
createdAt: z.string(),
|
|
26
|
+
updatedAt: z.string().nullable(),
|
|
27
|
+
});
|
|
28
|
+
const LockSchema = z.object({ pid: z.number().int().positive(), startedAt: z.string() });
|
|
29
|
+
function codeOf(error) {
|
|
30
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
|
|
31
|
+
? error.code
|
|
32
|
+
: undefined;
|
|
33
|
+
}
|
|
34
|
+
/** Signal 0 checks existence only. EPERM means the process exists under another user. */
|
|
35
|
+
export function processAlive(pid) {
|
|
36
|
+
try {
|
|
37
|
+
process.kill(pid, 0);
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
return codeOf(error) === "EPERM";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function unreadable(sessionId, reason) {
|
|
45
|
+
return new NaxError(`session metadata for "${sessionId}" is unreadable: ${reason}`, "SESSION_META_UNREADABLE", {
|
|
46
|
+
stage: "agent-server",
|
|
47
|
+
sessionId,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function encodeCursor(offset) {
|
|
51
|
+
return Buffer.from(String(offset), "utf8").toString("base64");
|
|
52
|
+
}
|
|
53
|
+
function decodeCursor(cursor) {
|
|
54
|
+
if (cursor === undefined || cursor === null || cursor === "")
|
|
55
|
+
return 0;
|
|
56
|
+
const text = Buffer.from(cursor, "base64").toString("utf8");
|
|
57
|
+
const offset = Number(text);
|
|
58
|
+
if (!/^\d+$/.test(text) || !Number.isSafeInteger(offset))
|
|
59
|
+
throw invalidParams("invalid cursor");
|
|
60
|
+
return offset;
|
|
61
|
+
}
|
|
62
|
+
const sortKey = (meta) => meta.updatedAt ?? meta.createdAt;
|
|
63
|
+
function infoOf(meta) {
|
|
64
|
+
return { sessionId: meta.sessionId, cwd: meta.cwd, title: meta.title, updatedAt: sortKey(meta) };
|
|
65
|
+
}
|
|
66
|
+
export function createSessionStorage(deps) {
|
|
67
|
+
const isAlive = deps.isAlive ?? processAlive;
|
|
68
|
+
const metaPath = (id) => join(deps.dir, `${id}${META_SUFFIX}`);
|
|
69
|
+
const lockPath = (id) => join(deps.dir, `${id}.lock`);
|
|
70
|
+
async function readMeta(sessionId) {
|
|
71
|
+
let text;
|
|
72
|
+
try {
|
|
73
|
+
text = await readFile(metaPath(sessionId), "utf8");
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (codeOf(error) === "ENOENT")
|
|
77
|
+
return null;
|
|
78
|
+
throw unreadable(sessionId, messageOf(error));
|
|
79
|
+
}
|
|
80
|
+
let json;
|
|
81
|
+
try {
|
|
82
|
+
json = JSON.parse(text);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
throw unreadable(sessionId, "invalid JSON");
|
|
86
|
+
}
|
|
87
|
+
const version = typeof json === "object" && json !== null && "schemaVersion" in json ? json.schemaVersion : undefined;
|
|
88
|
+
if (version !== 1)
|
|
89
|
+
throw unreadable(sessionId, `schemaVersion ${String(version)}; this build reads 1`);
|
|
90
|
+
const parsed = MetaSchema.safeParse(json);
|
|
91
|
+
if (!parsed.success)
|
|
92
|
+
throw unreadable(sessionId, parsed.error.issues[0]?.message ?? "bad shape");
|
|
93
|
+
return parsed.data;
|
|
94
|
+
}
|
|
95
|
+
/** The pid holding the lock, or undefined when the lock cannot be read (stale). */
|
|
96
|
+
async function lockHolder(path) {
|
|
97
|
+
try {
|
|
98
|
+
const parsed = LockSchema.safeParse(JSON.parse(await readFile(path, "utf8")));
|
|
99
|
+
return parsed.success ? parsed.data.pid : undefined;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function tryLock(path) {
|
|
106
|
+
const body = JSON.stringify({ pid: deps.pid, startedAt: deps.now().toISOString() });
|
|
107
|
+
try {
|
|
108
|
+
await writeFile(path, body, { flag: "wx" });
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (codeOf(error) === "EEXIST")
|
|
113
|
+
return false;
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async function acquireLock(sessionId) {
|
|
118
|
+
await mkdir(deps.dir, { recursive: true });
|
|
119
|
+
const path = lockPath(sessionId);
|
|
120
|
+
const release = async () => {
|
|
121
|
+
await rm(path, { force: true });
|
|
122
|
+
};
|
|
123
|
+
if (await tryLock(path))
|
|
124
|
+
return release;
|
|
125
|
+
const holder = await lockHolder(path);
|
|
126
|
+
if (holder !== undefined && holder !== deps.pid && isAlive(holder)) {
|
|
127
|
+
throw RequestError.invalidRequest(undefined, `session in use by pid ${holder}`);
|
|
128
|
+
}
|
|
129
|
+
deps.logger.info("session", "taking over a stale session lock", { sessionId, pid: holder });
|
|
130
|
+
await rm(path, { force: true });
|
|
131
|
+
if (await tryLock(path))
|
|
132
|
+
return release;
|
|
133
|
+
throw RequestError.invalidRequest(undefined, "session in use by another process");
|
|
134
|
+
}
|
|
135
|
+
async function list(query) {
|
|
136
|
+
const offset = decodeCursor(query.cursor);
|
|
137
|
+
let names;
|
|
138
|
+
try {
|
|
139
|
+
names = await readdir(deps.dir);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (codeOf(error) === "ENOENT")
|
|
143
|
+
return { sessions: [] };
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
const metas = [];
|
|
147
|
+
for (const name of names.filter((n) => n.endsWith(META_SUFFIX))) {
|
|
148
|
+
try {
|
|
149
|
+
const meta = await readMeta(name.slice(0, -META_SUFFIX.length));
|
|
150
|
+
if (meta !== null)
|
|
151
|
+
metas.push(meta);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
deps.logger.warn("session", "skipping unreadable session metadata", { file: name, error: messageOf(error) });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const matching = metas
|
|
158
|
+
.filter((meta) => query.cwd === undefined || query.cwd === null || meta.cwd === query.cwd)
|
|
159
|
+
.sort((a, b) => sortKey(b).localeCompare(sortKey(a)));
|
|
160
|
+
const end = offset + LIST_PAGE_SIZE;
|
|
161
|
+
return {
|
|
162
|
+
sessions: matching.slice(offset, end).map(infoOf),
|
|
163
|
+
...(end < matching.length ? { nextCursor: encodeCursor(end) } : {}),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
dir: deps.dir,
|
|
168
|
+
readMeta,
|
|
169
|
+
async writeMeta(meta) {
|
|
170
|
+
await mkdir(deps.dir, { recursive: true });
|
|
171
|
+
const path = metaPath(meta.sessionId);
|
|
172
|
+
const temp = `${path}.${deps.pid}.tmp`;
|
|
173
|
+
await writeFile(temp, `${JSON.stringify(meta, null, 2)}\n`);
|
|
174
|
+
await rename(temp, path);
|
|
175
|
+
},
|
|
176
|
+
async hasMeta(sessionId) {
|
|
177
|
+
try {
|
|
178
|
+
await stat(metaPath(sessionId));
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
async removeMeta(sessionId) {
|
|
186
|
+
await rm(metaPath(sessionId), { force: true });
|
|
187
|
+
},
|
|
188
|
+
acquireLock,
|
|
189
|
+
list,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ToolCallContent } from "@agentclientprotocol/sdk";
|
|
2
|
+
export type DiffContent = Extract<ToolCallContent, {
|
|
3
|
+
type: "diff";
|
|
4
|
+
}>;
|
|
5
|
+
export declare const WRITE_DIFF_OLD_MAX_BYTES: number;
|
|
6
|
+
export type OldText = {
|
|
7
|
+
readonly kind: "text";
|
|
8
|
+
readonly text: string;
|
|
9
|
+
} | {
|
|
10
|
+
readonly kind: "missing";
|
|
11
|
+
} | {
|
|
12
|
+
readonly kind: "too-large";
|
|
13
|
+
} | {
|
|
14
|
+
readonly kind: "unreadable";
|
|
15
|
+
} | {
|
|
16
|
+
readonly kind: "outside-workspace";
|
|
17
|
+
};
|
|
18
|
+
/** Reads a Write target's current text; never reads a file whose real path is outside `root` (the session cwd). */
|
|
19
|
+
export type ReadOldText = (absolutePath: string, root: string) => Promise<OldText>;
|
|
20
|
+
export interface OldTextFs {
|
|
21
|
+
realpath(path: string): Promise<string>;
|
|
22
|
+
stat(path: string): Promise<{
|
|
23
|
+
readonly size: number;
|
|
24
|
+
isFile(): boolean;
|
|
25
|
+
}>;
|
|
26
|
+
readFile(path: string, encoding: "utf8"): Promise<string>;
|
|
27
|
+
}
|
|
28
|
+
export declare function fsReadOldText(fs?: OldTextFs): ReadOldText;
|
|
29
|
+
export declare function editDiff(input: unknown, cwd: string): DiffContent | undefined;
|
|
30
|
+
export declare function toolDiff(name: string, input: unknown, cwd: string, readOld: ReadOldText): Promise<DiffContent | undefined>;
|