@ant0/mcp 0.0.0-stage → 0.3.22-beta.2

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 (52) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +95 -2
  3. package/THIRD_PARTY_NOTICES +311 -0
  4. package/dist/api/generated/schema.d.ts +3856 -0
  5. package/dist/api/generated/schema.js +6 -0
  6. package/dist/api/index.d.ts +171 -0
  7. package/dist/api/index.js +332 -0
  8. package/dist/bin.d.ts +3 -0
  9. package/dist/bin.js +59 -0
  10. package/dist/call-permits.d.ts +10 -0
  11. package/dist/call-permits.js +67 -0
  12. package/dist/connection.d.ts +20 -0
  13. package/dist/connection.js +157 -0
  14. package/dist/credential-file.d.ts +33 -0
  15. package/dist/credential-file.js +773 -0
  16. package/dist/daemon.d.ts +7 -0
  17. package/dist/daemon.js +260 -0
  18. package/dist/errors.d.ts +69 -0
  19. package/dist/errors.js +78 -0
  20. package/dist/export-files.d.ts +37 -0
  21. package/dist/export-files.js +167 -0
  22. package/dist/grant.d.ts +5 -0
  23. package/dist/grant.js +11 -0
  24. package/dist/http.d.ts +59 -0
  25. package/dist/http.js +556 -0
  26. package/dist/index.d.ts +19 -0
  27. package/dist/index.js +85 -0
  28. package/dist/key-contract.d.ts +325 -0
  29. package/dist/key-contract.js +241 -0
  30. package/dist/limits.d.ts +22 -0
  31. package/dist/limits.js +22 -0
  32. package/dist/local-routes.d.ts +26 -0
  33. package/dist/local-routes.js +146 -0
  34. package/dist/output-descriptor.d.ts +3 -0
  35. package/dist/output-descriptor.js +19 -0
  36. package/dist/output-worker-body.d.ts +3 -0
  37. package/dist/output-worker-body.js +77 -0
  38. package/dist/output-worker.d.ts +2 -0
  39. package/dist/output-worker.js +4 -0
  40. package/dist/output-writer.d.ts +39 -0
  41. package/dist/output-writer.js +199 -0
  42. package/dist/peer-watchdog.d.ts +4 -0
  43. package/dist/peer-watchdog.js +55 -0
  44. package/dist/server.d.ts +28 -0
  45. package/dist/server.js +33 -0
  46. package/dist/text-budget.d.ts +13 -0
  47. package/dist/text-budget.js +42 -0
  48. package/dist/tools.d.ts +38 -0
  49. package/dist/tools.js +1284 -0
  50. package/dist/transport.d.ts +45 -0
  51. package/dist/transport.js +313 -0
  52. package/package.json +66 -4
@@ -0,0 +1,7 @@
1
+ import { type Ant0Client } from "./api/index.js";
2
+ import { type Connection } from "./connection.js";
3
+ /** Long launches get only their requested daemon timeout plus a ten-second transport margin. */
4
+ export declare function requestTimeoutMs(method: string, path: string, body: string): number;
5
+ /** Typed API client with a direct, non-proxying HTTP transport and no redirects or retries. */
6
+ export declare function daemonClient(connection: Connection, lifetime: AbortSignal, consumer?: "api" | "mcp"): Ant0Client;
7
+ //# sourceMappingURL=daemon.d.ts.map
package/dist/daemon.js ADDED
@@ -0,0 +1,260 @@
1
+ import { createAnt0Client } from "./api/index.js";
2
+ import { request } from "node:http";
3
+ import { keyMode } from "./connection.js";
4
+ import { McpFailure } from "./errors.js";
5
+ import { LIMITS } from "./limits.js";
6
+ import { assertCredentialUnchangedAsync } from "./credential-file.js";
7
+ import { localRequestAllowed, mapDaemonError, matchLocalRoute } from "./local-routes.js";
8
+ // Profile path segments: MCP tools always send a UUID, while the CLI may also pass an exact name.
9
+ const UUID = "[0-9a-f-]{36}";
10
+ const PROFILE_REF = "[^/]+";
11
+ const LOCAL_READ_PATH = new RegExp(`^/v1/(health|licence|automation/status|profiles/${UUID}|inventory/(?:proxies|profiles(?:/${UUID})?))$`);
12
+ /** Delegated inventory reads (unchanged from the earlier credential format). */
13
+ const KEY_READ_PATH = new RegExp(`^/v1/(automation/status|inventory/(?:proxies|profiles(?:/${PROFILE_REF})?))$`);
14
+ /** The CLI additionally inspects the endpoint-free lifecycle of a run it could not confirm. */
15
+ const CLI_READ_PATH = new RegExp(`^/v1/(automation/status|inventory/(?:proxies|profiles(?:/${PROFILE_REF})?)|profiles/${PROFILE_REF}/run)$`);
16
+ /** Operations: MCP drives one saved profile; CDP start and bulk stay explicit CLI actions. */
17
+ const MCP_OPERATION_PATH = new RegExp(`^/v1/profiles/${UUID}/(?:run|stop)$`);
18
+ const CLI_OPERATION_PATH = new RegExp(`^/v1/profiles/(?:${PROFILE_REF}/(?:run|start|stop)|bulk-(?:start|stop))$`);
19
+ function parsedBody(text) {
20
+ try {
21
+ const value = JSON.parse(text);
22
+ return value !== null && typeof value === "object" && !Array.isArray(value)
23
+ ? value
24
+ : undefined;
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /** Long launches get only their requested daemon timeout plus a ten-second transport margin. */
31
+ export function requestTimeoutMs(method, path, body) {
32
+ if (method !== "POST")
33
+ return LIMITS.httpMs;
34
+ const value = parsedBody(body);
35
+ const ids = value?.ids;
36
+ if (/\/bulk-(?:start|stop)$/.test(path)) {
37
+ return Array.isArray(ids) && ids.length >= 1 && ids.length <= 50
38
+ ? ids.length * 60_000 + 10_000
39
+ : LIMITS.httpMs;
40
+ }
41
+ if (/\/(?:run|start)$/.test(path)) {
42
+ const requested = value?.timeout_s;
43
+ const seconds = requested === undefined
44
+ ? 60
45
+ : typeof requested === "number" &&
46
+ Number.isInteger(requested) &&
47
+ requested >= 1 &&
48
+ requested <= 600
49
+ ? requested
50
+ : 0;
51
+ return seconds === 0 ? LIMITS.httpMs : seconds * 1_000 + 10_000;
52
+ }
53
+ return 70_000;
54
+ }
55
+ /** Typed API client with a direct, non-proxying HTTP transport and no redirects or retries. */
56
+ export function daemonClient(connection, lifetime, consumer = "mcp") {
57
+ const boundedFetch = async (input) => {
58
+ if (!(input instanceof Request))
59
+ throw new McpFailure("internal");
60
+ const url = new URL(input.url);
61
+ const method = input.method;
62
+ // Local-bearer-only routes (identity tools). Key-mode connections never consult this table,
63
+ // so their allowlists below are unchanged.
64
+ const local = consumer === "mcp" && !keyMode(connection)
65
+ ? matchLocalRoute(method, url.pathname)
66
+ : undefined;
67
+ const body = method === "POST" || (local !== undefined && method === "PATCH")
68
+ ? Buffer.from(await input.clone().arrayBuffer())
69
+ : Buffer.alloc(0);
70
+ if (body.length > LIMITS.bodyBytes)
71
+ throw new McpFailure("configuration");
72
+ const mutation = (method === "POST" &&
73
+ (consumer === "mcp" ? MCP_OPERATION_PATH : CLI_OPERATION_PATH).test(url.pathname)) ||
74
+ (local !== undefined && local.method !== "GET" && local.readOnly !== true);
75
+ const allowedRead = !keyMode(connection)
76
+ ? LOCAL_READ_PATH
77
+ : consumer === "mcp"
78
+ ? KEY_READ_PATH
79
+ : CLI_READ_PATH;
80
+ const inventoryQuery = /^\/v1\/inventory\/(?:profiles|proxies)$/.test(url.pathname);
81
+ if (url.origin !== connection.origin ||
82
+ url.username ||
83
+ url.password ||
84
+ url.hash ||
85
+ (local
86
+ ? !localRequestAllowed(local, url, body, (text) => parsedBody(text) !== undefined)
87
+ : !((method === "GET" && allowedRead.test(url.pathname)) || mutation) ||
88
+ (method === "GET" && body.length !== 0) ||
89
+ (method === "POST" &&
90
+ (url.searchParams.size !== 0 || !parsedBody(body.toString("utf8")))) ||
91
+ [...url.searchParams.keys()].some((key) => !inventoryQuery ||
92
+ !["limit", "offset", "q", "group", "tag", "running", "trashed"].includes(key))))
93
+ throw new McpFailure("configuration");
94
+ // Raw PNG bytes (screenshots) get their own cap; every other body keeps 1 MiB.
95
+ const bodyLimit = local?.binary ? LIMITS.screenshotBytes : LIMITS.bodyBytes;
96
+ const timeout = local ? 70_000 : requestTimeoutMs(method, url.pathname, body.toString("utf8"));
97
+ const deadline = AbortSignal.timeout(timeout);
98
+ const signal = AbortSignal.any([lifetime, input.signal, deadline]);
99
+ const credentialCheck = async () => {
100
+ if (!connection.credential)
101
+ return;
102
+ try {
103
+ await assertCredentialUnchangedAsync(connection.credential, signal);
104
+ }
105
+ catch {
106
+ throw new McpFailure(deadline.aborted ? "deadline" : signal.aborted ? "cancelled" : "configuration");
107
+ }
108
+ };
109
+ if (connection.credential) {
110
+ await credentialCheck();
111
+ }
112
+ const response = await new Promise((resolve, reject) => {
113
+ if (signal.aborted)
114
+ return reject(new McpFailure("cancelled"));
115
+ let settled = false;
116
+ const finish = (code, body) => {
117
+ if (settled)
118
+ return;
119
+ settled = true;
120
+ clearTimeout(timer);
121
+ signal.removeEventListener("abort", abort);
122
+ if (code) {
123
+ req.destroy();
124
+ void drained.then(() => reject(new McpFailure(code)));
125
+ }
126
+ else {
127
+ try {
128
+ let response;
129
+ if (local?.binary) {
130
+ response = new Response(new Uint8Array(body), {
131
+ headers: { "content-type": "image/png" },
132
+ });
133
+ }
134
+ else {
135
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(body);
136
+ if (!local?.text)
137
+ JSON.parse(text);
138
+ response = new Response(text, {
139
+ headers: { "content-type": local?.text ? "text/plain" : "application/json" },
140
+ });
141
+ }
142
+ void drained.then(() => resolve(response));
143
+ }
144
+ catch {
145
+ req.destroy();
146
+ void drained.then(() => reject(new McpFailure(mutation ? "indeterminate" : "response")));
147
+ }
148
+ }
149
+ };
150
+ const abort = () => finish(mutation ? "indeterminate" : deadline.aborted ? "deadline" : "cancelled");
151
+ const req = request(url, {
152
+ method,
153
+ agent: false,
154
+ maxHeaderSize: 16 * 1024,
155
+ headers: {
156
+ authorization: `Bearer ${connection.token}`,
157
+ accept: "application/json",
158
+ "accept-encoding": "identity",
159
+ ...(body.length > 0 ? { "content-type": "application/json" } : {}),
160
+ ...(keyMode(connection) ? { "x-ant0-consumer": consumer } : {}),
161
+ },
162
+ });
163
+ // Keep the handler's permit until the local request has closed, not merely until destroy()
164
+ // was requested. agent:false also closes successful requests rather than pooling sockets.
165
+ const drained = new Promise((resolve) => req.once("close", resolve));
166
+ const timer = setTimeout(() => finish(mutation ? "indeterminate" : "deadline"), timeout);
167
+ signal.addEventListener("abort", abort, { once: true });
168
+ req.on("error", () => finish(mutation ? "indeterminate" : "unavailable"));
169
+ req.on("response", (res) => {
170
+ res.on("error", () => finish(mutation ? "indeterminate" : "response"));
171
+ const status = res.statusCode;
172
+ const stopRoute = method === "POST" && /^\/v1\/profiles\/[^/]+\/stop$/.test(url.pathname);
173
+ const expectedStatus = local?.status ?? (stopRoute ? 204 : 200);
174
+ if (local &&
175
+ (status === 400 ||
176
+ status === 409 ||
177
+ status === 422 ||
178
+ status === 423 ||
179
+ (local.page && (status === 408 || status === 403)))) {
180
+ // Read only the daemon's error `code`; no message, details or other field is kept.
181
+ const chunks = [];
182
+ let size = 0;
183
+ res.on("data", (chunk) => {
184
+ size += chunk.length;
185
+ if (size > LIMITS.bodyBytes)
186
+ return finish("upstream");
187
+ chunks.push(chunk);
188
+ });
189
+ res.on("end", () => finish(mapDaemonError(status, Buffer.concat(chunks, size), local.page === true)));
190
+ res.on("close", () => {
191
+ if (!res.complete)
192
+ finish("upstream");
193
+ });
194
+ return;
195
+ }
196
+ if (status !== expectedStatus) {
197
+ res.destroy();
198
+ return finish(status === 401
199
+ ? "unauthorized"
200
+ : status === 403
201
+ ? "forbidden"
202
+ : status === 404
203
+ ? "not_found"
204
+ : local && status === 503
205
+ ? "unavailable"
206
+ : "upstream");
207
+ }
208
+ if (res.headers["content-encoding"] && res.headers["content-encoding"] !== "identity") {
209
+ return finish(mutation ? "indeterminate" : "response");
210
+ }
211
+ if (Number(res.headers["content-length"]) > bodyLimit)
212
+ return finish(mutation ? "indeterminate" : "body_limit");
213
+ const chunks = [];
214
+ let size = 0;
215
+ res.on("data", (chunk) => {
216
+ size += chunk.length;
217
+ if (size > bodyLimit)
218
+ return finish(mutation ? "indeterminate" : "body_limit");
219
+ chunks.push(chunk);
220
+ });
221
+ res.on("end", () => {
222
+ if (settled)
223
+ return;
224
+ if (expectedStatus === 204) {
225
+ if (size !== 0)
226
+ return finish("indeterminate");
227
+ settled = true;
228
+ clearTimeout(timer);
229
+ signal.removeEventListener("abort", abort);
230
+ // Only a stop answer may carry the sync state, and only the two known values pass.
231
+ const sync = res.headers["ant0-sync"];
232
+ const headers = stopRoute && (sync === "done" || sync === "pending") ? { "ant0-sync": sync } : {};
233
+ void drained.then(() => resolve(new Response(null, { status: 204, headers })));
234
+ return;
235
+ }
236
+ finish(undefined, Buffer.concat(chunks, size));
237
+ });
238
+ res.on("close", () => {
239
+ if (!res.complete)
240
+ finish(mutation ? "indeterminate" : "response");
241
+ });
242
+ });
243
+ req.end(body);
244
+ });
245
+ // A credential that changed mid-flight invalidates the reply, never the effect already applied.
246
+ try {
247
+ await credentialCheck();
248
+ }
249
+ catch (error) {
250
+ throw mutation ? new McpFailure("indeterminate") : error;
251
+ }
252
+ return response;
253
+ };
254
+ return createAnt0Client({
255
+ baseUrl: connection.origin,
256
+ token: connection.token,
257
+ fetch: boundedFetch,
258
+ });
259
+ }
260
+ //# sourceMappingURL=daemon.js.map
@@ -0,0 +1,69 @@
1
+ declare const MESSAGES: {
2
+ readonly configuration: "invalid local daemon configuration";
3
+ readonly token_file: "the local daemon token file is not private; the path and the fix are in the error output of ant0 mcp serve";
4
+ readonly unavailable: "local daemon unavailable";
5
+ readonly unauthorized: "local daemon authorization required";
6
+ readonly forbidden: "local daemon denied this request";
7
+ readonly not_found: "item not found";
8
+ readonly upstream: "local daemon request failed";
9
+ readonly response: "invalid local daemon response";
10
+ readonly body_limit: "local daemon response exceeds limit";
11
+ readonly result_limit: "tool result exceeds limit; request fewer items";
12
+ readonly deadline: "local daemon request timed out";
13
+ readonly cancelled: "request cancelled";
14
+ readonly indeterminate: "operation outcome is unknown; check the current state before retrying";
15
+ readonly invalid_request: "The daemon rejected the input.";
16
+ readonly profile_running: "Stop the profile first.";
17
+ readonly profile_synced: "This profile syncs with the cloud; remove it in the Ant0 app.";
18
+ readonly conflict: "The daemon reported a conflict; check the profile and retry.";
19
+ readonly ref_stale: "The ref is stale; take a new snapshot and use a ref from it.";
20
+ readonly not_running: "The profile is not running; start it with ant0_profile_run first.";
21
+ readonly unsupported_input: "This control cannot be driven by typing or pointer input.";
22
+ readonly not_editable: "The field is disabled or read-only.";
23
+ readonly select_failed: "The select did not take the requested option.";
24
+ readonly out_of_view: "The target is outside the viewport or has no box.";
25
+ readonly focus_mismatch: "The target was not (or no longer) the focused element, so typing stopped; earlier characters or fields may already have been entered, and with submit the form may already have been submitted. Take a new snapshot, check the page state before retrying, and retry only what is missing. If its tab is in the background select it with ant0_tabs first.";
26
+ readonly obscured: "Another element covers the target, so that click was not sent (earlier fields of a fill may already have been entered); close the overlay or scroll and retry.";
27
+ readonly tab_hidden: "The tab is in the background (or went there mid-action; earlier characters or fields may already have been entered): call ant0_tabs with action select for it first (this changes the tab the user sees), check the page state, then retry.";
28
+ readonly tab_required: "Several tabs are open: call ant0_tabs to list them and pass the tab id as tab.";
29
+ readonly destination_blocked: "This URL points to a local or private-network address, which the page tools refuse. Use a public http(s) URL.";
30
+ readonly page_timeout: "The wait did not finish in time.";
31
+ readonly no_history: "There is no history entry in that direction.";
32
+ readonly arguments: "invalid tool arguments";
33
+ readonly unknown_tool: "unknown tool";
34
+ readonly busy: "too many concurrent calls";
35
+ readonly frame: "invalid MCP input frame";
36
+ readonly frame_limit: "MCP input frame exceeds limit";
37
+ readonly input: "MCP input failed";
38
+ readonly output: "MCP output failed";
39
+ readonly stdio: "MCP requires pipe or socket stdout";
40
+ readonly peer: "MCP peer did not answer ping";
41
+ readonly backpressure: "MCP output stalled";
42
+ readonly internal: "MCP adapter failed";
43
+ };
44
+ export type FailureCode = keyof typeof MESSAGES;
45
+ /** Tool discovery must advertise the same fixed structured failures that errorResult emits. */
46
+ export declare const FAILURE_OUTPUT_SCHEMA: {
47
+ type: "object";
48
+ anyOf: {
49
+ type: string;
50
+ additionalProperties: boolean;
51
+ required: string[];
52
+ properties: {
53
+ error: {
54
+ const: string;
55
+ };
56
+ message: {
57
+ const: "invalid local daemon configuration" | "the local daemon token file is not private; the path and the fix are in the error output of ant0 mcp serve" | "local daemon unavailable" | "local daemon authorization required" | "local daemon denied this request" | "item not found" | "local daemon request failed" | "invalid local daemon response" | "local daemon response exceeds limit" | "tool result exceeds limit; request fewer items" | "local daemon request timed out" | "request cancelled" | "operation outcome is unknown; check the current state before retrying" | "The daemon rejected the input." | "Stop the profile first." | "This profile syncs with the cloud; remove it in the Ant0 app." | "The daemon reported a conflict; check the profile and retry." | "The ref is stale; take a new snapshot and use a ref from it." | "The profile is not running; start it with ant0_profile_run first." | "This control cannot be driven by typing or pointer input." | "The field is disabled or read-only." | "The select did not take the requested option." | "The target is outside the viewport or has no box." | "The target was not (or no longer) the focused element, so typing stopped; earlier characters or fields may already have been entered, and with submit the form may already have been submitted. Take a new snapshot, check the page state before retrying, and retry only what is missing. If its tab is in the background select it with ant0_tabs first." | "Another element covers the target, so that click was not sent (earlier fields of a fill may already have been entered); close the overlay or scroll and retry." | "The tab is in the background (or went there mid-action; earlier characters or fields may already have been entered): call ant0_tabs with action select for it first (this changes the tab the user sees), check the page state, then retry." | "Several tabs are open: call ant0_tabs to list them and pass the tab id as tab." | "This URL points to a local or private-network address, which the page tools refuse. Use a public http(s) URL." | "The wait did not finish in time." | "There is no history entry in that direction." | "invalid tool arguments" | "unknown tool" | "too many concurrent calls" | "invalid MCP input frame" | "MCP input frame exceeds limit" | "MCP input failed" | "MCP output failed" | "MCP requires pipe or socket stdout" | "MCP peer did not answer ping" | "MCP output stalled" | "MCP adapter failed";
58
+ };
59
+ };
60
+ }[];
61
+ };
62
+ /** Only these fixed strings cross the diagnostic boundary. Never retain a raw cause. */
63
+ export declare class McpFailure extends Error {
64
+ readonly code: FailureCode;
65
+ constructor(code: FailureCode);
66
+ }
67
+ export declare function safeFailure(error: unknown): McpFailure;
68
+ export {};
69
+ //# sourceMappingURL=errors.d.ts.map
package/dist/errors.js ADDED
@@ -0,0 +1,78 @@
1
+ import { isAnt0ApiError } from "./api/index.js";
2
+ import { CredentialFailure } from "./key-contract.js";
3
+ const MESSAGES = {
4
+ configuration: "invalid local daemon configuration",
5
+ token_file: "the local daemon token file is not private; the path and the fix are in the error output of ant0 mcp serve",
6
+ unavailable: "local daemon unavailable",
7
+ unauthorized: "local daemon authorization required",
8
+ forbidden: "local daemon denied this request",
9
+ not_found: "item not found",
10
+ upstream: "local daemon request failed",
11
+ response: "invalid local daemon response",
12
+ body_limit: "local daemon response exceeds limit",
13
+ result_limit: "tool result exceeds limit; request fewer items",
14
+ deadline: "local daemon request timed out",
15
+ cancelled: "request cancelled",
16
+ indeterminate: "operation outcome is unknown; check the current state before retrying",
17
+ invalid_request: "The daemon rejected the input.",
18
+ profile_running: "Stop the profile first.",
19
+ profile_synced: "This profile syncs with the cloud; remove it in the Ant0 app.",
20
+ conflict: "The daemon reported a conflict; check the profile and retry.",
21
+ ref_stale: "The ref is stale; take a new snapshot and use a ref from it.",
22
+ not_running: "The profile is not running; start it with ant0_profile_run first.",
23
+ unsupported_input: "This control cannot be driven by typing or pointer input.",
24
+ not_editable: "The field is disabled or read-only.",
25
+ select_failed: "The select did not take the requested option.",
26
+ out_of_view: "The target is outside the viewport or has no box.",
27
+ focus_mismatch: "The target was not (or no longer) the focused element, so typing stopped; earlier characters or fields may already have been entered, and with submit the form may already have been submitted. Take a new snapshot, check the page state before retrying, and retry only what is missing. If its tab is in the background select it with ant0_tabs first.",
28
+ obscured: "Another element covers the target, so that click was not sent (earlier fields of a fill may already have been entered); close the overlay or scroll and retry.",
29
+ tab_hidden: "The tab is in the background (or went there mid-action; earlier characters or fields may already have been entered): call ant0_tabs with action select for it first (this changes the tab the user sees), check the page state, then retry.",
30
+ tab_required: "Several tabs are open: call ant0_tabs to list them and pass the tab id as tab.",
31
+ destination_blocked: "This URL points to a local or private-network address, which the page tools refuse. Use a public http(s) URL.",
32
+ page_timeout: "The wait did not finish in time.",
33
+ no_history: "There is no history entry in that direction.",
34
+ arguments: "invalid tool arguments",
35
+ unknown_tool: "unknown tool",
36
+ busy: "too many concurrent calls",
37
+ frame: "invalid MCP input frame",
38
+ frame_limit: "MCP input frame exceeds limit",
39
+ input: "MCP input failed",
40
+ output: "MCP output failed",
41
+ stdio: "MCP requires pipe or socket stdout",
42
+ peer: "MCP peer did not answer ping",
43
+ backpressure: "MCP output stalled",
44
+ internal: "MCP adapter failed",
45
+ };
46
+ /** Tool discovery must advertise the same fixed structured failures that errorResult emits. */
47
+ export const FAILURE_OUTPUT_SCHEMA = {
48
+ type: "object",
49
+ anyOf: Object.entries(MESSAGES).map(([code, message]) => ({
50
+ type: "object",
51
+ additionalProperties: false,
52
+ required: ["error", "message"],
53
+ properties: { error: { const: `mcp.${code}` }, message: { const: message } },
54
+ })),
55
+ };
56
+ /** Only these fixed strings cross the diagnostic boundary. Never retain a raw cause. */
57
+ export class McpFailure extends Error {
58
+ code;
59
+ constructor(code) {
60
+ super(MESSAGES[code]);
61
+ this.code = code;
62
+ }
63
+ }
64
+ export function safeFailure(error) {
65
+ if (error instanceof CredentialFailure)
66
+ return new McpFailure("response");
67
+ if (isAnt0ApiError(error)) {
68
+ return new McpFailure(error.status === 401
69
+ ? "unauthorized"
70
+ : error.status === 403
71
+ ? "forbidden"
72
+ : error.status === 404
73
+ ? "not_found"
74
+ : "upstream");
75
+ }
76
+ return error instanceof McpFailure ? error : new McpFailure("internal");
77
+ }
78
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,37 @@
1
+ export declare const EXPORT_TTL_HOURS = 24;
2
+ /** `<ANT0_HOME>/exports/cookies`. */
3
+ export declare function cookieExportDir(home: string): string;
4
+ /** `<ANT0_HOME>/exports/screenshots`. */
5
+ export declare function screenshotExportDir(home: string): string;
6
+ /** `<ANT0_HOME>/imports/cookies`: the only place `ant0_cookies_import` reads files from. */
7
+ export declare function cookieImportDir(home: string): string;
8
+ /** Delete our own files older than the TTL. Regular files with our name pattern only; best effort. */
9
+ export declare function sweepExports(dir: string, now?: number): void;
10
+ /**
11
+ * Write one export file and return its absolute path. The leaf directory is mode 0700 and the
12
+ * file 0600 (written under a temp name with flag "wx", then renamed in the same directory). On
13
+ * Windows the mode bits are ignored and the user-profile ACL inheritance protects the folder.
14
+ * Failures carry no cookie data.
15
+ */
16
+ export declare function writeCookieExport(home: string, profileId: string, extension: "json" | "txt", data: string, now?: Date, test?: {
17
+ suffix?: string;
18
+ beforeRename?: (temp: string) => void;
19
+ }): string;
20
+ /** Write one screenshot (PNG bytes) with the same guarantees as a cookie export. */
21
+ export declare function writeScreenshotExport(home: string, profileId: string, png: Buffer, now?: Date, test?: {
22
+ suffix?: string;
23
+ beforeRename?: (temp: string) => void;
24
+ }): string;
25
+ /** Sweep now and then hourly (unref'd, so it never keeps the process alive). Returns the stopper. */
26
+ export declare const SWEEP_INTERVAL_MS = 3600000;
27
+ export declare function startExportSweeper(home: string): () => void;
28
+ /**
29
+ * Read one cookie file from `<ANT0_HOME>/imports/cookies` (UTF-8, at most one request body).
30
+ * The directory is created 0700 if missing. Every failure (missing, unreadable, outside the
31
+ * directory, symlink, directory, FIFO, too large, swapped, bad UTF-8) is the same `arguments`
32
+ * failure, so the tool is not an existence or content oracle for other paths.
33
+ */
34
+ export declare function readImportFile(home: string, path: string, test?: {
35
+ afterLstat?: (path: string) => void;
36
+ }): string;
37
+ //# sourceMappingURL=export-files.d.ts.map
@@ -0,0 +1,167 @@
1
+ import { chmodSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, readdirSync, renameSync, unlinkSync, writeSync, } from "node:fs";
2
+ import { randomBytes } from "node:crypto";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { McpFailure } from "./errors.js";
5
+ import { LIMITS } from "./limits.js";
6
+ export const EXPORT_TTL_HOURS = 24;
7
+ const NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}-\d{8}T\d{6}Z-[0-9a-f]{4}\.(?:json|txt|png)(?:\.tmp)?$/;
8
+ /** `<ANT0_HOME>/exports/cookies`. */
9
+ export function cookieExportDir(home) {
10
+ return join(home, "exports", "cookies");
11
+ }
12
+ /** `<ANT0_HOME>/exports/screenshots`. */
13
+ export function screenshotExportDir(home) {
14
+ return join(home, "exports", "screenshots");
15
+ }
16
+ /** `<ANT0_HOME>/imports/cookies`: the only place `ant0_cookies_import` reads files from. */
17
+ export function cookieImportDir(home) {
18
+ return join(home, "imports", "cookies");
19
+ }
20
+ /** Create one of our private leaf directories (0700) and refuse a symlink or non-directory. */
21
+ function ensurePrivateDir(dir) {
22
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
23
+ const stat = lstatSync(dir);
24
+ if (!stat.isDirectory() || stat.isSymbolicLink())
25
+ throw new McpFailure("configuration");
26
+ chmodSync(dir, 0o700); // our own leaf directory only
27
+ }
28
+ function timestamp(now) {
29
+ return now
30
+ .toISOString()
31
+ .replace(/\.\d+Z$/, "Z")
32
+ .replace(/[-:]/g, "");
33
+ }
34
+ /** Delete our own files older than the TTL. Regular files with our name pattern only; best effort. */
35
+ export function sweepExports(dir, now = Date.now()) {
36
+ let names;
37
+ try {
38
+ names = readdirSync(dir);
39
+ }
40
+ catch {
41
+ return;
42
+ }
43
+ for (const name of names) {
44
+ if (!NAME.test(name))
45
+ continue;
46
+ try {
47
+ const path = join(dir, name);
48
+ const stat = lstatSync(path); // never follows a symlink
49
+ if (stat.isFile() && now - stat.mtimeMs > EXPORT_TTL_HOURS * 3_600_000)
50
+ unlinkSync(path);
51
+ }
52
+ catch {
53
+ /* ignore */
54
+ }
55
+ }
56
+ }
57
+ /**
58
+ * Write one export file and return its absolute path. The leaf directory is mode 0700 and the
59
+ * file 0600 (written under a temp name with flag "wx", then renamed in the same directory). On
60
+ * Windows the mode bits are ignored and the user-profile ACL inheritance protects the folder.
61
+ * Failures carry no cookie data.
62
+ */
63
+ export function writeCookieExport(home, profileId, extension, data, now = new Date(), test = {}) {
64
+ return writeExport(cookieExportDir(resolve(home)), profileId, extension, data, now, test);
65
+ }
66
+ /** Write one screenshot (PNG bytes) with the same guarantees as a cookie export. */
67
+ export function writeScreenshotExport(home, profileId, png, now = new Date(), test = {}) {
68
+ return writeExport(screenshotExportDir(resolve(home)), profileId, "png", png, now, test);
69
+ }
70
+ function writeExport(dir, profileId, extension, data, now, test) {
71
+ try {
72
+ ensurePrivateDir(dir);
73
+ sweepExports(dir, now.getTime());
74
+ const name = `${profileId}-${timestamp(now)}-${test.suffix ?? randomBytes(2).toString("hex")}.${extension}`;
75
+ const final = join(dir, name);
76
+ const temp = `${final}.tmp`;
77
+ const fd = openSync(temp, "wx", 0o600);
78
+ try {
79
+ const bytes = typeof data === "string" ? Buffer.from(data, "utf8") : data;
80
+ let written = 0;
81
+ while (written < bytes.length)
82
+ written += writeSync(fd, bytes, written);
83
+ }
84
+ catch (error) {
85
+ closeSync(fd);
86
+ try {
87
+ unlinkSync(temp);
88
+ }
89
+ catch {
90
+ /* ignore */
91
+ }
92
+ throw error;
93
+ }
94
+ closeSync(fd);
95
+ test.beforeRename?.(temp);
96
+ renameSync(temp, final);
97
+ return final;
98
+ }
99
+ catch (error) {
100
+ throw error instanceof McpFailure ? error : new McpFailure("internal");
101
+ }
102
+ }
103
+ /** Sweep now and then hourly (unref'd, so it never keeps the process alive). Returns the stopper. */
104
+ export const SWEEP_INTERVAL_MS = 3_600_000;
105
+ export function startExportSweeper(home) {
106
+ const dirs = [cookieExportDir(resolve(home)), screenshotExportDir(resolve(home))];
107
+ const sweep = () => {
108
+ for (const dir of dirs) {
109
+ try {
110
+ sweepExports(dir);
111
+ }
112
+ catch {
113
+ /* ignore */
114
+ }
115
+ }
116
+ };
117
+ sweep();
118
+ const timer = setInterval(sweep, SWEEP_INTERVAL_MS);
119
+ timer.unref();
120
+ return () => clearInterval(timer);
121
+ }
122
+ /**
123
+ * Read one cookie file from `<ANT0_HOME>/imports/cookies` (UTF-8, at most one request body).
124
+ * The directory is created 0700 if missing. Every failure (missing, unreadable, outside the
125
+ * directory, symlink, directory, FIFO, too large, swapped, bad UTF-8) is the same `arguments`
126
+ * failure, so the tool is not an existence or content oracle for other paths.
127
+ */
128
+ export function readImportFile(home, path, test = {}) {
129
+ const fail = () => new McpFailure("arguments");
130
+ if (!isAbsolute(path) || path.includes("\0"))
131
+ throw fail();
132
+ let fd;
133
+ try {
134
+ const dir = cookieImportDir(resolve(home));
135
+ ensurePrivateDir(dir);
136
+ const inside = relative(realpathSync(dir), realpathSync(path));
137
+ if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside))
138
+ throw fail();
139
+ const stat = lstatSync(path);
140
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > LIMITS.bodyBytes)
141
+ throw fail();
142
+ test.afterLstat?.(path);
143
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0));
144
+ const opened = fstatSync(fd);
145
+ if (!opened.isFile() || opened.ino !== stat.ino || opened.dev !== stat.dev)
146
+ throw fail();
147
+ const buffer = Buffer.alloc(LIMITS.bodyBytes + 1);
148
+ let size = 0;
149
+ while (size < buffer.length) {
150
+ const count = readSync(fd, buffer, size, buffer.length - size, null);
151
+ if (count === 0)
152
+ break;
153
+ size += count;
154
+ }
155
+ if (size > LIMITS.bodyBytes)
156
+ throw fail();
157
+ return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, size));
158
+ }
159
+ catch {
160
+ throw fail();
161
+ }
162
+ finally {
163
+ if (fd !== undefined)
164
+ closeSync(fd);
165
+ }
166
+ }
167
+ //# sourceMappingURL=export-files.js.map
@@ -0,0 +1,5 @@
1
+ import { type Ant0Client } from "./api/index.js";
2
+ import type { Connection } from "./connection.js";
3
+ import { type KeyGrant } from "./key-contract.js";
4
+ export declare function resolveGrant(connection: Connection, client: Ant0Client, consumer: "api" | "mcp", signal?: AbortSignal): Promise<KeyGrant | undefined>;
5
+ //# sourceMappingURL=grant.d.ts.map
package/dist/grant.js ADDED
@@ -0,0 +1,11 @@
1
+ import { unwrap } from "./api/index.js";
2
+ import { fileGrant, grantFromStatus } from "./key-contract.js";
3
+ export async function resolveGrant(connection, client, consumer, signal) {
4
+ if (connection.credential)
5
+ return fileGrant(connection.credential.value);
6
+ if (!connection.apiKey)
7
+ return undefined;
8
+ const status = unwrap(await client.GET("/v1/automation/status", signal ? { signal } : {}));
9
+ return grantFromStatus(status, connection.token, consumer).grant;
10
+ }
11
+ //# sourceMappingURL=grant.js.map