@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.
Files changed (56) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/LICENSE +21 -0
  3. package/README.md +227 -0
  4. package/dist/client/backend.d.ts +30 -0
  5. package/dist/client/backend.js +238 -0
  6. package/dist/client/capabilities.d.ts +42 -0
  7. package/dist/client/capabilities.js +60 -0
  8. package/dist/client/connection.d.ts +31 -0
  9. package/dist/client/connection.js +32 -0
  10. package/dist/client/elicitation.d.ts +34 -0
  11. package/dist/client/elicitation.js +184 -0
  12. package/dist/client/env.d.ts +8 -0
  13. package/dist/client/env.js +21 -0
  14. package/dist/client/errors.d.ts +36 -0
  15. package/dist/client/errors.js +92 -0
  16. package/dist/client/events.d.ts +33 -0
  17. package/dist/client/events.js +96 -0
  18. package/dist/client/inbound.d.ts +40 -0
  19. package/dist/client/inbound.js +100 -0
  20. package/dist/client/index.d.ts +14 -0
  21. package/dist/client/index.js +12 -0
  22. package/dist/client/launch.d.ts +47 -0
  23. package/dist/client/launch.js +145 -0
  24. package/dist/client/open.d.ts +35 -0
  25. package/dist/client/open.js +154 -0
  26. package/dist/client/options.d.ts +46 -0
  27. package/dist/client/options.js +91 -0
  28. package/dist/client/permissions.d.ts +36 -0
  29. package/dist/client/permissions.js +92 -0
  30. package/dist/client/pre-approval.d.ts +24 -0
  31. package/dist/client/pre-approval.js +22 -0
  32. package/dist/client/race.d.ts +22 -0
  33. package/dist/client/race.js +20 -0
  34. package/dist/client/registry.d.ts +35 -0
  35. package/dist/client/registry.js +43 -0
  36. package/dist/client/resume.d.ts +37 -0
  37. package/dist/client/resume.js +93 -0
  38. package/dist/client/stream-scrub.d.ts +7 -0
  39. package/dist/client/stream-scrub.js +37 -0
  40. package/dist/client/text.d.ts +29 -0
  41. package/dist/client/text.js +62 -0
  42. package/dist/client/tool-calls.d.ts +42 -0
  43. package/dist/client/tool-calls.js +147 -0
  44. package/dist/client/tool-display.d.ts +23 -0
  45. package/dist/client/tool-display.js +90 -0
  46. package/dist/client/tool-events.d.ts +35 -0
  47. package/dist/client/tool-events.js +177 -0
  48. package/dist/client/tool-host.d.ts +25 -0
  49. package/dist/client/tool-host.js +178 -0
  50. package/dist/client/turn.d.ts +19 -0
  51. package/dist/client/turn.js +52 -0
  52. package/dist/client/usage.d.ts +36 -0
  53. package/dist/client/usage.js +65 -0
  54. package/dist/server/index.d.ts +5 -0
  55. package/dist/server/index.js +1 -0
  56. package/package.json +57 -0
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Agent text made safe to show (S4 spec §6.4 "untrusted fields", §7): control
3
+ * characters stripped, the session's secret values scrubbed, byte caps that never
4
+ * split a character. Shared by error excerpts (errors.ts), the approval display
5
+ * (tool-display.ts), turn events (stream-scrub.ts, tool-events.ts) and questions
6
+ * (elicitation.ts).
7
+ */
8
+ /** Shorter secret values are not replaced verbatim: they would garble ordinary text. */
9
+ export const MIN_SECRET_LENGTH = 8;
10
+ /** A label longer than this is cut before cleaning; the result is far shorter. */
11
+ const LABEL_SCAN_CHARS = 16 * 1024;
12
+ export function isRecord(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ /** Control characters removed, except newline and tab. */
16
+ export function stripControl(text) {
17
+ return text.replace(/\p{Cc}/gu, (c) => (c === "\n" || c === "\t" ? c : ""));
18
+ }
19
+ /** Invisible format characters removed (bidi overrides, zero-width): they can hide text from a person. */
20
+ export function stripInvisible(text) {
21
+ return text.replace(/\p{Cf}/gu, "");
22
+ }
23
+ /** Each known secret value of 8 or more characters replaced by [REDACTED]. */
24
+ export function scrubSecrets(text, secrets) {
25
+ return secrets
26
+ .filter((secret) => secret.length >= MIN_SECRET_LENGTH)
27
+ .reduce((acc, secret) => acc.split(secret).join("[REDACTED]"), text);
28
+ }
29
+ export function capBytes(text, maxBytes) {
30
+ const bytes = Buffer.from(text, "utf8");
31
+ if (bytes.byteLength <= maxBytes)
32
+ return text;
33
+ // A cut inside a multi-byte character decodes to U+FFFD; drop it.
34
+ return bytes.subarray(0, maxBytes).toString("utf8").replace(/�+$/u, "");
35
+ }
36
+ /**
37
+ * `value` with every string, keys included, scrubbed of the session's secret values.
38
+ * Expects acyclic JSON-like data (capStrings output). Keys are written as data, so a
39
+ * `__proto__` key stays an own property.
40
+ */
41
+ export function scrubDeep(value, secrets) {
42
+ if (typeof value === "string")
43
+ return scrubSecrets(value, secrets);
44
+ if (Array.isArray(value))
45
+ return value.map((item) => scrubDeep(item, secrets));
46
+ if (!isRecord(value))
47
+ return value;
48
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [scrubSecrets(key, secrets), scrubDeep(item, secrets)]));
49
+ }
50
+ /**
51
+ * A one-line label from agent text: control and invisible characters removed,
52
+ * whitespace collapsed, secrets scrubbed, at most `maxChars` code points. Undefined
53
+ * for a non-string or a label that is empty after cleaning.
54
+ */
55
+ export function cleanLabel(value, secrets, maxChars) {
56
+ if (typeof value !== "string")
57
+ return undefined;
58
+ const visible = stripInvisible(stripControl(value.slice(0, LABEL_SCAN_CHARS)));
59
+ const text = scrubSecrets(visible.replace(/\s+/g, " ").trim(), secrets);
60
+ const capped = Array.from(text).slice(0, maxChars).join("");
61
+ return capped === "" ? undefined : capped;
62
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Embedder tools as the MCP tool host serves them (S4 spec §6.6: tools/list and
3
+ * tools/call). A call runs only while a turn runs, at most
4
+ * MAX_CONCURRENT_TOOL_CALLS at once, under the turn's binding signal (cancel,
5
+ * timeout, close, turn end, agent process exit) combined with its HTTP request's
6
+ * (D4-f). `approval: "never"` runs under every profile, as on the native backend;
7
+ * anything else asks the caller first. Adapter pre-approval (R12) makes this the
8
+ * tools' only approval point. Every failure reaches the agent as an MCP tool error
9
+ * (isError), never as a protocol error.
10
+ */
11
+ import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
12
+ import { type ApprovalDecidedBy, type EmbedderTool, type SessionAskPort } from "@nathapp/nax-agent";
13
+ export declare const MAX_CONCURRENT_TOOL_CALLS = 8;
14
+ /** Byte cap of an approval summary (native: EMBEDDER_SUMMARY_BYTES). */
15
+ export declare const TOOL_SUMMARY_BYTES = 1024;
16
+ export declare const NO_TURN_TEXT = "No active turn: embedder tools run only while a turn is running.";
17
+ export declare const TOO_MANY_TEXT = "Too many concurrent tool calls: at most 8 run at once.";
18
+ export interface ToolCallDeps {
19
+ readonly sessionId: string;
20
+ readonly tools: readonly EmbedderTool[];
21
+ readonly asks: SessionAskPort;
22
+ readonly currentTurnId: () => string | undefined;
23
+ /** The running turn's binding signal (inbound.ts activeSignal), or undefined between turns. */
24
+ readonly turnSignal: () => AbortSignal | undefined;
25
+ /** The session's secret values (env secrets and the host token), scrubbed from approval summaries. */
26
+ readonly secrets: readonly string[];
27
+ }
28
+ export interface ToolCalls {
29
+ /** tools/list: exactly the session's embedder tools. */
30
+ list(): Tool[];
31
+ /** tools/call. `requestSignal` aborts when the HTTP request goes away. */
32
+ call(name: string, args: unknown, requestSignal: AbortSignal): Promise<CallToolResult>;
33
+ /** Resolves once every call in flight has answered. */
34
+ drain(): Promise<void>;
35
+ }
36
+ /** The native backend's reason for an embedder approval. */
37
+ export declare function approvalReason(name: string): string;
38
+ /** nax-agent's askDenyReason, over its public reason constants. */
39
+ export declare function denyReason(decidedBy: ApprovalDecidedBy): string;
40
+ /** The approval summary (D4-h): described or JSON input, redacted, stripped, the session's secrets scrubbed, one line, capped. */
41
+ export declare function toolSummary(tool: EmbedderTool, input: unknown, secrets: readonly string[]): string;
42
+ export declare function createToolCalls(deps: ToolCallDeps): ToolCalls;
@@ -0,0 +1,147 @@
1
+ import { ASK_CANCELLED_REASON, ASK_DENIED_REASON, ASK_NO_CHANNEL_REASON, ASK_PROFILE_REASON, ASK_TIMEOUT_REASON, ASK_UNSHOWABLE_REASON, capStrings, redactSecrets, } from "@nathapp/nax-agent";
2
+ import { capBytes, scrubSecrets, stripControl, stripInvisible } from "#src/client/text";
3
+ export const MAX_CONCURRENT_TOOL_CALLS = 8;
4
+ /** Byte cap of an approval summary (native: EMBEDDER_SUMMARY_BYTES). */
5
+ export const TOOL_SUMMARY_BYTES = 1024;
6
+ /** Redaction scans at most this many bytes of a tool input (native: 16x the summary cap). */
7
+ const SCAN_BYTES = TOOL_SUMMARY_BYTES * 16;
8
+ const SHOWN_NAME_CHARS = 64;
9
+ export const NO_TURN_TEXT = "No active turn: embedder tools run only while a turn is running.";
10
+ export const TOO_MANY_TEXT = `Too many concurrent tool calls: at most ${MAX_CONCURRENT_TOOL_CALLS} run at once.`;
11
+ function textResult(text, isError) {
12
+ return { content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) };
13
+ }
14
+ /** The native backend's reason for an embedder approval. */
15
+ export function approvalReason(name) {
16
+ return `"${name}" asks before every run`;
17
+ }
18
+ /** nax-agent's askDenyReason, over its public reason constants. */
19
+ export function denyReason(decidedBy) {
20
+ switch (decidedBy) {
21
+ case "timeout":
22
+ return ASK_TIMEOUT_REASON;
23
+ case "human":
24
+ return ASK_DENIED_REASON;
25
+ case "cancelled":
26
+ return ASK_CANCELLED_REASON;
27
+ case "unshowable":
28
+ return ASK_UNSHOWABLE_REASON;
29
+ case "profile":
30
+ return ASK_PROFILE_REASON;
31
+ default:
32
+ return ASK_NO_CHANNEL_REASON;
33
+ }
34
+ }
35
+ function describeInput(tool, input) {
36
+ if (tool.describe !== undefined) {
37
+ try {
38
+ return String(redactSecrets(capStrings(String(tool.describe(input)), SCAN_BYTES)));
39
+ }
40
+ catch {
41
+ // A throwing describe falls back to the input, as on the native backend.
42
+ }
43
+ }
44
+ try {
45
+ return JSON.stringify(redactSecrets(capStrings(input, SCAN_BYTES))) ?? "null";
46
+ }
47
+ catch {
48
+ return "[input not serializable]";
49
+ }
50
+ }
51
+ /** The approval summary (D4-h): described or JSON input, redacted, stripped, the session's secrets scrubbed, one line, capped. */
52
+ export function toolSummary(tool, input, secrets) {
53
+ const visible = scrubSecrets(stripInvisible(stripControl(describeInput(tool, input))), secrets);
54
+ return capBytes(visible.replace(/[\n\t]+/g, " ").trim(), TOOL_SUMMARY_BYTES);
55
+ }
56
+ function abandoned(name) {
57
+ return textResult(`Tool "${name}" was abandoned: the turn ended.`, true);
58
+ }
59
+ function runSafely(tool, input, ctx) {
60
+ return Promise.resolve()
61
+ .then(() => tool.run(input, ctx))
62
+ .then((result) => result === undefined || result === null
63
+ ? textResult(`Tool "${tool.name}" returned no result.`, true)
64
+ : textResult(String(result.content), result.isError === true), (err) => textResult(`Tool "${tool.name}" failed: ${err instanceof Error ? err.message : String(err)}`, true));
65
+ }
66
+ /** Answers at once when the signal aborts: a run that ignores its signal is abandoned and its late result ignored. */
67
+ async function invoke(tool, input, ctx) {
68
+ if (ctx.signal.aborted)
69
+ return abandoned(tool.name);
70
+ let onAbort = () => { };
71
+ const aborted = new Promise((resolve) => {
72
+ onAbort = () => resolve(abandoned(tool.name));
73
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
74
+ });
75
+ try {
76
+ return await Promise.race([runSafely(tool, input, ctx), aborted]);
77
+ }
78
+ finally {
79
+ ctx.signal.removeEventListener("abort", onAbort);
80
+ }
81
+ }
82
+ /** undefined: go ahead. Otherwise the answer that replaces the run. */
83
+ async function approve(deps, tool, input, ctx) {
84
+ if (tool.approval === "never")
85
+ return undefined;
86
+ try {
87
+ const outcome = await deps.asks.requestApproval({
88
+ callId: ctx.toolCallId,
89
+ tool: tool.name,
90
+ summary: toolSummary(tool, input, deps.secrets),
91
+ reason: approvalReason(tool.name),
92
+ signal: ctx.signal,
93
+ });
94
+ return outcome.decision === "allow" ? undefined : textResult(`Denied: ${denyReason(outcome.decidedBy)}`, true);
95
+ }
96
+ catch {
97
+ // The turn ended between the turn check and the ask (the port's "no-turn"): fail closed.
98
+ return textResult(NO_TURN_TEXT, true);
99
+ }
100
+ }
101
+ export function createToolCalls(deps) {
102
+ const byName = new Map(deps.tools.map((tool) => [tool.name, tool]));
103
+ const inFlight = new Set();
104
+ let accepted = 0;
105
+ const run = async (tool, args, signal) => {
106
+ accepted += 1;
107
+ const input = args ?? {};
108
+ const ctx = { sessionId: deps.sessionId, toolCallId: `mcp-${accepted}`, signal };
109
+ if (signal.aborted)
110
+ return abandoned(tool.name);
111
+ const denied = await approve(deps, tool, input, ctx);
112
+ return denied ?? invoke(tool, input, ctx);
113
+ };
114
+ return {
115
+ list: () => deps.tools.map((tool) => ({
116
+ name: tool.name,
117
+ description: tool.description,
118
+ inputSchema: { ...tool.inputSchema, type: "object" },
119
+ // #2365: this host is the tools' only approval point. Claude's plan mode
120
+ // (profiles none/read) asks before any MCP tool not marked read-only,
121
+ // ahead of the mcp__nax__<tool> pre-approval.
122
+ annotations: { readOnlyHint: true },
123
+ })),
124
+ async call(name, args, requestSignal) {
125
+ const tool = byName.get(name);
126
+ if (tool === undefined) {
127
+ return textResult(`Unknown tool "${stripControl(name).slice(0, SHOWN_NAME_CHARS)}"`, true);
128
+ }
129
+ const turnSignal = deps.turnSignal();
130
+ if (deps.currentTurnId() === undefined || turnSignal === undefined)
131
+ return textResult(NO_TURN_TEXT, true);
132
+ if (inFlight.size >= MAX_CONCURRENT_TOOL_CALLS)
133
+ return textResult(TOO_MANY_TEXT, true);
134
+ const pending = run(tool, args, AbortSignal.any([turnSignal, requestSignal]));
135
+ inFlight.add(pending);
136
+ try {
137
+ return await pending;
138
+ }
139
+ finally {
140
+ inFlight.delete(pending);
141
+ }
142
+ },
143
+ async drain() {
144
+ await Promise.allSettled([...inFlight]);
145
+ },
146
+ };
147
+ }
@@ -0,0 +1,23 @@
1
+ export declare const SUMMARY_MAX_BYTES = 1024;
2
+ /**
3
+ * Raw agent text above these sizes is withheld without being masked: maskForPrompt
4
+ * is quadratic (8 KiB takes about 4 ms, 256 KiB seconds), and truncating first
5
+ * would show a cut secret prefix.
6
+ */
7
+ export declare const SUMMARY_RAW_MAX_BYTES: number;
8
+ export declare const COMMAND_RAW_MAX_BYTES: number;
9
+ export interface ToolCallDisplay {
10
+ readonly callId?: string;
11
+ readonly tool: string;
12
+ readonly summary: string;
13
+ readonly command?: string;
14
+ /** False when agent text held a secret that could not be masked safely. */
15
+ readonly showable: boolean;
16
+ }
17
+ /**
18
+ * The agent's tool call id without invisible characters or whitespace; undefined
19
+ * when it is not a string, is empty or oversized, or held a secret. Approval events
20
+ * and tool events both use it, so their callIds match (S4-5 D5-e).
21
+ */
22
+ export declare function cleanCallId(value: unknown, secrets: readonly string[]): string | undefined;
23
+ export declare function describeToolCall(toolCall: unknown, secrets: readonly string[]): ToolCallDisplay;
@@ -0,0 +1,90 @@
1
+ import { maskForPrompt, redactSecrets, TOOL_CALL_INPUT_BYTES } from "@nathapp/nax-agent";
2
+ import { capBytes, isRecord, scrubSecrets, stripControl, stripInvisible } from "#src/client/text";
3
+ export const SUMMARY_MAX_BYTES = 1024;
4
+ /**
5
+ * Raw agent text above these sizes is withheld without being masked: maskForPrompt
6
+ * is quadratic (8 KiB takes about 4 ms, 256 KiB seconds), and truncating first
7
+ * would show a cut secret prefix.
8
+ */
9
+ export const SUMMARY_RAW_MAX_BYTES = 8 * 1024;
10
+ export const COMMAND_RAW_MAX_BYTES = 32 * 1024;
11
+ const CALL_ID_MAX_CHARS = 512;
12
+ const WITHHELD = "(details withheld: they could not be shown safely)";
13
+ const KINDS = new Set([
14
+ "read",
15
+ "edit",
16
+ "delete",
17
+ "move",
18
+ "search",
19
+ "execute",
20
+ "think",
21
+ "fetch",
22
+ "switch_mode",
23
+ "other",
24
+ ]);
25
+ const SUMMARY = { rawMaxBytes: SUMMARY_RAW_MAX_BYTES, capBytes: SUMMARY_MAX_BYTES, oneLine: true };
26
+ const COMMAND = { rawMaxBytes: COMMAND_RAW_MAX_BYTES, capBytes: TOOL_CALL_INPUT_BYTES, oneLine: false };
27
+ /** Visible, secret-free text: strip, scrub the session's secrets, mask pattern secrets, redact. */
28
+ function clean(text, secrets) {
29
+ const masked = maskForPrompt(scrubSecrets(stripInvisible(stripControl(text)), secrets));
30
+ return masked.ok ? { ok: true, text: redactSecrets(masked.masked) } : { ok: false };
31
+ }
32
+ function show(raw, secrets, limits) {
33
+ if (Buffer.byteLength(raw, "utf8") > limits.rawMaxBytes)
34
+ return { ok: false };
35
+ const text = limits.oneLine ? raw.replace(/[\n\t\u2028\u2029]+\s*/g, " ") : raw;
36
+ const shown = clean(text, secrets);
37
+ return shown.ok ? { ok: true, text: capBytes(shown.text, limits.capBytes) } : { ok: false };
38
+ }
39
+ function kindOf(call) {
40
+ return typeof call.kind === "string" && KINDS.has(call.kind) ? call.kind : "other";
41
+ }
42
+ /**
43
+ * The agent's tool call id without invisible characters or whitespace; undefined
44
+ * when it is not a string, is empty or oversized, or held a secret. Approval events
45
+ * and tool events both use it, so their callIds match (S4-5 D5-e).
46
+ */
47
+ export function cleanCallId(value, secrets) {
48
+ if (typeof value !== "string" || value.length > CALL_ID_MAX_CHARS)
49
+ return undefined;
50
+ const id = stripInvisible(stripControl(value)).replace(/\s+/g, "");
51
+ if (id === "")
52
+ return undefined;
53
+ const shown = clean(id, secrets);
54
+ // An id that held a secret is dropped, not shown masked: it would no longer match the agent's id.
55
+ return shown.ok && shown.text === id ? id : undefined;
56
+ }
57
+ function firstPath(call) {
58
+ if (!Array.isArray(call.locations))
59
+ return undefined;
60
+ const first = call.locations[0];
61
+ return isRecord(first) && typeof first.path === "string" && first.path !== "" ? first.path : undefined;
62
+ }
63
+ function summarySource(call, kind) {
64
+ const title = typeof call.title === "string" ? call.title.trim() : "";
65
+ if (title !== "")
66
+ return title;
67
+ const path = firstPath(call);
68
+ return path === undefined ? `${kind} tool call` : `${kind} ${path}`;
69
+ }
70
+ function commandSource(call, kind) {
71
+ if (kind !== "execute" || !isRecord(call.rawInput))
72
+ return undefined;
73
+ const command = call.rawInput.command;
74
+ return typeof command === "string" && command !== "" ? command : undefined;
75
+ }
76
+ export function describeToolCall(toolCall, secrets) {
77
+ const call = isRecord(toolCall) ? toolCall : {};
78
+ const kind = kindOf(call);
79
+ const callId = cleanCallId(call.toolCallId, secrets);
80
+ const summary = show(summarySource(call, kind), secrets, SUMMARY);
81
+ const rawCommand = commandSource(call, kind);
82
+ const command = rawCommand === undefined ? undefined : show(rawCommand, secrets, COMMAND);
83
+ return {
84
+ ...(callId === undefined ? {} : { callId }),
85
+ tool: kind,
86
+ summary: summary.ok ? summary.text : `${kind} tool call ${WITHHELD}`,
87
+ ...(command?.ok ? { command: command.text } : {}),
88
+ showable: summary.ok && (command === undefined || command.ok),
89
+ };
90
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Tool calls on the turn's event stream (S4 spec §6.7 tool rows, S4-5 D5-c to D5-f).
3
+ * tool_call and tool_call_update notifications are merged per call id, cleaned as
4
+ * for approvals (cleanCallId), so tool_call.callId matches approval_requested.callId.
5
+ * A call's tool_call event goes out when the call is used: a permission request
6
+ * names it (announce), or it reports in_progress, completed or failed. Claude
7
+ * streams a call's input after first reporting it, so the event carries the input
8
+ * known at that moment (D5-c). completed/failed answers it with one tool_result;
9
+ * flush() answers an announced call left without one with an error result, so every
10
+ * tool_call has exactly one tool_result (D5-e). A call never used emits nothing. Its
11
+ * name is the agent's tool name, else its first real title, else its kind (D5-d).
12
+ * Input and preview are agent data: capped, scrubbed of the session's secret values
13
+ * and redacted best-effort (D5-f). At most MAX_TRACKED_CALLS calls per turn.
14
+ */
15
+ import { type TurnEvent } from "@nathapp/nax-agent";
16
+ export declare const MAX_TRACKED_CALLS = 512;
17
+ export declare const TOOL_NAME_MAX_CHARS = 200;
18
+ export declare const UNANSWERED_PREVIEW = "Not answered: the turn ended.";
19
+ /** A diff larger than this (old plus new text, in characters) is shown without line counts. */
20
+ export declare const DIFF_COUNT_MAX_CHARS: number;
21
+ export interface ToolEvents {
22
+ /** A tool_call or tool_call_update of this turn. */
23
+ onUpdate(update: unknown): void;
24
+ /** A permission request names this call (a ToolCallUpdate): its tool_call goes out now. */
25
+ announce(toolCall: unknown): void;
26
+ /** Answers each announced call that has no result yet. */
27
+ flush(): void;
28
+ }
29
+ export declare function inputOf(raw: unknown, secrets: readonly string[]): unknown;
30
+ export declare function diffSummary(diff: Readonly<Record<string, unknown>>): string;
31
+ export declare function previewOf(call: {
32
+ readonly content?: unknown;
33
+ readonly rawOutput?: unknown;
34
+ }, secrets: readonly string[]): string;
35
+ export declare function createToolEvents(emit: (event: TurnEvent) => void, secrets: readonly string[]): ToolEvents;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Tool calls on the turn's event stream (S4 spec §6.7 tool rows, S4-5 D5-c to D5-f).
3
+ * tool_call and tool_call_update notifications are merged per call id, cleaned as
4
+ * for approvals (cleanCallId), so tool_call.callId matches approval_requested.callId.
5
+ * A call's tool_call event goes out when the call is used: a permission request
6
+ * names it (announce), or it reports in_progress, completed or failed. Claude
7
+ * streams a call's input after first reporting it, so the event carries the input
8
+ * known at that moment (D5-c). completed/failed answers it with one tool_result;
9
+ * flush() answers an announced call left without one with an error result, so every
10
+ * tool_call has exactly one tool_result (D5-e). A call never used emits nothing. Its
11
+ * name is the agent's tool name, else its first real title, else its kind (D5-d).
12
+ * Input and preview are agent data: capped, scrubbed of the session's secret values
13
+ * and redacted best-effort (D5-f). At most MAX_TRACKED_CALLS calls per turn.
14
+ */
15
+ import { capStrings, redactSecrets, TOOL_CALL_INPUT_BYTES, TOOL_RESULT_PREVIEW_BYTES, } from "@nathapp/nax-agent";
16
+ import { capBytes, cleanLabel, isRecord, scrubDeep, scrubSecrets, stripControl, stripInvisible, } from "#src/client/text";
17
+ import { cleanCallId } from "#src/client/tool-display";
18
+ export const MAX_TRACKED_CALLS = 512;
19
+ export const TOOL_NAME_MAX_CHARS = 200;
20
+ export const UNANSWERED_PREVIEW = "Not answered: the turn ended.";
21
+ /** A diff larger than this (old plus new text, in characters) is shown without line counts. */
22
+ export const DIFF_COUNT_MAX_CHARS = 1024 * 1024;
23
+ /** Redaction scans at most this much of a string or a preview, as nax-agent's own emitter does. */
24
+ const REDACTION_SCAN_BYTES = TOOL_RESULT_PREVIEW_BYTES * 16;
25
+ const PLACEHOLDER_TITLES = new Set(["tool call", "tool"]);
26
+ function realTitle(value, secrets) {
27
+ const title = cleanLabel(value, secrets, TOOL_NAME_MAX_CHARS);
28
+ return title === undefined || PLACEHOLDER_TITLES.has(title.toLowerCase()) ? undefined : title;
29
+ }
30
+ const present = (value) => value !== undefined && value !== null;
31
+ function merged(state, update, secrets) {
32
+ const name = state.name ?? cleanLabel(update.name, secrets, TOOL_NAME_MAX_CHARS);
33
+ const title = state.title ?? realTitle(update.title, secrets);
34
+ const kind = cleanLabel(update.kind, secrets, TOOL_NAME_MAX_CHARS) ?? state.kind;
35
+ return {
36
+ ...state,
37
+ ...(name === undefined ? {} : { name }),
38
+ ...(title === undefined ? {} : { title }),
39
+ ...(kind === undefined ? {} : { kind }),
40
+ ...(present(update.rawInput) ? { rawInput: update.rawInput } : {}),
41
+ ...(Array.isArray(update.content) ? { content: update.content } : {}),
42
+ ...(present(update.rawOutput) ? { rawOutput: update.rawOutput } : {}),
43
+ };
44
+ }
45
+ function nameOf(state) {
46
+ return state.name ?? state.title ?? state.kind ?? "tool";
47
+ }
48
+ export function inputOf(raw, secrets) {
49
+ if (!present(raw))
50
+ return {};
51
+ const redacted = redactSecrets(scrubDeep(capStrings(raw, REDACTION_SCAN_BYTES), secrets));
52
+ let json;
53
+ try {
54
+ json = JSON.stringify(redacted) ?? "null";
55
+ }
56
+ catch {
57
+ return { truncated: true, preview: "[input not serializable]" };
58
+ }
59
+ if (Buffer.byteLength(json, "utf8") <= TOOL_CALL_INPUT_BYTES)
60
+ return redacted;
61
+ return { truncated: true, preview: capBytes(json, TOOL_CALL_INPUT_BYTES) };
62
+ }
63
+ function lines(text) {
64
+ return text === "" ? [] : text.split("\n");
65
+ }
66
+ /** Lines added and removed, as a multiset difference (linear time; moved lines count as unchanged). */
67
+ function lineDelta(oldText, newText) {
68
+ const pool = new Map();
69
+ for (const line of lines(oldText))
70
+ pool.set(line, (pool.get(line) ?? 0) + 1);
71
+ let added = 0;
72
+ for (const line of lines(newText)) {
73
+ const left = pool.get(line) ?? 0;
74
+ if (left > 0)
75
+ pool.set(line, left - 1);
76
+ else
77
+ added += 1;
78
+ }
79
+ let removed = 0;
80
+ for (const left of pool.values())
81
+ removed += left;
82
+ return { added, removed };
83
+ }
84
+ export function diffSummary(diff) {
85
+ const path = typeof diff.path === "string" && diff.path !== "" ? diff.path : "(unknown path)";
86
+ const oldText = typeof diff.oldText === "string" ? diff.oldText : "";
87
+ const newText = typeof diff.newText === "string" ? diff.newText : "";
88
+ if (oldText.length + newText.length > DIFF_COUNT_MAX_CHARS)
89
+ return `edit ${path}`;
90
+ const { added, removed } = lineDelta(oldText, newText);
91
+ return `edit ${path} (+${added} -${removed})`;
92
+ }
93
+ function contentPart(item) {
94
+ if (!isRecord(item))
95
+ return "";
96
+ if (item.type === "diff")
97
+ return diffSummary(item);
98
+ if (item.type !== "content" || !isRecord(item.content))
99
+ return "";
100
+ const block = item.content;
101
+ if (block.type === "text" && typeof block.text === "string")
102
+ return block.text;
103
+ if (block.type === "resource_link" && typeof block.uri === "string")
104
+ return block.uri;
105
+ return "";
106
+ }
107
+ function contentText(content) {
108
+ if (!Array.isArray(content))
109
+ return "";
110
+ return content
111
+ .map(contentPart)
112
+ .filter((part) => part !== "")
113
+ .join("\n");
114
+ }
115
+ export function previewOf(call, secrets) {
116
+ const fromContent = contentText(call.content);
117
+ let raw = fromContent;
118
+ if (raw === "" && typeof call.rawOutput === "string")
119
+ raw = call.rawOutput;
120
+ const visible = stripInvisible(stripControl(capBytes(raw, REDACTION_SCAN_BYTES)));
121
+ return capBytes(redactSecrets(scrubSecrets(visible, secrets)), TOOL_RESULT_PREVIEW_BYTES);
122
+ }
123
+ function isStarted(status) {
124
+ return status === "in_progress" || status === "completed" || status === "failed";
125
+ }
126
+ export function createToolEvents(emit, secrets) {
127
+ const calls = new Map();
128
+ const merge = (update) => {
129
+ if (!isRecord(update))
130
+ return undefined;
131
+ const id = cleanCallId(update.toolCallId, secrets);
132
+ if (id === undefined)
133
+ return undefined;
134
+ const known = calls.get(id);
135
+ if (known === undefined && calls.size >= MAX_TRACKED_CALLS)
136
+ return undefined;
137
+ const next = merged(known ?? { id, announced: false, resolved: false }, update, secrets);
138
+ calls.set(id, next);
139
+ return next;
140
+ };
141
+ const announce = (state) => {
142
+ if (state.announced)
143
+ return state;
144
+ const next = { ...state, announced: true };
145
+ calls.set(state.id, next);
146
+ emit({ type: "tool_call", callId: state.id, name: nameOf(state), input: inputOf(state.rawInput, secrets) });
147
+ return next;
148
+ };
149
+ const resolve = (state, isError, preview) => {
150
+ if (state.resolved)
151
+ return;
152
+ calls.set(state.id, { ...state, resolved: true });
153
+ emit({ type: "tool_result", callId: state.id, isError, preview });
154
+ };
155
+ return {
156
+ onUpdate(update) {
157
+ const state = merge(update);
158
+ const status = isRecord(update) ? update.status : undefined;
159
+ if (state === undefined || !isStarted(status))
160
+ return;
161
+ const shown = announce(state);
162
+ if (status !== "in_progress")
163
+ resolve(shown, status === "failed", previewOf(shown, secrets));
164
+ },
165
+ announce(toolCall) {
166
+ const state = merge(toolCall);
167
+ if (state !== undefined)
168
+ announce(state);
169
+ },
170
+ flush() {
171
+ for (const state of [...calls.values()]) {
172
+ if (state.announced)
173
+ resolve(state, true, UNANSWERED_PREVIEW);
174
+ }
175
+ },
176
+ };
177
+ }
@@ -0,0 +1,25 @@
1
+ import type { McpServer } from "@agentclientprotocol/sdk";
2
+ import type { ToolCalls } from "#src/client/tool-calls";
3
+ export type HttpMcpServer = Extract<McpServer, {
4
+ type: "http";
5
+ }>;
6
+ export declare const TOOL_HOST_PATH = "/mcp";
7
+ export declare const MAX_BODY_BYTES: number;
8
+ /** Past this many body bytes the 413 is sent at once and the connection closed. */
9
+ export declare const MAX_DRAIN_BYTES: number;
10
+ export interface ToolHost {
11
+ /** Known before start(), so every redaction set can include it. */
12
+ readonly token: string;
13
+ /** Listens on 127.0.0.1, an ephemeral port; returns the session/new server entry. */
14
+ start(): Promise<HttpMcpServer>;
15
+ /** Resolves once every call in flight has answered. */
16
+ drain(): Promise<void>;
17
+ /**
18
+ * Revokes the token, aborts every call in flight, drops open connections and
19
+ * closes the port (bounded wait). Idempotent; safe before start(); start()
20
+ * after it refuses.
21
+ */
22
+ stop(): Promise<void>;
23
+ }
24
+ export declare function newToolHostToken(): string;
25
+ export declare function createToolHost(calls: ToolCalls, token?: string): ToolHost;