@tangle-network/agent-app 0.51.12 → 0.51.14
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/dist/app-auth/index.js +1 -1
- package/dist/assistant/index.js +1 -1
- package/dist/chat-react/index.js +1 -1
- package/dist/chat-routes/index.js +2 -2
- package/dist/{chunk-TA5Q4I2K.js → chunk-7KKOFMLD.js} +4 -2
- package/dist/chunk-7KKOFMLD.js.map +1 -0
- package/dist/{chunk-YFGG722I.js → chunk-ELROJHE2.js} +2 -2
- package/dist/{chunk-BYAQQPLN.js → chunk-O3I7RQCB.js} +4 -4
- package/dist/chunk-O3I7RQCB.js.map +1 -0
- package/dist/{chunk-5P6TB74H.js → chunk-SMRF4UMN.js} +11 -13
- package/dist/chunk-SMRF4UMN.js.map +1 -0
- package/dist/{chunk-WWFE5EXY.js → chunk-TSZIYQAZ.js} +11 -4
- package/dist/chunk-TSZIYQAZ.js.map +1 -0
- package/dist/crypto/index.js +1 -1
- package/dist/interactions/index.js +3 -1
- package/dist/interactions/route.d.ts +2 -0
- package/dist/openui/index.js +8 -3
- package/dist/openui/index.js.map +1 -1
- package/dist/openui/route.d.ts +2 -0
- package/dist/platform/index.js +1 -1
- package/dist/preset-cloudflare/index.js +1 -1
- package/dist/public-consultation/index.js +2 -2
- package/dist/web-react/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5P6TB74H.js.map +0 -1
- package/dist/chunk-BYAQQPLN.js.map +0 -1
- package/dist/chunk-TA5Q4I2K.js.map +0 -1
- package/dist/chunk-WWFE5EXY.js.map +0 -1
- /package/dist/{chunk-YFGG722I.js.map → chunk-ELROJHE2.js.map} +0 -0
|
@@ -204,18 +204,16 @@ function createTangleSsoHandlers(opts) {
|
|
|
204
204
|
if (!opts.callbackUrl) throw new Error("TangleSsoHandlerOptions.callbackUrl is required");
|
|
205
205
|
if (!opts.stateCookieName) throw new Error("TangleSsoHandlerOptions.stateCookieName is required");
|
|
206
206
|
const callbackUrl = new URL(opts.callbackUrl);
|
|
207
|
-
if (opts.
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
throw new Error("SSO HTTPS callbacks require Secure cookies");
|
|
218
|
-
}
|
|
207
|
+
if (opts.stateSecret.length < 32) throw new Error("SSO stateSecret must contain at least 32 characters");
|
|
208
|
+
if (callbackUrl.username || callbackUrl.password || callbackUrl.hash || callbackUrl.search) {
|
|
209
|
+
throw new Error("SSO callbackUrl must be fixed and have no credentials, query, or fragment");
|
|
210
|
+
}
|
|
211
|
+
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(callbackUrl.hostname);
|
|
212
|
+
if (callbackUrl.protocol !== "https:" && !(callbackUrl.protocol === "http:" && loopback)) {
|
|
213
|
+
throw new Error("SSO requires HTTPS except on loopback");
|
|
214
|
+
}
|
|
215
|
+
if (callbackUrl.protocol === "https:" && !opts.secureCookies) {
|
|
216
|
+
throw new Error("SSO HTTPS callbacks require Secure cookies");
|
|
219
217
|
}
|
|
220
218
|
const sessionCookieName = opts.sessionCookieName ?? DEFAULT_SESSION_COOKIE;
|
|
221
219
|
let mintSessionCookies;
|
|
@@ -496,4 +494,4 @@ export {
|
|
|
496
494
|
createAdminGuard,
|
|
497
495
|
assertBillableBalance
|
|
498
496
|
};
|
|
499
|
-
//# sourceMappingURL=chunk-
|
|
497
|
+
//# sourceMappingURL=chunk-SMRF4UMN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platform/sso.ts","../src/platform/guards.ts"],"sourcesContent":["/**\n * Tangle SSO for agent apps. OIDC callers use the registered runtime client\n * with S256 PKCE. Legacy API-key callers remain explicit during migration.\n * OIDC never falls back to cross-site exchange. Account matching and native\n * session cookie minting remain shared.\n */\n\nimport { clearCookieHeader, readCookieValue, serializeCookie } from '../web/index'\n\nconst DEFAULT_STATE_TTL_SECONDS = 600\nconst DEFAULT_SESSION_TTL_SECONDS = 60 * 60 * 24 * 7\nconst DEFAULT_REDIRECT_PATH = '/app'\nconst DEFAULT_LOGIN_PATH = '/login'\nconst DEFAULT_SESSION_COOKIE = 'better-auth.session_token'\n\n// ── Signed state ────────────────────────────────────────────────────────────\n\n/** Define configuration options for managing SSO state including secret, lifetime, and clock injection */\nexport interface SsoStateConfig {\n /** HMAC-SHA256 secret (e.g. the app's auth secret). */\n secret: string\n /** State lifetime in ms. Default 600 000. */\n ttlMs?: number\n /** Injectable clock (ms since epoch). Default Date.now. */\n now?: () => number\n}\n\nfunction randomHex(bytes: number): string {\n const buf = new Uint8Array(bytes)\n crypto.getRandomValues(buf)\n return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nasync function hmacBytes(secret: string, value: string): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n return new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value)))\n}\n\nasync function hmacHex(secret: string, value: string): Promise<string> {\n return Array.from(await hmacBytes(secret, value), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/** Mint a `<randomHex32>.<timestamp36>.<hmacHex>` state value. The timestamp\n * is inside the signed payload, so expiry survives cookie-attribute tampering. */\nexport async function createSignedSsoState(config: SsoStateConfig): Promise<string> {\n if (!config.secret) throw new Error('SsoStateConfig.secret is required')\n const now = config.now ?? Date.now\n const payload = `${randomHex(16)}.${now().toString(36)}`\n return `${payload}.${await hmacHex(config.secret, payload)}`\n}\n\n/** Verify the MAC (constant-time) and the signed TTL. */\nexport async function verifySignedSsoState(state: string, config: SsoStateConfig): Promise<boolean> {\n if (!config.secret) throw new Error('SsoStateConfig.secret is required')\n const parts = state.split('.')\n if (parts.length !== 3) return false\n const [random, timestamp, mac] = parts\n if (!random || !timestamp || !mac || !/^[0-9a-z]+$/.test(timestamp)) return false\n const expected = await hmacHex(config.secret, `${random}.${timestamp}`)\n if (!constantTimeEqual(mac, expected)) return false\n const mintedAt = parseInt(timestamp, 36)\n if (!Number.isFinite(mintedAt)) return false\n const now = config.now ?? Date.now\n const ttlMs = config.ttlMs ?? DEFAULT_STATE_TTL_SECONDS * 1000\n const age = now() - mintedAt\n return age >= 0 && age <= ttlMs\n}\n\n// ── Seams ───────────────────────────────────────────────────────────────────\n\n/** Describe the result of exchanging SSO credentials including API key, user info, and optional plan details */\nexport interface TangleSsoExchangeResult {\n apiKey: string\n /** The platform's canonical verified-email proof. */\n emailVerified: boolean\n user: { id: string; email: string; name?: string | null }\n plan?: { tier: string } | null\n}\n\n/** Structural mirror of the platform auth wire client — any object with these\n * two methods satisfies it without this module importing the concrete class. */\nexport interface TangleSsoAuthClient {\n authorizeUrl(options: { state: string; redirectUri?: string }): string\n exchange(code: string): Promise<TangleSsoExchangeResult>\n}\n\n/** First-party login exchanges identity without minting a Platform API key. */\nexport interface TangleIdentitySsoExchangeResult {\n kind: 'identity'\n emailVerified: boolean\n user: TangleSsoExchangeResult['user']\n apiKey?: never\n keyId?: never\n}\n\nexport interface TangleIdentitySsoAuthClient {\n authorizeUrl(options: { state: string; redirectUri?: string }): string\n exchange(code: string): Promise<TangleIdentitySsoExchangeResult>\n}\n\n/** Token fields the callback persists from the runtime's OIDC exchange. */\nexport interface TangleOidcSsoTokens {\n accessToken: string\n tokenType: string\n expiresIn?: number\n refreshToken?: string\n idToken?: string\n scope?: string\n}\n\n/** Verified identity returned by the runtime's OIDC userinfo lookup. */\nexport interface TangleOidcSsoUser {\n id: string\n email: string\n emailVerified: true\n name?: string\n}\n\n/** The caller needs only the OIDC operations used by this callback. Keeping\n * this structural prevents legacy consumers from needing the optional\n * Runtime peer just to load the SSO declarations. */\nexport interface TangleOidcSsoAuthClient {\n authorizeUrl(options: {\n state: string\n codeChallenge: string\n nonce?: string\n prompt?: 'login' | 'consent' | 'none'\n loginHint?: string\n }): string\n exchange(code: string, codeVerifier: string): Promise<{\n tokens: TangleOidcSsoTokens\n user: TangleOidcSsoUser\n }>\n revoke(token: string, tokenTypeHint?: 'access_token' | 'refresh_token'): Promise<void>\n}\n\n/** Local account shape required by the verified Tangle SSO account policy.\n * Consumers map their user/link tables into this shape before resolving an\n * exchange. */\nexport interface TangleSsoLocalAccount {\n userId: string\n email: string\n emailVerified: boolean\n platformUserId: string | null\n}\n\n/** Reasons a local account lookup must stop instead of linking an exchange. */\nexport type TangleSsoAccountConflictReason =\n | 'ambiguous-platform-id'\n | 'platform-id-email-conflict'\n | 'unverified-email'\n | 'email-platform-id-conflict'\n | 'ambiguous-email'\n | 'invalid-platform-id'\n | 'invalid-email'\n | 'platform-match-mismatch'\n | 'email-match-mismatch'\n\n/** Result of applying the verified Tangle SSO account matching policy. */\nexport type TangleSsoAccountResolution =\n | { kind: 'existing'; userId: string; matchedBy: 'platform-id' | 'verified-email' }\n | { kind: 'create' }\n | { kind: 'reject'; reason: TangleSsoAccountConflictReason }\n\n/** Inputs for {@link resolveTangleSsoAccount}. `platformUserId` is the\n * platform's stable identity. */\nexport interface TangleSsoAccountResolutionInput {\n email: string\n platformMatches: readonly TangleSsoLocalAccount[]\n emailMatches: readonly TangleSsoLocalAccount[]\n platformUserId: string\n}\n\n/** Normalize an email for comparisons and persistence queries. */\nexport function normalizeTangleSsoEmail(email: string): string {\n return email.trim().toLowerCase()\n}\n\nfunction normalizedPlatformUserId(value: string | null | undefined): string | null {\n const normalized = value?.trim()\n return normalized ? normalized : null\n}\n\n/**\n * Resolve a platform exchange against all local rows found by stable platform\n * identity and normalized email.\n *\n * A stable platform id takes precedence over email. Every ambiguous or\n * contradictory result rejects, and email fallback requires a verified local\n * email that is not already bound to another platform id. The resolver is\n * pure so each consumer can query its own schema, including schemas without\n * unique indexes, then rerun it after an insert race.\n */\nexport function resolveTangleSsoAccount(\n input: TangleSsoAccountResolutionInput,\n): TangleSsoAccountResolution {\n const email = normalizeTangleSsoEmail(input.email)\n const platformUserId = normalizedPlatformUserId(input.platformUserId)\n if (!email) return { kind: 'reject', reason: 'invalid-email' }\n if (!platformUserId) return { kind: 'reject', reason: 'invalid-platform-id' }\n\n if (input.platformMatches.length > 1) {\n return { kind: 'reject', reason: 'ambiguous-platform-id' }\n }\n if (input.emailMatches.length > 1) {\n return { kind: 'reject', reason: 'ambiguous-email' }\n }\n\n if (input.platformMatches.some((account) => normalizedPlatformUserId(account.platformUserId) !== platformUserId)) {\n return { kind: 'reject', reason: 'platform-match-mismatch' }\n }\n if (input.emailMatches.some((account) => normalizeTangleSsoEmail(account.email) !== email)) {\n return { kind: 'reject', reason: 'email-match-mismatch' }\n }\n\n const platformMatch = input.platformMatches[0]\n const emailMatch = input.emailMatches[0]\n\n if (platformMatch) {\n if (emailMatch && emailMatch.userId !== platformMatch.userId) {\n return { kind: 'reject', reason: 'platform-id-email-conflict' }\n }\n return { kind: 'existing', userId: platformMatch.userId, matchedBy: 'platform-id' }\n }\n\n if (!emailMatch) return { kind: 'create' }\n const existingPlatformUserId = normalizedPlatformUserId(emailMatch.platformUserId)\n if (existingPlatformUserId === platformUserId) {\n return { kind: 'existing', userId: emailMatch.userId, matchedBy: 'platform-id' }\n }\n if (emailMatch.emailVerified !== true) {\n return { kind: 'reject', reason: 'unverified-email' }\n }\n\n if (existingPlatformUserId && existingPlatformUserId !== platformUserId) {\n return { kind: 'reject', reason: 'email-platform-id-conflict' }\n }\n\n // The platform proof is already verified. A verified local email row is safe\n // to link when it is unbound or already carries this same platform id.\n return { kind: 'existing', userId: emailMatch.userId, matchedBy: 'verified-email' }\n}\n\n/** Thrown by an account store when the verified SSO policy rejects a link. */\nexport class TangleSsoAccountConflictError extends Error {\n readonly reason: TangleSsoAccountConflictReason\n\n constructor(reason: TangleSsoAccountConflictReason, message = 'Tangle SSO account linking was rejected') {\n super(message)\n this.name = 'TangleSsoAccountConflictError'\n this.reason = reason\n }\n}\n\n/** Thrown by `upsertUserByEmail` when the app-local user row cannot be\n * created; the callback handler maps it to `?error=tangle_user_create_failed`.\n * Any other store error propagates. */\nexport class TangleSsoUserCreateError extends Error {\n constructor(message = 'Failed to create local user for Tangle SSO') {\n super(message)\n this.name = 'TangleSsoUserCreateError'\n }\n}\n\n/**\n * Account persistence seam. Covers both storage styles in use: link-table\n * apps (a per-user platform-link row) and session-column apps (the key on the\n * session row) — `saveTangleLink` receives both `userId` and `sessionToken`,\n * and each app persists with the key it needs. `createSession` runs first so\n * the token is always available to `saveTangleLink`.\n */\nexport interface TangleSsoAccountStore {\n /** Resolve the local account before any user, session, or link write.\n * Implementations must query every candidate by stable platform id and\n * normalized email, then apply `resolveTangleSsoAccount` (or an equivalent\n * fail-closed policy). The callback rejects `kind: 'reject'` results before\n * it calls `upsertUserByEmail`. */\n resolveAccount(input: { email: string; platformUserId: string }): Promise<TangleSsoAccountResolution>\n /** Find-or-create the app-local user selected by `resolveAccount`.\n * `tangleUserId` is the platform's stable user id — match on it first when\n * the app stores it (emails are mutable on the platform; the id is not),\n * falling back to email for first-time logins. */\n upsertUserByEmail(input: {\n email: string\n name: string | null\n tangleUserId: string\n resolution: Exclude<TangleSsoAccountResolution, { kind: 'reject' }>\n }): Promise<{ userId: string }>\n /** Create an app session row; returns the session-cookie token value. */\n createSession(input: {\n userId: string\n expiresAt: Date\n ipAddress: string | null\n userAgent: string | null\n }): Promise<{ token: string }>\n /** Persist the platform link (API key + platform identity). */\n saveTangleLink(input: {\n userId: string\n sessionToken: string\n tangleUserId: string\n email: string\n name: string | null\n apiKey: string\n planTier: string | null\n }): Promise<void>\n}\n\n/**\n * OIDC tokens are server-side credentials, not API keys. Implementations must\n * encrypt them at rest and bind them to the exact local session. Refresh and\n * disconnect must serialize updates to the same grant.\n */\nexport interface TangleOidcSsoAccountStore extends Omit<TangleSsoAccountStore, 'saveTangleLink'> {\n /** Atomically bind the grant to this exact session. If persistence partially\n * fails, `deleteSession` must remove every row and credential for it. */\n saveTangleLink(input: {\n userId: string\n sessionToken: string\n tangleUserId: string\n email: string\n name: string | null\n tokens: TangleOidcSsoTokens\n accessTokenExpiresAt: Date\n }): Promise<void>\n /** Remove an unpublished local session if callback persistence fails.\n * This must also remove any grant rows or credentials partially written by\n * a rejected `saveTangleLink`, keyed by this exact session token. */\n deleteSession(input: { sessionToken: string }): Promise<void>\n}\n\n/** Persist only the stable identity link for a first-party app. */\nexport interface TangleIdentitySsoAccountStore extends Omit<TangleSsoAccountStore, 'saveTangleLink'> {\n /** `upsertUserByEmail` may create the local user, but must not publish a new\n * platform link or update an existing user's verified-email state. The\n * callback has not yet created a session or prepared its cookie. */\n upsertUserByEmail: TangleSsoAccountStore['upsertUserByEmail']\n /** Commit the identity link and any verified-email update atomically. Do not\n * reject after committing. If the store can partially write before throwing,\n * `deleteSession` must remove only writes made for this session token. */\n saveTangleLink(input: {\n userId: string\n sessionToken: string\n tangleUserId: string\n email: string\n name: string | null\n }): Promise<void>\n /** Remove an unpublished session and any link or verification writes that a\n * rejected `saveTangleLink` made for its exact token. Preserve preexisting\n * links and other sessions. */\n deleteSession(input: { sessionToken: string }): Promise<void>\n}\n\n// ── Session cookie ──────────────────────────────────────────────────────────\n\n/** Successful-login context handed to the `setSessionCookie` seam. */\nexport interface TangleSsoSessionCookieArgs {\n /** Session token returned by `store.createSession`. */\n token: string\n /** Session expiry (now + `sessionTtlSeconds`). */\n expiresAt: Date\n /** Mirrors `sessionTtlSeconds` after defaulting. */\n ttlSeconds: number\n /** Mirrors `TangleSsoHandlerOptions.secureCookies`. */\n secure: boolean\n}\n\n/**\n * Sign a session token to better-call's signed-cookie contract — the value\n * better-auth's `getSignedCookie` verifies: `<token>.<signature>` where the\n * signature is the raw HMAC-SHA256 of the token under `secret`, encoded as\n * STANDARD base64 WITH padding (32 bytes → 44 chars ending `=`; better-call\n * rejects any other length or suffix, so url-safe/unpadded variants read back\n * as a null session). The joined value is percent-encoded once at cookie\n * serialization, matching better-call's `serializeSignedCookie` byte-exactly.\n */\nexport async function signSessionCookieValue(token: string, secret: string): Promise<string> {\n if (!secret) throw new Error('signSessionCookieValue requires a non-empty secret')\n const sig = await hmacBytes(secret, token)\n let bin = ''\n for (const byte of sig) bin += String.fromCharCode(byte)\n return `${token}.${btoa(bin)}`\n}\n\n/** Structural slice of a `betterAuth()` instance — only what cookie minting\n * reads. No better-auth import: the signing contract is implemented by\n * `signSessionCookieValue`, byte-compatible with better-auth's own\n * `makeSignature`. */\nexport interface BetterAuthSessionCookieSource {\n $context: PromiseLike<{\n secret: string\n authCookies: {\n sessionToken: {\n /** Final cookie name — better-auth decides the `__Secure-` prefix\n * (and any `advanced.cookiePrefix`) once at `betterAuth()` init. */\n name: string\n attributes: {\n secure?: boolean\n sameSite?: string\n path?: string\n httpOnly?: boolean\n domain?: string\n }\n }\n }\n }>\n}\n\n/** Define options to customize warning behavior for shadowed cookie names in authentication sessions */\nexport interface BetterAuthSessionCookieMinterOptions {\n /** Receives the shadowed-cookie-name warning (see below). Default\n * console.warn. */\n warn?: (message: string) => void\n}\n\n/**\n * Canonical `setSessionCookie` wiring for better-auth apps: mint the session\n * Set-Cookie exactly as better-auth's own login flows do — name + attributes\n * from `auth.$context.authCookies.sessionToken` (better-auth stays\n * authoritative over prefix/name/attributes) and the value signed to\n * better-call's `getSignedCookie` contract. A raw unprefixed\n * `better-auth.session_token` left by an earlier login is explicitly expired\n * so it cannot shadow the real cookie.\n *\n * Warns when the app's session cookie still has better-auth's DEFAULT name:\n * the Tangle platform (id.tangle.tools) sets a `Domain=.tangle.tools` cookie\n * under that exact name, and equal-path cookies are sent oldest-first — the\n * platform's cookie is always older (the user signs in there before the app's\n * callback runs), so the app reads the platform's token, fails its own\n * signature check, and every fresh login lands logged-out. Per-app\n * `advanced.cookiePrefix` is the fix.\n *\n * Throws on a domain-scoped session cookie for the same reason: a\n * `Domain=`-wide session cookie is exactly the shadowing footgun.\n */\nexport function createBetterAuthSessionCookieMinter(\n auth: BetterAuthSessionCookieSource,\n options: BetterAuthSessionCookieMinterOptions = {},\n): (args: TangleSsoSessionCookieArgs) => Promise<string[]> {\n const warn = options.warn ?? ((message: string) => console.warn(message))\n return async ({ token, ttlSeconds }) => {\n const ctx = await auth.$context\n if (!ctx.secret) {\n throw new Error('createBetterAuthSessionCookieMinter: auth context has no secret')\n }\n const { name, attributes } = ctx.authCookies.sessionToken\n if (attributes.domain) {\n throw new Error(\n `createBetterAuthSessionCookieMinter: refusing a domain-scoped session cookie (Domain=${attributes.domain}) — ` +\n 'a domain-wide session cookie shadows sibling apps that share the parent domain',\n )\n }\n if (name === DEFAULT_SESSION_COOKIE || name === `__Secure-${DEFAULT_SESSION_COOKIE}`) {\n warn(\n `[tangle-sso] session cookie is named \"${name}\" — better-auth's default. ` +\n 'The Tangle platform (id.tangle.tools) sets a Domain=.tangle.tools cookie under the same name, ' +\n \"and the platform's (older) cookie wins the Cookie-header order, so this app's sessions read back null. \" +\n \"Set a per-app prefix: betterAuth({ advanced: { cookiePrefix: '<app>' } }).\",\n )\n }\n const sameSite = typeof attributes.sameSite === 'string' ? attributes.sameSite : 'lax'\n const cookieOptions = {\n name,\n path: typeof attributes.path === 'string' ? attributes.path : '/',\n httpOnly: attributes.httpOnly !== false,\n sameSite: (sameSite.charAt(0).toUpperCase() + sameSite.slice(1)) as 'Lax' | 'Strict' | 'None',\n secure: Boolean(attributes.secure) || name.startsWith('__Secure-'),\n maxAgeSeconds: ttlSeconds,\n }\n const cookies = [serializeCookie(await signSessionCookieValue(token, ctx.secret), cookieOptions)]\n if (name !== DEFAULT_SESSION_COOKIE) {\n cookies.push(clearCookieHeader({ ...cookieOptions, name: DEFAULT_SESSION_COOKIE }))\n }\n return cookies\n }\n}\n\n// ── Handlers ────────────────────────────────────────────────────────────────\n\n/** Define configuration options for handling Tangle SSO authentication and session management */\nexport interface TangleSsoHandlerOptions {\n protocol?: 'legacy'\n auth: TangleSsoAuthClient\n store: TangleSsoAccountStore\n /** HMAC secret for the state cookie. */\n stateSecret: string\n /** Absolute callback URL registered with the platform. */\n callbackUrl: string\n stateCookieName: string\n /** Default 'better-auth.session_token'. Ignored when `setSessionCookie` is\n * provided. The default path prepends `__Secure-` iff `secureCookies`. */\n sessionCookieName?: string\n /** Mint the host auth framework's own session cookie(s); return complete\n * Set-Cookie header values (the handler appends them verbatim and sets no\n * session cookie itself). Supply this when the framework should stay\n * authoritative over name/prefix/signing/attributes — e.g. better-auth:\n * `auth.$context.authCookies.sessionToken` + `makeSignature`. */\n setSessionCookie?: (\n args: TangleSsoSessionCookieArgs,\n ) => readonly string[] | Promise<readonly string[]>\n /** HMAC-SHA256 secret the host auth framework verifies session cookies with\n * (better-auth: its `secret`). Required when `setSessionCookie` is absent —\n * the default cookie is minted to better-call's signed contract via\n * `signSessionCookieValue`; an unsigned or mis-signed value reads back as a\n * null session, so there is deliberately no fallback to `stateSecret`\n * (which is not guaranteed to be the auth secret). */\n sessionCookieSecret?: string\n /** Adds `Secure` to every cookie this module sets, and (default session\n * cookie only) the `__Secure-` name prefix. Must match the auth\n * framework's own secure-cookie decision (better-auth: https `baseURL` /\n * `advanced.useSecureCookies`), or it will look up a different cookie name\n * than the one set here. */\n secureCookies: boolean\n /** Default 604 800 (7 days). */\n sessionTtlSeconds?: number\n /** Default 600. Applies to both the cookie Max-Age and the signed TTL. */\n stateTtlSeconds?: number\n /** Default '/app'. */\n defaultRedirectPath?: string\n /** Default '/login'. */\n loginPath?: string\n /** Failure log hook (e.g. console.error). Default no-op. */\n log?: (message: string, error?: unknown) => void\n now?: () => number\n}\n\n/** Registered OIDC client and token store. The OIDC caller supplies the Runtime PKCE helper. */\nexport interface TangleOidcSsoHandlerOptions extends Omit<TangleSsoHandlerOptions, 'protocol' | 'auth' | 'store'> {\n protocol: 'oidc'\n auth: TangleOidcSsoAuthClient\n store: TangleOidcSsoAccountStore\n /** Pass the Runtime's `createPkcePair` helper from the OIDC-only caller. */\n createPkcePair: () => Promise<{ verifier: string; challenge: string }>\n}\n\nexport interface TangleIdentitySsoHandlerOptions extends Omit<TangleSsoHandlerOptions, 'protocol' | 'auth' | 'store'> {\n protocol: 'identity'\n auth: TangleIdentitySsoAuthClient\n store: TangleIdentitySsoAccountStore\n}\n\n/** Define handlers for SSO start and callback routes managing authentication flow and session cookies */\nexport interface TangleSsoHandlers {\n /** GET start route: mint + sign state, set the state cookie, 302 to the\n * platform authorize URL. `?redirect=` carries the post-login path. */\n start(request: Request): Promise<Response>\n /** GET callback route: verify state, exchange the code, upsert the user,\n * create the session, save the platform link, set the session cookie\n * (via the `setSessionCookie` seam, else signed to better-call's contract\n * with `sessionCookieSecret`), 302 to the saved redirect. Every failure\n * 302s to `loginPath?error=…` with the state cookie cleared. */\n callback(request: Request): Promise<Response>\n}\n\n/** Redirect targets must stay on this app's origin. A prefix check on `/`\n * and `//` is not enough: in the WHATWG parser a backslash is a path\n * separator for special schemes, so `/\\host` resolves to `https://host/`,\n * and tab or newline are stripped before parsing, so `/\\t/host` is `//host`.\n * Parse the value against a fixed origin and accept it only when that origin\n * survives; the result is the parser's normalised path, query and fragment.\n * Backslash and control characters are rejected up front as well, so the\n * decision does not rest on one parser's handling of them.\n *\n * The input staying on-origin is not enough either: dot-segment removal\n * turns `/.//host` or `/a/..//host` into the pathname `//host` with the\n * origin intact, and a browser resolves that Location off-origin. So the\n * emitted value must itself resolve on-origin and come back unchanged. */\nconst REDIRECT_REFERENCE_ORIGIN = 'https://redirect-reference.invalid'\n\nfunction sanitizeRedirectPath(value: string | null, fallback: string): string {\n if (!value || !value.startsWith('/') || /[\\\\\\u0000-\\u001f\\u007f]/.test(value)) return fallback\n const path = resolveOnReferenceOrigin(value)\n if (path === null || resolveOnReferenceOrigin(path) !== path) return fallback\n return path\n}\n\n/** `path + search + hash` of `value` resolved against the reference origin,\n * or null when the parse fails or lands on another origin. */\nfunction resolveOnReferenceOrigin(value: string): string | null {\n let url: URL\n try {\n url = new URL(value, REDIRECT_REFERENCE_ORIGIN)\n } catch {\n return null\n }\n if (url.origin !== REDIRECT_REFERENCE_ORIGIN) return null\n return `${url.pathname}${url.search}${url.hash}`\n}\n\nfunction redirectResponse(location: string, headers = new Headers()): Response {\n headers.set('Location', location)\n headers.set('Cache-Control', 'no-store')\n headers.set('Referrer-Policy', 'no-referrer')\n return new Response(null, { status: 302, headers })\n}\n\n/** Real client IP: `CF-Connecting-IP` behind Cloudflare, else the first\n * `x-forwarded-for` hop (the rest of the list is sender-controlled). */\nfunction clientIp(request: Request): string | null {\n return (\n request.headers.get('CF-Connecting-IP') ??\n request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??\n null\n )\n}\n\ninterface StateCookiePayload {\n s: string\n r: string\n v?: string\n m?: string\n}\n\nfunction parseStateCookiePayload(raw: string | null): StateCookiePayload | null {\n if (!raw || raw.length > 4096) return null\n try {\n const parsed = JSON.parse(raw) as unknown\n if (parsed === null || typeof parsed !== 'object') return null\n const { s, r, v, m } = parsed as Record<string, unknown>\n if (typeof s !== 'string' || typeof r !== 'string') return null\n return { s, r, ...(typeof v === 'string' ? { v } : {}), ...(typeof m === 'string' ? { m } : {}) }\n } catch { return null }\n}\n\nfunction stateBinding(payload: StateCookiePayload, callbackUrl: string): string {\n return JSON.stringify([payload.s, payload.r, payload.v ?? null, callbackUrl])\n}\n\n/** Create Tangle SSO handlers to manage authentication state, callbacks, and session cookies */\nexport function createTangleSsoHandlers(\n opts: TangleSsoHandlerOptions | TangleOidcSsoHandlerOptions | TangleIdentitySsoHandlerOptions,\n): TangleSsoHandlers {\n if (!opts.stateSecret) throw new Error('TangleSsoHandlerOptions.stateSecret is required')\n if (!opts.callbackUrl) throw new Error('TangleSsoHandlerOptions.callbackUrl is required')\n if (!opts.stateCookieName) throw new Error('TangleSsoHandlerOptions.stateCookieName is required')\n const callbackUrl = new URL(opts.callbackUrl)\n // Startup hardening applies to EVERY protocol. The checks were previously\n // gated on 'oidc' | 'identity', which left 'legacy' (the default when\n // `protocol` is omitted — the configuration every product shipped before\n // the typed variants existed) accepting a short stateSecret, a non-HTTPS\n // callback, credentials/query/fragment in the callback URL, and https with\n // non-Secure cookies (issue #749). The same configuration rules protect\n // every flow; only the runtime origin checks remain protocol-specific.\n if (opts.stateSecret.length < 32) throw new Error('SSO stateSecret must contain at least 32 characters')\n if (callbackUrl.username || callbackUrl.password || callbackUrl.hash || callbackUrl.search) {\n throw new Error('SSO callbackUrl must be fixed and have no credentials, query, or fragment')\n }\n const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(callbackUrl.hostname)\n if (callbackUrl.protocol !== 'https:' && !(callbackUrl.protocol === 'http:' && loopback)) {\n throw new Error('SSO requires HTTPS except on loopback')\n }\n if (callbackUrl.protocol === 'https:' && !opts.secureCookies) {\n throw new Error('SSO HTTPS callbacks require Secure cookies')\n }\n const sessionCookieName = opts.sessionCookieName ?? DEFAULT_SESSION_COOKIE\n let mintSessionCookies: (args: TangleSsoSessionCookieArgs) => Promise<readonly string[]>\n if (opts.setSessionCookie) {\n const seam = opts.setSessionCookie\n mintSessionCookies = async (args) => await seam(args)\n } else if (opts.sessionCookieSecret) {\n const secret = opts.sessionCookieSecret\n mintSessionCookies = async ({ token, secure, ttlSeconds }) => [\n serializeCookie(await signSessionCookieValue(token, secret), {\n name: secure ? `__Secure-${sessionCookieName}` : sessionCookieName,\n secure,\n maxAgeSeconds: ttlSeconds,\n }),\n ]\n } else {\n throw new Error('TangleSsoHandlerOptions requires setSessionCookie or sessionCookieSecret')\n }\n const sessionTtlSeconds = opts.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS\n const stateTtlSeconds = opts.stateTtlSeconds ?? DEFAULT_STATE_TTL_SECONDS\n if (!Number.isFinite(stateTtlSeconds) || stateTtlSeconds <= 0\n || !Number.isFinite(sessionTtlSeconds) || sessionTtlSeconds <= 0) {\n throw new Error('SSO lifetimes must be positive and finite')\n }\n const defaultRedirectPath = sanitizeRedirectPath(opts.defaultRedirectPath ?? DEFAULT_REDIRECT_PATH, DEFAULT_REDIRECT_PATH)\n const loginPath = sanitizeRedirectPath(opts.loginPath ?? DEFAULT_LOGIN_PATH, DEFAULT_LOGIN_PATH)\n const log = opts.log ?? (() => {})\n const now = opts.now ?? Date.now\n const stateConfig: SsoStateConfig = { secret: opts.stateSecret, ttlMs: stateTtlSeconds * 1000, now }\n const stateCookieOpts = { name: opts.stateCookieName, secure: opts.secureCookies }\n function loginErrorRedirect(code: string): Response {\n const headers = new Headers()\n headers.append('Set-Cookie', clearCookieHeader(stateCookieOpts))\n const target = new URL(loginPath, REDIRECT_REFERENCE_ORIGIN)\n target.searchParams.set('error', code)\n return redirectResponse(`${target.pathname}${target.search}${target.hash}`, headers)\n }\n return {\n async start(request) {\n if (request.method !== 'GET') return new Response(null, { status: 405, headers: { Allow: 'GET' } })\n const url = new URL(request.url)\n if ((opts.protocol === 'oidc' || opts.protocol === 'identity') && url.origin !== callbackUrl.origin) {\n return loginErrorRedirect('tangle_origin_mismatch')\n }\n const redirectPath = sanitizeRedirectPath(url.searchParams.get('redirect'), defaultRedirectPath)\n const state = await createSignedSsoState(stateConfig)\n const payload: StateCookiePayload = { s: state, r: redirectPath }\n let authorizationUrl: string\n if (opts.protocol === 'oidc') {\n const pkce = await opts.createPkcePair()\n payload.v = pkce.verifier\n payload.m = await hmacHex(opts.stateSecret, stateBinding(payload, opts.callbackUrl))\n authorizationUrl = opts.auth.authorizeUrl({ state, codeChallenge: pkce.challenge })\n if (new URL(authorizationUrl).searchParams.get('redirect_uri') !== opts.callbackUrl) {\n throw new Error('PlatformOidcClient.redirectUri must equal callbackUrl')\n }\n } else {\n authorizationUrl = opts.auth.authorizeUrl({ state, redirectUri: opts.callbackUrl })\n }\n const cookie = serializeCookie(JSON.stringify(payload), {\n ...stateCookieOpts,\n maxAgeSeconds: stateTtlSeconds,\n })\n const headers = new Headers()\n headers.append('Set-Cookie', cookie)\n return redirectResponse(authorizationUrl, headers)\n },\n async callback(request) {\n if (request.method !== 'GET') return new Response(null, { status: 405, headers: { Allow: 'GET' } })\n const url = new URL(request.url)\n if ((opts.protocol === 'oidc' || opts.protocol === 'identity')\n && (url.origin !== callbackUrl.origin || url.pathname !== callbackUrl.pathname)) {\n return loginErrorRedirect('tangle_origin_mismatch')\n }\n const code = url.searchParams.get('code')\n const stateFromPlatform = url.searchParams.get('state')\n if (!code || !stateFromPlatform || url.searchParams.has('error')) return loginErrorRedirect('tangle_callback_missing')\n const payload = parseStateCookiePayload(readCookieValue(request.headers.get('cookie'), opts.stateCookieName))\n if (!payload || !constantTimeEqual(payload.s, stateFromPlatform)) return loginErrorRedirect('tangle_state_mismatch')\n if (!(await verifySignedSsoState(payload.s, stateConfig))) return loginErrorRedirect('tangle_state_mismatch')\n if (opts.protocol === 'oidc' && (!payload.v || !/^[A-Za-z0-9_-]{43,128}$/.test(payload.v)\n || !payload.m || !constantTimeEqual(payload.m, await hmacHex(opts.stateSecret, stateBinding(payload, opts.callbackUrl))))) {\n return loginErrorRedirect('tangle_state_mismatch')\n }\n const tokenRequestedAt = now()\n let oidcTokens: TangleOidcSsoTokens | undefined\n let legacyExchange: TangleSsoExchangeResult | undefined\n let createdSession: string | undefined\n let committed = false\n try {\n let exchanged: { user: TangleSsoExchangeResult['user']; emailVerified: boolean }\n try {\n if (opts.protocol === 'oidc') {\n const result = await opts.auth.exchange(code, payload.v!)\n oidcTokens = result.tokens\n if (!oidcTokens.refreshToken || !Number.isFinite(oidcTokens.expiresIn) || oidcTokens.expiresIn! <= 0) {\n throw new Error('OIDC requires offline_access and a finite access-token lifetime')\n }\n exchanged = { user: result.user, emailVerified: result.user.emailVerified }\n } else if (opts.protocol === 'identity') {\n const identity = await opts.auth.exchange(code)\n if (identity.kind !== 'identity' || 'apiKey' in identity || 'keyId' in identity\n || !identity.user || typeof identity.user.id !== 'string' || !identity.user.id.trim()\n || typeof identity.user.email !== 'string' || !identity.user.email.trim()) {\n throw new Error('Identity exchange returned an invalid result')\n }\n exchanged = identity\n } else {\n legacyExchange = await opts.auth.exchange(code)\n exchanged = legacyExchange\n }\n } catch {\n log('[tangle-sso] exchange failed')\n return loginErrorRedirect('tangle_exchange_failed')\n }\n if (exchanged.emailVerified !== true) {\n log('[tangle-sso] exchange did not include a verified-email proof')\n return loginErrorRedirect('tangle_exchange_failed')\n }\n let userId: string\n try {\n const email = normalizeTangleSsoEmail(exchanged.user.email)\n const resolution = await opts.store.resolveAccount({ email, platformUserId: exchanged.user.id })\n if (resolution.kind === 'reject') throw new TangleSsoAccountConflictError(resolution.reason)\n ;({ userId } = await opts.store.upsertUserByEmail({\n email,\n name: exchanged.user.name ?? null,\n tangleUserId: exchanged.user.id,\n resolution,\n }))\n } catch (err) {\n if (err instanceof TangleSsoAccountConflictError) {\n log('[tangle-sso] account linking conflict', err.reason)\n return loginErrorRedirect('tangle_account_conflict')\n }\n if (err instanceof TangleSsoUserCreateError) return loginErrorRedirect('tangle_user_create_failed')\n throw err\n }\n const expiresAt = new Date(now() + sessionTtlSeconds * 1000)\n const { token } = await opts.store.createSession({\n userId,\n expiresAt,\n ipAddress: clientIp(request),\n userAgent: request.headers.get('user-agent'),\n })\n createdSession = token\n const link = {\n userId,\n sessionToken: token,\n tangleUserId: exchanged.user.id,\n email: normalizeTangleSsoEmail(exchanged.user.email),\n name: exchanged.user.name ?? null,\n }\n if (opts.protocol === 'oidc') {\n const headers = new Headers()\n headers.append('Set-Cookie', clearCookieHeader(stateCookieOpts))\n const sessionCookies = await mintSessionCookies({ token, expiresAt, ttlSeconds: sessionTtlSeconds, secure: opts.secureCookies })\n for (const cookie of sessionCookies) headers.append('Set-Cookie', cookie)\n const response = redirectResponse(sanitizeRedirectPath(payload.r, defaultRedirectPath), headers)\n await opts.store.saveTangleLink({\n ...link,\n tokens: oidcTokens!,\n accessTokenExpiresAt: new Date(tokenRequestedAt + oidcTokens!.expiresIn! * 1000),\n })\n committed = true\n return response\n }\n if (opts.protocol === 'identity') {\n const headers = new Headers()\n headers.append('Set-Cookie', clearCookieHeader(stateCookieOpts))\n const sessionCookies = await mintSessionCookies({ token, expiresAt, ttlSeconds: sessionTtlSeconds, secure: opts.secureCookies })\n for (const cookie of sessionCookies) headers.append('Set-Cookie', cookie)\n const response = redirectResponse(sanitizeRedirectPath(payload.r, defaultRedirectPath), headers)\n await opts.store.saveTangleLink(link)\n committed = true\n return response\n }\n await opts.store.saveTangleLink({ ...link, apiKey: legacyExchange!.apiKey, planTier: legacyExchange!.plan?.tier ?? null })\n const headers = new Headers()\n headers.append('Set-Cookie', clearCookieHeader(stateCookieOpts))\n const sessionCookies = await mintSessionCookies({ token, expiresAt, ttlSeconds: sessionTtlSeconds, secure: opts.secureCookies })\n for (const cookie of sessionCookies) headers.append('Set-Cookie', cookie)\n return redirectResponse(sanitizeRedirectPath(payload.r, defaultRedirectPath), headers)\n } catch (error) {\n if (opts.protocol !== 'oidc' && opts.protocol !== 'identity') throw error\n log('[tangle-sso] local session persistence failed')\n return loginErrorRedirect('tangle_session_failed')\n } finally {\n if ((opts.protocol === 'oidc' || opts.protocol === 'identity') && !committed) {\n if (createdSession) {\n try { await opts.store.deleteSession({ sessionToken: createdSession }) }\n catch { log('[tangle-sso] unpublished session cleanup failed') }\n }\n if (opts.protocol === 'oidc' && oidcTokens) {\n try { if (oidcTokens.refreshToken) await opts.auth.revoke(oidcTokens.refreshToken, 'refresh_token') }\n catch { log('[tangle-sso] rejected grant refresh revocation failed') }\n try { await opts.auth.revoke(oidcTokens.accessToken, 'access_token') }\n catch { log('[tangle-sso] rejected grant access revocation failed') }\n }\n }\n }\n },\n }\n}\n","/**\n * Request guards for agent-app routes: session auth (302 redirect for pages,\n * JSON 401 for APIs), admin allowlisting (404 — the route stays invisible to\n * non-admins), and the billable-balance gate (402 with a stable code).\n * Session resolution is a seam; thrown Responses follow the router convention\n * of surfacing a thrown Response as the route result.\n */\n\nimport { isTangleBillingEnforcementDisabled } from '../runtime/model'\n\n/** Define options for configuring authentication guard behavior and session retrieval */\nexport interface AuthGuardOptions<Session> {\n /** e.g. a better-auth `auth.api.getSession` wrapped by the app. */\n getSession(request: Request): Promise<Session | null | undefined>\n /** Default '/login'. */\n loginPath?: string\n}\n\n/** Resolve user authentication and session requirements for page and API requests */\nexport interface AuthGuard<Session> {\n /** Page guard — throws a 302 redirect Response to `loginPath`. */\n requireUser(request: Request): Promise<Session>\n /** API guard — throws JSON 401 `{ error: 'Unauthorized', code: 'auth.unauthenticated' }`. */\n requireApiUser(request: Request): Promise<Session>\n /** `apiResponse` selects the 401 JSON path over the redirect. */\n requireSession(request: Request, opts?: { apiResponse?: boolean }): Promise<Session>\n getOptionalSession(request: Request): Promise<Session | null>\n}\n\n/** Create an authentication guard that enforces session presence and handles unauthorized access responses */\nexport function createAuthGuard<Session>(opts: AuthGuardOptions<Session>): AuthGuard<Session> {\n const loginPath = opts.loginPath ?? '/login'\n\n async function requireSession(request: Request, o: { apiResponse?: boolean } = {}): Promise<Session> {\n const session = await opts.getSession(request)\n if (!session) {\n if (o.apiResponse) {\n throw Response.json({ error: 'Unauthorized', code: 'auth.unauthenticated' }, { status: 401 })\n }\n throw new Response(null, { status: 302, headers: { Location: loginPath } })\n }\n return session\n }\n\n return {\n requireSession,\n requireUser: (request) => requireSession(request),\n requireApiUser: (request) => requireSession(request, { apiResponse: true }),\n getOptionalSession: async (request) => (await opts.getSession(request)) ?? null,\n }\n}\n\n/** Resolve a value or an HTTP response indicating failure in a guarded operation */\nexport type GuardResolution<T> = { ok: true; value: T } | { ok: false; response: Response }\n\n/**\n * Adapt a guard that THROWS a Response (the quartet above — the router\n * convention) to the `{ok: true, value} | {ok: false, response}` resolution\n * shape the route factories take (`/chat-routes` `authorize`,\n * `/interactions` `resolveConnection`, `/chat-routes` upload `authorize`).\n * Every product wrote this try/catch by hand; it lives here once.\n */\nexport async function guardResolution<T>(run: () => Promise<T>): Promise<GuardResolution<T>> {\n try {\n return { ok: true, value: await run() }\n } catch (err) {\n if (err instanceof Response) return { ok: false, response: err }\n throw err\n }\n}\n\n/** Comma/whitespace separated → trimmed, lowercased, empties dropped. */\nexport function parseAdminEmails(raw: string | null | undefined): string[] {\n return (raw ?? '')\n .split(/[,\\s]+/)\n .map((e) => e.trim().toLowerCase())\n .filter(Boolean)\n}\n\n/** Define options to resolve user session and control access based on allowed admin emails */\nexport interface AdminGuardOptions<Session> {\n requireUser(request: Request): Promise<Session>\n emailOf(session: Session): string | null | undefined\n /** Resolved per request; an EMPTY allowlist refuses everyone. */\n allowedEmails(): string[]\n}\n\n/** Non-admins (and empty allowlists) get 404, keeping the route invisible —\n * better than a \"forbidden\" footprint that advertises its existence. */\nexport function createAdminGuard<Session>(opts: AdminGuardOptions<Session>): (request: Request) => Promise<Session> {\n return async (request) => {\n const session = await opts.requireUser(request)\n const allowed = opts.allowedEmails()\n if (allowed.length === 0) throw new Response('Not found', { status: 404 })\n const email = (opts.emailOf(session) ?? '').toLowerCase()\n if (!allowed.includes(email)) throw new Response('Not found', { status: 404 })\n return session\n }\n}\n\n/** Describe the billable balance state including overage permission and remaining USD balance */\nexport interface BillableBalanceState {\n overageAllowed: boolean\n remainingBalanceUsd: number\n}\n\n/** Define options to assert and customize billable balance enforcement behavior */\nexport interface AssertBillableBalanceOptions {\n env?: Record<string, string | undefined>\n /** App-specific enforcement override flag (e.g. 'GTM_BILLING_ENFORCEMENT'),\n * fed to `isTangleBillingEnforcementDisabled`. */\n enforcementEnvVar?: string\n /** Default 'Add balance or upgrade your plan to invoke this agent.'. */\n errorMessage?: string\n /** Merged into the 402 JSON body (e.g. `{ organizationId }`). */\n errorBody?: Record<string, unknown>\n}\n\n/**\n * Gate a billable turn: passes when enforcement is disabled (dev default),\n * the tier allows overage, or remaining balance is positive. Otherwise throws\n * a 402 Response with the stable `billing.balance_required` code so clients\n * can route to the billing screen.\n */\nexport function assertBillableBalance(state: BillableBalanceState, opts: AssertBillableBalanceOptions = {}): void {\n if (isTangleBillingEnforcementDisabled({ env: opts.env, enforcementEnvVar: opts.enforcementEnvVar })) return\n if (state.overageAllowed || state.remainingBalanceUsd > 0) return\n // errorBody first: the stable error/code contract always wins over caller extras.\n throw Response.json(\n {\n ...opts.errorBody,\n error: opts.errorMessage ?? 'Add balance or upgrade your plan to invoke this agent.',\n code: 'billing.balance_required',\n },\n { status: 402 },\n )\n}\n"],"mappings":";;;;;;;;;;AASA,IAAM,4BAA4B;AAClC,IAAM,8BAA8B,KAAK,KAAK,KAAK;AACnD,IAAM,wBAAwB;AAC9B,IAAM,qBAAqB;AAC3B,IAAM,yBAAyB;AAc/B,SAAS,UAAU,OAAuB;AACxC,QAAM,MAAM,IAAI,WAAW,KAAK;AAChC,SAAO,gBAAgB,GAAG;AAC1B,SAAO,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AACxE;AAEA,eAAe,UAAU,QAAgB,OAAoC;AAC3E,QAAM,MAAM,MAAM,OAAO,OAAO;AAAA,IAC9B;AAAA,IACA,IAAI,YAAY,EAAE,OAAO,MAAM;AAAA,IAC/B,EAAE,MAAM,QAAQ,MAAM,UAAU;AAAA,IAChC;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AACA,SAAO,IAAI,WAAW,MAAM,OAAO,OAAO,KAAK,QAAQ,KAAK,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC,CAAC;AAC9F;AAEA,eAAe,QAAQ,QAAgB,OAAgC;AACrE,SAAO,MAAM,KAAK,MAAM,UAAU,QAAQ,KAAK,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AACnG;AAEA,SAAS,kBAAkB,GAAW,GAAoB;AACxD,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,IAAK,SAAQ,EAAE,WAAW,CAAC,IAAI,EA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M,EAAE,KAAK,EAAE,YAAY,CAAC,EACjC,OAAO,OAAO;AACnB;AAYO,SAAS,iBAA0B,MAA0E;AAClH,SAAO,OAAO,YAAY;AACxB,UAAM,UAAU,MAAM,KAAK,YAAY,OAAO;AAC9C,UAAM,UAAU,KAAK,cAAc;AACnC,QAAI,QAAQ,WAAW,EAAG,OAAM,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;AACzE,UAAM,SAAS,KAAK,QAAQ,OAAO,KAAK,IAAI,YAAY;AACxD,QAAI,CAAC,QAAQ,SAAS,KAAK,EAAG,OAAM,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;AAC7E,WAAO;AAAA,EACT;AACF;AA0BO,SAAS,sBAAsB,OAA6B,OAAqC,CAAC,GAAS;AAChH,MAAI,mCAAmC,EAAE,KAAK,KAAK,KAAK,mBAAmB,KAAK,kBAAkB,CAAC,EAAG;AACtG,MAAI,MAAM,kBAAkB,MAAM,sBAAsB,EAAG;AAE3D,QAAM,SAAS;AAAA,IACb;AAAA,MACE,GAAG,KAAK;AAAA,MACR,OAAO,KAAK,gBAAgB;AAAA,MAC5B,MAAM;AAAA,IACR;AAAA,IACA,EAAE,QAAQ,IAAI;AAAA,EAChB;AACF;","names":["headers","sessionCookies"]}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseJsonObjectBody
|
|
3
|
+
} from "./chunk-3NCPXNBZ.js";
|
|
1
4
|
import {
|
|
2
5
|
interactionFromWireRequest,
|
|
3
6
|
isSafeInteractionFieldKey,
|
|
@@ -160,6 +163,7 @@ function validateInteractionAnswerBody(body) {
|
|
|
160
163
|
}
|
|
161
164
|
return { ok: true, id, outcome, data };
|
|
162
165
|
}
|
|
166
|
+
var DEFAULT_MAX_BODY_BYTES = 64 * 1024;
|
|
163
167
|
function mapInteractionRespondFailure(error, logger = console) {
|
|
164
168
|
if (error.code === "INVALID_INTERACTION_ANSWER") {
|
|
165
169
|
return Response.json(
|
|
@@ -201,9 +205,12 @@ function createInteractionAnswerRoute(options) {
|
|
|
201
205
|
return Response.json({ interactions: result.value });
|
|
202
206
|
}
|
|
203
207
|
async function answer(request) {
|
|
204
|
-
const body = await request.
|
|
205
|
-
if (
|
|
206
|
-
return Response.json(
|
|
208
|
+
const [body, bodyError] = await parseJsonObjectBody(request, { maxBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES });
|
|
209
|
+
if (bodyError) {
|
|
210
|
+
return Response.json(
|
|
211
|
+
bodyError.status === 413 ? { error: "JSON body is too large" } : { error: "Invalid JSON body" },
|
|
212
|
+
{ status: bodyError.status }
|
|
213
|
+
);
|
|
207
214
|
}
|
|
208
215
|
const validation = validateInteractionAnswerBody(body);
|
|
209
216
|
if (!validation.ok) return Response.json({ error: validation.error }, { status: 400 });
|
|
@@ -366,4 +373,4 @@ export {
|
|
|
366
373
|
mapInteractionRespondFailure,
|
|
367
374
|
createInteractionAnswerRoute
|
|
368
375
|
};
|
|
369
|
-
//# sourceMappingURL=chunk-
|
|
376
|
+
//# sourceMappingURL=chunk-TSZIYQAZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/interactions/sidecar.ts","../src/interactions/route.ts"],"sourcesContent":["/**\n * Server-side client for the sandbox sidecar's generic interaction routes\n * (`GET/POST {runtimeUrl}/agents/sessions/{sessionId}/interactions`). The\n * transport supports structural connections and older response shapes across\n * question/permission/plan interactions. Exact-run cancellation belongs to the\n * native SDK, not this session-wide compatibility surface.\n *\n * Server-only: the sidecar bearer must never reach browser code. The caller\n * supplies the connection as a structural value (runtime URL + bearer +\n * session id) — no sandbox-SDK import, so any box-resolution strategy works.\n */\n\nimport type { InteractionData, InteractionOutcome, InteractionRequestWire } from './contract'\n\n/** Describe error details including code, message, and upstream HTTP status for sidecar interactions */\nexport interface SidecarInteractionsError {\n code: string\n message: string\n /** Upstream HTTP status; 0 when the sidecar was unreachable. */\n status: number\n}\n\n/** Represent the outcome of sidecar interactions with success or error details */\nexport type SidecarInteractionsResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: SidecarInteractionsError }\n\n/** Where and how to reach one session's interaction registry. */\nexport interface SidecarInteractionsConnection {\n runtimeUrl: string\n authToken?: string\n /** The sidecar agent-session id (the chat thread's session). */\n sessionId: string\n /** Request deadline. A pending interaction means the box is up and the\n * sidecar responsive; a short default keeps a wedged runtime from stalling\n * the answering request. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global fetch. */\n fetchImpl?: typeof fetch\n}\n\nconst DEFAULT_TIMEOUT_MS = 5_000\n\n/** Strips bearer tokens / key material before an upstream message is logged\n * or surfaced. */\nfunction sanitizeUpstreamMessage(input: unknown): string {\n const message = input instanceof Error ? input.message : String(input)\n return message\n .replace(/Bearer\\s+[^\\s]+/gi, 'Bearer [redacted]')\n .replace(/\\b(?:sk|pk|tc)[_-][A-Za-z0-9_-]{8,}\\b/g, '[redacted-key]')\n}\n\n/** One transport for session controls and interaction answers. Keep the established\n * error codes per family; authentication, deadlines and decoding cannot drift. */\nasync function sidecarFetch(\n connection: SidecarInteractionsConnection,\n family: 'interactions' | 'session',\n init: { method: 'GET' | 'POST'; body?: Record<string, unknown> } = { method: 'GET' },\n): Promise<SidecarInteractionsResult<Record<string, unknown>>> {\n const session = `/agents/sessions/${encodeURIComponent(connection.sessionId)}`\n const path = family === 'interactions' ? `${session}/interactions`\n : init.method === 'POST' ? `${session}/abort` : session\n const failure = (code: string, message: unknown, status: number): SidecarInteractionsResult<never> => ({\n succeeded: false, error: { code, message: sanitizeUpstreamMessage(message), status },\n })\n let response: Response\n let parsed: unknown\n try {\n response = await (connection.fetchImpl ?? fetch)(`${connection.runtimeUrl.replace(/\\/$/, '')}${path}`, {\n method: init.method,\n headers: {\n ...(connection.authToken ? { authorization: `Bearer ${connection.authToken}` } : {}),\n ...(init.method === 'POST' ? { 'content-type': 'application/json' } : {}),\n },\n ...(init.method === 'POST' ? { body: JSON.stringify(init.body ?? {}) } : {}),\n redirect: 'manual',\n credentials: 'omit',\n signal: AbortSignal.timeout(connection.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n if (response.redirected || response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {\n await response.body?.cancel().catch(() => undefined)\n return failure('UPSTREAM_REDIRECT', 'The sidecar request refused a redirect.', response.status)\n }\n try { parsed = await response.json() } catch { parsed = undefined }\n } catch (error) {\n return family === 'interactions'\n ? failure('UPSTREAM_UNREACHABLE', error, 0)\n : failure('SIDECAR_UNREACHABLE', error, 502)\n }\n const payload = asRecord(parsed)\n if (!response.ok || payload?.success === false) {\n const error = asRecord(payload?.error)\n return failure(\n typeof error?.code === 'string' && error.code ? error.code\n : family === 'interactions' ? 'UPSTREAM_ERROR' : 'SIDECAR_SESSION_FAILED',\n typeof error?.message === 'string' && error.message ? error.message\n : `sidecar ${family} ${init.method} failed (${response.status})`,\n response.status,\n )\n }\n if (!payload) return failure('MALFORMED_RESPONSE', 'The sidecar returned no JSON object.', response.status)\n return { succeeded: true, value: payload }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown> : undefined\n}\n\n/** Outstanding (unanswered) interactions for the session — the sidecar's\n * registry is authoritative, so this is the reconnect/reload source of truth. */\nexport async function listSessionInteractions(\n connection: SidecarInteractionsConnection,\n): Promise<SidecarInteractionsResult<InteractionRequestWire[]>> {\n const result = await sidecarFetch(connection, 'interactions')\n if (!result.succeeded) return result\n const data = result.value.data as { interactions?: unknown } | undefined\n if (!Array.isArray(data?.interactions)) {\n return {\n succeeded: false,\n error: { code: 'MALFORMED_RESPONSE', message: 'sidecar list returned no interactions array', status: 200 },\n }\n }\n return { succeeded: true, value: data.interactions as InteractionRequestWire[] }\n}\n\n/** Resolves one interaction. `data` is required by the sidecar only for\n * `accepted` outcomes and is validated fail-closed against the answerSpec\n * (400 INVALID_INTERACTION_ANSWER on mismatch). */\nexport async function respondToSessionInteraction(\n connection: SidecarInteractionsConnection,\n response: { id: string; outcome: InteractionOutcome; data?: InteractionData },\n): Promise<SidecarInteractionsResult<void>> {\n const result = await sidecarFetch(connection, 'interactions', {\n method: 'POST',\n body: {\n id: response.id,\n outcome: response.outcome,\n ...(response.data ? { data: response.data } : {}),\n },\n })\n if (!result.succeeded) return result\n // An HTTP success is not an acknowledgement that the answer was applied.\n // Current runtimes return success:true; retain the supported data.ok receipt.\n if (result.value.success !== true && asRecord(result.value.data)?.ok !== true) {\n return {\n succeeded: false,\n error: { code: 'MALFORMED_RESPONSE', message: 'sidecar answer returned no acknowledgement', status: 200 },\n }\n }\n return { succeeded: true, value: undefined }\n}\n\n/**\n * A sandbox session's lifecycle as the sidecar reports it.\n *\n * Every field is optional because the sidecar's payload has grown over time and\n * an older box answers with a subset. A reader that assumes a field is present\n * mis-reads an old box as terminal; the shapes below are read defensively for\n * that reason, not out of caution about types.\n */\nexport interface SidecarSessionState {\n state?: string\n activeExecutionId?: string | null\n activeExecutionStatus?: string | null\n reconnectable?: boolean\n registryAuthority?: string | null\n terminalReason?: string | null\n lastEventAt?: string | number | null\n outstandingInteractions?: unknown[]\n}\n\nexport interface SidecarAbortResult {\n cancelled: boolean\n reason?: string\n session?: SidecarSessionState\n}\n\n/**\n * Whether a session has finished and will not produce more events.\n *\n * The three early returns are the ones that matter: a session with a live\n * execution, one the platform says is reconnectable, or one holding an\n * unanswered interaction is NOT terminal however its `state` string reads. An\n * app that treats such a session as finished abandons a turn mid-flight, or\n * leaves an agent blocked on an answer nobody will send.\n */\nexport function isTerminalSidecarState(state: {\n state?: string\n activeExecutionId?: string | null\n reconnectable?: boolean\n outstandingInteractions?: unknown[]\n}): boolean {\n if (state.activeExecutionId) return false\n if (state.reconnectable === true) return false\n if (state.outstandingInteractions && state.outstandingInteractions.length > 0) return false\n return TERMINAL_SESSION_STATES.includes(state.state ?? '') || state.reconnectable === false\n}\n\nconst TERMINAL_SESSION_STATES = ['completed', 'failed', 'aborted', 'expired', 'idle', 'terminal']\n\n/** Read the session payload defensively: newer boxes nest under `data`, and\n * the execution id appears either on the session or on `activeExecution`. */\nfunction sessionStateFromPayload(payload: Record<string, unknown>): SidecarSessionState {\n const data = (payload.data && typeof payload.data === 'object' ? payload.data : payload) as Record<string, unknown>\n const session = data.session && typeof data.session === 'object'\n ? data.session as Record<string, unknown>\n : data\n const activeExecution = data.activeExecution && typeof data.activeExecution === 'object'\n ? data.activeExecution as Record<string, unknown>\n : session.activeExecution && typeof session.activeExecution === 'object'\n ? session.activeExecution as Record<string, unknown>\n : null\n const interactions = session.outstandingInteractions ?? session.interactions\n return {\n ...(typeof session.state === 'string' ? { state: session.state } : {}),\n ...(typeof session.activeExecutionId === 'string'\n ? { activeExecutionId: session.activeExecutionId }\n : session.activeExecutionId === null ? { activeExecutionId: null } : {}),\n ...(typeof session.reconnectable === 'boolean' ? { reconnectable: session.reconnectable } : {}),\n ...(typeof session.registryAuthority === 'string'\n ? { registryAuthority: session.registryAuthority }\n : session.registryAuthority === null ? { registryAuthority: null } : {}),\n ...(typeof session.terminalReason === 'string'\n ? { terminalReason: session.terminalReason }\n : session.terminalReason === null ? { terminalReason: null } : {}),\n ...(typeof session.lastEventAt === 'string' || typeof session.lastEventAt === 'number' || session.lastEventAt === null\n ? { lastEventAt: session.lastEventAt }\n : {}),\n ...(Array.isArray(interactions) ? { outstandingInteractions: interactions } : {}),\n ...(activeExecution && typeof activeExecution.id === 'string' && typeof session.activeExecutionId !== 'string'\n ? { activeExecutionId: activeExecution.id }\n : {}),\n ...(activeExecution && typeof activeExecution.status === 'string'\n ? { activeExecutionStatus: activeExecution.status }\n : activeExecution === null && session.activeExecution === null ? { activeExecutionStatus: null } : {}),\n }\n}\n\n/** The session's current lifecycle, for reconnect and resume decisions. */\nexport async function getSessionState(\n connection: SidecarInteractionsConnection,\n): Promise<SidecarInteractionsResult<SidecarSessionState>> {\n const result = await sidecarFetch(connection, 'session')\n if (!result.succeeded) return result\n return { succeeded: true, value: sessionStateFromPayload(result.value) }\n}\n\n/**\n * Cancel a running session.\n *\n * A 404 is reported as a SUCCESSFUL no-op rather than an error: the caller's\n * intent is \"this session must not be running\", and a session the sidecar has\n * never heard of already satisfies that. Surfacing it as a failure makes every\n * cancel-after-completion look like an outage.\n */\nexport async function abortSession(\n connection: SidecarInteractionsConnection,\n): Promise<SidecarInteractionsResult<SidecarAbortResult>> {\n const result = await sidecarFetch(connection, 'session', { method: 'POST' })\n if (!result.succeeded) {\n if (result.error.status === 404) return { succeeded: true, value: { cancelled: false, reason: 'not-found' } }\n return result\n }\n const data = (result.value.data && typeof result.value.data === 'object'\n ? result.value.data\n : result.value) as Record<string, unknown>\n const reason = typeof data.reason === 'string' && data.reason.trim()\n ? data.reason.trim()\n : typeof data.noopReason === 'string' && data.noopReason.trim()\n ? data.noopReason.trim()\n : undefined\n return {\n succeeded: true,\n value: {\n cancelled: data.cancelled === true,\n ...(reason ? { reason } : {}),\n ...(data.session && typeof data.session === 'object' ? { session: sessionStateFromPayload(result.value) } : {}),\n },\n }\n}\n","/**\n * Framework-neutral interaction-answer endpoints, lifted out of the per-app\n * route files (gtm `api.chat.interactions`, legal `api.chat.interactions`,\n * tax `api.sessions.$id.interactions` — three byte-similar forks):\n *\n * list(request) — GET: outstanding asks for a live turn (reload restore)\n * answer(request) — POST `{ id, outcome, data? }`: resolve one ask\n *\n * The product supplies ONE seam, `resolveConnection`: authenticate the caller,\n * authorize the thread/session, and resolve the sidecar connection. Everything\n * behind the seam is mechanism the forks kept re-fixing:\n *\n * - body validation (safe field keys, typed values),\n * - sidecar error → client contract mapping (every \"the ask is gone\" shape\n * becomes 410 so the card flips to its expired state),\n * - duplicate resolution: after answering, every other outstanding ask with\n * the same content signature (a re-emitted duplicate) gets the same answer,\n * - unblock verification: re-list and fail loud (503 INTERACTION_STILL_PENDING)\n * when the sidecar accepted the POST but the ask is still open,\n * - best-effort list: sidecar failures return `{ interactions: [],\n * unavailable }` so a reload restore never breaks the live stream.\n *\n * Handlers return web-standard `Response`s (Workers, Node 18+, Deno) — no\n * router import anywhere.\n */\n\nimport {\n interactionFromWireRequest,\n isSafeInteractionFieldKey,\n questionInteractionContentSignature,\n type InteractionData,\n type InteractionRequestWire,\n} from './contract'\nimport {\n listSessionInteractions,\n respondToSessionInteraction,\n type SidecarInteractionsConnection,\n type SidecarInteractionsError,\n} from './sidecar'\nimport { parseJsonObjectBody } from '../web/core'\n\n// A client resolves an ask by answering (`accepted`) or refusing (`declined`).\n// Withdrawal (`cancelled`) is an agent/broker outcome delivered via the\n// `interaction.cancel` event, never a client POST, so it is not accepted here.\n/** Define possible outcomes for an interaction client as accepted or declined */\nexport type InteractionClientOutcome = 'accepted' | 'declined'\n\n/** Validate interaction answer body and return success with data or failure with error message */\nexport type InteractionAnswerBodyValidation =\n | { ok: true; id: string; outcome: InteractionClientOutcome; data?: InteractionData }\n | { ok: false; error: string }\n\n/** Validates the client POST body: `{ id, outcome, data? }` with\n * identifier-safe field keys and primitive/string-array values only. */\nexport function validateInteractionAnswerBody(body: Record<string, unknown>): InteractionAnswerBodyValidation {\n const id = typeof body.id === 'string' && body.id ? body.id : null\n if (!id) return { ok: false, error: 'Missing interaction id' }\n const outcome = body.outcome\n if (outcome !== 'accepted' && outcome !== 'declined') {\n return { ok: false, error: 'Invalid outcome: expected accepted or declined' }\n }\n if (body.data === undefined) return { ok: true, id, outcome }\n if (!body.data || typeof body.data !== 'object' || Array.isArray(body.data)) {\n return { ok: false, error: 'Invalid data: expected an object of field values' }\n }\n const data: InteractionData = {}\n for (const [key, value] of Object.entries(body.data)) {\n if (!isSafeInteractionFieldKey(key)) {\n return { ok: false, error: 'Invalid data: field names must contain only letters, numbers, underscores, or hyphens' }\n }\n const validValue =\n typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ||\n (Array.isArray(value) && value.every((item) => typeof item === 'string'))\n if (!validValue) {\n return { ok: false, error: 'Invalid data: field values must be strings, numbers, booleans, or string arrays' }\n }\n data[key] = value as InteractionData[string]\n }\n return { ok: true, id, outcome, data }\n}\n\n/** How big the POST body may be before the route refuses to parse it. An\n * answer carries an interaction id, an outcome, and field values — 64 KiB is\n * generous; refusing larger bodies before parsing bounds per-request memory\n * (issue #748). */\nconst DEFAULT_MAX_BODY_BYTES = 64 * 1024\n\n/** Provide logging methods for warnings and errors in interaction routes */\nexport type InteractionRouteLogger = Pick<Console, 'warn' | 'error'>\n\n/** Sidecar error → the client-actionable contract. Every \"the ask is gone\"\n * shape maps to 410 so the card flips to its expired state — a raw 404/409\n * must never surface. */\nexport function mapInteractionRespondFailure(\n error: SidecarInteractionsError,\n logger: InteractionRouteLogger = console,\n): Response {\n if (error.code === 'INVALID_INTERACTION_ANSWER') {\n return Response.json(\n { code: 'INVALID_INTERACTION_ANSWER', error: 'This question needs an answer from the card above — pick one of the listed options.' },\n { status: 400 },\n )\n }\n if (error.status === 404) {\n return Response.json(\n { code: 'INTERACTION_EXPIRED', error: 'This question is no longer waiting for an answer.' },\n { status: 410 },\n )\n }\n if (error.status === 501 || error.code === 'NOT_IMPLEMENTED') {\n return Response.json(\n { code: 'INTERACTIONS_UNSUPPORTED', error: 'This agent backend cannot accept answers this way.' },\n { status: 501 },\n )\n }\n logger.error('[interactions] respond failed:', error)\n return Response.json(\n { code: 'INTERACTION_UPSTREAM_FAILED', error: 'Could not reach the agent. Try again.' },\n { status: 503 },\n )\n}\n\n/** The product seam's verdict for one request. `response` short-circuits with\n * a product-authored Response (401/404/429…); `unavailable` means the caller\n * is fine but the sandbox runtime is not reachable — the factory shapes that\n * per intent (empty list for `list`, 503 for `answer`). */\nexport type InteractionConnectionResolution =\n | { ok: true; connection: SidecarInteractionsConnection }\n | { ok: false; response: Response }\n | { ok: false; unavailable: string }\n\n/** Define arguments required to resolve interaction connections based on request and intent */\nexport interface ResolveInteractionConnectionArgs {\n request: Request\n intent: 'list' | 'answer'\n /** The parsed, validated POST body (answer intent only) so the resolver can\n * read product routing fields (workspaceId/threadId) without re-parsing. */\n body?: Record<string, unknown>\n}\n\n/** Describe the arguments provided before processing an interaction answer including request, body, and connection details */\nexport interface BeforeInteractionAnswerArgs {\n request: Request\n /** Original parsed body, including product routing fields. */\n body: Record<string, unknown>\n /** Shared validation result; products never need to parse the answer again. */\n answer: Extract<InteractionAnswerBodyValidation, { ok: true }>\n connection: SidecarInteractionsConnection\n /** The route's single authoritative pre-answer sidecar snapshot. */\n outstanding: InteractionRequestWire[]\n answeredRequest?: InteractionRequestWire\n /** Content-identical questions that the shared route will also answer. */\n duplicateRequests: InteractionRequestWire[]\n}\n\n/** Define arguments for durable interaction routes including a stable caller-created attempt key */\nexport interface DurableInteractionRouteArgs extends BeforeInteractionAnswerArgs {\n /** Caller-created opaque identifier, stable across an ambiguous retry. */\n attemptKey: string\n}\n\n/** Crash-recoverable persistence lifecycle for the answer route. The product\n * binds this structural port to its OWN durable store — agent-app ships no\n * implementation (the `/durable-chat` module that used to provide one was\n * removed in 0.44.0 after nine repos produced zero imports of it). Existing\n * `beforeAnswer` behavior remains independent and unchanged. */\nexport interface DurableInteractionRoutePersistence<TPrepared = unknown> {\n guarantee: 'reconciled' | 'best-effort'\n prepare(args: DurableInteractionRouteArgs): TPrepared | Promise<TPrepared>\n /** Resolve an ambiguous retry (for example, the sidecar says the ask is\n * already gone). Only `settled:true` permits the route to report success. */\n reconcile(args: DurableInteractionRouteArgs & { prepared: TPrepared }):\n | { settled: boolean }\n | Promise<{ settled: boolean }>\n /** Record the authority acknowledgement before terminal projection. */\n acknowledge(args: DurableInteractionRouteArgs & {\n prepared: TPrepared\n duplicateIds: string[]\n }): void | Promise<void>\n /** Idempotently materialize terminal status and accepted values. */\n finalize(args: DurableInteractionRouteArgs & {\n prepared: TPrepared\n duplicateIds: string[]\n }): void | Promise<void>\n fail?(args: DurableInteractionRouteArgs & { prepared: TPrepared; error: unknown }): void | Promise<void>\n}\n\n/** Define options to authenticate, authorize, and manage persistence for interaction answer routes */\nexport interface InteractionAnswerRouteOptions {\n /** Authenticate + authorize the caller and resolve the sidecar connection.\n * This is the only product-supplied step: session auth, workspace/thread\n * access, rate limiting, and box resolution all live here. */\n resolveConnection: (args: ResolveInteractionConnectionArgs) => Promise<InteractionConnectionResolution>\n /** Product persistence seam that runs before the answer can unblock and\n * finalize the agent turn. A throw aborts the request before any answer POST. */\n beforeAnswer?: (args: BeforeInteractionAnswerArgs) => void | Promise<void>\n /** Additive crash-recoverable settlement. When configured, POST requires an\n * `attemptKey`; accepted values are finalized only after sidecar ack. */\n durable?: DurableInteractionRoutePersistence\n /** Request-body byte cap before parsing. Default 64 KiB. */\n maxBodyBytes?: number\n logger?: InteractionRouteLogger\n}\n\n/** Define routes to list outstanding interactions and resolve answers for live turns */\nexport interface InteractionAnswerRoute {\n /** GET — outstanding interactions for a live turn. Failures return an empty\n * list with an explicit `unavailable` code: the caller is a best-effort\n * reload restore, and the live/replayed stream must stay untouched when the\n * sidecar cannot answer. */\n list: (request: Request) => Promise<Response>\n /** POST `{ id, outcome, data?, ...productFields }` — resolve one ask, answer\n * content-identical duplicates the same way, then re-list to prove the run\n * actually unblocked. */\n answer: (request: Request) => Promise<Response>\n}\n\n/** Create an interaction answer route that handles listing and resolving interaction requests */\nexport function createInteractionAnswerRoute(options: InteractionAnswerRouteOptions): InteractionAnswerRoute {\n const logger = options.logger ?? console\n\n async function list(request: Request): Promise<Response> {\n const resolution = await options.resolveConnection({ request, intent: 'list' })\n if (!resolution.ok) {\n if ('response' in resolution) return resolution.response\n return Response.json({ interactions: [], unavailable: resolution.unavailable })\n }\n const result = await listSessionInteractions(resolution.connection)\n if (!result.succeeded) {\n logger.warn('[interactions] list failed:', result.error)\n return Response.json({ interactions: [], unavailable: result.error.code })\n }\n return Response.json({ interactions: result.value })\n }\n\n async function answer(request: Request): Promise<Response> {\n // Bounded body parse (streaming cap, content-length precheck, 413) — the\n // same primitive every other route boundary in the package uses.\n const [body, bodyError] = await parseJsonObjectBody(request, { maxBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES })\n if (bodyError) {\n return Response.json(\n bodyError.status === 413\n ? { error: 'JSON body is too large' }\n : { error: 'Invalid JSON body' },\n { status: bodyError.status },\n )\n }\n const validation = validateInteractionAnswerBody(body)\n if (!validation.ok) return Response.json({ error: validation.error }, { status: 400 })\n const attemptKey = typeof body.attemptKey === 'string' ? body.attemptKey.trim() : ''\n if (options.durable && !attemptKey) {\n return Response.json({ error: 'Missing attemptKey for durable interaction answer' }, { status: 400 })\n }\n\n const resolution = await options.resolveConnection({ request, intent: 'answer', body })\n if (!resolution.ok) {\n if ('response' in resolution) return resolution.response\n return mapInteractionRespondFailure(\n { code: resolution.unavailable, message: 'sandbox runtime unavailable', status: 0 },\n logger,\n )\n }\n const connection = resolution.connection\n const answerPayload = {\n outcome: validation.outcome,\n ...(validation.data ? { data: validation.data } : {}),\n }\n\n // Snapshot the answered ask's content signature BEFORE resolving it, so any\n // content-identical duplicates still outstanding afterwards (the agent may\n // have re-emitted the same question N times) can be answered the same way.\n const before = await listSessionInteractions(connection)\n if (!before.succeeded && (options.beforeAnswer || options.durable)) {\n return mapInteractionRespondFailure(before.error, logger)\n }\n const answeredRequest = before.succeeded ? before.value.find((item) => item.id === validation.id) : undefined\n if (options.beforeAnswer && !options.durable && !answeredRequest) {\n return mapInteractionRespondFailure(\n { code: 'NOT_FOUND', message: 'interaction not found', status: 404 },\n logger,\n )\n }\n const answeredSignature = answeredRequest\n ? questionInteractionContentSignature(interactionFromWireRequest(answeredRequest))\n : null\n const duplicateRequests = before.succeeded && answeredSignature\n ? before.value.filter((item) => item.id !== validation.id && (\n questionInteractionContentSignature(interactionFromWireRequest(item)) === answeredSignature\n ))\n : []\n\n const lifecycleArgs: BeforeInteractionAnswerArgs = {\n request,\n body,\n answer: validation,\n connection,\n outstanding: before.succeeded ? before.value : [],\n ...(answeredRequest ? { answeredRequest } : {}),\n duplicateRequests,\n }\n\n if (options.beforeAnswer && answeredRequest) {\n try {\n await options.beforeAnswer(lifecycleArgs)\n } catch (error) {\n logger.error('[interactions] beforeAnswer failed:', error)\n return Response.json(\n { code: 'INTERACTION_BEFORE_ANSWER_FAILED', error: 'Could not save the answer. Try again.' },\n { status: 503 },\n )\n }\n }\n\n let prepared: unknown\n const durableArgs = options.durable\n ? { ...lifecycleArgs, attemptKey }\n : null\n if (options.durable && durableArgs) {\n try {\n prepared = await options.durable.prepare(durableArgs)\n } catch (error) {\n logger.error('[interactions] durable prepare failed:', error)\n return Response.json(\n { code: 'INTERACTION_PREPARE_FAILED', error: 'Could not prepare the answer. Try again.' },\n { status: 503 },\n )\n }\n if (!answeredRequest) {\n let reconciled: { settled: boolean }\n try {\n reconciled = await options.durable.reconcile({ ...durableArgs, prepared })\n } catch (error) {\n logger.error('[interactions] durable reconcile failed:', error)\n reconciled = { settled: false }\n }\n if (reconciled.settled) return Response.json({ ok: true, idempotent: true })\n return Response.json(\n { code: 'INTERACTION_RECONCILIATION_PENDING', error: 'The answer status is still being checked. Retry with the same attempt.' },\n { status: 503 },\n )\n }\n }\n\n const result = await respondToSessionInteraction(connection, { id: validation.id, ...answerPayload })\n if (!result.succeeded) {\n if (options.durable && durableArgs) {\n let reconciled: { settled: boolean }\n try {\n reconciled = await options.durable.reconcile({ ...durableArgs, prepared })\n } catch {\n reconciled = { settled: false }\n }\n if (reconciled.settled) return Response.json({ ok: true, idempotent: true })\n if (result.error.status === 404) {\n return Response.json(\n { code: 'INTERACTION_RECONCILIATION_PENDING', error: 'The answer status is still being checked. Retry with the same attempt.' },\n { status: 503 },\n )\n }\n try {\n await options.durable.fail?.({ ...durableArgs, prepared, error: result.error })\n } catch {\n // The upstream failure remains authoritative; a persistence cleanup\n // failure must not replace its client-facing mapping.\n }\n }\n return mapInteractionRespondFailure(result.error, logger)\n }\n\n let remaining = await listSessionInteractions(connection)\n const acknowledgedDuplicateIds: string[] = []\n if (remaining.succeeded && answeredSignature) {\n const remainingDuplicates = remaining.value.filter((item) => {\n if (item.id === validation.id) return false\n return questionInteractionContentSignature(interactionFromWireRequest(item)) === answeredSignature\n })\n for (const duplicate of remainingDuplicates) {\n const duplicateResult = await respondToSessionInteraction(connection, { id: duplicate.id, ...answerPayload })\n if (!duplicateResult.succeeded) break\n acknowledgedDuplicateIds.push(duplicate.id)\n }\n if (remainingDuplicates.length > 0) remaining = await listSessionInteractions(connection)\n }\n\n // Prove the run actually unblocked: neither the answered id nor any\n // content-duplicate may still be outstanding. If one is, the sidecar\n // accepted the POST but did not release the run — report it rather than\n // tell the user it was answered.\n if (remaining.succeeded && remaining.value.some((item) => item.id === validation.id || (\n answeredSignature && questionInteractionContentSignature(interactionFromWireRequest(item)) === answeredSignature\n ))) {\n logger.error('[interactions] respond returned ok but interaction is still pending:', {\n sessionId: connection.sessionId,\n interactionId: validation.id,\n })\n return Response.json(\n { code: 'INTERACTION_STILL_PENDING', error: 'The agent did not accept the answer. Try answering again.' },\n { status: 503 },\n )\n }\n\n if (options.durable && durableArgs) {\n try {\n await options.durable.acknowledge({\n ...durableArgs,\n prepared,\n duplicateIds: acknowledgedDuplicateIds,\n })\n await options.durable.finalize({\n ...durableArgs,\n prepared,\n duplicateIds: acknowledgedDuplicateIds,\n })\n } catch (error) {\n logger.error('[interactions] durable finalize failed:', error)\n return Response.json(\n { code: 'INTERACTION_FINALIZE_FAILED', error: 'The answer was accepted but is still being saved. Retry to reconcile it.' },\n { status: 503 },\n )\n }\n }\n\n return Response.json({ ok: true })\n }\n\n return { list, answer }\n}\n"],"mappings":";;;;;;;;;;AAyCA,IAAM,qBAAqB;AAI3B,SAAS,wBAAwB,OAAwB;AACvD,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,SAAO,QACJ,QAAQ,qBAAqB,mBAAmB,EAChD,QAAQ,0CAA0C,gBAAgB;AACvE;AAIA,eAAe,aACb,YACA,QACA,OAAmE,EAAE,QAAQ,MAAM,GACtB;AAC7D,QAAM,UAAU,oBAAoB,mBAAmB,WAAW,SAAS,CAAC;AAC5E,QAAM,OAAO,WAAW,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+B,OAAO,2EAA2E;AAAA,UACzH,EAAE,QAAQ,IAAI;AAAA,QAChB;AAAA,MACF;AAAA,IACF;AAEA,WAAO,SAAS,KAAK,EAAE,IAAI,KAAK,CAAC;AAAA,EACnC;AAEA,SAAO,EAAE,MAAM,OAAO;AACxB;","names":[]}
|
package/dist/crypto/index.js
CHANGED
|
@@ -7,7 +7,9 @@ import {
|
|
|
7
7
|
mapInteractionRespondFailure,
|
|
8
8
|
respondToSessionInteraction,
|
|
9
9
|
validateInteractionAnswerBody
|
|
10
|
-
} from "../chunk-
|
|
10
|
+
} from "../chunk-TSZIYQAZ.js";
|
|
11
|
+
import "../chunk-3NCPXNBZ.js";
|
|
12
|
+
import "../chunk-TXD5HXLE.js";
|
|
11
13
|
import {
|
|
12
14
|
INTERACTION_CANCEL_EVENT,
|
|
13
15
|
INTERACTION_EVENT,
|
|
@@ -133,6 +133,8 @@ export interface InteractionAnswerRouteOptions {
|
|
|
133
133
|
/** Additive crash-recoverable settlement. When configured, POST requires an
|
|
134
134
|
* `attemptKey`; accepted values are finalized only after sidecar ack. */
|
|
135
135
|
durable?: DurableInteractionRoutePersistence;
|
|
136
|
+
/** Request-body byte cap before parsing. Default 64 KiB. */
|
|
137
|
+
maxBodyBytes?: number;
|
|
136
138
|
logger?: InteractionRouteLogger;
|
|
137
139
|
}
|
|
138
140
|
/** Define routes to list outstanding interactions and resolve answers for live turns */
|
package/dist/openui/index.js
CHANGED
|
@@ -2,6 +2,10 @@ import {
|
|
|
2
2
|
OPENUI_INPUT_KINDS,
|
|
3
3
|
OPENUI_INTERACTIVE_AUTHORING_GUIDE
|
|
4
4
|
} from "../chunk-UGWQLQDS.js";
|
|
5
|
+
import {
|
|
6
|
+
parseJsonObjectBody
|
|
7
|
+
} from "../chunk-3NCPXNBZ.js";
|
|
8
|
+
import "../chunk-TXD5HXLE.js";
|
|
5
9
|
|
|
6
10
|
// src/openui/segments.ts
|
|
7
11
|
var FENCE = /```openui\s*\n([\s\S]*?)```/g;
|
|
@@ -258,6 +262,7 @@ function describeOpenUIAction(submission) {
|
|
|
258
262
|
}
|
|
259
263
|
|
|
260
264
|
// src/openui/route.ts
|
|
265
|
+
var DEFAULT_MAX_BODY_BYTES = 64 * 1024;
|
|
261
266
|
function failure(code, error, status, extra) {
|
|
262
267
|
return Response.json({ ok: false, code, error, ...extra ?? {} }, { status });
|
|
263
268
|
}
|
|
@@ -265,9 +270,9 @@ function createOpenUIActionRoute(options) {
|
|
|
265
270
|
const logger = options.logger ?? console;
|
|
266
271
|
async function handle(request) {
|
|
267
272
|
if (request.method !== "POST") return failure("OPENUI_METHOD_NOT_ALLOWED", "Method not allowed", 405);
|
|
268
|
-
const body = await request.
|
|
269
|
-
if (
|
|
270
|
-
return failure("OPENUI_BODY_INVALID", "Invalid JSON body", 400);
|
|
273
|
+
const [body, bodyError] = await parseJsonObjectBody(request, { maxBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES });
|
|
274
|
+
if (bodyError) {
|
|
275
|
+
return bodyError.status === 413 ? failure("OPENUI_BODY_TOO_LARGE", "JSON body is too large", 413) : failure("OPENUI_BODY_INVALID", "Invalid JSON body", 400);
|
|
271
276
|
}
|
|
272
277
|
const parsed = validateOpenUIActionBody(body);
|
|
273
278
|
if (!parsed.ok) return failure(parsed.code, parsed.error, 400);
|
package/dist/openui/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openui/segments.ts","../../src/openui/values.ts","../../src/openui/action.ts","../../src/openui/route.ts"],"sourcesContent":["/**\n * Splitting an assistant message into prose and agent-authored UI.\n *\n * An agent emits a page by fencing it as ```` ```openui ```` in its reply (the\n * inline path) or by calling `render_ui` (the persisted-artifact path). Every\n * product that renders the inline path had forked the same scanner into its own\n * chat-message body; this is that scanner, once, with no React and no renderer\n * import — the node union stays owned by `@tangle-network/ui`'s `./openui`.\n */\n\n/**\n * The narrowest thing a host can assert about a parsed node: it names a type.\n * A renderer's node union satisfies this, so\n * `parseOpenUISegments<OpenUIComponentNode>(text)` hands typed nodes straight\n * to the renderer with no cast at the call site.\n */\nexport interface OpenUINode {\n type: string\n id?: string\n}\n\n/** One piece of an assistant message: prose, or a page to render. */\nexport type OpenUISegment<TNode extends OpenUINode = OpenUINode> =\n | { type: 'markdown'; text: string }\n | { type: 'openui'; nodes: TNode[] }\n\nconst FENCE = /```openui\\s*\\n([\\s\\S]*?)```/g\n\nfunction isNodeLike(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { type?: unknown }).type === 'string'\n )\n}\n\n/** Every array entry (or the single object) that names a node type. */\nfunction nodesFrom(parsed: unknown): unknown[] {\n const candidates = Array.isArray(parsed) ? parsed : [parsed]\n return candidates.filter(isNodeLike)\n}\n\nfunction pushText<TNode extends OpenUINode>(segments: Array<OpenUISegment<TNode>>, text: string): void {\n const trimmed = text.trim()\n if (trimmed) segments.push({ type: 'markdown', text: trimmed })\n}\n\n/**\n * Split message content into markdown and OpenUI segments, in source order.\n *\n * A fence whose body is not JSON, or whose JSON carries no node at all, is\n * returned as a fenced `json` markdown segment rather than an empty page: the\n * content is still streaming, or the agent wrote something malformed, and both\n * cases are better shown than swallowed into a blank card.\n *\n * The type argument is the caller's assertion about the node union it will\n * render; this function checks only that each node names a `type`, and the\n * renderer rejects types it does not know.\n */\nexport function parseOpenUISegments<TNode extends OpenUINode = OpenUINode>(\n content: string,\n): Array<OpenUISegment<TNode>> {\n const segments: Array<OpenUISegment<TNode>> = []\n let lastIndex = 0\n\n // `FENCE` carries the `g` flag and therefore `lastIndex` state; reset it so\n // concurrent/repeat calls cannot resume mid-string from a previous scan.\n FENCE.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = FENCE.exec(content)) !== null) {\n if (match.index > lastIndex) pushText(segments, content.slice(lastIndex, match.index))\n const body = match[1] ?? ''\n let nodes: unknown[] = []\n try {\n nodes = nodesFrom(JSON.parse(body) as unknown)\n } catch {\n nodes = []\n }\n if (nodes.length > 0) segments.push({ type: 'openui', nodes: nodes as TNode[] })\n else pushText(segments, `\\`\\`\\`json\\n${body}\\`\\`\\``)\n lastIndex = match.index + match[0].length\n }\n\n if (lastIndex < content.length) pushText(segments, content.slice(lastIndex))\n if (segments.length === 0 && content.trim()) segments.push({ type: 'markdown', text: content })\n return segments\n}\n\n/** Whether a message carries any agent-authored page at all. */\nexport function hasOpenUISegment(content: string): boolean {\n return parseOpenUISegments(content).some((segment) => segment.type === 'openui')\n}\n\n/** A page read back out of the vault, and its title when one was stored. */\nexport interface OpenUIArtifact<TNode extends OpenUINode = OpenUINode> {\n title?: string\n nodes: TNode[]\n}\n\n/** Why a stored page could not be read. */\nexport interface OpenUIArtifactError {\n code: 'artifact_not_json' | 'artifact_no_nodes'\n message: string\n}\n\n/** Reading a stored page either produces nodes or says why it did not. */\nexport type OpenUIArtifactResult<TNode extends OpenUINode = OpenUINode> =\n | { succeeded: true; value: OpenUIArtifact<TNode> }\n | { succeeded: false; error: OpenUIArtifactError }\n\n/**\n * Read a `render_ui` artifact back out of the vault.\n *\n * Two shapes are in the wild and a product cannot tell them apart from the\n * path: the bare node tree that `preset-cloudflare`'s handler writes\n * (`JSON.stringify(args.schema)`), and the `{ title, schema }` envelope some\n * products write themselves. Reading only one of them renders an empty panel\n * for the other, with nothing on screen to say why — so this reads both and\n * fails loud when it is neither.\n */\nexport function parseOpenUIArtifact<TNode extends OpenUINode = OpenUINode>(\n content: string,\n): OpenUIArtifactResult<TNode> {\n let parsed: unknown\n try {\n parsed = JSON.parse(content) as unknown\n } catch {\n return { succeeded: false, error: { code: 'artifact_not_json', message: 'Stored page is not JSON.' } }\n }\n\n const envelope =\n parsed && typeof parsed === 'object' && !Array.isArray(parsed) && 'schema' in parsed\n ? (parsed as { schema: unknown; title?: unknown })\n : null\n const nodes = nodesFrom(envelope ? envelope.schema : parsed)\n if (nodes.length === 0) {\n return { succeeded: false, error: { code: 'artifact_no_nodes', message: 'Stored page carries no nodes.' } }\n }\n const title = envelope && typeof envelope.title === 'string' ? envelope.title : undefined\n return { succeeded: true, value: { nodes: nodes as TNode[], ...(title ? { title } : {}) } }\n}\n","/**\n * The value half of an interactive OpenUI page: what a field holds, and whether\n * a submitted set of field values matches the form the agent authored.\n *\n * The NODE vocabulary (which fields exist, how they render) has one owner —\n * `@tangle-network/ui`'s `./openui` entry. This module does not restate it. It\n * declares the narrowest STRUCTURAL port a host needs to check a submission:\n * the field's id, its kind, and the constraints that make a value legal. A\n * renderer's richer node type satisfies this port by assignment, so the two\n * packages stay in step without either importing the other.\n */\n\n/** A value one OpenUI field can hold. `string[]` is a multi-select. */\nexport type OpenUIValue = string | number | boolean | string[]\n\n/** Submitted field values, keyed by field id. */\nexport type OpenUIFormValues = Record<string, OpenUIValue>\n\n/**\n * Field ids the host will accept: identifier-safe, and never a key that would\n * reach `Object.prototype`. A submission arrives from a browser and is used to\n * index an object, so this is a boundary check, not a style rule.\n */\nexport function isSafeOpenUIFieldId(id: string): boolean {\n return /^[A-Za-z0-9_-]+$/.test(id) && id !== '__proto__' && id !== 'constructor' && id !== 'prototype'\n}\n\n/** The input kinds a form field can be. */\nexport type OpenUIFieldKind = 'text' | 'number' | 'currency' | 'select' | 'checkbox' | 'slider'\n\nconst FIELD_KINDS: ReadonlySet<string> = new Set<OpenUIFieldKind>([\n 'text',\n 'number',\n 'currency',\n 'select',\n 'checkbox',\n 'slider',\n])\n\n/** Whether a string names an input kind this contract knows. */\nexport function isOpenUIFieldKind(kind: string): kind is OpenUIFieldKind {\n return FIELD_KINDS.has(kind)\n}\n\n/**\n * One field, reduced to what a value check needs. A renderer node carrying\n * labels, placeholders, and layout is assignable to this — the extra\n * presentation properties are simply not read here.\n */\nexport interface OpenUIFieldSpec {\n id: string\n kind: OpenUIFieldKind\n required?: boolean\n /** `number` / `currency` / `slider` bounds, inclusive. */\n min?: number\n max?: number\n /** Increment `number` / `currency` / `slider` values must land on, measured from `min ?? 0`. */\n step?: number\n /** Longest accepted `text` value. */\n maxLength?: number\n /** Accepted `select` values. */\n options?: ReadonlyArray<{ value: string }>\n /** A `select` that accepts more than one option; its value is a `string[]`. */\n multiple?: boolean\n}\n\n/** A form the host can check a submission against. */\nexport interface OpenUIFormSpec {\n id: string\n fields: readonly OpenUIFieldSpec[]\n}\n\n/** Why one field's value was rejected. */\nexport type OpenUIFieldIssueCode =\n | 'required'\n | 'type'\n | 'range'\n | 'step'\n | 'option'\n | 'length'\n | 'unknown_field'\n | 'duplicate_field'\n | 'unsafe_field_id'\n\n/** One rejected field, named so a card can mark exactly that input. */\nexport interface OpenUIFieldIssue {\n fieldId: string\n code: OpenUIFieldIssueCode\n message: string\n}\n\n/** The outcome of checking a submission against a form. */\nexport type OpenUIFormValidation =\n | { ok: true; values: OpenUIFormValues }\n | { ok: false; issues: OpenUIFieldIssue[] }\n\nfunction issue(fieldId: string, code: OpenUIFieldIssueCode, message: string): OpenUIFieldIssue {\n return { fieldId, code, message }\n}\n\n/** Floating-point step arithmetic: 0.1 increments must not reject 0.3. */\nconst STEP_EPSILON = 1e-9\n\nfunction checkNumeric(field: OpenUIFieldSpec, value: number): OpenUIFieldIssue | null {\n if (!Number.isFinite(value)) return issue(field.id, 'type', `${field.id} must be a finite number`)\n if (field.min !== undefined && value < field.min) {\n return issue(field.id, 'range', `${field.id} must be at least ${field.min}`)\n }\n if (field.max !== undefined && value > field.max) {\n return issue(field.id, 'range', `${field.id} must be at most ${field.max}`)\n }\n if (field.step !== undefined && field.step > 0) {\n const offset = (value - (field.min ?? 0)) / field.step\n if (Math.abs(offset - Math.round(offset)) > STEP_EPSILON) {\n return issue(field.id, 'step', `${field.id} must move in steps of ${field.step}`)\n }\n }\n return null\n}\n\nfunction isEmpty(value: OpenUIValue): boolean {\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\nfunction checkField(field: OpenUIFieldSpec, value: OpenUIValue | undefined): OpenUIFieldIssue | null {\n if (value === undefined || isEmpty(value)) {\n // A checkbox is never \"empty\" — `false` is an answer — so only a genuinely\n // absent value can fail the required check for one.\n if (field.required) return issue(field.id, 'required', `${field.id} is required`)\n return null\n }\n\n switch (field.kind) {\n case 'text': {\n if (typeof value !== 'string') return issue(field.id, 'type', `${field.id} must be text`)\n if (field.maxLength !== undefined && value.length > field.maxLength) {\n return issue(field.id, 'length', `${field.id} must be at most ${field.maxLength} characters`)\n }\n return null\n }\n case 'number':\n case 'currency':\n case 'slider': {\n if (typeof value !== 'number') return issue(field.id, 'type', `${field.id} must be a number`)\n return checkNumeric(field, value)\n }\n case 'checkbox': {\n if (typeof value !== 'boolean') return issue(field.id, 'type', `${field.id} must be true or false`)\n return null\n }\n case 'select': {\n const allowed = field.options ? new Set(field.options.map((option) => option.value)) : null\n if (field.multiple) {\n if (!Array.isArray(value)) return issue(field.id, 'type', `${field.id} must be a list of choices`)\n if (allowed) {\n const rejected = value.find((entry) => !allowed.has(entry))\n if (rejected !== undefined) {\n return issue(field.id, 'option', `${field.id} does not offer \"${rejected}\"`)\n }\n }\n return null\n }\n if (typeof value !== 'string') return issue(field.id, 'type', `${field.id} must be a single choice`)\n if (allowed && !allowed.has(value)) return issue(field.id, 'option', `${field.id} does not offer \"${value}\"`)\n return null\n }\n }\n}\n\n/**\n * Check submitted values against the form the agent authored.\n *\n * Fails loud on both sides of the shape: a value the form never declared is an\n * error (`unknown_field`), not a silently ignored extra, because a host that\n * drops it would act on a form different from the one the user filled in. A\n * `required` field with no value is an error even when the caller simply never\n * sent the key.\n *\n * On success the returned `values` contain only declared fields, in the form's\n * own field order — the object a handler should act on.\n */\nexport function validateOpenUIFormValues(spec: OpenUIFormSpec, values: OpenUIFormValues): OpenUIFormValidation {\n const issues: OpenUIFieldIssue[] = []\n const seen = new Set<string>()\n for (const field of spec.fields) {\n if (!isSafeOpenUIFieldId(field.id)) {\n issues.push(issue(field.id, 'unsafe_field_id', `${field.id} is not a usable field id`))\n continue\n }\n if (seen.has(field.id)) {\n issues.push(issue(field.id, 'duplicate_field', `${field.id} is declared more than once`))\n continue\n }\n seen.add(field.id)\n }\n\n for (const key of Object.keys(values)) {\n if (!seen.has(key)) issues.push(issue(key, 'unknown_field', `${key} is not a field on this form`))\n }\n\n const accepted: OpenUIFormValues = {}\n for (const field of spec.fields) {\n if (!seen.has(field.id)) continue\n const value = Object.prototype.hasOwnProperty.call(values, field.id) ? values[field.id] : undefined\n const problem = checkField(field, value)\n if (problem) {\n issues.push(problem)\n continue\n }\n if (value !== undefined) accepted[field.id] = value\n }\n\n if (issues.length > 0) return { ok: false, issues }\n return { ok: true, values: accepted }\n}\n","/**\n * What travels when a user presses a button on a page the agent authored.\n *\n * The submission is a plain REST body, not a chat turn. That is the entire\n * point of this module: pressing \"Recalculate\" on an agent-authored form must\n * cost the same as pressing a button on a hand-built screen — one product route\n * call, no model tokens, no sandbox wake-up. The wire shape here is therefore\n * deliberately small and self-contained: an action id, the form it belongs to,\n * that form's current values, and enough addressing for the product to find the\n * page. Nothing in it references a session, a turn, or a run.\n */\n\nimport { isSafeOpenUIFieldId, type OpenUIFormValues, type OpenUIValue } from './values'\n\n/** What the browser POSTs when an action fires. */\nexport interface OpenUIActionSubmission {\n /** The action's stable id, as authored on the page. */\n actionId: string\n /** The form whose values are attached, when the action sits in one. */\n formId?: string\n /** Current values of that form, keyed by field id. Empty for a bare action. */\n values: OpenUIFormValues\n /** The node the action was rendered on, when the page carries several. */\n nodeId?: string\n /** Vault path of the persisted `render_ui` artifact this page came from. */\n artifactPath?: string\n}\n\n/** Parsed submission, or the reason the body was refused. */\nexport type OpenUIActionBodyValidation =\n | { ok: true; submission: OpenUIActionSubmission }\n | { ok: false; code: OpenUIActionBodyErrorCode; error: string }\n\n/** Why a submission body was refused before any handler ran. */\nexport type OpenUIActionBodyErrorCode =\n | 'OPENUI_ACTION_ID_MISSING'\n | 'OPENUI_ACTION_ID_INVALID'\n | 'OPENUI_FORM_ID_INVALID'\n | 'OPENUI_NODE_ID_INVALID'\n | 'OPENUI_ARTIFACT_PATH_INVALID'\n | 'OPENUI_VALUES_INVALID'\n | 'OPENUI_FIELD_ID_INVALID'\n | 'OPENUI_FIELD_VALUE_INVALID'\n\n/** Ids the host accepts on the wire: identifier-safe, same rule as field ids. */\nexport function isSafeOpenUIActionId(id: string): boolean {\n return isSafeOpenUIFieldId(id)\n}\n\nfunction isOpenUIValue(value: unknown): value is OpenUIValue {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n (Array.isArray(value) && value.every((entry) => typeof entry === 'string'))\n )\n}\n\nfunction optionalId(\n value: unknown,\n code: OpenUIActionBodyErrorCode,\n label: string,\n): { ok: true; value: string | undefined } | { ok: false; code: OpenUIActionBodyErrorCode; error: string } {\n if (value === undefined || value === null) return { ok: true, value: undefined }\n if (typeof value !== 'string' || !isSafeOpenUIActionId(value)) {\n return { ok: false, code, error: `Invalid ${label}: letters, numbers, underscores, and hyphens only` }\n }\n return { ok: true, value }\n}\n\n/** A vault path is a product-addressed string, not an identifier — bound its\n * length and reject traversal rather than the character class. */\nfunction isSafeArtifactPath(path: string): boolean {\n return path.length > 0 && path.length <= 512 && !path.includes('..') && !path.startsWith('/')\n}\n\n/**\n * Validate a raw JSON body into a submission. Every rejection names a code so\n * the browser can tell \"the page sent something malformed\" from \"the product\n * refused the action\".\n */\nexport function validateOpenUIActionBody(body: Record<string, unknown>): OpenUIActionBodyValidation {\n const actionId = body.actionId\n if (typeof actionId !== 'string' || actionId.trim() === '') {\n return { ok: false, code: 'OPENUI_ACTION_ID_MISSING', error: 'Missing actionId' }\n }\n if (!isSafeOpenUIActionId(actionId)) {\n return {\n ok: false,\n code: 'OPENUI_ACTION_ID_INVALID',\n error: 'Invalid actionId: letters, numbers, underscores, and hyphens only',\n }\n }\n\n const formId = optionalId(body.formId, 'OPENUI_FORM_ID_INVALID', 'formId')\n if (!formId.ok) return formId\n const nodeId = optionalId(body.nodeId, 'OPENUI_NODE_ID_INVALID', 'nodeId')\n if (!nodeId.ok) return nodeId\n\n let artifactPath: string | undefined\n if (body.artifactPath !== undefined && body.artifactPath !== null) {\n if (typeof body.artifactPath !== 'string' || !isSafeArtifactPath(body.artifactPath)) {\n return { ok: false, code: 'OPENUI_ARTIFACT_PATH_INVALID', error: 'Invalid artifactPath' }\n }\n artifactPath = body.artifactPath\n }\n\n const values: OpenUIFormValues = {}\n if (body.values !== undefined && body.values !== null) {\n if (typeof body.values !== 'object' || Array.isArray(body.values)) {\n return { ok: false, code: 'OPENUI_VALUES_INVALID', error: 'Invalid values: expected an object of field values' }\n }\n for (const [key, value] of Object.entries(body.values as Record<string, unknown>)) {\n if (!isSafeOpenUIFieldId(key)) {\n return {\n ok: false,\n code: 'OPENUI_FIELD_ID_INVALID',\n error: 'Invalid values: field names must contain only letters, numbers, underscores, or hyphens',\n }\n }\n if (!isOpenUIValue(value)) {\n return {\n ok: false,\n code: 'OPENUI_FIELD_VALUE_INVALID',\n error: 'Invalid values: field values must be strings, numbers, booleans, or string arrays',\n }\n }\n values[key] = value\n }\n }\n\n return {\n ok: true,\n submission: {\n actionId,\n values,\n ...(formId.value ? { formId: formId.value } : {}),\n ...(nodeId.value ? { nodeId: nodeId.value } : {}),\n ...(artifactPath ? { artifactPath } : {}),\n },\n }\n}\n\nfunction describeValue(value: OpenUIValue): string {\n if (Array.isArray(value)) return value.join(', ')\n return String(value)\n}\n\n/**\n * One plain line recording what the user did, for the product to carry into the\n * NEXT turn's context.\n *\n * The action itself spends no model tokens; without a record of it the agent\n * would later reason about a page the user has already changed. Appending this\n * to the thread (as a note, a system line, or a stored part) is how the agent\n * catches up on the next turn the user actually pays for.\n */\nexport function describeOpenUIAction(submission: OpenUIActionSubmission): string {\n const entries = Object.entries(submission.values)\n const where = submission.formId ? ` on form \"${submission.formId}\"` : ''\n if (entries.length === 0) return `User pressed \"${submission.actionId}\"${where}.`\n const pairs = entries.map(([key, value]) => `${key}=${describeValue(value)}`).join(', ')\n return `User pressed \"${submission.actionId}\"${where} with ${pairs}.`\n}\n","/**\n * The host half of an interactive OpenUI page: one POST endpoint that turns a\n * button press into a product function call.\n *\n * THE SEAM THAT KEEPS IT FREE. This factory has no agent connection, no session\n * id, no sandbox, and no turn — look at {@link OpenUIActionRouteOptions}: the\n * only things a product supplies are an authorizer and a map of plain handlers.\n * There is no seam here through which a model call could be made, which is what\n * makes \"manipulating agent-authored UI costs nothing\" a structural property\n * rather than a promise. Compare `./interactions`, whose answer route exists\n * precisely to unblock a running turn: that one resolves a sidecar connection,\n * and this one cannot.\n *\n * A handler returns data, a replacement page, or a typed failure. If it wants\n * the agent to know what happened, the product records\n * {@link describeOpenUIAction} into the thread — read on the NEXT turn the user\n * chooses to spend, never as a side effect of the click.\n *\n * Handlers return web-standard `Response`s (Workers, Node 18+, Deno).\n */\n\nimport {\n describeOpenUIAction,\n validateOpenUIActionBody,\n type OpenUIActionSubmission,\n} from './action'\nimport type { OpenUINode } from './segments'\nimport {\n validateOpenUIFormValues,\n type OpenUIFieldIssue,\n type OpenUIFormSpec,\n type OpenUIFormValues,\n} from './values'\n\n/** Logging surface the route uses; `console` by default. */\nexport type OpenUIActionLogger = Pick<Console, 'warn' | 'error'>\n\n/** The product's verdict on who is calling. `response` short-circuits with a\n * product-authored Response (401/403/404/429…). */\nexport type OpenUIActionResolution<TContext> =\n | { ok: true; context: TContext }\n | { ok: false; response: Response }\n\n/** What a handler is given: the caller's request, the parsed submission, and\n * whatever the product's authorizer resolved. */\nexport interface OpenUIActionHandlerArgs<TContext> {\n request: Request\n submission: OpenUIActionSubmission\n context: TContext\n}\n\n/** What a handler returns. A replacement `schema` re-renders the page in place;\n * `values` writes corrected/derived values back into the form. */\nexport type OpenUIActionResult<TNode extends OpenUINode = OpenUINode> =\n | {\n ok: true\n /** Short confirmation for the card, in the user's language. */\n message?: string\n /** Values to write back into the form (server-corrected or derived). */\n values?: OpenUIFormValues\n /** A page to render in place of the current one. */\n schema?: TNode | TNode[]\n /** Anything else the client should read (totals, ids, links). */\n data?: Record<string, unknown>\n }\n | {\n ok: false\n /** Machine-readable reason, surfaced to the client verbatim. */\n code: string\n /** One sentence the user can act on. */\n message: string\n /** HTTP status; defaults to 400. */\n status?: number\n /** Field-level rejections, so the card can mark the offending inputs. */\n issues?: OpenUIFieldIssue[]\n }\n\n/** One product action, keyed in {@link OpenUIActionRouteOptions.actions} by the\n * `action.id` the agent authored on the page. */\nexport type OpenUIActionHandler<TContext, TNode extends OpenUINode = OpenUINode> = (\n args: OpenUIActionHandlerArgs<TContext>,\n) => OpenUIActionResult<TNode> | Promise<OpenUIActionResult<TNode>>\n\n/** How the route is wired. Note what is absent: nothing here can reach a model. */\nexport interface OpenUIActionRouteOptions<TContext, TNode extends OpenUINode = OpenUINode> {\n /**\n * Authenticate and authorize the caller, and resolve whatever the handlers\n * need (db handle, workspace, user). The only product-supplied gate.\n */\n resolve: (args: {\n request: Request\n submission: OpenUIActionSubmission\n }) => OpenUIActionResolution<TContext> | Promise<OpenUIActionResolution<TContext>>\n /** Handlers by action id. An id with no handler is a 404, never a no-op. */\n actions: Record<string, OpenUIActionHandler<TContext, TNode>>\n /**\n * Form specs by form id. When the submission names a form listed here, its\n * values are checked against the spec before the handler runs, and rejections\n * come back as field issues. Omit a form to leave checking to its handler.\n */\n forms?: Record<string, OpenUIFormSpec>\n /**\n * Called after a successful handler with the line the agent should read on\n * its next turn. Persist it against the thread; do NOT start a turn from it.\n */\n recordForAgent?: (args: {\n request: Request\n submission: OpenUIActionSubmission\n context: TContext\n note: string\n }) => void | Promise<void>\n logger?: OpenUIActionLogger\n}\n\n/** The endpoint a product mounts. */\nexport interface OpenUIActionRoute {\n /** POST `{ actionId, formId?, values?, nodeId?, artifactPath? }`. */\n handle: (request: Request) => Promise<Response>\n}\n\nfunction failure(code: string, error: string, status: number, extra?: Record<string, unknown>): Response {\n return Response.json({ ok: false, code, error, ...(extra ?? {}) }, { status })\n}\n\n/**\n * Build the action endpoint for agent-authored pages.\n *\n * ```ts\n * const route = createOpenUIActionRoute({\n * resolve: async ({ request }) => {\n * const session = await auth(request)\n * if (!session) return { ok: false, response: new Response('Unauthorized', { status: 401 }) }\n * return { ok: true, context: { db, workspaceId: session.workspaceId } }\n * },\n * forms: { deduction_form: DEDUCTION_FORM },\n * actions: {\n * recalculate: async ({ submission, context }) => {\n * const totals = recompute(context.db, submission.values)\n * return { ok: true, data: totals, schema: totalsPage(totals) }\n * },\n * },\n * })\n * export const action = ({ request }: ActionFunctionArgs) => route.handle(request)\n * ```\n */\nexport function createOpenUIActionRoute<TContext, TNode extends OpenUINode = OpenUINode>(\n options: OpenUIActionRouteOptions<TContext, TNode>,\n): OpenUIActionRoute {\n const logger = options.logger ?? console\n\n async function handle(request: Request): Promise<Response> {\n if (request.method !== 'POST') return failure('OPENUI_METHOD_NOT_ALLOWED', 'Method not allowed', 405)\n\n const body = (await request.json().catch(() => null)) as Record<string, unknown> | null\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n return failure('OPENUI_BODY_INVALID', 'Invalid JSON body', 400)\n }\n\n const parsed = validateOpenUIActionBody(body)\n if (!parsed.ok) return failure(parsed.code, parsed.error, 400)\n const submission = parsed.submission\n\n // Unknown ids are refused before the authorizer runs: a page that names an\n // action the product never registered is a broken page, and answering it\n // 404 is what makes that visible instead of a button that does nothing.\n const handler = Object.prototype.hasOwnProperty.call(options.actions, submission.actionId)\n ? options.actions[submission.actionId]\n : undefined\n if (!handler) {\n return failure(\n 'OPENUI_ACTION_UNKNOWN',\n `No handler is registered for \"${submission.actionId}\".`,\n 404,\n { actionId: submission.actionId },\n )\n }\n\n const resolution = await options.resolve({ request, submission })\n if (!resolution.ok) return resolution.response\n\n const spec =\n submission.formId && options.forms\n ? Object.prototype.hasOwnProperty.call(options.forms, submission.formId)\n ? options.forms[submission.formId]\n : undefined\n : undefined\n let values = submission.values\n if (spec) {\n const checked = validateOpenUIFormValues(spec, submission.values)\n if (!checked.ok) {\n return failure('OPENUI_VALUES_REJECTED', 'Some fields need fixing before this can run.', 422, {\n issues: checked.issues,\n })\n }\n values = checked.values\n }\n\n const checkedSubmission: OpenUIActionSubmission = { ...submission, values }\n\n let result: OpenUIActionResult<TNode>\n try {\n result = await handler({ request, submission: checkedSubmission, context: resolution.context })\n } catch (error) {\n logger.error('[openui] action handler failed:', error)\n return failure('OPENUI_ACTION_FAILED', 'That action could not be completed. Try again.', 500, {\n actionId: submission.actionId,\n })\n }\n\n if (!result.ok) {\n return failure(result.code, result.message, result.status ?? 400, {\n actionId: submission.actionId,\n ...(result.issues ? { issues: result.issues } : {}),\n })\n }\n\n if (options.recordForAgent) {\n try {\n await options.recordForAgent({\n request,\n submission: checkedSubmission,\n context: resolution.context,\n note: describeOpenUIAction(checkedSubmission),\n })\n } catch (error) {\n // The user's action already succeeded. Losing the agent-facing note\n // degrades the next turn's context; it must not fail the click.\n logger.warn('[openui] recordForAgent failed:', error)\n }\n }\n\n return Response.json({\n ok: true,\n actionId: submission.actionId,\n ...(result.message ? { message: result.message } : {}),\n ...(result.values ? { values: result.values } : {}),\n ...(result.schema ? { schema: result.schema } : {}),\n ...(result.data ? { data: result.data } : {}),\n })\n }\n\n return { handle }\n}\n"],"mappings":";;;;;;AA0BA,IAAM,QAAQ;AAEd,SAAS,WAAW,OAAyB;AAC3C,SACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAQ,MAA6B,SAAS;AAElD;AAGA,SAAS,UAAU,QAA4B;AAC7C,QAAM,aAAa,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AAC3D,SAAO,WAAW,OAAO,UAAU;AACrC;AAEA,SAAS,SAAmC,UAAuC,MAAoB;AACrG,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,QAAS,UAAS,KAAK,EAAE,MAAM,YAAY,MAAM,QAAQ,CAAC;AAChE;AAcO,SAAS,oBACd,SAC6B;AAC7B,QAAM,WAAwC,CAAC;AAC/C,MAAI,YAAY;AAIhB,QAAM,YAAY;AAClB,MAAI;AACJ,UAAQ,QA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cAAM,QAAQ,eAAe;AAAA,UAC3B;AAAA,UACA,YAAY;AAAA,UACZ,SAAS,WAAW;AAAA,UACpB,MAAM,qBAAqB,iBAAiB;AAAA,QAC9C,CAAC;AAAA,MACH,SAAS,OAAO;AAGd,eAAO,KAAK,mCAAmC,KAAK;AAAA,MACtD;AAAA,IACF;AAEA,WAAO,SAAS,KAAK;AAAA,MACnB,IAAI;AAAA,MACJ,UAAU,WAAW;AAAA,MACrB,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;AAAA,MACpD,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;AAAA,MACjD,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;AAAA,MACjD,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;AAAA,IAC7C,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,OAAO;AAClB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/openui/segments.ts","../../src/openui/values.ts","../../src/openui/action.ts","../../src/openui/route.ts"],"sourcesContent":["/**\n * Splitting an assistant message into prose and agent-authored UI.\n *\n * An agent emits a page by fencing it as ```` ```openui ```` in its reply (the\n * inline path) or by calling `render_ui` (the persisted-artifact path). Every\n * product that renders the inline path had forked the same scanner into its own\n * chat-message body; this is that scanner, once, with no React and no renderer\n * import — the node union stays owned by `@tangle-network/ui`'s `./openui`.\n */\n\n/**\n * The narrowest thing a host can assert about a parsed node: it names a type.\n * A renderer's node union satisfies this, so\n * `parseOpenUISegments<OpenUIComponentNode>(text)` hands typed nodes straight\n * to the renderer with no cast at the call site.\n */\nexport interface OpenUINode {\n type: string\n id?: string\n}\n\n/** One piece of an assistant message: prose, or a page to render. */\nexport type OpenUISegment<TNode extends OpenUINode = OpenUINode> =\n | { type: 'markdown'; text: string }\n | { type: 'openui'; nodes: TNode[] }\n\nconst FENCE = /```openui\\s*\\n([\\s\\S]*?)```/g\n\nfunction isNodeLike(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { type?: unknown }).type === 'string'\n )\n}\n\n/** Every array entry (or the single object) that names a node type. */\nfunction nodesFrom(parsed: unknown): unknown[] {\n const candidates = Array.isArray(parsed) ? parsed : [parsed]\n return candidates.filter(isNodeLike)\n}\n\nfunction pushText<TNode extends OpenUINode>(segments: Array<OpenUISegment<TNode>>, text: string): void {\n const trimmed = text.trim()\n if (trimmed) segments.push({ type: 'markdown', text: trimmed })\n}\n\n/**\n * Split message content into markdown and OpenUI segments, in source order.\n *\n * A fence whose body is not JSON, or whose JSON carries no node at all, is\n * returned as a fenced `json` markdown segment rather than an empty page: the\n * content is still streaming, or the agent wrote something malformed, and both\n * cases are better shown than swallowed into a blank card.\n *\n * The type argument is the caller's assertion about the node union it will\n * render; this function checks only that each node names a `type`, and the\n * renderer rejects types it does not know.\n */\nexport function parseOpenUISegments<TNode extends OpenUINode = OpenUINode>(\n content: string,\n): Array<OpenUISegment<TNode>> {\n const segments: Array<OpenUISegment<TNode>> = []\n let lastIndex = 0\n\n // `FENCE` carries the `g` flag and therefore `lastIndex` state; reset it so\n // concurrent/repeat calls cannot resume mid-string from a previous scan.\n FENCE.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = FENCE.exec(content)) !== null) {\n if (match.index > lastIndex) pushText(segments, content.slice(lastIndex, match.index))\n const body = match[1] ?? ''\n let nodes: unknown[] = []\n try {\n nodes = nodesFrom(JSON.parse(body) as unknown)\n } catch {\n nodes = []\n }\n if (nodes.length > 0) segments.push({ type: 'openui', nodes: nodes as TNode[] })\n else pushText(segments, `\\`\\`\\`json\\n${body}\\`\\`\\``)\n lastIndex = match.index + match[0].length\n }\n\n if (lastIndex < content.length) pushText(segments, content.slice(lastIndex))\n if (segments.length === 0 && content.trim()) segments.push({ type: 'markdown', text: content })\n return segments\n}\n\n/** Whether a message carries any agent-authored page at all. */\nexport function hasOpenUISegment(content: string): boolean {\n return parseOpenUISegments(content).some((segment) => segment.type === 'openui')\n}\n\n/** A page read back out of the vault, and its title when one was stored. */\nexport interface OpenUIArtifact<TNode extends OpenUINode = OpenUINode> {\n title?: string\n nodes: TNode[]\n}\n\n/** Why a stored page could not be read. */\nexport interface OpenUIArtifactError {\n code: 'artifact_not_json' | 'artifact_no_nodes'\n message: string\n}\n\n/** Reading a stored page either produces nodes or says why it did not. */\nexport type OpenUIArtifactResult<TNode extends OpenUINode = OpenUINode> =\n | { succeeded: true; value: OpenUIArtifact<TNode> }\n | { succeeded: false; error: OpenUIArtifactError }\n\n/**\n * Read a `render_ui` artifact back out of the vault.\n *\n * Two shapes are in the wild and a product cannot tell them apart from the\n * path: the bare node tree that `preset-cloudflare`'s handler writes\n * (`JSON.stringify(args.schema)`), and the `{ title, schema }` envelope some\n * products write themselves. Reading only one of them renders an empty panel\n * for the other, with nothing on screen to say why — so this reads both and\n * fails loud when it is neither.\n */\nexport function parseOpenUIArtifact<TNode extends OpenUINode = OpenUINode>(\n content: string,\n): OpenUIArtifactResult<TNode> {\n let parsed: unknown\n try {\n parsed = JSON.parse(content) as unknown\n } catch {\n return { succeeded: false, error: { code: 'artifact_not_json', message: 'Stored page is not JSON.' } }\n }\n\n const envelope =\n parsed && typeof parsed === 'object' && !Array.isArray(parsed) && 'schema' in parsed\n ? (parsed as { schema: unknown; title?: unknown })\n : null\n const nodes = nodesFrom(envelope ? envelope.schema : parsed)\n if (nodes.length === 0) {\n return { succeeded: false, error: { code: 'artifact_no_nodes', message: 'Stored page carries no nodes.' } }\n }\n const title = envelope && typeof envelope.title === 'string' ? envelope.title : undefined\n return { succeeded: true, value: { nodes: nodes as TNode[], ...(title ? { title } : {}) } }\n}\n","/**\n * The value half of an interactive OpenUI page: what a field holds, and whether\n * a submitted set of field values matches the form the agent authored.\n *\n * The NODE vocabulary (which fields exist, how they render) has one owner —\n * `@tangle-network/ui`'s `./openui` entry. This module does not restate it. It\n * declares the narrowest STRUCTURAL port a host needs to check a submission:\n * the field's id, its kind, and the constraints that make a value legal. A\n * renderer's richer node type satisfies this port by assignment, so the two\n * packages stay in step without either importing the other.\n */\n\n/** A value one OpenUI field can hold. `string[]` is a multi-select. */\nexport type OpenUIValue = string | number | boolean | string[]\n\n/** Submitted field values, keyed by field id. */\nexport type OpenUIFormValues = Record<string, OpenUIValue>\n\n/**\n * Field ids the host will accept: identifier-safe, and never a key that would\n * reach `Object.prototype`. A submission arrives from a browser and is used to\n * index an object, so this is a boundary check, not a style rule.\n */\nexport function isSafeOpenUIFieldId(id: string): boolean {\n return /^[A-Za-z0-9_-]+$/.test(id) && id !== '__proto__' && id !== 'constructor' && id !== 'prototype'\n}\n\n/** The input kinds a form field can be. */\nexport type OpenUIFieldKind = 'text' | 'number' | 'currency' | 'select' | 'checkbox' | 'slider'\n\nconst FIELD_KINDS: ReadonlySet<string> = new Set<OpenUIFieldKind>([\n 'text',\n 'number',\n 'currency',\n 'select',\n 'checkbox',\n 'slider',\n])\n\n/** Whether a string names an input kind this contract knows. */\nexport function isOpenUIFieldKind(kind: string): kind is OpenUIFieldKind {\n return FIELD_KINDS.has(kind)\n}\n\n/**\n * One field, reduced to what a value check needs. A renderer node carrying\n * labels, placeholders, and layout is assignable to this — the extra\n * presentation properties are simply not read here.\n */\nexport interface OpenUIFieldSpec {\n id: string\n kind: OpenUIFieldKind\n required?: boolean\n /** `number` / `currency` / `slider` bounds, inclusive. */\n min?: number\n max?: number\n /** Increment `number` / `currency` / `slider` values must land on, measured from `min ?? 0`. */\n step?: number\n /** Longest accepted `text` value. */\n maxLength?: number\n /** Accepted `select` values. */\n options?: ReadonlyArray<{ value: string }>\n /** A `select` that accepts more than one option; its value is a `string[]`. */\n multiple?: boolean\n}\n\n/** A form the host can check a submission against. */\nexport interface OpenUIFormSpec {\n id: string\n fields: readonly OpenUIFieldSpec[]\n}\n\n/** Why one field's value was rejected. */\nexport type OpenUIFieldIssueCode =\n | 'required'\n | 'type'\n | 'range'\n | 'step'\n | 'option'\n | 'length'\n | 'unknown_field'\n | 'duplicate_field'\n | 'unsafe_field_id'\n\n/** One rejected field, named so a card can mark exactly that input. */\nexport interface OpenUIFieldIssue {\n fieldId: string\n code: OpenUIFieldIssueCode\n message: string\n}\n\n/** The outcome of checking a submission against a form. */\nexport type OpenUIFormValidation =\n | { ok: true; values: OpenUIFormValues }\n | { ok: false; issues: OpenUIFieldIssue[] }\n\nfunction issue(fieldId: string, code: OpenUIFieldIssueCode, message: string): OpenUIFieldIssue {\n return { fieldId, code, message }\n}\n\n/** Floating-point step arithmetic: 0.1 increments must not reject 0.3. */\nconst STEP_EPSILON = 1e-9\n\nfunction checkNumeric(field: OpenUIFieldSpec, value: number): OpenUIFieldIssue | null {\n if (!Number.isFinite(value)) return issue(field.id, 'type', `${field.id} must be a finite number`)\n if (field.min !== undefined && value < field.min) {\n return issue(field.id, 'range', `${field.id} must be at least ${field.min}`)\n }\n if (field.max !== undefined && value > field.max) {\n return issue(field.id, 'range', `${field.id} must be at most ${field.max}`)\n }\n if (field.step !== undefined && field.step > 0) {\n const offset = (value - (field.min ?? 0)) / field.step\n if (Math.abs(offset - Math.round(offset)) > STEP_EPSILON) {\n return issue(field.id, 'step', `${field.id} must move in steps of ${field.step}`)\n }\n }\n return null\n}\n\nfunction isEmpty(value: OpenUIValue): boolean {\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\nfunction checkField(field: OpenUIFieldSpec, value: OpenUIValue | undefined): OpenUIFieldIssue | null {\n if (value === undefined || isEmpty(value)) {\n // A checkbox is never \"empty\" — `false` is an answer — so only a genuinely\n // absent value can fail the required check for one.\n if (field.required) return issue(field.id, 'required', `${field.id} is required`)\n return null\n }\n\n switch (field.kind) {\n case 'text': {\n if (typeof value !== 'string') return issue(field.id, 'type', `${field.id} must be text`)\n if (field.maxLength !== undefined && value.length > field.maxLength) {\n return issue(field.id, 'length', `${field.id} must be at most ${field.maxLength} characters`)\n }\n return null\n }\n case 'number':\n case 'currency':\n case 'slider': {\n if (typeof value !== 'number') return issue(field.id, 'type', `${field.id} must be a number`)\n return checkNumeric(field, value)\n }\n case 'checkbox': {\n if (typeof value !== 'boolean') return issue(field.id, 'type', `${field.id} must be true or false`)\n return null\n }\n case 'select': {\n const allowed = field.options ? new Set(field.options.map((option) => option.value)) : null\n if (field.multiple) {\n if (!Array.isArray(value)) return issue(field.id, 'type', `${field.id} must be a list of choices`)\n if (allowed) {\n const rejected = value.find((entry) => !allowed.has(entry))\n if (rejected !== undefined) {\n return issue(field.id, 'option', `${field.id} does not offer \"${rejected}\"`)\n }\n }\n return null\n }\n if (typeof value !== 'string') return issue(field.id, 'type', `${field.id} must be a single choice`)\n if (allowed && !allowed.has(value)) return issue(field.id, 'option', `${field.id} does not offer \"${value}\"`)\n return null\n }\n }\n}\n\n/**\n * Check submitted values against the form the agent authored.\n *\n * Fails loud on both sides of the shape: a value the form never declared is an\n * error (`unknown_field`), not a silently ignored extra, because a host that\n * drops it would act on a form different from the one the user filled in. A\n * `required` field with no value is an error even when the caller simply never\n * sent the key.\n *\n * On success the returned `values` contain only declared fields, in the form's\n * own field order — the object a handler should act on.\n */\nexport function validateOpenUIFormValues(spec: OpenUIFormSpec, values: OpenUIFormValues): OpenUIFormValidation {\n const issues: OpenUIFieldIssue[] = []\n const seen = new Set<string>()\n for (const field of spec.fields) {\n if (!isSafeOpenUIFieldId(field.id)) {\n issues.push(issue(field.id, 'unsafe_field_id', `${field.id} is not a usable field id`))\n continue\n }\n if (seen.has(field.id)) {\n issues.push(issue(field.id, 'duplicate_field', `${field.id} is declared more than once`))\n continue\n }\n seen.add(field.id)\n }\n\n for (const key of Object.keys(values)) {\n if (!seen.has(key)) issues.push(issue(key, 'unknown_field', `${key} is not a field on this form`))\n }\n\n const accepted: OpenUIFormValues = {}\n for (const field of spec.fields) {\n if (!seen.has(field.id)) continue\n const value = Object.prototype.hasOwnProperty.call(values, field.id) ? values[field.id] : undefined\n const problem = checkField(field, value)\n if (problem) {\n issues.push(problem)\n continue\n }\n if (value !== undefined) accepted[field.id] = value\n }\n\n if (issues.length > 0) return { ok: false, issues }\n return { ok: true, values: accepted }\n}\n","/**\n * What travels when a user presses a button on a page the agent authored.\n *\n * The submission is a plain REST body, not a chat turn. That is the entire\n * point of this module: pressing \"Recalculate\" on an agent-authored form must\n * cost the same as pressing a button on a hand-built screen — one product route\n * call, no model tokens, no sandbox wake-up. The wire shape here is therefore\n * deliberately small and self-contained: an action id, the form it belongs to,\n * that form's current values, and enough addressing for the product to find the\n * page. Nothing in it references a session, a turn, or a run.\n */\n\nimport { isSafeOpenUIFieldId, type OpenUIFormValues, type OpenUIValue } from './values'\n\n/** What the browser POSTs when an action fires. */\nexport interface OpenUIActionSubmission {\n /** The action's stable id, as authored on the page. */\n actionId: string\n /** The form whose values are attached, when the action sits in one. */\n formId?: string\n /** Current values of that form, keyed by field id. Empty for a bare action. */\n values: OpenUIFormValues\n /** The node the action was rendered on, when the page carries several. */\n nodeId?: string\n /** Vault path of the persisted `render_ui` artifact this page came from. */\n artifactPath?: string\n}\n\n/** Parsed submission, or the reason the body was refused. */\nexport type OpenUIActionBodyValidation =\n | { ok: true; submission: OpenUIActionSubmission }\n | { ok: false; code: OpenUIActionBodyErrorCode; error: string }\n\n/** Why a submission body was refused before any handler ran. */\nexport type OpenUIActionBodyErrorCode =\n | 'OPENUI_ACTION_ID_MISSING'\n | 'OPENUI_ACTION_ID_INVALID'\n | 'OPENUI_FORM_ID_INVALID'\n | 'OPENUI_NODE_ID_INVALID'\n | 'OPENUI_ARTIFACT_PATH_INVALID'\n | 'OPENUI_VALUES_INVALID'\n | 'OPENUI_FIELD_ID_INVALID'\n | 'OPENUI_FIELD_VALUE_INVALID'\n\n/** Ids the host accepts on the wire: identifier-safe, same rule as field ids. */\nexport function isSafeOpenUIActionId(id: string): boolean {\n return isSafeOpenUIFieldId(id)\n}\n\nfunction isOpenUIValue(value: unknown): value is OpenUIValue {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n (Array.isArray(value) && value.every((entry) => typeof entry === 'string'))\n )\n}\n\nfunction optionalId(\n value: unknown,\n code: OpenUIActionBodyErrorCode,\n label: string,\n): { ok: true; value: string | undefined } | { ok: false; code: OpenUIActionBodyErrorCode; error: string } {\n if (value === undefined || value === null) return { ok: true, value: undefined }\n if (typeof value !== 'string' || !isSafeOpenUIActionId(value)) {\n return { ok: false, code, error: `Invalid ${label}: letters, numbers, underscores, and hyphens only` }\n }\n return { ok: true, value }\n}\n\n/** A vault path is a product-addressed string, not an identifier — bound its\n * length and reject traversal rather than the character class. */\nfunction isSafeArtifactPath(path: string): boolean {\n return path.length > 0 && path.length <= 512 && !path.includes('..') && !path.startsWith('/')\n}\n\n/**\n * Validate a raw JSON body into a submission. Every rejection names a code so\n * the browser can tell \"the page sent something malformed\" from \"the product\n * refused the action\".\n */\nexport function validateOpenUIActionBody(body: Record<string, unknown>): OpenUIActionBodyValidation {\n const actionId = body.actionId\n if (typeof actionId !== 'string' || actionId.trim() === '') {\n return { ok: false, code: 'OPENUI_ACTION_ID_MISSING', error: 'Missing actionId' }\n }\n if (!isSafeOpenUIActionId(actionId)) {\n return {\n ok: false,\n code: 'OPENUI_ACTION_ID_INVALID',\n error: 'Invalid actionId: letters, numbers, underscores, and hyphens only',\n }\n }\n\n const formId = optionalId(body.formId, 'OPENUI_FORM_ID_INVALID', 'formId')\n if (!formId.ok) return formId\n const nodeId = optionalId(body.nodeId, 'OPENUI_NODE_ID_INVALID', 'nodeId')\n if (!nodeId.ok) return nodeId\n\n let artifactPath: string | undefined\n if (body.artifactPath !== undefined && body.artifactPath !== null) {\n if (typeof body.artifactPath !== 'string' || !isSafeArtifactPath(body.artifactPath)) {\n return { ok: false, code: 'OPENUI_ARTIFACT_PATH_INVALID', error: 'Invalid artifactPath' }\n }\n artifactPath = body.artifactPath\n }\n\n const values: OpenUIFormValues = {}\n if (body.values !== undefined && body.values !== null) {\n if (typeof body.values !== 'object' || Array.isArray(body.values)) {\n return { ok: false, code: 'OPENUI_VALUES_INVALID', error: 'Invalid values: expected an object of field values' }\n }\n for (const [key, value] of Object.entries(body.values as Record<string, unknown>)) {\n if (!isSafeOpenUIFieldId(key)) {\n return {\n ok: false,\n code: 'OPENUI_FIELD_ID_INVALID',\n error: 'Invalid values: field names must contain only letters, numbers, underscores, or hyphens',\n }\n }\n if (!isOpenUIValue(value)) {\n return {\n ok: false,\n code: 'OPENUI_FIELD_VALUE_INVALID',\n error: 'Invalid values: field values must be strings, numbers, booleans, or string arrays',\n }\n }\n values[key] = value\n }\n }\n\n return {\n ok: true,\n submission: {\n actionId,\n values,\n ...(formId.value ? { formId: formId.value } : {}),\n ...(nodeId.value ? { nodeId: nodeId.value } : {}),\n ...(artifactPath ? { artifactPath } : {}),\n },\n }\n}\n\nfunction describeValue(value: OpenUIValue): string {\n if (Array.isArray(value)) return value.join(', ')\n return String(value)\n}\n\n/**\n * One plain line recording what the user did, for the product to carry into the\n * NEXT turn's context.\n *\n * The action itself spends no model tokens; without a record of it the agent\n * would later reason about a page the user has already changed. Appending this\n * to the thread (as a note, a system line, or a stored part) is how the agent\n * catches up on the next turn the user actually pays for.\n */\nexport function describeOpenUIAction(submission: OpenUIActionSubmission): string {\n const entries = Object.entries(submission.values)\n const where = submission.formId ? ` on form \"${submission.formId}\"` : ''\n if (entries.length === 0) return `User pressed \"${submission.actionId}\"${where}.`\n const pairs = entries.map(([key, value]) => `${key}=${describeValue(value)}`).join(', ')\n return `User pressed \"${submission.actionId}\"${where} with ${pairs}.`\n}\n","/**\n * The host half of an interactive OpenUI page: one POST endpoint that turns a\n * button press into a product function call.\n *\n * THE SEAM THAT KEEPS IT FREE. This factory has no agent connection, no session\n * id, no sandbox, and no turn — look at {@link OpenUIActionRouteOptions}: the\n * only things a product supplies are an authorizer and a map of plain handlers.\n * There is no seam here through which a model call could be made, which is what\n * makes \"manipulating agent-authored UI costs nothing\" a structural property\n * rather than a promise. Compare `./interactions`, whose answer route exists\n * precisely to unblock a running turn: that one resolves a sidecar connection,\n * and this one cannot.\n *\n * A handler returns data, a replacement page, or a typed failure. If it wants\n * the agent to know what happened, the product records\n * {@link describeOpenUIAction} into the thread — read on the NEXT turn the user\n * chooses to spend, never as a side effect of the click.\n *\n * Handlers return web-standard `Response`s (Workers, Node 18+, Deno).\n */\n\nimport {\n describeOpenUIAction,\n validateOpenUIActionBody,\n type OpenUIActionSubmission,\n} from './action'\nimport type { OpenUINode } from './segments'\nimport {\n validateOpenUIFormValues,\n type OpenUIFieldIssue,\n type OpenUIFormSpec,\n type OpenUIFormValues,\n} from './values'\nimport { parseJsonObjectBody } from '../web/core'\n\n/** Logging surface the route uses; `console` by default. */\nexport type OpenUIActionLogger = Pick<Console, 'warn' | 'error'>\n\n/** The product's verdict on who is calling. `response` short-circuits with a\n * product-authored Response (401/403/404/429…). */\nexport type OpenUIActionResolution<TContext> =\n | { ok: true; context: TContext }\n | { ok: false; response: Response }\n\n/** What a handler is given: the caller's request, the parsed submission, and\n * whatever the product's authorizer resolved. */\nexport interface OpenUIActionHandlerArgs<TContext> {\n request: Request\n submission: OpenUIActionSubmission\n context: TContext\n}\n\n/** What a handler returns. A replacement `schema` re-renders the page in place;\n * `values` writes corrected/derived values back into the form. */\nexport type OpenUIActionResult<TNode extends OpenUINode = OpenUINode> =\n | {\n ok: true\n /** Short confirmation for the card, in the user's language. */\n message?: string\n /** Values to write back into the form (server-corrected or derived). */\n values?: OpenUIFormValues\n /** A page to render in place of the current one. */\n schema?: TNode | TNode[]\n /** Anything else the client should read (totals, ids, links). */\n data?: Record<string, unknown>\n }\n | {\n ok: false\n /** Machine-readable reason, surfaced to the client verbatim. */\n code: string\n /** One sentence the user can act on. */\n message: string\n /** HTTP status; defaults to 400. */\n status?: number\n /** Field-level rejections, so the card can mark the offending inputs. */\n issues?: OpenUIFieldIssue[]\n }\n\n/** One product action, keyed in {@link OpenUIActionRouteOptions.actions} by the\n * `action.id` the agent authored on the page. */\nexport type OpenUIActionHandler<TContext, TNode extends OpenUINode = OpenUINode> = (\n args: OpenUIActionHandlerArgs<TContext>,\n) => OpenUIActionResult<TNode> | Promise<OpenUIActionResult<TNode>>\n\n/** How big the POST body may be before the route refuses to parse it. A\n * click carries action ids and form values — 64 KiB covers generous forms with\n * headroom; anything larger is abuse or a mistake, and refusing it before\n * parsing bounds per-request memory (issue #748). */\nconst DEFAULT_MAX_BODY_BYTES = 64 * 1024\n\n/** How the route is wired. Note what is absent: nothing here can reach a model. */\nexport interface OpenUIActionRouteOptions<TContext, TNode extends OpenUINode = OpenUINode> {\n /**\n * Authenticate and authorize the caller, and resolve whatever the handlers\n * need (db handle, workspace, user). The only product-supplied gate.\n */\n resolve: (args: {\n request: Request\n submission: OpenUIActionSubmission\n }) => OpenUIActionResolution<TContext> | Promise<OpenUIActionResolution<TContext>>\n /** Handlers by action id. An id with no handler is a 404, never a no-op. */\n actions: Record<string, OpenUIActionHandler<TContext, TNode>>\n /**\n * Form specs by form id. When the submission names a form listed here, its\n * values are checked against the spec before the handler runs, and rejections\n * come back as field issues. Omit a form to leave checking to its handler.\n */\n forms?: Record<string, OpenUIFormSpec>\n /**\n * Called after a successful handler with the line the agent should read on\n * its next turn. Persist it against the thread; do NOT start a turn from it.\n */\n recordForAgent?: (args: {\n request: Request\n submission: OpenUIActionSubmission\n context: TContext\n note: string\n }) => void | Promise<void>\n /** Request-body byte cap before parsing. Default 64 KiB. */\n maxBodyBytes?: number\n logger?: OpenUIActionLogger\n}\n\n/** The endpoint a product mounts. */\nexport interface OpenUIActionRoute {\n /** POST `{ actionId, formId?, values?, nodeId?, artifactPath? }`. */\n handle: (request: Request) => Promise<Response>\n}\n\nfunction failure(code: string, error: string, status: number, extra?: Record<string, unknown>): Response {\n return Response.json({ ok: false, code, error, ...(extra ?? {}) }, { status })\n}\n\n/**\n * Build the action endpoint for agent-authored pages.\n *\n * ```ts\n * const route = createOpenUIActionRoute({\n * resolve: async ({ request }) => {\n * const session = await auth(request)\n * if (!session) return { ok: false, response: new Response('Unauthorized', { status: 401 }) }\n * return { ok: true, context: { db, workspaceId: session.workspaceId } }\n * },\n * forms: { deduction_form: DEDUCTION_FORM },\n * actions: {\n * recalculate: async ({ submission, context }) => {\n * const totals = recompute(context.db, submission.values)\n * return { ok: true, data: totals, schema: totalsPage(totals) }\n * },\n * },\n * })\n * export const action = ({ request }: ActionFunctionArgs) => route.handle(request)\n * ```\n */\nexport function createOpenUIActionRoute<TContext, TNode extends OpenUINode = OpenUINode>(\n options: OpenUIActionRouteOptions<TContext, TNode>,\n): OpenUIActionRoute {\n const logger = options.logger ?? console\n\n async function handle(request: Request): Promise<Response> {\n if (request.method !== 'POST') return failure('OPENUI_METHOD_NOT_ALLOWED', 'Method not allowed', 405)\n\n // Bounded body parse (streaming cap, content-length precheck, 413) — the\n // same primitive every other route boundary in the package uses.\n const [body, bodyError] = await parseJsonObjectBody(request, { maxBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES })\n if (bodyError) {\n return bodyError.status === 413\n ? failure('OPENUI_BODY_TOO_LARGE', 'JSON body is too large', 413)\n : failure('OPENUI_BODY_INVALID', 'Invalid JSON body', 400)\n }\n\n const parsed = validateOpenUIActionBody(body)\n if (!parsed.ok) return failure(parsed.code, parsed.error, 400)\n const submission = parsed.submission\n\n // Unknown ids are refused before the authorizer runs: a page that names an\n // action the product never registered is a broken page, and answering it\n // 404 is what makes that visible instead of a button that does nothing.\n const handler = Object.prototype.hasOwnProperty.call(options.actions, submission.actionId)\n ? options.actions[submission.actionId]\n : undefined\n if (!handler) {\n return failure(\n 'OPENUI_ACTION_UNKNOWN',\n `No handler is registered for \"${submission.actionId}\".`,\n 404,\n { actionId: submission.actionId },\n )\n }\n\n const resolution = await options.resolve({ request, submission })\n if (!resolution.ok) return resolution.response\n\n const spec =\n submission.formId && options.forms\n ? Object.prototype.hasOwnProperty.call(options.forms, submission.formId)\n ? options.forms[submission.formId]\n : undefined\n : undefined\n let values = submission.values\n if (spec) {\n const checked = validateOpenUIFormValues(spec, submission.values)\n if (!checked.ok) {\n return failure('OPENUI_VALUES_REJECTED', 'Some fields need fixing before this can run.', 422, {\n issues: checked.issues,\n })\n }\n values = checked.values\n }\n\n const checkedSubmission: OpenUIActionSubmission = { ...submission, values }\n\n let result: OpenUIActionResult<TNode>\n try {\n result = await handler({ request, submission: checkedSubmission, context: resolution.context })\n } catch (error) {\n logger.error('[openui] action handler failed:', error)\n return failure('OPENUI_ACTION_FAILED', 'That action could not be completed. Try again.', 500, {\n actionId: submission.actionId,\n })\n }\n\n if (!result.ok) {\n return failure(result.code, result.message, result.status ?? 400, {\n actionId: submission.actionId,\n ...(result.issues ? { issues: result.issues } : {}),\n })\n }\n\n if (options.recordForAgent) {\n try {\n await options.recordForAgent({\n request,\n submission: checkedSubmission,\n context: resolution.context,\n note: describeOpenUIAction(checkedSubmission),\n })\n } catch (error) {\n // The user's action already succeeded. Losing the agent-facing note\n // degrades the next turn's context; it must not fail the click.\n logger.warn('[openui] recordForAgent failed:', error)\n }\n }\n\n return Response.json({\n ok: true,\n actionId: submission.actionId,\n ...(result.message ? { message: result.message } : {}),\n ...(result.values ? { values: result.values } : {}),\n ...(result.schema ? { schema: result.schema } : {}),\n ...(result.data ? { data: result.data } : {}),\n })\n }\n\n return { handle }\n}\n"],"mappings":";;;;;;;;;;AA0BA,IAAM,QAAQ;AAEd,SAAS,WAAW,OAAyB;AAC3C,SACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAQ,MAA6B,SAAS;AAElD;AAGA,SAAS,UAAU,QAA4B;AAC7C,QAAM,aAAa,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AAC3D,SAAO,WAAW,OAAO,UAAU;AACrC;AAEA,SAAS,SAAmC,UAAuC,MAAoB;AACrG,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,QAAS,UAAS,KAAK,EAAE,MAAM,YAAY,MAAM,QAAQ,CAAC;AA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