@tangle-network/agent-app 0.60.13 → 0.60.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/agent-surfaces/cli.js +1 -1
- package/dist/agent-surfaces/index.d.ts +5 -2
- package/dist/agent-surfaces/index.js +1 -1
- package/dist/chat-routes/index.js +3 -2
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/{chunk-3G7IOCSV.js → chunk-HGKDZQ52.js} +14 -19
- package/dist/chunk-HGKDZQ52.js.map +1 -0
- package/dist/chunk-XB4KZVUV.js +151 -0
- package/dist/chunk-XB4KZVUV.js.map +1 -0
- package/dist/{chunk-FNRUXPXE.js → chunk-XPTYP3FP.js} +2 -2
- package/dist/chunk-YG66IHDU.js +80 -0
- package/dist/chunk-YG66IHDU.js.map +1 -0
- package/dist/{chunk-53K4S3K6.js → chunk-YXYQ6MJL.js} +1 -78
- package/dist/chunk-YXYQ6MJL.js.map +1 -0
- package/dist/operator/chat-adapter.d.ts +98 -0
- package/dist/operator/index.d.ts +2 -0
- package/dist/operator/index.js +307 -7
- package/dist/operator/index.js.map +1 -1
- package/dist/operator/platform-agent-keys.d.ts +47 -0
- package/dist/platform/agent-keys.d.ts +63 -0
- package/dist/platform/index.d.ts +1 -0
- package/dist/platform/index.js +12 -2
- package/dist/platform/index.js.map +1 -1
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/public-consultation/index.js +3 -2
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/stream/index.js +6 -4
- package/package.json +1 -1
- package/dist/chunk-3G7IOCSV.js.map +0 -1
- package/dist/chunk-53K4S3K6.js.map +0 -1
- package/dist/chunk-MLDKEEFQ.js +0 -48
- package/dist/chunk-MLDKEEFQ.js.map +0 -1
- /package/dist/{chunk-FNRUXPXE.js.map → chunk-XPTYP3FP.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts"],"sourcesContent":["/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. */\n serviceToken: string | (() => string)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiKey),\n deduct: (input) => http.deduct(input),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,8BAA8B,CAAC,YAAY,SAAS,SAAS;AAG5D,SAAS,wBAAwB,WAAgB,cAAsB,UAA2B;AACvG,MAAI,UAAU,aAAa,gBAAgB,UAAU,KAAM,QAAO;AAClE,QAAM,OAAO,CAAC,GAAG,UAAU,aAAa,KAAK,CAAC;AAC9C,MAAI,KA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,MAAM,KAAK,WAAW,MAAM;AAC7C,aAAO,EAAE,SAAS,SAAS,SAAS,eAAe,SAAS,cAAc;AAAA,IAC5E;AAAA,IACA,mBAAmB,CAAC,WAAW,KAAK,kBAAkB,MAAM;AAAA,IAC5D,QAAQ,CAAC,UAAU,KAAK,OAAO,KAAK;AAAA,EACtC;AACF;","names":["body","body"]}
|
|
1
|
+
{"version":3,"sources":["../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts"],"sourcesContent":["/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. */\n serviceToken: string | (() => string)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiK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SAAS,kBAAkB,KAAkC;AAClE,SAAO,IAAI,eAAe,SAAY,IAAI,YAAY,OAAO,IAAI,eAAe;AAClF;AAWO,SAAS,kCACd,MACA,UACuC;AACvC,SAAO;AAAA,IACL,iBAAiB,CAAC,WAAW,SAAS,gBAAgB,MAAM;AAAA,IAC5D,SAAS,OAAO,YAAY,MAAM,KAAK,gBAAgB,MAAM,GAAG;AAAA,IAChE,YAAY,OAAO,WAAW;AAC5B,YAAM,WAAW,MAAM,KAAK,WAAW,MAAM;AAC7C,aAAO,EAAE,SAAS,SAAS,SAAS,eAAe,SAAS,cAAc;AAAA,IAC5E;AAAA,IACA,mBAAmB,CAAC,WAAW,KAAK,kBAAkB,MAAM;AAAA,IAC5D,QAAQ,CAAC,UAAU,KAAK,OAAO,KAAK;AAAA,EACtC;AACF;","names":["body","body"]}
|
|
@@ -102,8 +102,8 @@ interface GatewayConsultationContext {
|
|
|
102
102
|
/** Compose gateway admission, scoped knowledge and the maintained persisted chat route. */
|
|
103
103
|
export declare function createPublicConsultation(options: PublicConsultationOptions): {
|
|
104
104
|
authorizeConsumer(agent: ConsultationAgent, consumer: ConsultationConsumer): Promise<{
|
|
105
|
-
reason?: undefined;
|
|
106
105
|
allow: true;
|
|
106
|
+
reason?: undefined;
|
|
107
107
|
code?: undefined;
|
|
108
108
|
} | {
|
|
109
109
|
allow: false;
|
|
@@ -121,9 +121,9 @@ export declare function createPublicConsultation(options: PublicConsultationOpti
|
|
|
121
121
|
executionBudget?: ChatTurnExecutionLimits;
|
|
122
122
|
maxOutputTokens?: number;
|
|
123
123
|
}) => Promise<{
|
|
124
|
-
start?: undefined;
|
|
125
124
|
status: 'unsupported';
|
|
126
125
|
reason: string;
|
|
126
|
+
start?: undefined;
|
|
127
127
|
} | {
|
|
128
128
|
reason?: undefined;
|
|
129
129
|
status: 'prepared';
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createChatTurnRoutes,
|
|
3
3
|
streamChatRouteAsSandboxEvents
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-XPTYP3FP.js";
|
|
5
5
|
import "../chunk-6VRVRWYN.js";
|
|
6
6
|
import "../chunk-UTAIRVOK.js";
|
|
7
7
|
import "../chunk-RN4WPTBH.js";
|
|
8
8
|
import "../chunk-3NCPXNBZ.js";
|
|
9
|
-
import "../chunk-
|
|
9
|
+
import "../chunk-YXYQ6MJL.js";
|
|
10
|
+
import "../chunk-YG66IHDU.js";
|
|
10
11
|
import "../chunk-OEHEHPPA.js";
|
|
11
12
|
import "../chunk-HTAFI247.js";
|
|
12
13
|
import "../chunk-ZVEEWGDK.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/public-consultation/index.ts"],"sourcesContent":["import { searchKnowledge, type KnowledgeIndex, type KnowledgePage } from '@tangle-network/agent-knowledge'\nimport { createChatTurnRoutes, type ChatTurnExecutionLimits, type ChatTurnLock, type ChatTurnMessageStore, type ChatTurnRouteProducer } from '../chat-routes/turn-routes'\nimport { streamChatRouteAsSandboxEvents } from '../chat-routes/gateway-adapter'\nimport type { TurnEventStore } from '../stream/turn-buffer'\nimport type { McpToolDefinition } from '../tools/mcp-rpc'\n\nexport interface PublishedKnowledgePage {\n readonly id: string\n readonly title: string\n readonly text: string\n}\n\n/** A server-created publication. Every selected page's complete text is public. */\nexport interface KnowledgePublication {\n readonly id: string\n readonly revision: string\n readonly ownerId: string\n readonly systemPrompt: string\n read(pageId: string): PublishedKnowledgePage | null\n search(query: string): PublishedKnowledgePage[]\n}\n\n/** Select content at publication time, before any payer or model input exists. */\nexport function createKnowledgePublication(input: {\n id: string\n revision: string\n ownerId: string\n systemPrompt: string\n index: KnowledgeIndex\n pageIds: readonly string[]\n}): KnowledgePublication {\n for (const value of [input.id, input.revision, input.ownerId]) requireIdentity(value)\n const pages: KnowledgePage[] = []\n for (const id of new Set(input.pageIds)) {\n const matches = input.index.pages.filter(page => page.id === id)\n if (matches.length !== 1) throw new Error('Publication page must resolve exactly once')\n const page = matches[0]!\n // Owner metadata, paths, links and source records can refer to private resources.\n pages.push({ id: page.id, title: page.title, text: page.text, path: page.id,\n frontmatter: {}, sourceIds: [], tags: [], outLinks: [] })\n }\n const index: KnowledgeIndex = { root: '', generatedAt: '', sources: [], pages, graph: { nodes: [], edges: [] } }\n const publicPage = (page: KnowledgePage): PublishedKnowledgePage =>\n Object.freeze({ id: page.id, title: page.title, text: page.text })\n return Object.freeze({\n id: input.id, revision: input.revision, ownerId: input.ownerId, systemPrompt: input.systemPrompt,\n read: (id: string) => {\n const page = pages.find(candidate => candidate.id === id)\n return page ? publicPage(page) : null\n },\n search: (query: string) => searchKnowledge(index, query, { limit: 10 }).map(hit => publicPage(hit.page)),\n })\n}\n\n/** Authenticated server identity. Never construct this from model arguments or request JSON. */\nexport interface ConsultationConsumer {\n method: string\n consumerId: string\n keyId?: string\n ownerId?: string\n requestId: string\n threadId?: string\n}\n\nexport interface ConsultationAgent {\n id: string\n ownerId: string\n}\n\nexport interface ConsultationIdentity {\n readonly publicationId: string\n readonly publicationRevision: string\n readonly consumerId: string\n readonly paymentMethod: string\n readonly workspaceId: string\n readonly threadId: string\n}\n\nexport interface ConsultationExecutionControl {\n readonly identity: ConsultationIdentity\n readonly signal: AbortSignal\n readonly executionLimits?: Readonly<ChatTurnExecutionLimits>\n}\n\nexport type PreparedConsultationExecution =\n | { status: 'unsupported'; reason: string }\n | { status: 'prepared'; produce(input: ConsultationExecution): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer> }\n\nexport interface ConsultationExecution extends ConsultationExecutionControl {\n readonly identity: ConsultationIdentity\n readonly systemPrompt: string\n readonly prompt: string\n readonly priorMessages: ReadonlyArray<{ role: string; content: string }>\n readonly tools: McpToolDefinition[]\n}\n\nexport interface PublicConsultationOptions {\n /** Resolve only deliberately published snapshots. Return null after revocation. */\n resolvePublication(agentId: string): Promise<KnowledgePublication | null>\n /** Payment authentication does not substitute for this admission decision. */\n allowConsumer(publication: KnowledgePublication, consumer: ConsultationConsumer): Promise<boolean>\n store: ChatTurnMessageStore\n turnStore: TurnEventStore\n /** Shared durable single-flight lock. Use createDurableTurnLock with thread scope. */\n turnLock: ChatTurnLock<void>\n /** Create or read the stored parent row. Return its actual persisted ownership. */\n ensureConversation(identity: ConsultationIdentity): Promise<{ workspaceId: string; threadId: string }>\n /** Prepare without compute. Refuse limits the isolated executor cannot enforce across all model and tool calls. */\n prepareExecution(input: ConsultationExecutionControl): Promise<PreparedConsultationExecution>\n}\n\ninterface GatewayConsultationContext {\n consumerId: string\n paymentMethod: string\n requestId: string\n threadId?: string\n keyInfo: { keyId: string; ownerId?: string } | null\n messages: Array<{ role: string; content: string }>\n}\n\n/** Compose gateway admission, scoped knowledge and the maintained persisted chat route. */\nexport function createPublicConsultation(options: PublicConsultationOptions) {\n if (typeof options.turnLock?.acquire !== 'function' || typeof options.turnLock.release !== 'function') {\n throw new Error('Public consultation requires a shared turn lock')\n }\n async function ownsConversation(identity: ConsultationIdentity) {\n const conversation = await options.ensureConversation(identity)\n return conversation?.workspaceId === identity.workspaceId && conversation.threadId === identity.threadId\n }\n async function resolve(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n requireIdentity(consumer.consumerId)\n requireIdentity(consumer.method)\n requireIdentity(consumer.threadId)\n const publication = await options.resolvePublication(agent.id)\n if (!publication || publication.id !== agent.id || publication.ownerId !== agent.ownerId\n || await options.allowConsumer(publication, consumer) !== true) return null\n const workspaceId = await scopedId([publication.ownerId, publication.id, publication.revision, consumer.method, consumer.consumerId])\n const threadId = await scopedId([workspaceId, consumer.threadId!])\n const identity: ConsultationIdentity = Object.freeze({\n publicationId: publication.id, publicationRevision: publication.revision,\n consumerId: consumer.consumerId, paymentMethod: consumer.method, workspaceId, threadId,\n })\n return { publication, identity }\n }\n\n return {\n async authorizeConsumer(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n const scope = await resolve(agent, consumer)\n return scope\n ? { allow: true as const }\n : { allow: false as const, reason: 'Consultation access denied', code: 'consultation_forbidden' }\n },\n async readKnowledge(agent: ConsultationAgent, consumer: ConsultationConsumer, pageId: string) {\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n return scope.publication.read(pageId)\n },\n async readHistory(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n if (!await ownsConversation(scope.identity)) throw new Error('Consultation conversation conflict')\n return (await options.store.listMessages(scope.identity.threadId))\n .map(({ role, content }) => ({ role, content }))\n },\n async getSandbox(agent: ConsultationAgent, context?: GatewayConsultationContext) {\n if (!context) throw new Error('Authenticated consultation identity is required')\n const consumer: ConsultationConsumer = {\n consumerId: context.consumerId, method: context.paymentMethod,\n requestId: context.requestId, threadId: context.threadId,\n keyId: context.keyInfo?.keyId, ownerId: context.keyInfo?.ownerId,\n }\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n // Client-supplied history and owner system prompts never enter this producer.\n const prompt = context.messages.filter(message => message.role === 'user').at(-1)?.content\n if (!prompt) throw new Error('Consultation requires a user message')\n type PromptOptions = { signal?: AbortSignal; executionBudget?: ChatTurnExecutionLimits; maxOutputTokens?: number }\n const prepare = async (streamOptions?: PromptOptions) => {\n const signal = streamOptions?.signal ?? new AbortController().signal\n signal.throwIfAborted()\n const supplied = streamOptions?.executionBudget\n const executionLimits = supplied || streamOptions?.maxOutputTokens !== undefined\n ? Object.freeze({ ...supplied, ...(streamOptions?.maxOutputTokens !== undefined\n ? { maxOutputTokens: Math.min(streamOptions.maxOutputTokens, supplied?.maxOutputTokens ?? Infinity) } : {}) })\n : undefined\n if (executionLimits && Object.values(executionLimits).some(value => typeof value !== 'number' || !Number.isFinite(value) || value < 0)) {\n return { status: 'unsupported' as const, reason: 'Invalid consultation execution limits' }\n }\n const control = Object.freeze({ identity: scope.identity, signal, executionLimits })\n const prepared = await options.prepareExecution(control)\n signal.throwIfAborted()\n if (prepared?.status !== 'prepared' || typeof prepared.produce !== 'function') {\n return { status: 'unsupported' as const, reason: prepared?.status === 'unsupported'\n ? prepared.reason : 'Invalid consultation execution preparation' }\n }\n let started = false\n const start = () => {\n signal.throwIfAborted()\n if (started) throw new Error('Consultation execution already started')\n started = true\n const routes = createChatTurnRoutes({\n projectId: 'public-consultation', store: options.store, turnStore: options.turnStore, turnLock: options.turnLock,\n authorize: async ({ intent, body }) => {\n const current = await resolve(agent, consumer)\n if (intent !== 'turn' || !current\n || current.identity.workspaceId !== scope.identity.workspaceId\n || body?.workspaceId !== scope.identity.workspaceId || body.threadId !== scope.identity.threadId) {\n return { ok: false, response: Response.json({ error: 'Consultation access denied' }, { status: 403 }) }\n }\n if (!await ownsConversation(scope.identity)) {\n return { ok: false, response: Response.json({ error: 'Consultation conversation conflict' }, { status: 403 }) }\n }\n return { ok: true, tenantId: scope.identity.workspaceId,\n userId: scope.identity.consumerId, context: undefined }\n },\n produce: args => {\n signal.throwIfAborted()\n return prepared.produce({\n ...control,\n identity: scope.identity, systemPrompt: scope.publication.systemPrompt, prompt,\n priorMessages: args.priorMessages.map(({ role, content }) => ({ role, content })),\n tools: publicationTools(scope.publication, async () => {\n signal.throwIfAborted()\n const current = await resolve(agent, consumer)\n signal.throwIfAborted()\n if (!current || current.identity.workspaceId !== scope.identity.workspaceId) {\n throw new Error('Consultation access denied')\n }\n }),\n })\n },\n })\n return streamChatRouteAsSandboxEvents({\n routes, request: new Request('https://consultation.invalid/internal'),\n payload: { workspaceId: scope.identity.workspaceId, threadId: scope.identity.threadId,\n content: prompt, turnId: consumer.requestId }, signal, executionLimits,\n })\n }\n return { status: 'prepared' as const, start }\n }\n return {\n prepareBudgetedPrompt: (_message: string, streamOptions: PromptOptions) => prepare(streamOptions),\n streamPrompt: async function* (_message: string, streamOptions?: PromptOptions) {\n const prepared = await prepare(streamOptions)\n if (prepared.status !== 'prepared') throw new Error(prepared.reason)\n yield* prepared.start()\n },\n }\n },\n }\n}\n\nfunction publicationTools(publication: KnowledgePublication, authorize: () => Promise<void>): McpToolDefinition[] {\n return [\n { name: 'knowledge_search', description: 'Search published consultation knowledge.',\n inputSchema: { type: 'object', required: ['query'], properties: { query: { type: 'string' } }, additionalProperties: false },\n run: async args => { await authorize(); return publication.search(singleArgument(args, 'query')) } },\n { name: 'knowledge_read', description: 'Read a published page by its exact citation id.',\n inputSchema: { type: 'object', required: ['pageId'], properties: { pageId: { type: 'string' } }, additionalProperties: false },\n run: async args => { await authorize(); return publication.read(singleArgument(args, 'pageId')) } },\n ]\n}\n\nfunction singleArgument(args: Record<string, unknown>, name: string): string {\n const value = args[name]\n if (Object.keys(args).length !== 1 || typeof value !== 'string' || !value.trim() || value.length > 8192) {\n throw new Error('Invalid published knowledge arguments')\n }\n return value\n}\n\nfunction requireIdentity(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !value.trim() || value.length > 512) throw new Error('Invalid consultation identity')\n}\n\nasync function scopedId(parts: string[]): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(parts)))\n return `consultation:${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,uBAAgE;AAuBlE,SAAS,2BAA2B,OAOlB;AACvB,aAAW,SAAS,CAAC,MAAM,IAAI,MAAM,UAAU,MAAM,OAAO,EAAG,iBAAgB,KAAK;AACpF,QAAM,QAAyB,CAAC;AAChC,aAAW,MAAM,IAAI,IAAI,MAAM,OAAO,GAAG;AACvC,UAAM,UAAU,MAAM,MAAM,MAAM,OAAO,CAAAA,UAAQA,MAAK,OAAO,EAAE;AAC/D,QAAI,QAAQ,WAAW,EAAG,OAAM,IAAI,MAAM,4CAA4C;AACtF,UAAM,OAAO,QAAQ,CAAC;AAEtB,UAAM,KAAK;AAAA,MAAE,IAAI,KAAK;AAAA,MAAI,OAAO,KAAK;AAAA,MAAO,MAAM,KAAK;AAAA,MAAM,MAAM,KAAK;A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OAAO,CAAC;AAAA,MAAE;AAAA,IAAE;AAAA,IACrG;AAAA,MAAE,MAAM;AAAA,MAAkB,aAAa;AAAA,MACrC,aAAa,EAAE,MAAM,UAAU,UAAU,CAAC,QAAQ,GAAG,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,EAAE,GAAG,sBAAsB,MAAM;AAAA,MAC7H,KAAK,OAAM,SAAQ;AAAE,cAAM,UAAU;AAAG,eAAO,YAAY,KAAK,eAAe,MAAM,QAAQ,CAAC;AAAA,MAAE;AAAA,IAAE;AAAA,EACtG;AACF;AAEA,SAAS,eAAe,MAA+B,MAAsB;AAC3E,QAAM,QAAQ,KAAK,IAAI;AACvB,MAAI,OAAO,KAAK,IAAI,EAAE,WAAW,KAAK,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,MAAM,SAAS,MAAM;AACvG,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,OAAyC;AAChE,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,MAAM,SAAS,IAAK,OAAM,IAAI,MAAM,+BAA+B;AACvH;AAEA,eAAe,SAAS,OAAkC;AACxD,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC;AACpG,SAAO,gBAAgB,MAAM,KAAK,IAAI,WAAW,MAAM,GAAG,UAAQ,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC;AAChH;","names":["page"]}
|
|
1
|
+
{"version":3,"sources":["../../src/public-consultation/index.ts"],"sourcesContent":["import { searchKnowledge, type KnowledgeIndex, type KnowledgePage } from '@tangle-network/agent-knowledge'\nimport { createChatTurnRoutes, type ChatTurnExecutionLimits, type ChatTurnLock, type ChatTurnMessageStore, type ChatTurnRouteProducer } from '../chat-routes/turn-routes'\nimport { streamChatRouteAsSandboxEvents } from '../chat-routes/gateway-adapter'\nimport type { TurnEventStore } from '../stream/turn-buffer'\nimport type { McpToolDefinition } from '../tools/mcp-rpc'\n\nexport interface PublishedKnowledgePage {\n readonly id: string\n readonly title: string\n readonly text: string\n}\n\n/** A server-created publication. Every selected page's complete text is public. */\nexport interface KnowledgePublication {\n readonly id: string\n readonly revision: string\n readonly ownerId: string\n readonly systemPrompt: string\n read(pageId: string): PublishedKnowledgePage | null\n search(query: string): PublishedKnowledgePage[]\n}\n\n/** Select content at publication time, before any payer or model input exists. */\nexport function createKnowledgePublication(input: {\n id: string\n revision: string\n ownerId: string\n systemPrompt: string\n index: KnowledgeIndex\n pageIds: readonly string[]\n}): KnowledgePublication {\n for (const value of [input.id, input.revision, input.ownerId]) requireIdentity(value)\n const pages: KnowledgePage[] = []\n for (const id of new Set(input.pageIds)) {\n const matches = input.index.pages.filter(page => page.id === id)\n if (matches.length !== 1) throw new Error('Publication page must resolve exactly once')\n const page = matches[0]!\n // Owner metadata, paths, links and source records can refer to private resources.\n pages.push({ id: page.id, title: page.title, text: page.text, path: page.id,\n frontmatter: {}, sourceIds: [], tags: [], outLinks: [] })\n }\n const index: KnowledgeIndex = { root: '', generatedAt: '', sources: [], pages, graph: { nodes: [], edges: [] } }\n const publicPage = (page: KnowledgePage): PublishedKnowledgePage =>\n Object.freeze({ id: page.id, title: page.title, text: page.text })\n return Object.freeze({\n id: input.id, revision: input.revision, ownerId: input.ownerId, systemPrompt: input.systemPrompt,\n read: (id: string) => {\n const page = pages.find(candidate => candidate.id === id)\n return page ? publicPage(page) : null\n },\n search: (query: string) => searchKnowledge(index, query, { limit: 10 }).map(hit => publicPage(hit.page)),\n })\n}\n\n/** Authenticated server identity. Never construct this from model arguments or request JSON. */\nexport interface ConsultationConsumer {\n method: string\n consumerId: string\n keyId?: string\n ownerId?: string\n requestId: string\n threadId?: string\n}\n\nexport interface ConsultationAgent {\n id: string\n ownerId: string\n}\n\nexport interface ConsultationIdentity {\n readonly publicationId: string\n readonly publicationRevision: string\n readonly consumerId: string\n readonly paymentMethod: string\n readonly workspaceId: string\n readonly threadId: string\n}\n\nexport interface ConsultationExecutionControl {\n readonly identity: ConsultationIdentity\n readonly signal: AbortSignal\n readonly executionLimits?: Readonly<ChatTurnExecutionLimits>\n}\n\nexport type PreparedConsultationExecution =\n | { status: 'unsupported'; reason: string }\n | { status: 'prepared'; produce(input: ConsultationExecution): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer> }\n\nexport interface ConsultationExecution extends ConsultationExecutionControl {\n readonly identity: ConsultationIdentity\n readonly systemPrompt: string\n readonly prompt: string\n readonly priorMessages: ReadonlyArray<{ role: string; content: string }>\n readonly tools: McpToolDefinition[]\n}\n\nexport interface PublicConsultationOptions {\n /** Resolve only deliberately published snapshots. Return null after revocation. */\n resolvePublication(agentId: string): Promise<KnowledgePublication | null>\n /** Payment authentication does not substitute for this admission decision. */\n allowConsumer(publication: KnowledgePublication, consumer: ConsultationConsumer): Promise<boolean>\n store: ChatTurnMessageStore\n turnStore: TurnEventStore\n /** Shared durable single-flight lock. Use createDurableTurnLock with thread scope. */\n turnLock: ChatTurnLock<void>\n /** Create or read the stored parent row. Return its actual persisted ownership. */\n ensureConversation(identity: ConsultationIdentity): Promise<{ workspaceId: string; threadId: string }>\n /** Prepare without compute. Refuse limits the isolated executor cannot enforce across all model and tool calls. */\n prepareExecution(input: ConsultationExecutionControl): Promise<PreparedConsultationExecution>\n}\n\ninterface GatewayConsultationContext {\n consumerId: string\n paymentMethod: string\n requestId: string\n threadId?: string\n keyInfo: { keyId: string; ownerId?: string } | null\n messages: Array<{ role: string; content: string }>\n}\n\n/** Compose gateway admission, scoped knowledge and the maintained persisted chat route. */\nexport function createPublicConsultation(options: PublicConsultationOptions) {\n if (typeof options.turnLock?.acquire !== 'function' || typeof options.turnLock.release !== 'function') {\n throw new Error('Public consultation requires a shared turn lock')\n }\n async function ownsConversation(identity: ConsultationIdentity) {\n const conversation = await options.ensureConversation(identity)\n return conversation?.workspaceId === identity.workspaceId && conversation.threadId === identity.threadId\n }\n async function resolve(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n requireIdentity(consumer.consumerId)\n requireIdentity(consumer.method)\n requireIdentity(consumer.threadId)\n const publication = await options.resolvePublication(agent.id)\n if (!publication || publication.id !== agent.id || publication.ownerId !== agent.ownerId\n || await options.allowConsumer(publication, consumer) !== true) return null\n const workspaceId = await scopedId([publication.ownerId, publication.id, publication.revision, consumer.method, consumer.consumerId])\n const threadId = await scopedId([workspaceId, consumer.threadId!])\n const identity: ConsultationIdentity = Object.freeze({\n publicationId: publication.id, publicationRevision: publication.revision,\n consumerId: consumer.consumerId, paymentMethod: consumer.method, workspaceId, threadId,\n })\n return { publication, identity }\n }\n\n return {\n async authorizeConsumer(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n const scope = await resolve(agent, consumer)\n return scope\n ? { allow: true as const }\n : { allow: false as const, reason: 'Consultation access denied', code: 'consultation_forbidden' }\n },\n async readKnowledge(agent: ConsultationAgent, consumer: ConsultationConsumer, pageId: string) {\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n return scope.publication.read(pageId)\n },\n async readHistory(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n if (!await ownsConversation(scope.identity)) throw new Error('Consultation conversation conflict')\n return (await options.store.listMessages(scope.identity.threadId))\n .map(({ role, content }) => ({ role, content }))\n },\n async getSandbox(agent: ConsultationAgent, context?: GatewayConsultationContext) {\n if (!context) throw new Error('Authenticated consultation identity is required')\n const consumer: ConsultationConsumer = {\n consumerId: context.consumerId, method: context.paymentMethod,\n requestId: context.requestId, threadId: context.threadId,\n keyId: context.keyInfo?.keyId, ownerId: context.keyInfo?.ownerId,\n }\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n // Client-supplied history and owner system prompts never enter this producer.\n const prompt = context.messages.filter(message => message.role === 'user').at(-1)?.content\n if (!prompt) throw new Error('Consultation requires a user message')\n type PromptOptions = { signal?: AbortSignal; executionBudget?: ChatTurnExecutionLimits; maxOutputTokens?: number }\n const prepare = async (streamOptions?: PromptOptions) => {\n const signal = streamOptions?.signal ?? new AbortController().signal\n signal.throwIfAborted()\n const supplied = streamOptions?.executionBudget\n const executionLimits = supplied || streamOptions?.maxOutputTokens !== undefined\n ? Object.freeze({ ...supplied, ...(streamOptions?.maxOutputTokens !== undefined\n ? { maxOutputTokens: Math.min(streamOptions.maxOutputTokens, supplied?.maxOutputTokens ?? Infinity) } : {}) })\n : undefined\n if (executionLimits && Object.values(executionLimits).some(value => typeof value !== 'number' || !Number.isFinite(value) || value < 0)) {\n return { status: 'unsupported' as const, reason: 'Invalid consultation execution limits' }\n }\n const control = Object.freeze({ identity: scope.identity, signal, executionLimits })\n const prepared = await options.prepareExecution(control)\n signal.throwIfAborted()\n if (prepared?.status !== 'prepared' || typeof prepared.produce !== 'function') {\n return { status: 'unsupported' as const, reason: prepared?.status === 'unsupported'\n ? prepared.reason : 'Invalid consultation execution preparation' }\n }\n let started = false\n const start = () => {\n signal.throwIfAborted()\n if (started) throw new Error('Consultation execution already started')\n started = true\n const routes = createChatTurnRoutes({\n projectId: 'public-consultation', store: options.store, turnStore: options.turnStore, turnLock: options.turnLock,\n authorize: async ({ intent, body }) => {\n const current = await resolve(agent, consumer)\n if (intent !== 'turn' || !current\n || current.identity.workspaceId !== scope.identity.workspaceId\n || body?.workspaceId !== scope.identity.workspaceId || body.threadId !== scope.identity.threadId) {\n return { ok: false, response: Response.json({ error: 'Consultation access denied' }, { status: 403 }) }\n }\n if (!await ownsConversation(scope.identity)) {\n return { ok: false, response: Response.json({ error: 'Consultation conversation conflict' }, { status: 403 }) }\n }\n return { ok: true, tenantId: scope.identity.workspaceId,\n userId: scope.identity.consumerId, context: undefined }\n },\n produce: args => {\n signal.throwIfAborted()\n return prepared.produce({\n ...control,\n identity: scope.identity, systemPrompt: scope.publication.systemPrompt, prompt,\n priorMessages: args.priorMessages.map(({ role, content }) => ({ role, content })),\n tools: publicationTools(scope.publication, async () => {\n signal.throwIfAborted()\n const current = await resolve(agent, consumer)\n signal.throwIfAborted()\n if (!current || current.identity.workspaceId !== scope.identity.workspaceId) {\n throw new Error('Consultation access denied')\n }\n }),\n })\n },\n })\n return streamChatRouteAsSandboxEvents({\n routes, request: new Request('https://consultation.invalid/internal'),\n payload: { workspaceId: scope.identity.workspaceId, threadId: scope.identity.threadId,\n content: prompt, turnId: consumer.requestId }, signal, executionLimits,\n })\n }\n return { status: 'prepared' as const, start }\n }\n return {\n prepareBudgetedPrompt: (_message: string, streamOptions: PromptOptions) => prepare(streamOptions),\n streamPrompt: async function* (_message: string, streamOptions?: PromptOptions) {\n const prepared = await prepare(streamOptions)\n if (prepared.status !== 'prepared') throw new Error(prepared.reason)\n yield* prepared.start()\n },\n }\n },\n }\n}\n\nfunction publicationTools(publication: KnowledgePublication, authorize: () => Promise<void>): McpToolDefinition[] {\n return [\n { name: 'knowledge_search', description: 'Search published consultation knowledge.',\n inputSchema: { type: 'object', required: ['query'], properties: { query: { type: 'string' } }, additionalProperties: false },\n run: async args => { await authorize(); return publication.search(singleArgument(args, 'query')) } },\n { name: 'knowledge_read', description: 'Read a published page by its exact citation id.',\n inputSchema: { type: 'object', required: ['pageId'], properties: { pageId: { type: 'string' } }, additionalProperties: false },\n run: async args => { await authorize(); return publication.read(singleArgument(args, 'pageId')) } },\n ]\n}\n\nfunction singleArgument(args: Record<string, unknown>, name: string): string {\n const value = args[name]\n if (Object.keys(args).length !== 1 || typeof value !== 'string' || !value.trim() || value.length > 8192) {\n throw new Error('Invalid published knowledge arguments')\n }\n return value\n}\n\nfunction requireIdentity(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !value.trim() || value.length > 512) throw new Error('Invalid consultation identity')\n}\n\nasync function scopedId(parts: string[]): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(parts)))\n return `consultation:${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AK,KAAK,MAAM,SAAS,IAAK,OAAM,IAAI,MAAM,+BAA+B;AACvH;AAEA,eAAe,SAAS,OAAkC;AACxD,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC;AACpG,SAAO,gBAAgB,MAAM,KAAK,IAAI,WAAW,MAAM,GAAG,UAAQ,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC;AAChH;","names":["page"]}
|
package/dist/stream/index.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
|
-
buildUserTextParts,
|
|
3
2
|
consumeTurnStream,
|
|
3
|
+
observeTurnEvent,
|
|
4
|
+
parseTurnObservation
|
|
5
|
+
} from "../chunk-YXYQ6MJL.js";
|
|
6
|
+
import {
|
|
7
|
+
buildUserTextParts,
|
|
4
8
|
messageHasTurnId,
|
|
5
9
|
normalizeClientTurnId,
|
|
6
|
-
observeTurnEvent,
|
|
7
|
-
parseTurnObservation,
|
|
8
10
|
resolveChatTurn
|
|
9
|
-
} from "../chunk-
|
|
11
|
+
} from "../chunk-YG66IHDU.js";
|
|
10
12
|
import {
|
|
11
13
|
DEFAULT_RUNNING_TURN_LEASE_MS,
|
|
12
14
|
DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent-surfaces/index.ts"],"sourcesContent":["/**\n * Machine-readable surfaces for a Tangle product, generated from one config.\n *\n * Every product publishes the same four things an AI agent needs to become a\n * customer without a human doing the setup:\n *\n * - `/agent-setup.md`: a SKILL.md (Claude Code and Codex skill format) that\n * doubles as a copy-paste prompt. It takes a fresh agent from nothing to a\n * verified first call: one owner approval, a scoped key, install, call.\n * - `/llms.txt`: the llms.txt index, pointing at the setup skill first.\n * - `/.well-known/tangle-agent.json`: the Tangle agent manifest.\n * - Markdown for `Accept: text/markdown` on the product's pages, with\n * `Vary: Accept` on both representations so caches keep them apart.\n *\n * The signup section is rendered here, not in product config, so every\n * product describes Platform's agent signup identically and cannot drift.\n *\n * Web-standard `Request`/`Response` only: safe in Workers, Node and browsers.\n */\n\n/** Manifest schema this module emits. Additive over the 2026-06-16 shape. */\nexport const AGENT_MANIFEST_SCHEMA_VERSION = '2026-10-09'\n\nexport const TANGLE_PLATFORM_ORIGIN = 'https://id.tangle.tools'\n\nexport interface AgentSurfaceStep {\n title: string\n /** Fence language for the code block. */\n language: 'bash' | 'js' | 'ts' | 'python' | 'json'\n code: string\n /** What a successful run prints or returns. */\n expect: string\n}\n\nexport interface AgentSurfaceError {\n symptom: string\n cause: string\n fix: string\n}\n\nexport interface AgentSurfaceLink {\n label: string\n url: string\n}\n\n/**\n * How an agent obtains a key. `device` uses Platform's agent signup: the owner\n * approves once and the agent receives its own capped, revocable key.\n */\nexport type AgentSignup =\n | {\n kind: 'device'\n /** Platform trusted-app id the key is minted for (`sandbox`, `router`). */\n app: string\n /** Default lifetime spend cap the skill asks for, in USD. */\n budgetUsd?: number\n }\n | {\n kind: 'manual'\n /** Numbered steps the owner performs; each one is a human input. */\n steps: string[]\n }\n\nexport interface AgentSurfaceConfig {\n /** Short id used in the skill name: `tangle-<id>-setup`. */\n id: string\n name: string\n /** Public HTTPS origin, no trailing slash. */\n origin: string\n /** What the product is for, in one to three plain sentences. */\n summary: string\n useWhen: string[]\n signup: AgentSignup\n /** Environment variable the key is exported as. */\n apiKeyEnv: string\n /** Runtime prerequisites a fresh machine needs, e.g. `Node.js 20 or newer`. */\n prerequisites: string[]\n install: AgentSurfaceStep[]\n firstCall: AgentSurfaceStep[]\n verify: AgentSurfaceStep[]\n errors: AgentSurfaceError[]\n pricing: {\n /** Plain statement of how usage is charged. */\n summary: string\n /** Public, credential-free price data an agent can quote from. */\n quoteUrl?: string\n url?: string\n }\n next: AgentSurfaceLink[]\n docs?: string\n openapi?: string\n mcp?: { url: string; auth: string }\n related?: Array<{ name: string; manifest?: string; url?: string }>\n /** Extra manifest fields a product already publishes (kept verbatim). */\n manifest?: Record<string, unknown>\n}\n\nexport interface AgentSurfaceFile {\n path: string\n contentType: string\n body: string\n}\n\nconst MARKDOWN = 'text/markdown; charset=utf-8'\n\nfunction trimOrigin(origin: string): string {\n return origin.replace(/\\/+$/, '')\n}\n\nfunction fence(step: Pick<AgentSurfaceStep, 'language' | 'code'>): string {\n return ['```' + step.language, step.code.trimEnd(), '```'].join('\\n')\n}\n\n/**\n * The signup script the skill tells an agent to save and run. Node 18+ only,\n * no dependencies, in two short commands so a tool that kills long-running\n * commands cannot cut the wait: `start` returns at once with the link and the\n * confirmation code; `wait` polls for a few seconds and exits 0 once approved\n * or 3 while the owner has not approved yet. It never prints the key; it\n * writes `.tangle/api-key` with mode 0600.\n */\nexport function agentSignupScript(platformOrigin = TANGLE_PLATFORM_ORIGIN): string {\n // The specifier is interpolated so this module's own import scan (the\n // browser-safe subpath gate) does not read script text as an import.\n return `// Requests a scoped Tangle key for this agent. The owner approves once.\n// node tangle-signup.mjs start --app <app> --agent-name <name> [--owner-email <email>] [--budget-usd <n>]\n// node tangle-signup.mjs wait (run again while it exits 3; exits 0 once approved)\nimport { mkdirSync, readFileSync, writeFileSync } from ${JSON.stringify('node:fs')}\n\nconst command = process.argv[2]\nconst flag = (name) => {\n const index = process.argv.indexOf(\\`--\\${name}\\`)\n return index > 0 ? process.argv[index + 1] : undefined\n}\nconst platform = '${trimOrigin(platformOrigin)}'\nconst statePath = '.tangle/signup.json'\nmkdirSync('.tangle', { recursive: true, mode: 0o700 })\n\nasync function post(path, body) {\n const response = await fetch(platform + path, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n return { status: response.status, body: await response.json().catch(() => ({})) }\n}\n\nif (command === 'start') {\n const app = flag('app')\n if (!app) {\n console.error('Pass --app (for example --app sandbox)')\n process.exit(2)\n }\n const request = { app, agent_name: flag('agent-name') ?? 'coding-agent' }\n if (flag('owner-email')) request.owner_email = flag('owner-email')\n if (flag('budget-usd')) request.budget_usd = Number(flag('budget-usd'))\n const started = await post('/cross-site/device/start', request)\n if (started.status !== 200) {\n console.error(\\`Signup refused (HTTP \\${started.status}): \\${JSON.stringify(started.body)}\\`)\n process.exit(1)\n }\n const grant = started.body.data\n const saved = {\n app,\n device_code: grant.device_code,\n interval: grant.interval,\n expires_at: Date.now() + grant.expires_in * 1000,\n }\n writeFileSync(statePath, JSON.stringify(saved), { mode: 0o600 })\n console.log(grant.agent?.owner_notified\n ? \\`Approval email sent to \\${request.owner_email}.\\`\n : 'Send your owner this approval link.')\n console.log(\\`Approval link: \\${grant.verification_uri_complete}\\`)\n console.log(\\`Confirmation code: \\${grant.user_code} (expires in \\${Math.round(grant.expires_in / 60)} minutes)\\`)\n console.log('Next: run \\`node tangle-signup.mjs wait\\` until it prints Approved.')\n process.exit(0)\n}\n\nif (command === 'wait') {\n let saved\n try {\n saved = JSON.parse(readFileSync(statePath, 'utf8'))\n } catch {\n console.error('No pending signup. Run \\`node tangle-signup.mjs start\\` first.')\n process.exit(1)\n }\n const stopAt = Math.min(saved.expires_at, Date.now() + Number(flag('seconds') ?? 8) * 1000)\n for (;;) {\n const polled = await post('/cross-site/device/poll', { app: saved.app, device_code: saved.device_code })\n if (polled.status === 200) {\n const { api_key: apiKey, key, account } = polled.body.data\n writeFileSync('.tangle/api-key', \\`\\${apiKey}\\\\n\\`, { mode: 0o600 })\n console.log(\\`Approved. Key \"\\${key?.name ?? saved.app}\" saved to .tangle/api-key (spend cap $\\${key?.budget_usd ?? 'none'}).\\`)\n if (account && !account.funded) {\n console.log(\\`The owner's account has no credit yet. Ask the owner to add credits: \\${account.add_credits_url}\\`)\n }\n process.exit(0)\n }\n if (polled.status !== 428) {\n console.error(\\`Approval failed (HTTP \\${polled.status}): \\${JSON.stringify(polled.body)}\\`)\n process.exit(1)\n }\n if (Date.now() >= saved.expires_at) {\n console.error('The approval link expired. Run \\`node tangle-signup.mjs start\\` again.')\n process.exit(1)\n }\n if (Date.now() + saved.interval * 1000 > stopAt) {\n console.log('Still waiting for the owner to approve. Run \\`node tangle-signup.mjs wait\\` again.')\n process.exit(3)\n }\n await new Promise((resolve) => setTimeout(resolve, saved.interval * 1000))\n }\n}\n\nconsole.error('Usage: node tangle-signup.mjs start --app <app> --agent-name <name> [--owner-email <email>] | wait')\nprocess.exit(2)\n`\n}\n\nfunction signupSection(config: AgentSurfaceConfig): string[] {\n const env = config.apiKeyEnv\n if (config.signup.kind === 'manual') {\n return [\n '## 1. Get a key',\n '',\n 'This product does not yet support agent signup. Ask your owner to do the following, then continue:',\n '',\n ...config.signup.steps.map((step, index) => `${index + 1}. ${step}`),\n '',\n `Store the key outside version control and export it as \\`${env}\\`. Never print, log, or commit it.`,\n ]\n }\n const budget = config.signup.budgetUsd ?? 25\n return [\n '## 1. Get a scoped key (one owner approval)',\n '',\n 'Tangle issues each agent its own key, owned by a person who approves it once.',\n `Ask your owner which email address their Tangle account uses (or should use). Nothing is charged by signing up, and there is no free credit: ${config.name} work is paid from the owner's prepaid balance.`,\n '',\n 'Save this script as `tangle-signup.mjs` (Node.js 18 or newer, no dependencies):',\n '',\n fence({ language: 'js', code: agentSignupScript() }),\n '',\n 'Start the request with your own name and the owner\\'s email. It returns at once:',\n '',\n fence({\n language: 'bash',\n code: `node tangle-signup.mjs start --app ${config.signup.app} --agent-name \"<your agent name>\" --owner-email \"<owner email>\" --budget-usd ${budget}`,\n }),\n '',\n 'It prints the approval link and a confirmation code. Tangle emails the owner the same link; if you cannot give an email, omit `--owner-email` and send the owner the printed link yourself. Tell the owner the code if you can reach them.',\n '',\n 'Then wait for the approval. Each run returns within about 8 seconds: exit code 3 and `Still waiting` mean run it again; exit code 0 and `Approved` mean the key is saved. Keep each run short rather than wrapping it in one long blocking loop, since many agent tools stop long commands.',\n '',\n fence({ language: 'bash', code: 'node tangle-signup.mjs wait' }),\n '',\n 'What the owner does, once: sign in (or create an account and verify the email), check the confirmation code, and approve. That is the only human step.',\n '',\n `The key in \\`.tangle/api-key\\` (mode 600) can only be used for ${config.name}, can spend at most the cap you requested, and the owner can revoke it under Keys at any time. If \\`wait\\` says the account has no credit, ask the owner to add credits at the printed link before your first paid call.`,\n '',\n 'Then load the key without printing it, and keep it out of version control:',\n '',\n fence({\n language: 'bash',\n code: `export ${env}=\"$(cat .tangle/api-key)\"\\ngrep -qxF '.tangle/' .gitignore 2>/dev/null || echo '.tangle/' >> .gitignore`,\n }),\n '',\n 'Never print, log, paste, or commit the key.',\n ]\n}\n\nfunction stepsSection(heading: string, steps: AgentSurfaceStep[]): string[] {\n if (steps.length === 0) return []\n const lines = [heading, '']\n for (const step of steps) {\n lines.push(`${step.title}:`, '', fence(step), '', `Expected: ${step.expect}`, '')\n }\n return lines\n}\n\n/** The agent setup skill: valid SKILL.md and a plain copy-paste prompt. */\nexport function renderAgentSetupSkill(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n const description = `Set up ${config.name} for this agent end to end: get a scoped API key with one owner approval, install the client, make the first successful call, and verify it.`\n const lines: string[] = [\n '---',\n `name: tangle-${config.id}-setup`,\n `description: ${description}`,\n '---',\n '',\n `# Set up ${config.name}`,\n '',\n config.summary,\n '',\n 'Use it when:',\n '',\n ...config.useWhen.map((item) => `- ${item}`),\n '',\n 'Complete every step below in order and stop at the first failure; the error table at the end names the fix.',\n 'Prerequisites: ' + config.prerequisites.join('; ') + '.',\n '',\n ...signupSection(config),\n '',\n ...stepsSection('## 2. Install', config.install),\n ...stepsSection('## 3. Make the first call', config.firstCall),\n ...stepsSection('## 4. Verify it worked', config.verify),\n '## Common errors',\n '',\n '| Symptom | Cause | Fix |',\n '| --- | --- | --- |',\n ...config.errors.map(\n (error) => `| ${error.symptom.replace(/\\|/g, '\\\\|')} | ${error.cause.replace(/\\|/g, '\\\\|')} | ${error.fix.replace(/\\|/g, '\\\\|')} |`,\n ),\n '',\n '## Pricing',\n '',\n config.pricing.summary,\n ...(config.pricing.quoteUrl ? ['', `Current prices, no key needed: ${config.pricing.quoteUrl}`] : []),\n ...(config.pricing.url ? [`Pricing page: ${config.pricing.url}`] : []),\n '',\n '## Next',\n '',\n ...config.next.map((link) => `- [${link.label}](${link.url})`),\n '',\n '## Machine-readable surfaces',\n '',\n `- Agent manifest: ${origin}/.well-known/tangle-agent.json`,\n `- llms.txt: ${origin}/llms.txt`,\n `- This setup skill: ${origin}/agent-setup.md`,\n ...(config.openapi ? [`- OpenAPI: ${config.openapi}`] : []),\n ...(config.mcp ? [`- MCP server: ${config.mcp.url} (${config.mcp.auth})`] : []),\n '',\n ]\n return lines.join('\\n')\n}\n\n/** llms.txt index for the product. The setup skill is the first link. */\nexport function renderLlmsTxt(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n return [\n `# ${config.name}`,\n '',\n `> ${config.summary}`,\n '',\n `To set this product up from scratch, fetch ${origin}/agent-setup.md and follow it. It is a complete prompt and a SKILL.md: one owner approval, a scoped key, install, first call, verification.`,\n '',\n '## Start here',\n '',\n `- [Agent setup skill](${origin}/agent-setup.md): from nothing to a verified first call`,\n `- [Agent manifest](${origin}/.well-known/tangle-agent.json): machine-readable contract`,\n ...(config.openapi ? [`- [OpenAPI](${config.openapi}): HTTP API schema`] : []),\n ...(config.mcp ? [`- [MCP server](${config.mcp.url}): ${config.mcp.auth}`] : []),\n ...(config.docs ? [`- [Documentation](${config.docs})`] : []),\n '',\n '## Pricing',\n '',\n `- ${config.pricing.summary}`,\n ...(config.pricing.quoteUrl ? [`- [Machine-readable prices](${config.pricing.quoteUrl}): no key needed`] : []),\n '',\n '## Optional',\n '',\n ...config.next.map((link) => `- [${link.label}](${link.url})`),\n ...(config.related ?? []).map(\n (surface) => `- [${surface.name}](${surface.manifest ?? surface.url ?? ''})`,\n ),\n '',\n ].join('\\n')\n}\n\n/** Markdown for the product's home page, served for `Accept: text/markdown`. */\nexport function renderHomeMarkdown(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n return [\n `# ${config.name}`,\n '',\n config.summary,\n '',\n '## Use it when',\n '',\n ...config.useWhen.map((item) => `- ${item}`),\n '',\n '## Hand this to your agent',\n '',\n `An AI agent can set ${config.name} up by itself: fetch ${origin}/agent-setup.md and follow it. The owner approves once; nothing else needs a human.`,\n '',\n '## Pricing',\n '',\n config.pricing.summary,\n ...(config.pricing.quoteUrl ? ['', `Machine-readable prices: ${config.pricing.quoteUrl}`] : []),\n '',\n '## Machine-readable surfaces',\n '',\n `- ${origin}/llms.txt`,\n `- ${origin}/.well-known/tangle-agent.json`,\n `- ${origin}/agent-setup.md`,\n ...(config.openapi ? [`- ${config.openapi}`] : []),\n ...(config.mcp ? [`- ${config.mcp.url}`] : []),\n '',\n ].join('\\n')\n}\n\n/** The `/.well-known/tangle-agent.json` document. */\nexport function renderAgentManifest(config: AgentSurfaceConfig): Record<string, unknown> {\n const origin = trimOrigin(config.origin)\n const signup =\n config.signup.kind === 'device'\n ? {\n kind: 'device_authorization',\n app: config.signup.app,\n start: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/start`,\n poll: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/poll`,\n request: {\n app: config.signup.app,\n agent_name: 'string, 1-64 characters',\n owner_email: 'optional; Tangle emails this owner the approval link',\n budget_usd: `optional lifetime spend cap, 1-1000, default ${config.signup.budgetUsd ?? 25}`,\n },\n human_inputs: ['The owner approves the request once.'],\n key: {\n scope: `${config.signup.app} only`,\n revocable_at: `${TANGLE_PLATFORM_ORIGIN}/app/keys`,\n },\n payment: 'Prepaid credit on the owner account. No free credit; paid calls are refused until the owner adds credits.',\n add_credits: `${TANGLE_PLATFORM_ORIGIN}/app/billing`,\n }\n : { kind: 'manual', steps: config.signup.steps }\n return {\n ...config.manifest,\n schema_version: AGENT_MANIFEST_SCHEMA_VERSION,\n name: config.name,\n description: config.summary,\n homepage: `${origin}/`,\n llms: `${origin}/llms.txt`,\n agent_setup: `${origin}/agent-setup.md`,\n ...(config.docs ? { docs: config.docs } : {}),\n ...(config.openapi ? { openapi: config.openapi } : {}),\n ...(config.mcp ? { mcp: config.mcp } : {}),\n environment: { api_key: config.apiKeyEnv },\n signup,\n pricing: {\n summary: config.pricing.summary,\n ...(config.pricing.quoteUrl ? { quote: config.pricing.quoteUrl } : {}),\n ...(config.pricing.url ? { page: config.pricing.url } : {}),\n },\n ...(config.related?.length ? { related_surfaces: config.related } : {}),\n }\n}\n\n/** Every static surface as files, for products that ship them as assets. */\nexport function agentSurfaceFiles(config: AgentSurfaceConfig): AgentSurfaceFile[] {\n return [\n { path: 'agent-setup.md', contentType: MARKDOWN, body: renderAgentSetupSkill(config) },\n { path: 'llms.txt', contentType: 'text/plain; charset=utf-8', body: renderLlmsTxt(config) },\n { path: 'index.md', contentType: MARKDOWN, body: renderHomeMarkdown(config) },\n {\n path: '.well-known/tangle-agent.json',\n contentType: 'application/json; charset=utf-8',\n body: `${JSON.stringify(renderAgentManifest(config), null, 2)}\\n`,\n },\n ]\n}\n\n/**\n * True when `Accept` ranks `text/markdown` strictly above `text/html` and\n * gives it a nonzero weight. A browser's default header never does.\n */\nexport function prefersMarkdown(accept: string | null | undefined): boolean {\n if (!accept) return false\n let markdown = -1\n let html = -1\n for (const part of accept.split(',')) {\n const [rawType, ...params] = part.trim().split(';')\n const type = rawType?.trim().toLowerCase()\n let quality = 1\n for (const param of params) {\n const [key, value] = param.trim().split('=')\n if (key?.trim().toLowerCase() === 'q') {\n const parsed = Number(value)\n quality = Number.isFinite(parsed) ? parsed : 0\n }\n }\n if (type === 'text/markdown') markdown = Math.max(markdown, quality)\n if (type === 'text/html') html = Math.max(html, quality)\n }\n return markdown > 0 && markdown > html\n}\n\n/** A copy of `response` whose `Vary` includes `Accept`. */\nexport function withVaryAccept(response: Response): Response {\n const vary = response.headers.get('vary')\n if (vary && vary.split(',').some((value) => value.trim().toLowerCase() === 'accept')) {\n return response\n }\n const headers = new Headers(response.headers)\n headers.set('vary', vary ? `${vary}, Accept` : 'Accept')\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n}\n\nexport interface AgentSurfaceHandler {\n /**\n * Answers a surface request (`/agent-setup.md`, `/llms.txt`, the manifest,\n * or a negotiated markdown page), or `null` to let the app answer it.\n */\n handle(request: Request): Response | null\n /** Adds `Vary: Accept` when the path has a markdown representation. */\n finalize(request: Request, response: Response): Response\n}\n\n/**\n * Request handler over {@link agentSurfaceFiles}. `markdownPages` maps extra\n * HTML paths to markdown served on negotiation; `/` always maps to the home\n * markdown.\n */\nexport function createAgentSurfaceHandler(\n config: AgentSurfaceConfig,\n options: { markdownPages?: Record<string, string> } = {},\n): AgentSurfaceHandler {\n const files = new Map(agentSurfaceFiles(config).map((file) => [`/${file.path}`, file]))\n const negotiated = new Map<string, string>([\n ['/', renderHomeMarkdown(config)],\n ...Object.entries(options.markdownPages ?? {}),\n ])\n\n function respond(body: string, contentType: string, method: string, vary: boolean): Response {\n const headers = new Headers({\n 'content-type': contentType,\n 'cache-control': 'public, max-age=300',\n 'x-content-type-options': 'nosniff',\n })\n if (vary) headers.set('vary', 'Accept')\n return new Response(method === 'HEAD' ? null : body, { status: 200, headers })\n }\n\n return {\n handle(request) {\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n const path = new URL(request.url).pathname\n const file = files.get(path)\n if (file) return respond(file.body, file.contentType, request.method, false)\n const markdown = negotiated.get(path)\n if (markdown !== undefined && prefersMarkdown(request.headers.get('accept'))) {\n return respond(markdown, MARKDOWN, request.method, true)\n }\n return null\n },\n finalize(request, response) {\n return negotiated.has(new URL(request.url).pathname) ? withVaryAccept(response) : response\n },\n }\n}\n"],"mappings":";AAqBO,IAAM,gCAAgC;AAEtC,IAAM,yBAAyB;AAgFtC,IAAM,WAAW;AAEjB,SAAS,WAAW,QAAwB;AAC1C,SAAO,OAAO,QAAQ,QAAQ,EAAE;AAClC;AAEA,SAAS,MAAM,MAA2D;AACxE,SAAO,CAAC,QAAQ,KAAK,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AAA,MACjB,0BAA0B;AAAA,IAC5B,CAAC;AACD,QAAI,KAAM,SAAQ,IAAI,QAAQ,QAAQ;AACtC,WAAO,IAAI,SAAS,WAAW,SAAS,OAAO,MAAM,EAAE,QAAQ,KAAK,QAAQ,CAAC;AAAA,EAC/E;AAEA,SAAO;AAAA,IACL,OAAO,SAAS;AACd,UAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,OAAQ,QAAO;AAClE,YAAM,OAAO,IAAI,IAAI,QAAQ,GAAG,EAAE;AAClC,YAAM,OAAO,MAAM,IAAI,IAAI;AAC3B,UAAI,KAAM,QAAO,QAAQ,KAAK,MAAM,KAAK,aAAa,QAAQ,QAAQ,KAAK;AAC3E,YAAM,WAAW,WAAW,IAAI,IAAI;AACpC,UAAI,aAAa,UAAa,gBAAgB,QAAQ,QAAQ,IAAI,QAAQ,CAAC,GAAG;AAC5E,eAAO,QAAQ,UAAU,UAAU,QAAQ,QAAQ,IAAI;AAAA,MACzD;AACA,aAAO;AAAA,IACT;AAAA,IACA,SAAS,SAAS,UAAU;AAC1B,aAAO,WAAW,IAAI,IAAI,IAAI,QAAQ,GAAG,EAAE,QAAQ,IAAI,eAAe,QAAQ,IAAI;AAAA,IACpF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stream/turn-identity.ts","../src/stream/turn-observation.ts"],"sourcesContent":["import type { JsonRecord } from './stream-normalizer'\n\n/** Minimum read-only shape; typed chat parts need no dictionary index signature. */\ninterface TurnIdentityMessage {\n readonly id: string\n readonly role: 'user' | 'assistant' | 'system' | 'tool'\n readonly content: string\n readonly parts: readonly object[] | null\n}\n\n/** Retained compatibility shape for callers using unstructured message records. */\nexport interface PersistedChatMessageForTurn extends TurnIdentityMessage {\n id: string\n role: TurnIdentityMessage['role']\n content: string\n parts: Array<Record<string, unknown>> | null\n}\n\n/** Represent a chat turn with resolved user message insertion and prior message context */\nexport interface ResolvedChatTurn<Message extends TurnIdentityMessage = PersistedChatMessageForTurn> {\n turnIndex: number\n shouldInsertUserMessage: boolean\n priorMessages: Message[]\n userParts: JsonRecord[]\n /** The id of the user row this turn REUSES (retry dedup), when one was\n * found. Absent on the insert path, where no row exists yet.\n *\n * The reused row is deliberately EXCLUDED from `priorMessages` (it is this\n * turn's own user message, not prior context), so this field is the only\n * way a caller can name it. */\n reusedUserMessageId?: string\n}\n\n/** Normalize and validate a client turn ID string ensuring it meets format and length requirements */\nexport function normalizeClientTurnId(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined\n if (typeof value !== 'string') throw new Error('turnId must be a string')\n const trimmed = value.trim()\n if (!trimmed) throw new Error('turnId must not be blank')\n if (trimmed.length > 160) throw new Error('turnId is too long')\n if (!/^[A-Za-z0-9:_-]+$/.test(trimmed)) {\n throw new Error('turnId contains unsupported characters')\n }\n return trimmed\n}\n\n/** Build an array of text parts with optional turn ID for user input */\nexport function buildUserTextParts(text: string, turnId: string | undefined): JsonRecord[] {\n const part: JsonRecord = { type: 'text', text }\n if (turnId) part.turnId = turnId\n return [part]\n}\n\n/** Resolve whether a message contains any part with the specified turn ID */\nexport function messageHasTurnId(message: Pick<TurnIdentityMessage, 'parts'>, turnId: string): boolean {\n for (const part of message.parts ?? []) {\n if (part && typeof part === 'object' && 'turnId' in part && String(part.turnId ?? '') === turnId) {\n return true\n }\n }\n return false\n}\n\n/** Resolve a chat turn by determining message reuse and constructing user message parts */\nexport function resolveChatTurn<Message extends TurnIdentityMessage>(input: {\n existingMessages: readonly Message[]\n userContent: string\n turnId?: string\n /** True when the thread has a turn still RUNNING in the turn-event buffer\n * (`turnStore.listRunning(threadId)`).\n *\n * Without incremental persistence the trailing row of a thread mid-turn is\n * always the user row, so the content fallback below could assume it. With\n * incremental persistence the assistant row lands seconds into the turn, so\n * a retry of that same turn finds an ASSISTANT row trailing and would\n * insert a duplicate user row.\n *\n * This flag is the discriminator that keeps both cases right, and it needs\n * no new state: an assistant row trailing a turn that is still running is\n * that turn's in-flight draft (walk past it — this is a retry), whereas an\n * assistant row trailing a SETTLED turn is a completed answer (stop — the\n * user genuinely repeated a message and deserves a new turn). */\n hasRunningTurn?: boolean\n}): ResolvedChatTurn<Message> {\n const { existingMessages, userContent, turnId } = input\n const reusableIndex = findReusableUserMessageIndex(\n existingMessages,\n userContent,\n turnId,\n input.hasRunningTurn === true,\n )\n if (reusableIndex >= 0) {\n // Guarded read: `id` is typed `string`, but these rows come from a product\n // store the shell does not validate, so an adapter that omits it must\n // surface as \"no id\" rather than as the string \"undefined\".\n const reusedId = existingMessages[reusableIndex]?.id\n const priorMessages = existingMessages.slice(0, reusableIndex)\n return {\n turnIndex: countUserMessages(priorMessages),\n shouldInsertUserMessage: false,\n priorMessages,\n userParts: buildUserTextParts(userContent, turnId),\n ...(typeof reusedId === 'string' && reusedId ? { reusedUserMessageId: reusedId } : {}),\n }\n }\n\n return {\n turnIndex: countUserMessages(existingMessages),\n shouldInsertUserMessage: true,\n priorMessages: existingMessages.slice(),\n userParts: buildUserTextParts(userContent, turnId),\n }\n}\n\nfunction findReusableUserMessageIndex(\n messages: readonly TurnIdentityMessage[],\n userContent: string,\n turnId: string | undefined,\n hasRunningTurn: boolean,\n): number {\n if (turnId) {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (message?.role === 'user' && messageHasTurnId(message, turnId)) return index\n }\n // A caller-supplied id is authoritative. A different id with identical\n // text is a deliberate new turn, while a transport retry reuses the same\n // id and takes the match above. Falling through to content dedup here lets\n // an unrelated abandoned running row swallow an intentional repeat.\n return -1\n }\n\n // Content fallback for a client that sends no turnId. Only the trailing rows\n // of a turn still RUNNING are walked past (they are that turn's incrementally\n // persisted assistant draft); a settled assistant row still ends the scan, so\n // a user who genuinely repeats a message gets a new turn exactly as before.\n let index = messages.length - 1\n if (hasRunningTurn) {\n while (index >= 0 && messages[index]?.role === 'assistant') index -= 1\n }\n const latest = index >= 0 ? messages[index] : undefined\n if (latest?.role === 'user' && latest.content === userContent) return index\n\n return -1\n}\n\nfunction countUserMessages(messages: readonly TurnIdentityMessage[]): number {\n let count = 0\n for (const message of messages) if (message.role === 'user') count++\n return count\n}\n","/** Read-side checkpoints for native chat NDJSON. This never submits or cancels work. */\nexport interface TurnObservation {\n schema: 'turn-observation-v1'\n streamId: string | null\n /** Replay ordinals only. Unsequenced live frames cannot advance this cursor. */\n lastSeq: number\n outcome: 'completed' | 'failed' | null\n replayStatus: string | null\n eventCount: number\n}\n\nexport function parseTurnObservation(value?: unknown): TurnObservation {\n if (value === undefined) return {\n schema: 'turn-observation-v1', streamId: null, lastSeq: 0,\n outcome: null, replayStatus: null, eventCount: 0,\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Invalid turn observation')\n const v = value as Record<string, unknown>\n if (v.schema !== 'turn-observation-v1'\n || !(v.streamId === null || (typeof v.streamId === 'string' && /^[A-Za-z0-9_-]+$/.test(v.streamId)))\n || !Number.isSafeInteger(v.lastSeq) || Number(v.lastSeq) < 0\n || !Number.isSafeInteger(v.eventCount) || Number(v.eventCount) < 0\n || !(v.outcome === null || v.outcome === 'completed' || v.outcome === 'failed')\n || !(v.replayStatus === null || typeof v.replayStatus === 'string')\n || (v.streamId === null && Number(v.lastSeq) > 0)) throw new TypeError('Invalid turn observation')\n return {\n schema: 'turn-observation-v1', streamId: v.streamId as string | null,\n lastSeq: Number(v.lastSeq), outcome: v.outcome as TurnObservation['outcome'],\n replayStatus: v.replayStatus as string | null, eventCount: Number(v.eventCount),\n }\n}\n\nexport interface TurnObservationUpdate {\n checkpoint: TurnObservation\n /** False only for an already-checkpointed replay ordinal. */\n accepted: boolean\n event: Record<string, unknown>\n}\n\n/** Reduce an observed frame. Ordered replay gaps are errors, not silent lost work. */\nexport function observeTurnEvent(previous: TurnObservation, raw: unknown): TurnObservationUpdate {\n const checkpoint = parseTurnObservation(previous)\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new TypeError('Turn frame must be an object')\n const outer = raw as Record<string, unknown>\n const inner = outer.kind === 'event' ? outer.event : outer\n if (!inner || typeof inner !== 'object' || Array.isArray(inner)) throw new TypeError('Invalid turn event envelope')\n const event = inner as Record<string, unknown>\n if (typeof event.type !== 'string' || !event.type) throw new TypeError('Turn frame requires a type')\n\n // Even a duplicate marker must not switch which execution we are observing.\n if (event.type === 'turn') {\n if (typeof event.turnId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(event.turnId)) throw new TypeError('Invalid stream identity')\n if (checkpoint.streamId !== null && checkpoint.streamId !== event.turnId) throw new Error('Replay stream identity changed')\n checkpoint.streamId = event.turnId\n }\n const seq = outer.seq\n if (seq !== undefined && seq !== -1) {\n if (!Number.isSafeInteger(seq) || Number(seq) < 1) throw new TypeError('Invalid replay ordinal')\n if (checkpoint.streamId === null) throw new Error('Replay ordinal arrived before stream identity')\n if (Number(seq) <= checkpoint.lastSeq) return { checkpoint, accepted: false, event }\n if (Number(seq) !== checkpoint.lastSeq + 1) throw new Error('Replay has a gap; retain the checkpoint and inspect durable history')\n checkpoint.lastSeq = Number(seq)\n } else if (seq === -1 && event.type !== 'turn_status') {\n throw new TypeError('Only a turn-status sentinel may have ordinal -1')\n }\n\n if (event.type === 'error' || event.type === 'session.run.failed') checkpoint.outcome = 'failed'\n if (event.type === 'session.run.completed' && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n if (event.type === 'turn_status') {\n if (typeof event.status !== 'string') throw new TypeError('Turn status requires a value')\n checkpoint.replayStatus = event.status\n if (['error', 'failed', 'aborted', 'cancelled'].includes(event.status)) checkpoint.outcome = 'failed'\n if (['complete', 'completed'].includes(event.status) && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n }\n checkpoint.eventCount += 1\n return { checkpoint, accepted: true, event }\n}\n\nexport interface ConsumeTurnStreamOptions {\n checkpoint?: TurnObservation\n /** Commit evidence and its checkpoint durably before acknowledging this frame. */\n commit(update: TurnObservationUpdate): Promise<void>\n /** Bound untrusted frame memory, not total run duration or total transcript size. */\n maxFrameBytes?: number\n}\n\n/**\n * Consume one viewing connection. EOF without a terminal event stays incomplete.\n * A disconnect/abort propagates; the last committed checkpoint remains resumable.\n * The caller owns network observation windows separately from execution deadlines.\n */\nexport async function consumeTurnStream(\n body: AsyncIterable<Uint8Array>,\n options: ConsumeTurnStreamOptions,\n): Promise<TurnObservation> {\n const maxFrameBytes = options.maxFrameBytes ?? 4 * 1024 * 1024\n if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes < 1) throw new RangeError('Frame byte limit must be positive')\n let state = parseTurnObservation(options.checkpoint)\n const decoder = new TextDecoder('utf-8', { fatal: true })\n let pending = ''\n let frameBytes = 0\n async function accept(line: string): Promise<void> {\n if (!line.trim()) return\n const update = observeTurnEvent(state, JSON.parse(line))\n if (update.accepted) await options.commit(update)\n state = update.checkpoint\n }\n for await (const chunk of body) {\n // Count bytes before decoding: a malicious unterminated frame cannot grow\n // without bound, and splitting UTF-8 characters across chunks stays valid.\n let start = 0\n for (let end = 0; end < chunk.length; end += 1) {\n if (chunk[end] !== 10) continue\n frameBytes += end - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start, end + 1), { stream: true })\n await accept(pending)\n pending = ''; frameBytes = 0; start = end + 1\n }\n frameBytes += chunk.length - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start), { stream: true })\n }\n pending += decoder.decode()\n await accept(pending)\n return state\n}\n"],"mappings":";AAkCO,SAAS,sBAAsB,OAAoC;AACxE,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,yBAAyB;AACxE,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,0BAA0B;AACxD,MAAI,QAAQ,SAAS,IAAK,OAAM,IAAI,MAAM,oBAAoB;AAC9D,MAAI,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AAM,GAAG,MAAM,GAAI;AACvB,oBAAc,MAAM;AACpB,UAAI,aAAa,cAAe,OAAM,IAAI,WAAW,+BAA+B;AACpF,iBAAW,QAAQ,OAAO,MAAM,SAAS,OAAO,MAAM,CAAC,GAAG,EAAE,QAAQ,KAAK,CAAC;AAC1E,YAAM,OAAO,OAAO;AACpB,gBAAU;AAAI,mBAAa;AAAG,cAAQ,MAAM;AAAA,IAC9C;AACA,kBAAc,MAAM,SAAS;AAC7B,QAAI,aAAa,cAAe,OAAM,IAAI,WAAW,+BAA+B;AACpF,eAAW,QAAQ,OAAO,MAAM,SAAS,KAAK,GAAG,EAAE,QAAQ,KAAK,CAAC;AAAA,EACnE;AACA,aAAW,QAAQ,OAAO;AAC1B,QAAM,OAAO,OAAO;AACpB,SAAO;AACT;","names":["index"]}
|
package/dist/chunk-MLDKEEFQ.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
// src/platform/api-key-auth.ts
|
|
2
|
-
function createApiKeyRequestAuth(options) {
|
|
3
|
-
return async (request) => {
|
|
4
|
-
const authorization = request.headers.get("Authorization");
|
|
5
|
-
if (authorization === null) return null;
|
|
6
|
-
const bearer = /^Bearer +(\S+)$/i.exec(authorization);
|
|
7
|
-
if (!bearer) {
|
|
8
|
-
throw denied(401, "api_key.invalid", "Invalid API key");
|
|
9
|
-
}
|
|
10
|
-
const requiredScope = options.requiredScope(request);
|
|
11
|
-
const requiredScopes = typeof requiredScope === "string" ? [requiredScope] : Array.from(requiredScope ?? []);
|
|
12
|
-
if (!requiredScopes?.length || !requiredScopes.every((scope) => typeof scope === "string" && scope.trim())) {
|
|
13
|
-
throw denied(403, "api_key.route_denied", "API key access is not enabled for this route");
|
|
14
|
-
}
|
|
15
|
-
const key = await options.verify(`Bearer ${bearer[1]}`);
|
|
16
|
-
if (!key || !key.keyId?.trim() || !key.ownerId?.trim()) {
|
|
17
|
-
throw denied(401, "api_key.invalid", "Invalid API key");
|
|
18
|
-
}
|
|
19
|
-
if (!Number.isSafeInteger(key.expiresAt) || key.expiresAt <= Date.now()) {
|
|
20
|
-
throw denied(401, "api_key.expired", "An unexpired API key with a finite expiry is required");
|
|
21
|
-
}
|
|
22
|
-
if (!Array.isArray(key.scopes) || !requiredScopes.every((scope) => key.scopes.includes(scope))) {
|
|
23
|
-
throw denied(403, "api_key.insufficient_scope", `API key requires scopes: ${requiredScopes.join(", ")}`);
|
|
24
|
-
}
|
|
25
|
-
const identity = await options.resolveIdentity(key);
|
|
26
|
-
if (!identity) throw denied(401, "api_key.invalid_owner", "API key owner is unavailable");
|
|
27
|
-
const claim = await options.claimRequest(key, crypto.randomUUID());
|
|
28
|
-
if (claim.allowed !== true) {
|
|
29
|
-
const headers = new Headers();
|
|
30
|
-
if (Number.isFinite(claim.retryAfterSeconds) && claim.retryAfterSeconds > 0) {
|
|
31
|
-
headers.set("Retry-After", String(Math.ceil(claim.retryAfterSeconds)));
|
|
32
|
-
}
|
|
33
|
-
throw denied(429, "api_key.request_limit_exceeded", "API key request limit exceeded", headers);
|
|
34
|
-
}
|
|
35
|
-
if (key.expiresAt <= Date.now()) {
|
|
36
|
-
throw denied(401, "api_key.expired", "API key expired during authorization");
|
|
37
|
-
}
|
|
38
|
-
return identity;
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
function denied(status, code, error, headers) {
|
|
42
|
-
return Response.json({ error, code }, { status, headers });
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export {
|
|
46
|
-
createApiKeyRequestAuth
|
|
47
|
-
};
|
|
48
|
-
//# sourceMappingURL=chunk-MLDKEEFQ.js.map
|