@nathapp/nax-agent-acp 0.3.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 +63 -0
- package/LICENSE +21 -0
- package/README.md +227 -0
- package/dist/client/backend.d.ts +30 -0
- package/dist/client/backend.js +238 -0
- package/dist/client/capabilities.d.ts +42 -0
- package/dist/client/capabilities.js +60 -0
- package/dist/client/connection.d.ts +31 -0
- package/dist/client/connection.js +32 -0
- package/dist/client/elicitation.d.ts +34 -0
- package/dist/client/elicitation.js +184 -0
- package/dist/client/env.d.ts +8 -0
- package/dist/client/env.js +21 -0
- package/dist/client/errors.d.ts +36 -0
- package/dist/client/errors.js +92 -0
- package/dist/client/events.d.ts +33 -0
- package/dist/client/events.js +96 -0
- package/dist/client/inbound.d.ts +40 -0
- package/dist/client/inbound.js +100 -0
- package/dist/client/index.d.ts +14 -0
- package/dist/client/index.js +12 -0
- package/dist/client/launch.d.ts +47 -0
- package/dist/client/launch.js +145 -0
- package/dist/client/open.d.ts +35 -0
- package/dist/client/open.js +154 -0
- package/dist/client/options.d.ts +46 -0
- package/dist/client/options.js +91 -0
- package/dist/client/permissions.d.ts +36 -0
- package/dist/client/permissions.js +92 -0
- package/dist/client/pre-approval.d.ts +24 -0
- package/dist/client/pre-approval.js +22 -0
- package/dist/client/race.d.ts +22 -0
- package/dist/client/race.js +20 -0
- package/dist/client/registry.d.ts +35 -0
- package/dist/client/registry.js +43 -0
- package/dist/client/resume.d.ts +37 -0
- package/dist/client/resume.js +93 -0
- package/dist/client/stream-scrub.d.ts +7 -0
- package/dist/client/stream-scrub.js +37 -0
- package/dist/client/text.d.ts +29 -0
- package/dist/client/text.js +62 -0
- package/dist/client/tool-calls.d.ts +42 -0
- package/dist/client/tool-calls.js +147 -0
- package/dist/client/tool-display.d.ts +23 -0
- package/dist/client/tool-display.js +90 -0
- package/dist/client/tool-events.d.ts +35 -0
- package/dist/client/tool-events.js +177 -0
- package/dist/client/tool-host.d.ts +25 -0
- package/dist/client/tool-host.js +178 -0
- package/dist/client/turn.d.ts +19 -0
- package/dist/client/turn.js +52 -0
- package/dist/client/usage.d.ts +36 -0
- package/dist/client/usage.js +65 -0
- package/dist/server/index.d.ts +5 -0
- package/dist/server/index.js +1 -0
- package/package.json +57 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
const LABEL_MAX_CHARS = 200;
|
|
2
|
+
function isObject(value) {
|
|
3
|
+
return typeof value === "object" && value !== null;
|
|
4
|
+
}
|
|
5
|
+
/** Agent-supplied labels are display data: control characters stripped, capped (D-l). */
|
|
6
|
+
function label(value) {
|
|
7
|
+
if (typeof value !== "string")
|
|
8
|
+
return undefined;
|
|
9
|
+
const clean = value.replace(/\p{Cc}/gu, "").slice(0, LABEL_MAX_CHARS);
|
|
10
|
+
return clean === "" ? undefined : clean;
|
|
11
|
+
}
|
|
12
|
+
export function buildCapabilityRecord(init, entry) {
|
|
13
|
+
const caps = init.agentCapabilities ?? {};
|
|
14
|
+
const name = label(init.agentInfo?.name);
|
|
15
|
+
const version = label(init.agentInfo?.version);
|
|
16
|
+
return Object.freeze({
|
|
17
|
+
protocolVersion: init.protocolVersion,
|
|
18
|
+
...(name === undefined ? {} : { agentName: name }),
|
|
19
|
+
...(version === undefined ? {} : { agentVersion: version }),
|
|
20
|
+
loadSession: caps.loadSession === true,
|
|
21
|
+
resume: isObject(caps.sessionCapabilities?.resume),
|
|
22
|
+
close: isObject(caps.sessionCapabilities?.close),
|
|
23
|
+
mcpHttp: caps.mcpCapabilities?.http === true,
|
|
24
|
+
readOnlyMode: entry?.readOnlyMode !== undefined,
|
|
25
|
+
preApproval: entry?.preApproval !== undefined,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** The first requirement this agent cannot meet, or undefined. The model is checked after session/new. */
|
|
29
|
+
export function unmetRequirement(record, req) {
|
|
30
|
+
if ((req.profile === "none" || req.profile === "read") && !record.readOnlyMode) {
|
|
31
|
+
return {
|
|
32
|
+
capability: "profile",
|
|
33
|
+
reason: `profile "${req.profile}" needs a read-only agent mode; this agent has none`,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
if (req.toolCount > 0 && !(record.mcpHttp && record.preApproval)) {
|
|
37
|
+
return { capability: "tools", reason: "embedder tools need HTTP MCP support and adapter pre-approval" };
|
|
38
|
+
}
|
|
39
|
+
if (req.resume && !(record.resume || record.loadSession)) {
|
|
40
|
+
return { capability: "resume", reason: "the agent supports neither session/resume nor session/load" };
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
/** The value ids a select option offers, groups flattened; none for a boolean option. */
|
|
45
|
+
export function selectValues(option) {
|
|
46
|
+
if (option.type !== "select")
|
|
47
|
+
return [];
|
|
48
|
+
return option.options.flatMap((entry) => ("group" in entry ? entry.options.map((o) => o.value) : [entry.value]));
|
|
49
|
+
}
|
|
50
|
+
export function offersValue(options, configId, value) {
|
|
51
|
+
return options.some((option) => option.id === configId && selectValues(option).includes(value));
|
|
52
|
+
}
|
|
53
|
+
/** The id of the agent's model option (category "model") that offers `model`. */
|
|
54
|
+
export function modelOptionId(options, model) {
|
|
55
|
+
return options.find((option) => option.category === "model" && selectValues(option).includes(model))?.id;
|
|
56
|
+
}
|
|
57
|
+
/** The mode a profile selects (§6.4 layer 1): read-only for none/read, the default mode otherwise. */
|
|
58
|
+
export function modeFor(profile, entry) {
|
|
59
|
+
return profile === "none" || profile === "read" ? entry?.readOnlyMode : entry?.defaultMode;
|
|
60
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ACP client connection (S4 spec §6.1 connection). One ClientApp per agent
|
|
3
|
+
* process, attached with connect() for the session's lifetime (not connectWith).
|
|
4
|
+
* Outbound calls (including session/resume and session/load, S4-6) use the
|
|
5
|
+
* connection's request API directly; inbound
|
|
6
|
+
* session/update, session/request_permission and elicitation/create go to the
|
|
7
|
+
* backend's handlers. Requests are not bounded here: callers race them (race.ts),
|
|
8
|
+
* because the SDK's cancellation is cooperative and still waits for the agent's answer.
|
|
9
|
+
*/
|
|
10
|
+
import { type CreateElicitationRequest, type CreateElicitationResponse, type InitializeRequest, type InitializeResponse, type LoadSessionRequest, type LoadSessionResponse, type NewSessionRequest, type NewSessionResponse, type PromptRequest, type PromptResponse, type RequestPermissionRequest, type RequestPermissionResponse, type ResumeSessionRequest, type ResumeSessionResponse, type SessionNotification, type SetSessionConfigOptionRequest, type SetSessionConfigOptionResponse } from "@agentclientprotocol/sdk";
|
|
11
|
+
import type { LaunchTarget } from "#src/client/launch";
|
|
12
|
+
export interface InboundHandlers {
|
|
13
|
+
onUpdate(notification: SessionNotification): void;
|
|
14
|
+
onPermission(request: RequestPermissionRequest): Promise<RequestPermissionResponse>;
|
|
15
|
+
onElicitation(request: CreateElicitationRequest): Promise<CreateElicitationResponse>;
|
|
16
|
+
}
|
|
17
|
+
export interface AcpLink {
|
|
18
|
+
initialize(params: InitializeRequest): Promise<InitializeResponse>;
|
|
19
|
+
newSession(params: NewSessionRequest): Promise<NewSessionResponse>;
|
|
20
|
+
resumeSession(params: ResumeSessionRequest): Promise<ResumeSessionResponse>;
|
|
21
|
+
loadSession(params: LoadSessionRequest): Promise<LoadSessionResponse>;
|
|
22
|
+
setConfigOption(params: SetSessionConfigOptionRequest): Promise<SetSessionConfigOptionResponse>;
|
|
23
|
+
prompt(params: PromptRequest): Promise<PromptResponse>;
|
|
24
|
+
cancel(sessionId: string): Promise<void>;
|
|
25
|
+
closeSession(sessionId: string): Promise<void>;
|
|
26
|
+
/** Resolves when the connection closes, for any reason. */
|
|
27
|
+
readonly closed: Promise<void>;
|
|
28
|
+
/** Closes the connection; pending requests reject. */
|
|
29
|
+
close(reason?: unknown): void;
|
|
30
|
+
}
|
|
31
|
+
export declare function openConnection(target: LaunchTarget, handlers: InboundHandlers): AcpLink;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ACP client connection (S4 spec §6.1 connection). One ClientApp per agent
|
|
3
|
+
* process, attached with connect() for the session's lifetime (not connectWith).
|
|
4
|
+
* Outbound calls (including session/resume and session/load, S4-6) use the
|
|
5
|
+
* connection's request API directly; inbound
|
|
6
|
+
* session/update, session/request_permission and elicitation/create go to the
|
|
7
|
+
* backend's handlers. Requests are not bounded here: callers race them (race.ts),
|
|
8
|
+
* because the SDK's cancellation is cooperative and still waits for the agent's answer.
|
|
9
|
+
*/
|
|
10
|
+
import { client, methods, } from "@agentclientprotocol/sdk";
|
|
11
|
+
export function openConnection(target, handlers) {
|
|
12
|
+
const app = client({ name: "nax-agent-acp" })
|
|
13
|
+
.onNotification(methods.client.session.update, (ctx) => handlers.onUpdate(ctx.params))
|
|
14
|
+
.onRequest(methods.client.session.requestPermission, (ctx) => handlers.onPermission(ctx.params))
|
|
15
|
+
.onRequest(methods.client.elicitation.create, (ctx) => handlers.onElicitation(ctx.params));
|
|
16
|
+
const connection = target.kind === "stream" ? app.connect(target.stream) : app.connect(target.agent);
|
|
17
|
+
const agent = connection.agent;
|
|
18
|
+
return {
|
|
19
|
+
initialize: (params) => agent.request(methods.agent.initialize, params),
|
|
20
|
+
newSession: (params) => agent.request(methods.agent.session.new, params),
|
|
21
|
+
resumeSession: (params) => agent.request(methods.agent.session.resume, params),
|
|
22
|
+
loadSession: (params) => agent.request(methods.agent.session.load, params),
|
|
23
|
+
setConfigOption: (params) => agent.request(methods.agent.session.setConfigOption, params),
|
|
24
|
+
prompt: (params) => agent.request(methods.agent.session.prompt, params),
|
|
25
|
+
cancel: (sessionId) => agent.notify(methods.agent.session.cancel, { sessionId }),
|
|
26
|
+
closeSession: async (sessionId) => {
|
|
27
|
+
await agent.request(methods.agent.session.close, { sessionId });
|
|
28
|
+
},
|
|
29
|
+
closed: connection.closed,
|
|
30
|
+
close: (reason) => connection.close(reason),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* elicitation/create -> question events (S4 spec §6.8 as amended by S4-5 D5-i).
|
|
3
|
+
* Advertised under `ask` and `full` only; under `none` and `read` a request is
|
|
4
|
+
* declined unasked. A form is asked one field at a time through the session's ask
|
|
5
|
+
* port, under the turn binding's signal (D5-j):
|
|
6
|
+
* - no fields: the message alone; a reply accepts with empty content
|
|
7
|
+
* - a string field: the reply, as written
|
|
8
|
+
* - a single-select (`enum` or `oneOf`): a choice named by number, value or title,
|
|
9
|
+
* trimmed and case-insensitive
|
|
10
|
+
* - a multi-select (`array` with `enum`/`anyOf`/`oneOf` items): comma-separated choices
|
|
11
|
+
* A plain string field `<key>_custom` next to a select `<key>` is its free-text
|
|
12
|
+
* companion (Claude's AskUserQuestion "Other" box): not asked on its own; a reply
|
|
13
|
+
* naming no choice becomes its value. Any other field type, a malformed or oversized
|
|
14
|
+
* choice list, too many fields, or a non-form request declines the form unasked;
|
|
15
|
+
* a reply naming no choice without a companion, or an empty reply to a required
|
|
16
|
+
* field, declines after asking. Each decline is noted with noteQuestion. No reply
|
|
17
|
+
* (deadline, cancel, turn end, process exit) cancels. Question text is agent data:
|
|
18
|
+
* control and invisible characters stripped, secrets scrubbed, capped.
|
|
19
|
+
*/
|
|
20
|
+
import type { CreateElicitationRequest, CreateElicitationResponse } from "@agentclientprotocol/sdk";
|
|
21
|
+
import type { AgentSessionProfile, SessionAskPort } from "@nathapp/nax-agent";
|
|
22
|
+
export declare const QUESTION_MAX_BYTES = 4096;
|
|
23
|
+
export declare const MAX_FORM_FIELDS = 16;
|
|
24
|
+
export declare const MAX_CHOICES = 32;
|
|
25
|
+
export declare const NO_MATCH_NOTE = "declined: the reply matches no choice";
|
|
26
|
+
export declare const REQUIRED_NOTE = "declined: an answer is required";
|
|
27
|
+
export interface ElicitationContext {
|
|
28
|
+
readonly profile: AgentSessionProfile;
|
|
29
|
+
readonly asks: SessionAskPort;
|
|
30
|
+
readonly secrets: readonly string[];
|
|
31
|
+
/** The turn binding's signal: aborts on cancel, timeout, turn end and process exit. */
|
|
32
|
+
readonly signal: AbortSignal;
|
|
33
|
+
}
|
|
34
|
+
export declare function answerElicitation(request: CreateElicitationRequest, ctx: ElicitationContext): Promise<CreateElicitationResponse>;
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { capBytes, isRecord, scrubSecrets, stripControl, stripInvisible } from "#src/client/text";
|
|
2
|
+
export const QUESTION_MAX_BYTES = 4096;
|
|
3
|
+
export const MAX_FORM_FIELDS = 16;
|
|
4
|
+
export const MAX_CHOICES = 32;
|
|
5
|
+
export const NO_MATCH_NOTE = "declined: the reply matches no choice";
|
|
6
|
+
export const REQUIRED_NOTE = "declined: an answer is required";
|
|
7
|
+
const COMPANION_SUFFIX = "_custom";
|
|
8
|
+
/** Agent text longer than this is cut before cleaning; a question is far shorter. */
|
|
9
|
+
const QUESTION_SCAN_BYTES = 64 * 1024;
|
|
10
|
+
const CANCEL = { action: "cancel" };
|
|
11
|
+
const DECLINE = { action: "decline" };
|
|
12
|
+
const REFUSED = { ok: false };
|
|
13
|
+
function shown(text, secrets) {
|
|
14
|
+
const visible = stripInvisible(stripControl(capBytes(text, QUESTION_SCAN_BYTES)));
|
|
15
|
+
return capBytes(scrubSecrets(visible, secrets), QUESTION_MAX_BYTES);
|
|
16
|
+
}
|
|
17
|
+
function nonEmpty(value) {
|
|
18
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
|
|
19
|
+
}
|
|
20
|
+
function choiceOf(item) {
|
|
21
|
+
if (typeof item === "string")
|
|
22
|
+
return { value: item, label: item };
|
|
23
|
+
if (!isRecord(item) || typeof item.const !== "string")
|
|
24
|
+
return undefined;
|
|
25
|
+
const description = nonEmpty(item.description);
|
|
26
|
+
return {
|
|
27
|
+
value: item.const,
|
|
28
|
+
label: nonEmpty(item.title) ?? item.const,
|
|
29
|
+
...(description === undefined ? {} : { description }),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** [] when the schema declares no choices; undefined when its choice list is unusable. */
|
|
33
|
+
function choicesOf(schema) {
|
|
34
|
+
const list = schema.oneOf ?? schema.anyOf ?? schema.enum;
|
|
35
|
+
if (list === undefined || list === null)
|
|
36
|
+
return [];
|
|
37
|
+
if (!Array.isArray(list) || list.length === 0 || list.length > MAX_CHOICES)
|
|
38
|
+
return undefined;
|
|
39
|
+
const choices = list.map(choiceOf);
|
|
40
|
+
return choices.every((choice) => choice !== undefined) ? choices : undefined;
|
|
41
|
+
}
|
|
42
|
+
function fieldOf(key, schema, required) {
|
|
43
|
+
if (!isRecord(schema))
|
|
44
|
+
return undefined;
|
|
45
|
+
const title = nonEmpty(schema.title);
|
|
46
|
+
const description = nonEmpty(schema.description);
|
|
47
|
+
const base = {
|
|
48
|
+
key,
|
|
49
|
+
required,
|
|
50
|
+
...(title === undefined ? {} : { title }),
|
|
51
|
+
...(description === undefined ? {} : { description }),
|
|
52
|
+
};
|
|
53
|
+
if (schema.type === "string") {
|
|
54
|
+
const choices = choicesOf(schema);
|
|
55
|
+
if (choices === undefined)
|
|
56
|
+
return undefined;
|
|
57
|
+
return { ...base, kind: choices.length === 0 ? "text" : "single", choices };
|
|
58
|
+
}
|
|
59
|
+
if (schema.type !== "array" || !isRecord(schema.items))
|
|
60
|
+
return undefined;
|
|
61
|
+
const choices = choicesOf(schema.items);
|
|
62
|
+
return choices === undefined || choices.length === 0 ? undefined : { ...base, kind: "multi", choices };
|
|
63
|
+
}
|
|
64
|
+
/** Folds each `<key>_custom` text field into its select `<key>` (D5-i). */
|
|
65
|
+
function withCompanions(fields) {
|
|
66
|
+
const byKey = new Map(fields.map((field) => [field.key, field]));
|
|
67
|
+
const folded = new Set();
|
|
68
|
+
const linked = fields.map((field) => {
|
|
69
|
+
const companion = byKey.get(`${field.key}${COMPANION_SUFFIX}`);
|
|
70
|
+
if (field.kind === "text" || companion?.kind !== "text")
|
|
71
|
+
return field;
|
|
72
|
+
folded.add(companion.key);
|
|
73
|
+
return { ...field, companion: companion.key };
|
|
74
|
+
});
|
|
75
|
+
return linked.filter((field) => !folded.has(field.key));
|
|
76
|
+
}
|
|
77
|
+
function parseForm(request) {
|
|
78
|
+
if (!isRecord(request) || request.mode !== "form" || !isRecord(request.requestedSchema))
|
|
79
|
+
return REFUSED;
|
|
80
|
+
const schema = request.requestedSchema;
|
|
81
|
+
const properties = schema.properties ?? {};
|
|
82
|
+
if (!isRecord(properties))
|
|
83
|
+
return REFUSED;
|
|
84
|
+
const entries = Object.entries(properties);
|
|
85
|
+
if (entries.length > MAX_FORM_FIELDS)
|
|
86
|
+
return REFUSED;
|
|
87
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
88
|
+
const fields = entries.map(([key, property]) => fieldOf(key, property, required.has(key)));
|
|
89
|
+
return fields.every((field) => field !== undefined)
|
|
90
|
+
? { ok: true, fields: withCompanions(fields) }
|
|
91
|
+
: REFUSED;
|
|
92
|
+
}
|
|
93
|
+
function instruction(field) {
|
|
94
|
+
const own = field.companion === undefined ? "" : ", or type your own answer";
|
|
95
|
+
const skip = field.required ? "" : " Leave empty to skip.";
|
|
96
|
+
if (field.kind === "single")
|
|
97
|
+
return `Reply with one number or choice${own}.${skip}`;
|
|
98
|
+
if (field.kind === "multi")
|
|
99
|
+
return `Reply with numbers or choices, separated by commas${own}.${skip}`;
|
|
100
|
+
return field.required ? "Reply with your answer." : "Reply with your answer, or leave it empty to skip.";
|
|
101
|
+
}
|
|
102
|
+
function questionText(message, field, index, count) {
|
|
103
|
+
const head = count > 1 ? `(${index + 1}/${count}) ` : "";
|
|
104
|
+
const label = [field.title, field.description].filter((part) => part !== undefined).join(": ");
|
|
105
|
+
const heading = `${head}${label}`.trim();
|
|
106
|
+
return [
|
|
107
|
+
...(index === 0 && message.trim() !== "" ? [message.trim()] : []),
|
|
108
|
+
...(heading === "" ? [] : [heading]),
|
|
109
|
+
...field.choices.map((choice, i) => `${i + 1}. ${choice.label}${choice.description ? ` - ${choice.description}` : ""}`),
|
|
110
|
+
instruction(field),
|
|
111
|
+
].join("\n");
|
|
112
|
+
}
|
|
113
|
+
function matchChoice(choices, text) {
|
|
114
|
+
const byNumber = /^\d+$/.test(text) ? choices[Number(text) - 1] : undefined;
|
|
115
|
+
const wanted = text.toLowerCase();
|
|
116
|
+
return byNumber ?? choices.find((c) => c.value.toLowerCase() === wanted || c.label.toLowerCase() === wanted);
|
|
117
|
+
}
|
|
118
|
+
const accepted = (content) => ({ ok: true, content });
|
|
119
|
+
const NO_MATCH = { ok: false, note: NO_MATCH_NOTE };
|
|
120
|
+
function singleReply(field, reply) {
|
|
121
|
+
const choice = matchChoice(field.choices, reply);
|
|
122
|
+
if (choice !== undefined)
|
|
123
|
+
return accepted({ [field.key]: choice.value });
|
|
124
|
+
return field.companion === undefined || field.required ? NO_MATCH : accepted({ [field.companion]: reply });
|
|
125
|
+
}
|
|
126
|
+
function multiReply(field, reply) {
|
|
127
|
+
const parts = reply
|
|
128
|
+
.split(",")
|
|
129
|
+
.map((part) => part.trim())
|
|
130
|
+
.filter((part) => part !== "");
|
|
131
|
+
const matched = parts.map((part) => matchChoice(field.choices, part));
|
|
132
|
+
const values = [...new Set(matched.flatMap((choice) => (choice === undefined ? [] : [choice.value])))];
|
|
133
|
+
const others = parts.filter((_, i) => matched[i] === undefined);
|
|
134
|
+
if (others.length > 0 && field.companion === undefined)
|
|
135
|
+
return NO_MATCH;
|
|
136
|
+
if (values.length === 0 && field.required)
|
|
137
|
+
return NO_MATCH;
|
|
138
|
+
return accepted({
|
|
139
|
+
...(values.length === 0 ? {} : { [field.key]: values }),
|
|
140
|
+
...(others.length === 0 || field.companion === undefined ? {} : { [field.companion]: others.join(", ") }),
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function applyReply(field, reply) {
|
|
144
|
+
if (reply === "")
|
|
145
|
+
return field.required ? { ok: false, note: REQUIRED_NOTE } : accepted({});
|
|
146
|
+
if (field.kind === "single")
|
|
147
|
+
return singleReply(field, reply);
|
|
148
|
+
if (field.kind === "multi")
|
|
149
|
+
return multiReply(field, reply);
|
|
150
|
+
return accepted({ [field.key]: reply });
|
|
151
|
+
}
|
|
152
|
+
async function ask(text, ctx) {
|
|
153
|
+
if (ctx.signal.aborted)
|
|
154
|
+
return null;
|
|
155
|
+
return ctx.asks.askQuestion(shown(text, ctx.secrets), { signal: ctx.signal }).catch(() => null);
|
|
156
|
+
}
|
|
157
|
+
async function askFields(message, fields, ctx) {
|
|
158
|
+
if (fields.length === 0)
|
|
159
|
+
return (await ask(message, ctx)) === null ? CANCEL : { action: "accept", content: {} };
|
|
160
|
+
let content = {};
|
|
161
|
+
for (const [index, field] of fields.entries()) {
|
|
162
|
+
const reply = await ask(questionText(message, field, index, fields.length), ctx);
|
|
163
|
+
if (reply === null)
|
|
164
|
+
return CANCEL;
|
|
165
|
+
const outcome = applyReply(field, reply.trim());
|
|
166
|
+
if (!outcome.ok) {
|
|
167
|
+
ctx.asks.noteQuestion(outcome.note);
|
|
168
|
+
return DECLINE;
|
|
169
|
+
}
|
|
170
|
+
content = { ...content, ...outcome.content };
|
|
171
|
+
}
|
|
172
|
+
return { action: "accept", content };
|
|
173
|
+
}
|
|
174
|
+
export async function answerElicitation(request, ctx) {
|
|
175
|
+
if (ctx.profile !== "ask" && ctx.profile !== "full")
|
|
176
|
+
return DECLINE;
|
|
177
|
+
const message = typeof request.message === "string" ? request.message : "";
|
|
178
|
+
const parsed = parseForm(request);
|
|
179
|
+
if (!parsed.ok) {
|
|
180
|
+
ctx.asks.noteQuestion(shown(`declined: ${message}`, ctx.secrets));
|
|
181
|
+
return DECLINE;
|
|
182
|
+
}
|
|
183
|
+
return askFields(message, parsed.fields, ctx);
|
|
184
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface AgentEnvInput {
|
|
2
|
+
readonly source: Readonly<Record<string, string | undefined>>;
|
|
3
|
+
readonly inheritEnv: boolean;
|
|
4
|
+
readonly authEnv: readonly string[];
|
|
5
|
+
readonly extra: Readonly<Record<string, string>>;
|
|
6
|
+
}
|
|
7
|
+
export declare function buildAgentEnv(input: AgentEnvInput): Record<string, string>;
|
|
8
|
+
export declare function secretValues(env: Readonly<Record<string, string>>): readonly string[];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent's environment (S4 spec §6.2). By default an allowlist: the base
|
|
3
|
+
* keys, LC_*, the registry entry's auth variables, then `env`. `inheritEnv`
|
|
4
|
+
* passes the whole source instead (documented as handing the embedder's
|
|
5
|
+
* credentials to the agent). The redaction set is every secret-named value in
|
|
6
|
+
* the result (D-g).
|
|
7
|
+
*/
|
|
8
|
+
const BASE_KEYS = ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "LANG", "TERM"];
|
|
9
|
+
const SECRET_KEY = /KEY|TOKEN|SECRET|PASSWORD/i;
|
|
10
|
+
function allowed(key, authEnv) {
|
|
11
|
+
return BASE_KEYS.includes(key) || key.startsWith("LC_") || authEnv.includes(key);
|
|
12
|
+
}
|
|
13
|
+
export function buildAgentEnv(input) {
|
|
14
|
+
const picked = Object.entries(input.source).flatMap(([key, value]) => value !== undefined && (input.inheritEnv || allowed(key, input.authEnv)) ? [[key, value]] : []);
|
|
15
|
+
return { ...Object.fromEntries(picked), ...input.extra };
|
|
16
|
+
}
|
|
17
|
+
export function secretValues(env) {
|
|
18
|
+
return Object.entries(env)
|
|
19
|
+
.filter(([key, value]) => SECRET_KEY.test(key) && value.length > 0)
|
|
20
|
+
.map(([, value]) => value);
|
|
21
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errors of the ACP backend (S4 spec §5.7, §7). Classification (auth or not)
|
|
3
|
+
* runs on the agent's raw error here; only the classified code and a redacted,
|
|
4
|
+
* control-stripped excerpt of at most 4 KB reach messages and details.
|
|
5
|
+
*/
|
|
6
|
+
import { RequestError } from "@agentclientprotocol/sdk";
|
|
7
|
+
import { AgentSessionError, NaxError } from "@nathapp/nax-agent";
|
|
8
|
+
/** Byte cap of every agent-text excerpt (stderr, JSON-RPC messages). */
|
|
9
|
+
export declare const EXCERPT_BYTES = 4096;
|
|
10
|
+
/** Stop reasons other than end_turn, as NaxError codes owned by this package (§5.7). */
|
|
11
|
+
export declare const ACP_STOP_CODES: Readonly<{
|
|
12
|
+
readonly max_tokens: "ACP_STOP_MAX_TOKENS";
|
|
13
|
+
readonly max_turn_requests: "ACP_STOP_MAX_TURN_REQUESTS";
|
|
14
|
+
readonly refusal: "ACP_STOP_REFUSAL";
|
|
15
|
+
readonly cancelled: "ACP_STOP_CANCELLED";
|
|
16
|
+
}>;
|
|
17
|
+
export type AcpStopCode = (typeof ACP_STOP_CODES)[keyof typeof ACP_STOP_CODES];
|
|
18
|
+
/** Agent text made safe for an error: control characters stripped (except \n, \t), secrets redacted, capped. */
|
|
19
|
+
export declare function agentTextExcerpt(text: string, secrets: readonly string[]): string;
|
|
20
|
+
export declare function capabilityUnsupported(capability: string, reason: string): AgentSessionError;
|
|
21
|
+
export declare function backendUnavailable(reason: string, details?: Readonly<Record<string, unknown>>): AgentSessionError;
|
|
22
|
+
export declare function closedDuringOpen(sessionId: string): AgentSessionError;
|
|
23
|
+
/** The session cannot run another turn: closed, or its agent is gone and cannot be reconnected (§6.3 step 5). */
|
|
24
|
+
export declare function sessionLost(sessionId: string, reason: string): AgentSessionError;
|
|
25
|
+
/** The JSON-RPC error the agent answered with; undefined for transport failures. */
|
|
26
|
+
export declare function rpcErrorOf(err: unknown): RequestError | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* A rejected open-phase request: initialize, session/new, session/resume,
|
|
29
|
+
* session/load or session/set_config_option. Classification runs on the raw
|
|
30
|
+
* message; only the redacted excerpt escapes (§7).
|
|
31
|
+
*/
|
|
32
|
+
export declare function openRequestError(step: string, err: RequestError, secrets: readonly string[]): AgentSessionError;
|
|
33
|
+
/** A rejected session/prompt (§7: a JSON-RPC error on prompt is AGENT_SESSION_TURN_FAILED). */
|
|
34
|
+
export declare function promptRequestError(err: RequestError, secrets: readonly string[]): NaxError;
|
|
35
|
+
/** A stop reason other than end_turn. Own keys only: "__proto__" or "toString" is unknown, not a code. */
|
|
36
|
+
export declare function stopReasonError(stopReason: string): NaxError;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errors of the ACP backend (S4 spec §5.7, §7). Classification (auth or not)
|
|
3
|
+
* runs on the agent's raw error here; only the classified code and a redacted,
|
|
4
|
+
* control-stripped excerpt of at most 4 KB reach messages and details.
|
|
5
|
+
*/
|
|
6
|
+
import { RequestError } from "@agentclientprotocol/sdk";
|
|
7
|
+
import { AgentSessionError, NaxError, redactSecrets } from "@nathapp/nax-agent";
|
|
8
|
+
import { capBytes, scrubSecrets, stripControl } from "#src/client/text";
|
|
9
|
+
/** Byte cap of every agent-text excerpt (stderr, JSON-RPC messages). */
|
|
10
|
+
export const EXCERPT_BYTES = 4096;
|
|
11
|
+
/** JSON-RPC code of `RequestError.authRequired()`. */
|
|
12
|
+
const AUTH_REQUIRED_CODE = -32000;
|
|
13
|
+
/** JSON-RPC code of `RequestError.resourceNotFound()`: Claude's adapter answers an unknown session with it (D6-e). */
|
|
14
|
+
const RESOURCE_NOT_FOUND_CODE = -32002;
|
|
15
|
+
/** The steps whose not-found answer means the agent lost the stored session (§6.9 step 2). */
|
|
16
|
+
const RESTORE_STEPS = new Set(["session/resume", "session/load"]);
|
|
17
|
+
/** Agent text reporting a lost session, for agents that answer with another code. */
|
|
18
|
+
const SESSION_NOT_FOUND_TEXT = /session not found|no conversation found/i;
|
|
19
|
+
function lostOnRestore(step, err) {
|
|
20
|
+
return RESTORE_STEPS.has(step) && (err.code === RESOURCE_NOT_FOUND_CODE || SESSION_NOT_FOUND_TEXT.test(err.message));
|
|
21
|
+
}
|
|
22
|
+
/** Stop reasons other than end_turn, as NaxError codes owned by this package (§5.7). */
|
|
23
|
+
export const ACP_STOP_CODES = Object.freeze({
|
|
24
|
+
max_tokens: "ACP_STOP_MAX_TOKENS",
|
|
25
|
+
max_turn_requests: "ACP_STOP_MAX_TURN_REQUESTS",
|
|
26
|
+
refusal: "ACP_STOP_REFUSAL",
|
|
27
|
+
cancelled: "ACP_STOP_CANCELLED",
|
|
28
|
+
});
|
|
29
|
+
/** Agent text made safe for an error: control characters stripped (except \n, \t), secrets redacted, capped. */
|
|
30
|
+
export function agentTextExcerpt(text, secrets) {
|
|
31
|
+
return capBytes(redactSecrets(scrubSecrets(stripControl(text), secrets)), EXCERPT_BYTES);
|
|
32
|
+
}
|
|
33
|
+
export function capabilityUnsupported(capability, reason) {
|
|
34
|
+
return new AgentSessionError(`The ACP agent cannot meet the "${capability}" requirement: ${reason}`, "AGENT_SESSION_CAPABILITY_UNSUPPORTED", { capability });
|
|
35
|
+
}
|
|
36
|
+
export function backendUnavailable(reason, details = {}) {
|
|
37
|
+
return new AgentSessionError(`The ACP agent is unavailable: ${reason}`, "AGENT_SESSION_BACKEND_UNAVAILABLE", {
|
|
38
|
+
...details,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
export function closedDuringOpen(sessionId) {
|
|
42
|
+
return new AgentSessionError(`Session "${sessionId}" was closed while it was opening`, "AGENT_SESSION_CLOSED", {
|
|
43
|
+
sessionId,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/** The session cannot run another turn: closed, or its agent is gone and cannot be reconnected (§6.3 step 5). */
|
|
47
|
+
export function sessionLost(sessionId, reason) {
|
|
48
|
+
return new AgentSessionError(`ACP session "${sessionId}" is closed: ${reason}`, "AGENT_SESSION_CLOSED", {
|
|
49
|
+
sessionId,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/** The JSON-RPC error the agent answered with; undefined for transport failures. */
|
|
53
|
+
export function rpcErrorOf(err) {
|
|
54
|
+
return err instanceof RequestError ? err : undefined;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* A rejected open-phase request: initialize, session/new, session/resume,
|
|
58
|
+
* session/load or session/set_config_option. Classification runs on the raw
|
|
59
|
+
* message; only the redacted excerpt escapes (§7).
|
|
60
|
+
*/
|
|
61
|
+
export function openRequestError(step, err, secrets) {
|
|
62
|
+
const excerpt = agentTextExcerpt(err.message, secrets);
|
|
63
|
+
if (err.code === AUTH_REQUIRED_CODE) {
|
|
64
|
+
return new AgentSessionError(`The ACP agent requires authentication (${step}): ${excerpt}`, "AGENT_SESSION_AUTH_REQUIRED", { step });
|
|
65
|
+
}
|
|
66
|
+
if (lostOnRestore(step, err)) {
|
|
67
|
+
return new AgentSessionError(`The ACP agent no longer has this session (${step}): ${excerpt}`, "AGENT_SESSION_NOT_FOUND", { step });
|
|
68
|
+
}
|
|
69
|
+
return backendUnavailable(`${step} failed: ${excerpt}`, { step, rpcCode: err.code });
|
|
70
|
+
}
|
|
71
|
+
/** A rejected session/prompt (§7: a JSON-RPC error on prompt is AGENT_SESSION_TURN_FAILED). */
|
|
72
|
+
export function promptRequestError(err, secrets) {
|
|
73
|
+
const excerpt = agentTextExcerpt(err.message, secrets);
|
|
74
|
+
if (err.code === AUTH_REQUIRED_CODE) {
|
|
75
|
+
return new AgentSessionError(`The ACP agent requires authentication: ${excerpt}`, "AGENT_SESSION_AUTH_REQUIRED", {
|
|
76
|
+
step: "session/prompt",
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return new NaxError(`The ACP prompt failed: ${excerpt}`, "AGENT_SESSION_TURN_FAILED", {
|
|
80
|
+
stage: "acp",
|
|
81
|
+
rpcCode: err.code,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** A stop reason other than end_turn. Own keys only: "__proto__" or "toString" is unknown, not a code. */
|
|
85
|
+
export function stopReasonError(stopReason) {
|
|
86
|
+
if (Object.hasOwn(ACP_STOP_CODES, stopReason)) {
|
|
87
|
+
const code = ACP_STOP_CODES[stopReason];
|
|
88
|
+
return new NaxError(`The ACP agent stopped the turn: ${stopReason}`, code, { stage: "acp", stopReason });
|
|
89
|
+
}
|
|
90
|
+
const shown = agentTextExcerpt(stopReason, []).slice(0, 64);
|
|
91
|
+
return new NaxError(`The ACP agent ended the turn with an unknown stop reason "${shown}"`, "AGENT_SESSION_TURN_FAILED", { stage: "acp", stopReason: shown });
|
|
92
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* session/update -> TurnEvent (S4 spec §6.7, S4-5). Agent text is a text_delta and
|
|
3
|
+
* a thought a thinking_delta, round 0. Both are scrubbed of the session's secret
|
|
4
|
+
* values, holding back only the tail that could start a secret (D5-g); a delta of
|
|
5
|
+
* one stream, and any tool event, first flushes what the other stream holds, so the
|
|
6
|
+
* order is kept. Tool calls and results come from tool-events.ts (D5-c to D5-f);
|
|
7
|
+
* usage_update costs feed the session's cost meter (D5-b). User chunks, plans, mode,
|
|
8
|
+
* config and command updates, and anything unknown are dropped. finish() flushes
|
|
9
|
+
* held text and answers unanswered tool calls; settle(response) does that and then
|
|
10
|
+
* emits the turn's one usage event (D5-h). Nothing is emitted after finish(). The
|
|
11
|
+
* sink is the facade's; a throw from it is contained.
|
|
12
|
+
*/
|
|
13
|
+
import type { PromptResponse, SessionUpdate } from "@agentclientprotocol/sdk";
|
|
14
|
+
import type { TurnEventSink } from "@nathapp/nax-agent";
|
|
15
|
+
import { type CostMeter, type TurnSpend } from "#src/client/usage";
|
|
16
|
+
export interface CollectorOptions {
|
|
17
|
+
/** The session's secret values: env secrets and the tool host's token. */
|
|
18
|
+
readonly secrets?: readonly string[];
|
|
19
|
+
/** The session's cost meter; a fresh one when absent. */
|
|
20
|
+
readonly meter?: CostMeter;
|
|
21
|
+
}
|
|
22
|
+
export interface TurnCollector {
|
|
23
|
+
onUpdate(update: SessionUpdate): void;
|
|
24
|
+
/** A permission request names this tool call: its tool_call event goes out now (D5-c). */
|
|
25
|
+
announce(toolCall: unknown): void;
|
|
26
|
+
/** Flushes held text and answers announced calls without a result. Idempotent. */
|
|
27
|
+
finish(): void;
|
|
28
|
+
/** finish(), then the turn's one usage event; returns the turn's spend. */
|
|
29
|
+
settle(response: PromptResponse): TurnSpend;
|
|
30
|
+
/** The turn's agent message text, scrubbed (turn_end.output). */
|
|
31
|
+
output(): string;
|
|
32
|
+
}
|
|
33
|
+
export declare function createTurnCollector(emit: TurnEventSink | undefined, options?: CollectorOptions): TurnCollector;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { createStreamScrubber } from "#src/client/stream-scrub";
|
|
2
|
+
import { scrubSecrets } from "#src/client/text";
|
|
3
|
+
import { createToolEvents } from "#src/client/tool-events";
|
|
4
|
+
import { createCostMeter, turnSpend, usageEvent } from "#src/client/usage";
|
|
5
|
+
function createDeltas(send, secrets) {
|
|
6
|
+
const streams = { text_delta: createStreamScrubber(secrets), thinking_delta: createStreamScrubber(secrets) };
|
|
7
|
+
const out = (type, text) => {
|
|
8
|
+
if (text !== "")
|
|
9
|
+
send({ type, round: 0, text });
|
|
10
|
+
};
|
|
11
|
+
const flush = (type) => out(type, streams[type].flush());
|
|
12
|
+
return {
|
|
13
|
+
push(type, text) {
|
|
14
|
+
flush(type === "text_delta" ? "thinking_delta" : "text_delta");
|
|
15
|
+
out(type, streams[type].push(text));
|
|
16
|
+
},
|
|
17
|
+
flushAll() {
|
|
18
|
+
flush("thinking_delta");
|
|
19
|
+
flush("text_delta");
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function containedSink(emit) {
|
|
24
|
+
return (event) => {
|
|
25
|
+
try {
|
|
26
|
+
emit?.(event);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// The sink is the facade's event channel; a broken consumer must not break the turn.
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export function createTurnCollector(emit, options = {}) {
|
|
34
|
+
const secrets = options.secrets ?? [];
|
|
35
|
+
const meter = options.meter ?? createCostMeter();
|
|
36
|
+
meter.beginTurn();
|
|
37
|
+
const send = containedSink(emit);
|
|
38
|
+
const deltas = createDeltas(send, secrets);
|
|
39
|
+
const tools = createToolEvents((event) => {
|
|
40
|
+
deltas.flushAll();
|
|
41
|
+
send(event);
|
|
42
|
+
}, secrets);
|
|
43
|
+
const parts = [];
|
|
44
|
+
let done = false;
|
|
45
|
+
let spend;
|
|
46
|
+
const route = (update) => {
|
|
47
|
+
switch (update.sessionUpdate) {
|
|
48
|
+
case "agent_message_chunk":
|
|
49
|
+
if (update.content.type !== "text")
|
|
50
|
+
return;
|
|
51
|
+
parts.push(update.content.text);
|
|
52
|
+
deltas.push("text_delta", update.content.text);
|
|
53
|
+
return;
|
|
54
|
+
case "agent_thought_chunk":
|
|
55
|
+
if (update.content.type === "text")
|
|
56
|
+
deltas.push("thinking_delta", update.content.text);
|
|
57
|
+
return;
|
|
58
|
+
case "tool_call":
|
|
59
|
+
case "tool_call_update":
|
|
60
|
+
tools.onUpdate(update);
|
|
61
|
+
return;
|
|
62
|
+
case "usage_update":
|
|
63
|
+
meter.observe(update.cost);
|
|
64
|
+
return;
|
|
65
|
+
default:
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const finish = () => {
|
|
70
|
+
if (done)
|
|
71
|
+
return;
|
|
72
|
+
done = true;
|
|
73
|
+
deltas.flushAll();
|
|
74
|
+
tools.flush();
|
|
75
|
+
};
|
|
76
|
+
return {
|
|
77
|
+
onUpdate(update) {
|
|
78
|
+
if (!done)
|
|
79
|
+
route(update);
|
|
80
|
+
},
|
|
81
|
+
announce(toolCall) {
|
|
82
|
+
if (!done)
|
|
83
|
+
tools.announce(toolCall);
|
|
84
|
+
},
|
|
85
|
+
finish,
|
|
86
|
+
settle(response) {
|
|
87
|
+
finish();
|
|
88
|
+
if (spend === undefined) {
|
|
89
|
+
spend = turnSpend(response, meter);
|
|
90
|
+
send(usageEvent(spend));
|
|
91
|
+
}
|
|
92
|
+
return spend;
|
|
93
|
+
},
|
|
94
|
+
output: () => scrubSecrets(parts.join(""), secrets),
|
|
95
|
+
};
|
|
96
|
+
}
|