@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,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>;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diffs for Edit and Write tool calls (S5 spec §4.2), built from the tool input
|
|
3
|
+
* so the editor can show them at permission time, before the tool runs. Write's
|
|
4
|
+
* old text is read from disk through an injected reader (the server runs locally).
|
|
5
|
+
*/
|
|
6
|
+
import { readFile, realpath, stat } from "node:fs/promises";
|
|
7
|
+
import { isAbsolute, relative } from "node:path";
|
|
8
|
+
import { redactSecrets } from "@nathapp/nax-agent";
|
|
9
|
+
import { inputString, resolveToolPath } from "#src/server/translate/tool-kind";
|
|
10
|
+
export const WRITE_DIFF_OLD_MAX_BYTES = 1024 * 1024;
|
|
11
|
+
const NODE_FS = {
|
|
12
|
+
realpath: (path) => realpath(path),
|
|
13
|
+
stat,
|
|
14
|
+
readFile: (path, encoding) => readFile(path, encoding),
|
|
15
|
+
};
|
|
16
|
+
function isMissing(error) {
|
|
17
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
18
|
+
}
|
|
19
|
+
function isInside(root, path) {
|
|
20
|
+
const rel = relative(root, path);
|
|
21
|
+
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
|
|
22
|
+
}
|
|
23
|
+
export function fsReadOldText(fs = NODE_FS) {
|
|
24
|
+
return async (path, root) => {
|
|
25
|
+
try {
|
|
26
|
+
// Symlinks resolved on both sides: a link inside the workspace to a file outside it is outside.
|
|
27
|
+
const real = await fs.realpath(path);
|
|
28
|
+
if (!isInside(await fs.realpath(root), real))
|
|
29
|
+
return { kind: "outside-workspace" };
|
|
30
|
+
const info = await fs.stat(real);
|
|
31
|
+
if (!info.isFile())
|
|
32
|
+
return { kind: "unreadable" };
|
|
33
|
+
if (info.size > WRITE_DIFF_OLD_MAX_BYTES)
|
|
34
|
+
return { kind: "too-large" };
|
|
35
|
+
return { kind: "text", text: await fs.readFile(real, "utf8") };
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
return isMissing(error) ? { kind: "missing" } : { kind: "unreadable" };
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export function editDiff(input, cwd) {
|
|
43
|
+
const path = inputString(input, "path");
|
|
44
|
+
const oldText = inputString(input, "old_string");
|
|
45
|
+
const newText = inputString(input, "new_string");
|
|
46
|
+
if (path === undefined || oldText === undefined || newText === undefined)
|
|
47
|
+
return undefined;
|
|
48
|
+
return { type: "diff", path: resolveToolPath(cwd, path), oldText, newText };
|
|
49
|
+
}
|
|
50
|
+
async function writeDiff(input, cwd, readOld) {
|
|
51
|
+
const path = inputString(input, "path");
|
|
52
|
+
const newText = inputString(input, "content");
|
|
53
|
+
if (path === undefined || newText === undefined)
|
|
54
|
+
return undefined;
|
|
55
|
+
const absolute = resolveToolPath(cwd, path);
|
|
56
|
+
const old = await readOld(absolute, cwd);
|
|
57
|
+
switch (old.kind) {
|
|
58
|
+
case "text":
|
|
59
|
+
// Masked as live tool input is (the input's own text arrives masked from the session).
|
|
60
|
+
return { type: "diff", path: absolute, oldText: redactSecrets(old.text), newText };
|
|
61
|
+
case "missing":
|
|
62
|
+
return { type: "diff", path: absolute, oldText: null, newText };
|
|
63
|
+
case "too-large":
|
|
64
|
+
case "unreadable":
|
|
65
|
+
case "outside-workspace":
|
|
66
|
+
return {
|
|
67
|
+
type: "diff",
|
|
68
|
+
path: absolute,
|
|
69
|
+
oldText: null,
|
|
70
|
+
newText,
|
|
71
|
+
_meta: { naxAgent: { oldTextOmitted: old.kind } },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
export async function toolDiff(name, input, cwd, readOld) {
|
|
76
|
+
if (name === "Edit")
|
|
77
|
+
return editDiff(input, cwd);
|
|
78
|
+
if (name === "Write")
|
|
79
|
+
return writeDiff(input, cwd, readOld);
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* S3 session events -> ACP session updates (S5 spec §4.1-§4.3). One translator
|
|
3
|
+
* per turn: it remembers tool calls (for result diffs and permission requests)
|
|
4
|
+
* and approval requests (to fail a call the session mode denied). Permission
|
|
5
|
+
* requests, questions and the turn end are the session's job (S5-2).
|
|
6
|
+
*/
|
|
7
|
+
import type { SessionUpdate, ToolCallContent, ToolCallUpdate } from "@agentclientprotocol/sdk";
|
|
8
|
+
import type { SessionEvent } from "@nathapp/nax-agent";
|
|
9
|
+
import { type ReadOldText } from "#src/server/translate/diff";
|
|
10
|
+
/** Optional session updates the client advertised (`clientCapabilities.session`). */
|
|
11
|
+
export interface ClientUpdates {
|
|
12
|
+
readonly notices: boolean;
|
|
13
|
+
readonly compaction: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface EventTranslatorDeps {
|
|
16
|
+
readonly cwd: string;
|
|
17
|
+
readonly contextWindow?: number;
|
|
18
|
+
readonly readOldText: ReadOldText;
|
|
19
|
+
readonly clientUpdates: ClientUpdates;
|
|
20
|
+
/** The session's cost before this turn; `usage_update.cost` is the cumulative session cost. */
|
|
21
|
+
readonly priorCostUsd?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface EventTranslator {
|
|
24
|
+
translate(event: SessionEvent): Promise<readonly SessionUpdate[]>;
|
|
25
|
+
toolCallFor(callId: string): ToolCallUpdate | undefined;
|
|
26
|
+
/** The session's priced cost so far, including this turn's rounds. */
|
|
27
|
+
costUsd(): number;
|
|
28
|
+
}
|
|
29
|
+
export type UsageEvent = Extract<SessionEvent, {
|
|
30
|
+
type: "usage";
|
|
31
|
+
}>;
|
|
32
|
+
export declare function textContent(text: string): Extract<ToolCallContent, {
|
|
33
|
+
type: "content";
|
|
34
|
+
}>;
|
|
35
|
+
/** `sessionCostUsd`: the cumulative session cost after this round (ACP `cost.amount` is cumulative). */
|
|
36
|
+
export declare function usageUpdate(event: UsageEvent, contextWindow: number | undefined, sessionCostUsd: number): SessionUpdate[];
|
|
37
|
+
export declare function createEventTranslator(deps: EventTranslatorDeps): EventTranslator;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { toolDiff } from "#src/server/translate/diff";
|
|
2
|
+
import { announce } from "#src/server/translate/notice";
|
|
3
|
+
import { toolKind, toolLocations, toolTitle } from "#src/server/translate/tool-kind";
|
|
4
|
+
export function textContent(text) {
|
|
5
|
+
return { type: "content", content: { type: "text", text } };
|
|
6
|
+
}
|
|
7
|
+
/** `sessionCostUsd`: the cumulative session cost after this round (ACP `cost.amount` is cumulative). */
|
|
8
|
+
export function usageUpdate(event, contextWindow, sessionCostUsd) {
|
|
9
|
+
if (contextWindow === undefined)
|
|
10
|
+
return [];
|
|
11
|
+
const used = event.inputTokens + event.outputTokens + (event.cacheRead ?? 0) + (event.cacheWrite ?? 0);
|
|
12
|
+
return [
|
|
13
|
+
{
|
|
14
|
+
sessionUpdate: "usage_update",
|
|
15
|
+
used,
|
|
16
|
+
size: contextWindow,
|
|
17
|
+
cost: event.costSource === "unpriced" ? null : { amount: sessionCostUsd, currency: "USD" },
|
|
18
|
+
...(event.costSource !== undefined ? { _meta: { naxAgent: { costSource: event.costSource } } } : {}),
|
|
19
|
+
},
|
|
20
|
+
];
|
|
21
|
+
}
|
|
22
|
+
function toolResultUpdate(event, diff) {
|
|
23
|
+
return {
|
|
24
|
+
sessionUpdate: "tool_call_update",
|
|
25
|
+
toolCallId: event.callId,
|
|
26
|
+
status: event.isError ? "failed" : "completed",
|
|
27
|
+
content: [textContent(event.preview), ...(diff !== undefined ? [diff] : [])],
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function profileDenial(approval, event) {
|
|
31
|
+
if (approval === undefined || event.decidedBy !== "profile" || event.decision !== "deny")
|
|
32
|
+
return [];
|
|
33
|
+
return [
|
|
34
|
+
{
|
|
35
|
+
sessionUpdate: "tool_call_update",
|
|
36
|
+
toolCallId: approval.callId,
|
|
37
|
+
status: "failed",
|
|
38
|
+
content: [textContent(`Denied by the session mode: ${approval.reason}`)],
|
|
39
|
+
},
|
|
40
|
+
];
|
|
41
|
+
}
|
|
42
|
+
function streamResetUpdate(event, notices) {
|
|
43
|
+
return announce(notices, "info", "Response restarted", `The model stream was retried (attempt ${event.attempt}); text above may repeat.`);
|
|
44
|
+
}
|
|
45
|
+
export function createEventTranslator(deps) {
|
|
46
|
+
const calls = new Map();
|
|
47
|
+
const approvals = new Map();
|
|
48
|
+
let compactions = 0;
|
|
49
|
+
let sessionCostUsd = deps.priorCostUsd ?? 0;
|
|
50
|
+
const describeCall = (toolCallId, call) => {
|
|
51
|
+
const locations = toolLocations(call.name, call.input, deps.cwd);
|
|
52
|
+
return {
|
|
53
|
+
toolCallId,
|
|
54
|
+
title: toolTitle(call.name, call.input),
|
|
55
|
+
kind: toolKind(call.name),
|
|
56
|
+
rawInput: call.input,
|
|
57
|
+
...(locations !== undefined ? { locations } : {}),
|
|
58
|
+
...(call.diff !== undefined ? { content: [call.diff] } : {}),
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
async function toolCallUpdate(event) {
|
|
62
|
+
const diff = await toolDiff(event.name, event.input, deps.cwd, deps.readOldText);
|
|
63
|
+
const call = { name: event.name, input: event.input, ...(diff !== undefined ? { diff } : {}) };
|
|
64
|
+
calls.set(event.callId, call);
|
|
65
|
+
return { sessionUpdate: "tool_call", ...describeCall(event.callId, call), status: "in_progress" };
|
|
66
|
+
}
|
|
67
|
+
function usage(event) {
|
|
68
|
+
if (event.costSource !== "unpriced")
|
|
69
|
+
sessionCostUsd += event.costUsd;
|
|
70
|
+
return usageUpdate(event, deps.contextWindow, sessionCostUsd);
|
|
71
|
+
}
|
|
72
|
+
function compaction(event) {
|
|
73
|
+
if (!deps.clientUpdates.compaction)
|
|
74
|
+
return [];
|
|
75
|
+
compactions += 1;
|
|
76
|
+
return [
|
|
77
|
+
{
|
|
78
|
+
sessionUpdate: "compaction_update",
|
|
79
|
+
compactionId: `${event.turnId}-${compactions}`,
|
|
80
|
+
status: "completed",
|
|
81
|
+
_meta: { naxAgent: { reason: event.reason } },
|
|
82
|
+
},
|
|
83
|
+
];
|
|
84
|
+
}
|
|
85
|
+
function resolved(event) {
|
|
86
|
+
const approval = approvals.get(event.requestId);
|
|
87
|
+
approvals.delete(event.requestId);
|
|
88
|
+
return profileDenial(approval, event);
|
|
89
|
+
}
|
|
90
|
+
async function translate(event) {
|
|
91
|
+
switch (event.type) {
|
|
92
|
+
case "text_delta":
|
|
93
|
+
return [{ sessionUpdate: "agent_message_chunk", content: { type: "text", text: event.text } }];
|
|
94
|
+
case "thinking_delta":
|
|
95
|
+
return [{ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: event.text } }];
|
|
96
|
+
case "stream_reset":
|
|
97
|
+
return [streamResetUpdate(event, deps.clientUpdates.notices)];
|
|
98
|
+
case "tool_call":
|
|
99
|
+
return [await toolCallUpdate(event)];
|
|
100
|
+
case "tool_result":
|
|
101
|
+
return [toolResultUpdate(event, calls.get(event.callId)?.diff)];
|
|
102
|
+
case "usage":
|
|
103
|
+
return usage(event);
|
|
104
|
+
case "compaction":
|
|
105
|
+
return compaction(event);
|
|
106
|
+
case "approval_requested":
|
|
107
|
+
if (event.callId !== undefined)
|
|
108
|
+
approvals.set(event.requestId, { callId: event.callId, reason: event.reason });
|
|
109
|
+
return [];
|
|
110
|
+
case "approval_resolved":
|
|
111
|
+
return resolved(event);
|
|
112
|
+
case "turn_start":
|
|
113
|
+
case "question":
|
|
114
|
+
case "turn_end":
|
|
115
|
+
return [];
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
translate,
|
|
120
|
+
costUsd: () => sessionCostUsd,
|
|
121
|
+
toolCallFor(callId) {
|
|
122
|
+
const call = calls.get(callId);
|
|
123
|
+
return call === undefined ? undefined : { ...describeCall(callId, call), status: "pending" };
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** A `notice` session update (S5 spec §4.1, §4.3, §4.4). */
|
|
2
|
+
import type { SessionUpdate } from "@agentclientprotocol/sdk";
|
|
3
|
+
export type NoticeSeverity = "info" | "warning" | "error";
|
|
4
|
+
export declare function notice(severity: NoticeSeverity, title: string, description?: string): SessionUpdate;
|
|
5
|
+
/**
|
|
6
|
+
* A notice when the client advertised `session.notices`; otherwise the same text
|
|
7
|
+
* as an agent message, which every client shows (ACP: agents MUST NOT send
|
|
8
|
+
* notices to a client that did not advertise them).
|
|
9
|
+
*/
|
|
10
|
+
export declare function announce(notices: boolean, severity: NoticeSeverity, title: string, description?: string): SessionUpdate;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function notice(severity, title, description) {
|
|
2
|
+
return { sessionUpdate: "notice", severity, title, ...(description !== undefined ? { description } : {}) };
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* A notice when the client advertised `session.notices`; otherwise the same text
|
|
6
|
+
* as an agent message, which every client shows (ACP: agents MUST NOT send
|
|
7
|
+
* notices to a client that did not advertise them).
|
|
8
|
+
*/
|
|
9
|
+
export function announce(notices, severity, title, description) {
|
|
10
|
+
if (notices)
|
|
11
|
+
return notice(severity, title, description);
|
|
12
|
+
const text = description === undefined ? title : `${title}: ${description}`;
|
|
13
|
+
return { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `\n\n${text}\n\n` } };
|
|
14
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A stored transcript as session updates for `session/load` (S5 spec §5.4).
|
|
3
|
+
* Inputs and results go through nax-agent's live masking and caps (M-7), so a
|
|
4
|
+
* replay never shows more than the live turn did. Write gets no diff: the file's
|
|
5
|
+
* old content at that time is gone.
|
|
6
|
+
*/
|
|
7
|
+
import type { SessionUpdate } from "@agentclientprotocol/sdk";
|
|
8
|
+
import { type TranscriptDoc } from "@nathapp/nax-agent";
|
|
9
|
+
export type TranscriptMessage = TranscriptDoc["messages"][number];
|
|
10
|
+
export declare const NO_RESULT_TEXT = "No result was recorded for this call.";
|
|
11
|
+
export declare function replayTranscript(messages: readonly TranscriptMessage[], cwd: string): readonly SessionUpdate[];
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { displayToolInput, toolResultPreview } from "@nathapp/nax-agent";
|
|
2
|
+
import { editDiff } from "#src/server/translate/diff";
|
|
3
|
+
import { textContent } from "#src/server/translate/events";
|
|
4
|
+
import { toolKind, toolLocations, toolTitle } from "#src/server/translate/tool-kind";
|
|
5
|
+
export const NO_RESULT_TEXT = "No result was recorded for this call.";
|
|
6
|
+
function replayCall(call, result, cwd) {
|
|
7
|
+
const input = displayToolInput(call.input);
|
|
8
|
+
const diff = call.name === "Edit" ? editDiff(input, cwd) : undefined;
|
|
9
|
+
const locations = toolLocations(call.name, input, cwd);
|
|
10
|
+
const shown = result === undefined ? NO_RESULT_TEXT : toolResultPreview(result.content);
|
|
11
|
+
return {
|
|
12
|
+
sessionUpdate: "tool_call",
|
|
13
|
+
toolCallId: call.id,
|
|
14
|
+
title: toolTitle(call.name, input),
|
|
15
|
+
kind: toolKind(call.name),
|
|
16
|
+
status: result === undefined || result.isError ? "failed" : "completed",
|
|
17
|
+
rawInput: input,
|
|
18
|
+
...(locations !== undefined ? { locations } : {}),
|
|
19
|
+
content: [textContent(shown), ...(diff !== undefined ? [diff] : [])],
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function replayMessage(message, results, cwd) {
|
|
23
|
+
switch (message.role) {
|
|
24
|
+
case "user":
|
|
25
|
+
return message.content === ""
|
|
26
|
+
? []
|
|
27
|
+
: [{ sessionUpdate: "user_message_chunk", content: { type: "text", text: message.content } }];
|
|
28
|
+
case "tool-result":
|
|
29
|
+
return [];
|
|
30
|
+
case "assistant": {
|
|
31
|
+
const thoughts = (message.thinking ?? [])
|
|
32
|
+
.filter((block) => block.text !== "")
|
|
33
|
+
.map((block) => ({
|
|
34
|
+
sessionUpdate: "agent_thought_chunk",
|
|
35
|
+
content: { type: "text", text: block.text },
|
|
36
|
+
}));
|
|
37
|
+
const said = message.content === ""
|
|
38
|
+
? []
|
|
39
|
+
: [{ sessionUpdate: "agent_message_chunk", content: { type: "text", text: message.content } }];
|
|
40
|
+
const calls = (message.toolCalls ?? []).map((call) => replayCall(call, results.get(call.id), cwd));
|
|
41
|
+
return [...thoughts, ...said, ...calls];
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export function replayTranscript(messages, cwd) {
|
|
46
|
+
const results = new Map();
|
|
47
|
+
for (const message of messages) {
|
|
48
|
+
if (message.role === "tool-result") {
|
|
49
|
+
results.set(message.toolCallId, { content: message.content, isError: message.isError === true });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return messages.flatMap((message) => replayMessage(message, results, cwd));
|
|
53
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A turn's end as the answer to `session/prompt` (S5 spec §4.4). `errored` is a
|
|
3
|
+
* JSON-RPC error so editors show a failure, not a normal stop; a credential
|
|
4
|
+
* failure is `auth_required` (S5-4 M-32). `interrupted` only occurs after a
|
|
5
|
+
* resume and is reported the same way if it ever reaches here.
|
|
6
|
+
*/
|
|
7
|
+
import { type PromptResponse, RequestError, type SessionUpdate, type Usage } from "@agentclientprotocol/sdk";
|
|
8
|
+
import { type SessionEvent, type TokenUsage } from "@nathapp/nax-agent";
|
|
9
|
+
export type TurnEndEvent = Extract<SessionEvent, {
|
|
10
|
+
type: "turn_end";
|
|
11
|
+
}>;
|
|
12
|
+
export type PromptOutcome = {
|
|
13
|
+
readonly kind: "response";
|
|
14
|
+
readonly response: PromptResponse;
|
|
15
|
+
readonly notices: readonly SessionUpdate[];
|
|
16
|
+
} | {
|
|
17
|
+
readonly kind: "error";
|
|
18
|
+
readonly error: RequestError;
|
|
19
|
+
};
|
|
20
|
+
export declare function toAcpUsage(usage: TokenUsage): Usage;
|
|
21
|
+
/** `notices`: whether the client advertised `session.notices` (else warnings become agent text). */
|
|
22
|
+
export declare function promptOutcome(end: TurnEndEvent, turnTimeoutSeconds: number, notices: boolean): PromptOutcome;
|