Update Site source

This commit is contained in:
Meghdad committed 2026-10-12 23:20:56 +03:30
commit 9a4ce930c7
126 files changed
+25723

No files matched your search

@@ -0,0 +1,214 @@
import { randomUUID } from "node:crypto";
import {
mkdir,
readFile,
readdir,
rename,
rm,
writeFile,
} from "node:fs/promises";
import path from "node:path";
import { createInterface } from "node:readline";
import { parseArgs } from "node:util";
import { JSONRPCClient } from "json-rpc-2.0";
import { createPreviewBinding } from "./host-binding.mjs";
import {
driverMessageSchema,
grantsSchema,
sessionOptionsSchema,
} from "./protocol.mjs";
// The agent starts this script through its terminal tool after creating a local
// Site and selecting connector read actions, following references/app-integrations.md#local-preview:
// node <site-directory>/scripts/connector-preview/connector-preview-session.mjs <site-directory> <grants.json>
// During the agent development loop, the Site preview writes requests into a shared folder.
// This script checks each request with host-binding.mjs, then asks the agent over
// stdout to call the connector. The agent returns the tool result through stdin,
// and this script writes it back for the Site. The agent stops the script when
// previewing ends; neither the browser nor a deployed Site starts this process.
const { positionals, values } = parseArgs({
allowPositionals: true,
options: {
concurrency: { type: "string" },
"timeout-ms": { type: "string" },
"lifetime-ms": { type: "string" },
"max-calls": { type: "string" },
},
});
const [project, grantsFile] = positionals;
if (positionals.length !== 2 || !path.isAbsolute(project)) {
throw new Error(
"Usage: node connector-preview-session.mjs <absolute-site-directory> <grants.json> [--concurrency 64] [--timeout-ms 120000] [--lifetime-ms N] [--max-calls N]",
);
}
const limits = sessionOptionsSchema.parse(
Object.fromEntries(
[
["maxConcurrent", values.concurrency],
["timeoutMs", values["timeout-ms"]],
["lifetimeMs", values["lifetime-ms"]],
["maxCalls", values["max-calls"]],
]
.filter(([, value]) => value !== undefined)
.map(([key, value]) => [key, Number(value)]),
),
);
const grants = grantsSchema.parse(
JSON.parse(await readFile(grantsFile, "utf8")),
);
const root = path.join(project, ".sites-runtime", "connector-preview");
const id = randomUUID();
const directory = path.join(root, id);
const descriptor = path.join(root, "session.json");
const active = new Set();
const rpc = new JSONRPCClient(
(message) =>
new Promise((resolve, reject) => {
process.stdout.write(`${JSON.stringify(message)}\n`, (error) =>
error ? reject(error) : resolve(),
);
}),
);
const emit = (method, params) => rpc.notify(method, params);
let closing = false;
const binding = createPreviewBinding({
...limits,
tools: grants.map((grant) => ({
...grant,
async invoke(args) {
const requestId = randomUUID();
// JSON-RPC owns response matching and pending-call cleanup. Do not put an
// RPC timeout here: uncertain calls occupy their slot until they settle.
const response = await rpc.requestAdvanced({
jsonrpc: "2.0",
id: requestId,
method: "invoke",
params: {
connectorId: grant.connectorId,
actionName: grant.actionName,
arguments: args,
},
});
if (!closing)
emit("receipt", { id: requestId, at: new Date().toISOString() });
if (response.error)
throw new Error("The agent did not confirm a connector result.");
return response.result;
},
})),
});
await mkdir(directory, { recursive: true, mode: 0o700 });
try {
// One owner per project. A crashed session must be explicitly cleaned up;
// never silently take over another agent's connector session.
await writeFile(
descriptor,
JSON.stringify({
id,
expiresAt:
limits.lifetimeMs === undefined ? null : Date.now() + limits.lifetimeMs,
timeoutMs: limits.timeoutMs,
connectorIds: [...new Set(grants.map((grant) => grant.connectorId))],
}),
{ flag: "wx", mode: 0o600 },
);
} catch (error) {
binding.close();
await rm(directory, { recursive: true, force: true });
throw error;
}
async function serve(name) {
active.add(name);
try {
const body = await readFile(path.join(directory, name), "utf8");
const response = await binding.fetch(
new Request("http://preview/invoke", { method: "POST", body }),
);
if (!closing) {
const output = path.join(
directory,
name.replace(".request", ".response"),
);
await writeFile(`${output}.tmp`, await response.text(), { mode: 0o600 });
await rename(`${output}.tmp`, output);
}
} catch {
// A timed-out caller can remove its request. The native call is never retried.
} finally {
await rm(path.join(directory, name), { force: true });
active.delete(name);
}
}
let scanning = false;
// The mailbox crosses network namespaces through the shared project directory.
// Atomic renames keep the reader from seeing partially written messages.
const poller = setInterval(async () => {
if (closing || scanning) return;
scanning = true;
try {
for (const name of await readdir(directory)) {
if (/^[0-9a-f-]{36}\.request$/.test(name) && !active.has(name))
void serve(name);
}
} catch (error) {
if (!closing) {
emit("session_error", { code: error.code });
void close();
}
} finally {
scanning = false;
}
}, 50);
const expiry =
limits.lifetimeMs === undefined
? undefined
: setTimeout(() => {
void close();
}, limits.lifetimeMs);
if (process.stdin.isTTY) process.stdin.setRawMode(true);
const input = createInterface({ input: process.stdin, terminal: false });
input.on("line", (line) => {
try {
const message = driverMessageSchema.parse(JSON.parse(line));
if (message.method === "stop") {
void close();
return;
}
rpc.receive(message);
} catch {
emit("invalid_driver_message");
}
});
async function close() {
if (closing) return;
closing = true;
clearInterval(poller);
clearTimeout(expiry);
binding.close();
rpc.rejectAllPendingRequests("The connector preview session ended.");
await rm(descriptor, { force: true });
await rm(directory, { recursive: true, force: true });
if (process.stdin.isTTY) process.stdin.setRawMode(false);
input.close();
process.stdin.pause();
emit("closed");
}
input.on("close", () => {
void close();
});
process.stdin.on("data", (chunk) => {
if (chunk.includes(3)) void close();
});
process.on("SIGTERM", () => {
void close();
});
process.on("SIGINT", () => {
void close();
});
emit("ready", {
expiresInSeconds:
limits.lifetimeMs === undefined ? null : limits.lifetimeMs / 1000,
maxCalls: limits.maxCalls ?? null,
maxConcurrent: limits.maxConcurrent,
timeoutMs: limits.timeoutMs,
});
+217
View File
@@ -0,0 +1,217 @@
import { Readable } from "node:stream";
import { setMaxListeners } from "node:events";
import getRawBody from "raw-body";
import { z } from "zod/v4";
import {
grantSchema,
invocationSchema,
sessionOptionsSchema,
} from "./protocol.mjs";
// Checks connector calls while the agent builds and tests a Site locally.
// connector-preview-session.mjs uses this helper after the agent chooses the read
// actions the Site may use. For each Site request, it checks that selection and
// the session limits before asking the agent to make the actual tool call.
// It also handles timeouts, shutdown, and which result fields reach the Site.
// This runs in the agent's temporary session, not in the deployed Site.
const messages = {
invalid_request: "This app request is invalid or too large.",
binding_unavailable:
"Connected apps need an active agent preview session in this preview.",
tool_not_allowed: "This preview cannot use the requested app action.",
rate_limited:
"A request limit was reached while using this connector. Please wait before trying again.",
tool_error: "An error was reported while running this connector action.",
upstream_error:
"The app did not return a confirmed result. The action may have completed; check before trying again.",
};
const failure = (status) => ({ status, message: messages[status] });
const reply = (result) =>
Response.json(result, { headers: { "Cache-Control": "no-store" } });
const requestIdSchema = z
.string()
.regex(/^[A-Za-z0-9._:-]{1,128}$/)
.optional()
.catch(undefined);
const resultSchema = z.object({
error: z.never().optional(),
status: z.never().optional(),
content: z.array(z.object({ type: z.string() }).catchall(z.json())),
structuredContent: z.json().optional(),
isError: z.boolean().optional(),
requestId: requestIdSchema,
});
export function createPreviewBinding({ tools, ...options }) {
const { lifetimeMs, timeoutMs, maxCalls, maxConcurrent } =
sessionOptionsSchema.parse(options);
const grants = new Map();
for (const tool of tools) {
const { invoke, ...grant } = tool;
if (!grantSchema.safeParse(grant).success || typeof invoke !== "function")
throw new Error(
"Preview tools must be authenticated, resolved read actions.",
);
const key = JSON.stringify([tool.connectorId, tool.actionName]);
if (grants.has(key))
throw new Error(
"Ambiguous connector action; the host must resolve its connection first.",
);
grants.set(key, tool.invoke);
}
const expiresAt =
lifetimeMs === undefined ? Infinity : Date.now() + lifetimeMs;
const ended = new AbortController();
setMaxListeners(maxConcurrent, ended.signal);
const expiry =
lifetimeMs === undefined
? undefined
: setTimeout(() => ended.abort(), lifetimeMs);
expiry?.unref();
let remaining = maxCalls ?? Infinity;
let active = 0;
return {
close() {
clearTimeout(expiry);
ended.abort();
},
async fetch(request) {
if (ended.signal.aborted || Date.now() >= expiresAt)
return reply(failure("binding_unavailable"));
if (
request.method !== "POST" ||
new URL(request.url).pathname !== "/invoke"
)
return reply(failure("invalid_request"));
let call;
try {
const body = await readBounded(request, 65536);
call = invocationSchema.parse(JSON.parse(body));
} catch {
return reply(failure("invalid_request"));
}
// Recheck after reading the request; shutdown can happen while it streams.
if (ended.signal.aborted || Date.now() >= expiresAt)
return reply(failure("binding_unavailable"));
const invoke = grants.get(
JSON.stringify([call.connectorId, call.actionName]),
);
if (!invoke || remaining === 0) return reply(failure("tool_not_allowed"));
if (active >= maxConcurrent) return reply(failure("rate_limited"));
active++;
remaining--;
let deadline;
let onEnd;
try {
const result = await Promise.race([
// A timeout ends our wait, not the provider call. Count that work
// against concurrency until it settles, without blocking other slots.
Promise.resolve()
.then(() => invoke(call.arguments))
.then(publicResult)
.finally(() => {
active--;
}),
new Promise((resolve) => {
deadline = setTimeout(
() => resolve(failure("upstream_error")),
timeoutMs,
);
}),
new Promise((resolve) => {
onEnd = () => resolve(failure("upstream_error"));
ended.signal.addEventListener("abort", onEnd, { once: true });
}),
]);
if (ended.signal.aborted || Date.now() >= expiresAt)
return reply(failure("upstream_error"));
if (
new TextEncoder().encode(JSON.stringify(result)).byteLength >
8 * 1024 * 1024
)
return reply(failure("upstream_error"));
return reply(result);
} catch {
return reply(failure("upstream_error"));
} finally {
clearTimeout(deadline);
ended.signal.removeEventListener("abort", onEnd);
}
},
};
}
export async function readBounded(request, limit) {
if (!request.body) throw new Error("Missing body");
const stream = Readable.fromWeb(request.body);
try {
// raw-body owns byte limits and stream errors; strict decoding rejects
// malformed UTF-8 instead of silently changing the caller's arguments.
return new TextDecoder("utf-8", { fatal: true }).decode(
await getRawBody(stream, { limit }),
);
} finally {
stream.destroy();
}
}
function publicResult(result) {
const parsed = resultSchema.safeParse(result);
if (!parsed.success) return failure("upstream_error");
result = parsed.data;
// Native tools return MCP results; convert once at the preview host boundary.
// Never accept provider-authored top-level status or transport metadata.
const payload = {
content: result.content,
// Like the hosted binding, preserve every JSON value, including null.
...(result.structuredContent !== undefined
? { structuredContent: result.structuredContent }
: {}),
};
const requestId =
result.requestId === undefined ? {} : { requestId: result.requestId };
if (result.isError === true) {
const detail = result.structuredContent;
if (detail?.error_code === "RATE_LIMITED") {
const retryAfterMs =
readRetryAfterMs(detail.retry_after_seconds) ??
readRetryAfterMs(detail.retry_after);
return {
...failure("rate_limited"),
...requestId,
...(retryAfterMs === undefined ? {} : { retryAfterMs }),
};
}
const invalidArguments =
detail?.error_code === "INVALID_ARGUMENT" &&
detail.error_data?.type === "invalid_action_arguments" &&
detail.error_data?.failure_stage === "argument_binding";
return {
...failure(invalidArguments ? "invalid_request" : "tool_error"),
result: payload,
...requestId,
};
}
return { status: "success", result: payload, ...requestId };
}
function readRetryAfterMs(value) {
let milliseconds;
if (
typeof value === "number" ||
(typeof value === "string" && /^\d+$/.test(value.trim()))
) {
milliseconds = Number(value) * 1000;
} else if (
typeof value === "string" &&
/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(
value.trim(),
)
) {
milliseconds = Math.max(0, Date.parse(value) - Date.now());
}
return Number.isSafeInteger(milliseconds) && milliseconds >= 0
? milliseconds
: undefined;
}
+60
View File
@@ -0,0 +1,60 @@
import { z } from "zod";
const name = z
.string()
.min(1)
.max(256)
.regex(/^[^\s/\x00-\x1f\x7f]+$/u);
const fields = { connectorId: name, actionName: name };
// Reject extra invocation fields: account selection and native tool names belong
// to the owning agent, not to the generated Site's request envelope.
export const invocationSchema = z
.object({ ...fields, arguments: z.record(z.unknown()) })
.strict();
export const grantSchema = z
.object({ ...fields, readOnly: z.literal(true) })
.strict();
export const grantsSchema = z.array(grantSchema);
// Only the owning agent sets these limits. Sessions otherwise last until their
// owner closes them; Node timers need a signed 32-bit millisecond duration.
const duration = z
.number()
.int()
.positive()
.max(2 ** 31 - 1);
export const sessionOptionsSchema = z
.object({
timeoutMs: duration.default(120000),
maxConcurrent: z.number().int().positive().safe().default(64),
lifetimeMs: duration.optional(),
maxCalls: z.number().int().positive().safe().optional(),
})
.strict();
// The pipe carries JSON-RPC responses and a stop notification. Provider failures
// still travel inside result as MCP results; JSON-RPC errors mean driver failure.
export const driverMessageSchema = z.union([
z.object({ jsonrpc: z.literal("2.0"), method: z.literal("stop") }).strict(),
z
.object({
jsonrpc: z.literal("2.0"),
id: z.string().uuid(),
result: z.record(z.unknown()),
})
.strict(),
z
.object({
jsonrpc: z.literal("2.0"),
id: z.string().uuid(),
error: z
.object({
code: z.number().int(),
message: z.string(),
data: z.unknown().optional(),
})
.strict(),
})
.strict(),
]);