@tangle-network/agent-app 0.60.262 → 0.60.264
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/chat-routes/index.js +4 -3
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/turn-execution.d.ts +0 -1
- package/dist/{chunk-T4CV4TLI.js → chunk-3RRYI24K.js} +20 -7
- package/dist/chunk-3RRYI24K.js.map +1 -0
- package/dist/{chunk-ZLUQYQ4P.js → chunk-LO6VQ35O.js} +2 -2
- package/dist/chunk-UK7QG5BW.js +17 -0
- package/dist/chunk-UK7QG5BW.js.map +1 -0
- package/dist/{chunk-QTWTZYXC.js → chunk-VJBFCNAU.js} +30 -5
- package/dist/{chunk-QTWTZYXC.js.map → chunk-VJBFCNAU.js.map} +1 -1
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +2 -1
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/rollout/d1.d.ts +2 -11
- package/dist/rollout/d1.js +64 -21
- package/dist/rollout/d1.js.map +1 -1
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/router-turn.d.ts +11 -1
- package/dist/runtime/router-turn.js +3 -1
- package/dist/turn-trace/turn-facts.d.ts +18 -0
- package/package.json +1 -1
- package/dist/chunk-T4CV4TLI.js.map +0 -1
- /package/dist/{chunk-ZLUQYQ4P.js.map → chunk-LO6VQ35O.js.map} +0 -0
|
@@ -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"],"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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:${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;AAAA,MACvE,aAAa,CAAC;AAAA,MAAG,WAAW,CAAC;AAAA,MAAG,MAAM,CAAC;AAAA,MAAG,UAAU,CAAC;AAAA,IAAE,CAAC;AAAA,EAC5D;AAC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AAC,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"]}
|
package/dist/rollout/d1.d.ts
CHANGED
|
@@ -1,14 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The measurement a rollout guard reads: one row per turn with its lane, its
|
|
3
|
-
* first visible word and whether it failed, and the stage numbers computed
|
|
4
|
-
* from those rows.
|
|
5
|
-
*
|
|
6
|
-
* Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`
|
|
7
|
-
* carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an
|
|
8
|
-
* operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is
|
|
9
|
-
* measured on the turns of the workspaces it admits, in the lane being rolled
|
|
10
|
-
* out, since the time it went live.
|
|
11
|
-
*/
|
|
12
1
|
import { type RolloutStage, type StageMeasurement } from './index';
|
|
13
2
|
/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */
|
|
14
3
|
export interface D1LikeForRollout {
|
|
@@ -67,6 +56,8 @@ export declare function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'fi
|
|
|
67
56
|
export declare function createD1TurnTimingStore(options: {
|
|
68
57
|
db: D1LikeForRollout;
|
|
69
58
|
now?: () => number;
|
|
59
|
+
/** Fill omitted timing and model from the chat route's measurement of the same turn. Default true. */
|
|
60
|
+
measuredFacts?: boolean;
|
|
70
61
|
}): {
|
|
71
62
|
/** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */
|
|
72
63
|
record(row: TurnTimingRow): Promise<void>;
|
package/dist/rollout/d1.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
rolloutAdmits
|
|
3
3
|
} from "../chunk-7VTGB4DM.js";
|
|
4
|
+
import {
|
|
5
|
+
measuredTurnFacts
|
|
6
|
+
} from "../chunk-UK7QG5BW.js";
|
|
4
7
|
|
|
5
8
|
// src/rollout/d1.ts
|
|
6
9
|
var ROLLOUT_TURN_TIMING_SCHEMA_SQL = `
|
|
@@ -51,34 +54,74 @@ function stageMetrics(rows) {
|
|
|
51
54
|
failure_rate: rows.length ? rows.filter((row) => row.failed || row.firstTextMs === void 0 || row.firstTextMs === null).length / rows.length : null
|
|
52
55
|
};
|
|
53
56
|
}
|
|
57
|
+
var RECORD_COLUMNS = [
|
|
58
|
+
"turn_id",
|
|
59
|
+
"rollout",
|
|
60
|
+
"workspace_id",
|
|
61
|
+
"lane",
|
|
62
|
+
"first_visible_ms",
|
|
63
|
+
"first_text_ms",
|
|
64
|
+
"settled_ms",
|
|
65
|
+
"failed",
|
|
66
|
+
"failure_code",
|
|
67
|
+
"at",
|
|
68
|
+
"admission_ms",
|
|
69
|
+
"model",
|
|
70
|
+
"revision",
|
|
71
|
+
"arm",
|
|
72
|
+
"variant"
|
|
73
|
+
];
|
|
74
|
+
var tableColumns = /* @__PURE__ */ new WeakMap();
|
|
75
|
+
function readColumns(db, refresh) {
|
|
76
|
+
const cached = tableColumns.get(db);
|
|
77
|
+
if (cached && !refresh) return cached;
|
|
78
|
+
const read = Promise.resolve().then(() => db.prepare("PRAGMA table_info(rollout_turn_timing)").bind().all()).then(({ results = [] }) => results.length ? new Set(results.map((column) => column.name)) : null, () => null);
|
|
79
|
+
tableColumns.set(db, read);
|
|
80
|
+
return read;
|
|
81
|
+
}
|
|
82
|
+
function roundOrNull(value) {
|
|
83
|
+
return value === void 0 ? null : Math.round(value);
|
|
84
|
+
}
|
|
54
85
|
function createD1TurnTimingStore(options) {
|
|
55
86
|
const now = options.now ?? Date.now;
|
|
56
87
|
return {
|
|
57
88
|
/** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */
|
|
58
89
|
async record(row) {
|
|
59
90
|
try {
|
|
60
|
-
const
|
|
91
|
+
const measured = options.measuredFacts === false ? void 0 : measuredTurnFacts(row.turnId);
|
|
92
|
+
const values = {
|
|
93
|
+
turn_id: row.turnId,
|
|
94
|
+
rollout: row.rollout,
|
|
95
|
+
workspace_id: row.workspaceId,
|
|
96
|
+
lane: row.lane,
|
|
97
|
+
first_visible_ms: roundOrNull(row.firstVisibleMs ?? measured?.firstVisibleMs),
|
|
98
|
+
first_text_ms: roundOrNull(row.firstTextMs ?? measured?.firstTextMs),
|
|
99
|
+
settled_ms: Math.round(row.settledMs),
|
|
100
|
+
failed: row.failed ? 1 : 0,
|
|
101
|
+
failure_code: row.failureCode ?? null,
|
|
102
|
+
at: row.at ?? now(),
|
|
103
|
+
admission_ms: roundOrNull(row.admissionMs ?? measured?.admissionMs),
|
|
104
|
+
model: row.model ?? measured?.model ?? null,
|
|
105
|
+
revision: row.revision ?? null,
|
|
106
|
+
arm: row.arm ?? null,
|
|
107
|
+
variant: row.variant ?? null
|
|
108
|
+
};
|
|
109
|
+
let columns = await readColumns(options.db, false);
|
|
110
|
+
const explicit = {
|
|
111
|
+
first_visible_ms: row.firstVisibleMs,
|
|
112
|
+
admission_ms: row.admissionMs,
|
|
113
|
+
model: row.model,
|
|
114
|
+
revision: row.revision,
|
|
115
|
+
arm: row.arm,
|
|
116
|
+
variant: row.variant
|
|
117
|
+
};
|
|
118
|
+
if (columns && Object.entries(explicit).some(([column, value]) => value !== void 0 && !columns.has(column))) {
|
|
119
|
+
columns = await readColumns(options.db, true);
|
|
120
|
+
}
|
|
121
|
+
const written = RECORD_COLUMNS.filter((column) => columns ? columns.has(column) : column !== "variant" || row.variant !== void 0);
|
|
61
122
|
await options.db.prepare(
|
|
62
|
-
`INSERT OR IGNORE INTO rollout_turn_timing
|
|
63
|
-
|
|
64
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${variant ? ", ?" : ""})`
|
|
65
|
-
).bind(
|
|
66
|
-
row.turnId,
|
|
67
|
-
row.rollout,
|
|
68
|
-
row.workspaceId,
|
|
69
|
-
row.lane,
|
|
70
|
-
row.firstVisibleMs === void 0 ? null : Math.round(row.firstVisibleMs),
|
|
71
|
-
row.firstTextMs === void 0 ? null : Math.round(row.firstTextMs),
|
|
72
|
-
Math.round(row.settledMs),
|
|
73
|
-
row.failed ? 1 : 0,
|
|
74
|
-
row.failureCode ?? null,
|
|
75
|
-
row.at ?? now(),
|
|
76
|
-
row.admissionMs === void 0 ? null : Math.round(row.admissionMs),
|
|
77
|
-
row.model ?? null,
|
|
78
|
-
row.revision ?? null,
|
|
79
|
-
row.arm ?? null,
|
|
80
|
-
...row.variant === void 0 ? [] : [row.variant]
|
|
81
|
-
).run();
|
|
123
|
+
`INSERT OR IGNORE INTO rollout_turn_timing (${written.join(", ")}) VALUES (${written.map(() => "?").join(", ")})`
|
|
124
|
+
).bind(...written.map((column) => values[column])).run();
|
|
82
125
|
} catch (error) {
|
|
83
126
|
console.error(JSON.stringify({
|
|
84
127
|
event: "rollout_turn_timing_record_failed",
|
package/dist/rollout/d1.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n */\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n variant TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n`\n\n/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`\n\n/** Apply once through the product migration runner; old rows remain unknown. */\nexport const ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `\nALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;\nALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;\n`\n\n/** Apply once through the product migration runner before any row carries `variant`; old rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_VARIANT_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN variant TEXT;`\n\nexport interface TurnTimingRow {\n /** Request receipt to lifecycle start, before the existing relative durations. */\n admissionMs?: number\n model?: string\n revision?: string\n /** The rollout cohort arm (`assignRolloutArm`, or a synthetic cohort's label). Guards filter on it. */\n arm?: string\n /** The turn's experiment assignments, apart from `arm` so an experiment never changes the cohort a guard reads,\n * e.g. `billing_in_gate=1;prompt_prefix=0`. Written only when set, so a table without the column keeps recording. */\n variant?: string\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n /** From the lifecycle firstVisibleMs; absent when no reasoning, tool or answer streamed. */\n firstVisibleMs?: number\n settledMs: number\n failed: boolean\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstVisibleMs' | 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstVisible = rows.flatMap(row => row.firstVisibleMs == null ? [] : [row.firstVisibleMs]).sort((a, b) => a - b)\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_visible_p50_ms: percentile(firstVisible, 50),\n first_visible_p90_ms: percentile(firstVisible, 90),\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\nexport function createD1TurnTimingStore(options: { db: D1LikeForRollout; now?: () => number }) {\n const now = options.now ?? Date.now\n return {\n /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */\n async record(row: TurnTimingRow): Promise<void> {\n try {\n const variant = row.variant === undefined ? '' : ', variant'\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing\n (turn_id, rollout, workspace_id, lane, first_visible_ms, first_text_ms, settled_ms, failed, failure_code, at, admission_ms, model, revision, arm${variant})\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${variant ? ', ?' : ''})`,\n ).bind(row.turnId, row.rollout, row.workspaceId, row.lane,\n row.firstVisibleMs === undefined ? null : Math.round(row.firstVisibleMs),\n row.firstTextMs === undefined ? null : Math.round(row.firstTextMs), Math.round(row.settledMs),\n row.failed ? 1 : 0, row.failureCode ?? null, row.at ?? now(),\n row.admissionMs === undefined ? null : Math.round(row.admissionMs),\n row.model ?? null, row.revision ?? null, row.arm ?? null, ...(row.variant === undefined ? [] : [row.variant])).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_visible_ms, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_visible_ms: number | null; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstVisibleMs: row.first_visible_ms ?? undefined, firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n lane: input.lane,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() },\n }\n },\n }\n}\n"],"mappings":";;;;;AAuBO,IAAM,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsBvC,IAAM,kDACX;AAGK,IAAM,0CAA0C;AAAA;AAAA;AAAA;AAAA;AAAA;AAQhD,IAAM,4CACX;AA8BF,IAAM,oBAAoB;AAE1B,SAAS,WAAW,QAA2B,GAA0B;AACvE,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,SAAO,OAAO,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,KAAM,IAAI,MAAO,OAAO,MAAM,IAAI,CAAC,CAAC;AACrF;AAGO,SAAS,aAAa,MAAq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BAA4B,MAAM,IAAI;AAAA,QAC9C,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,KAAK,EAAE,YAAY,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE,YAAY,EAAE;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n *\n * By default `record` fills what the product's row leaves out from what the chat route measured for the same\n * `turnId` (its `turnStreamId`): `admissionMs`, `firstVisibleMs`, `firstTextMs` and the served `model`, on every\n * lane. It writes only the columns the table has (read once per isolate with `PRAGMA table_info`), so a table that\n * predates a migration keeps recording the columns it has instead of losing the row. `revision`, `arm` and\n * `variant` are the product's and are written when the row carries them. Pass `measuredFacts: false` to write\n * only the row's own values.\n */\nimport { measuredTurnFacts } from '../turn-trace/turn-facts'\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n variant TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n`\n\n/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`\n\n/** Apply once through the product migration runner; old rows remain unknown. */\nexport const ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `\nALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;\nALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;\n`\n\n/** Apply once through the product migration runner before any row carries `variant`; old rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_VARIANT_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN variant TEXT;`\n\nexport interface TurnTimingRow {\n /** Request receipt to lifecycle start, before the existing relative durations. */\n admissionMs?: number\n model?: string\n revision?: string\n /** The rollout cohort arm (`assignRolloutArm`, or a synthetic cohort's label). Guards filter on it. */\n arm?: string\n /** The turn's experiment assignments, apart from `arm` so an experiment never changes the cohort a guard reads,\n * e.g. `billing_in_gate=1;prompt_prefix=0`. Written only when set, so a table without the column keeps recording. */\n variant?: string\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n /** From the lifecycle firstVisibleMs; absent when no reasoning, tool or answer streamed. */\n firstVisibleMs?: number\n settledMs: number\n failed: boolean\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstVisibleMs' | 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstVisible = rows.flatMap(row => row.firstVisibleMs == null ? [] : [row.firstVisibleMs]).sort((a, b) => a - b)\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_visible_p50_ms: percentile(firstVisible, 50),\n first_visible_p90_ms: percentile(firstVisible, 90),\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\n/** Columns `record` writes, in order; `variant` and the ruler columns arrived by migration. */\nconst RECORD_COLUMNS = ['turn_id', 'rollout', 'workspace_id', 'lane', 'first_visible_ms', 'first_text_ms', 'settled_ms', 'failed',\n 'failure_code', 'at', 'admission_ms', 'model', 'revision', 'arm', 'variant'] as const\ntype RecordColumn = typeof RECORD_COLUMNS[number]\n\n/** The table's columns per database binding, read once per isolate; `null` when they could not be read. */\nconst tableColumns = new WeakMap<object, Promise<ReadonlySet<string> | null>>()\n\nfunction readColumns(db: D1LikeForRollout, refresh: boolean): Promise<ReadonlySet<string> | null> {\n const cached = tableColumns.get(db)\n if (cached && !refresh) return cached\n const read = Promise.resolve().then(() => db.prepare('PRAGMA table_info(rollout_turn_timing)').bind().all<{ name: string }>())\n .then(({ results = [] }) => results.length ? new Set(results.map(column => column.name)) : null, () => null)\n tableColumns.set(db, read)\n return read\n}\n\nfunction roundOrNull(value: number | undefined): number | null {\n return value === undefined ? null : Math.round(value)\n}\n\nexport function createD1TurnTimingStore(options: {\n db: D1LikeForRollout\n now?: () => number\n /** Fill omitted timing and model from the chat route's measurement of the same turn. Default true. */\n measuredFacts?: boolean\n}) {\n const now = options.now ?? Date.now\n return {\n /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */\n async record(row: TurnTimingRow): Promise<void> {\n try {\n // Read before any await: the facts belong to the request that is settling this turn.\n const measured = options.measuredFacts === false ? undefined : measuredTurnFacts(row.turnId)\n const values: Record<RecordColumn, unknown> = {\n turn_id: row.turnId, rollout: row.rollout, workspace_id: row.workspaceId, lane: row.lane,\n first_visible_ms: roundOrNull(row.firstVisibleMs ?? measured?.firstVisibleMs),\n first_text_ms: roundOrNull(row.firstTextMs ?? measured?.firstTextMs),\n settled_ms: Math.round(row.settledMs), failed: row.failed ? 1 : 0, failure_code: row.failureCode ?? null,\n at: row.at ?? now(), admission_ms: roundOrNull(row.admissionMs ?? measured?.admissionMs),\n model: row.model ?? measured?.model ?? null, revision: row.revision ?? null, arm: row.arm ?? null,\n variant: row.variant ?? null,\n }\n let columns = await readColumns(options.db, false)\n // A value the product passed whose column is unknown: the table may have migrated since the read.\n const explicit: Partial<Record<RecordColumn, unknown>> = { first_visible_ms: row.firstVisibleMs,\n admission_ms: row.admissionMs, model: row.model, revision: row.revision, arm: row.arm, variant: row.variant }\n if (columns && Object.entries(explicit).some(([column, value]) => value !== undefined && !columns!.has(column))) {\n columns = await readColumns(options.db, true)\n }\n // Columns unknown (no table yet, or a binding without PRAGMA): every column, `variant` only when set.\n const written = RECORD_COLUMNS.filter(column => columns ? columns.has(column) : column !== 'variant' || row.variant !== undefined)\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing (${written.join(', ')}) VALUES (${written.map(() => '?').join(', ')})`,\n ).bind(...written.map(column => values[column])).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_visible_ms, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_visible_ms: number | null; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstVisibleMs: row.first_visible_ms ?? undefined, firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n lane: input.lane,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() },\n }\n },\n }\n}\n"],"mappings":";;;;;;;;AA+BO,IAAM,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsBvC,IAAM,kDACX;AAGK,IAAM,0CAA0C;AAAA;AAAA;AAAA;AAAA;AAAA;AAQhD,IAAM,4CACX;AA8BF,IAAM,oBAAoB;AAE1B,SAAS,WAAW,QA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AO,cAAc,MAAM,MAAM,OAAO,EAAE,IAAI,IAAI,aAAa,CAAC,CAAC,EACxE,IAAI,UAAQ,EAAE,gBAAgB,IAAI,oBAAoB,QAAW,aAAa,IAAI,iBAAiB,QAAW,WAAW,IAAI,YAAY,QAAQ,IAAI,WAAW,EAAE,EAAE;AACvK,aAAO;AAAA,QACL,OAAO,MAAM,MAAM;AAAA,QACnB,MAAM,MAAM;AAAA,QACZ,SAAS,KAAK;AAAA,QACd,SAAS,aAAa,IAAI;AAAA,QAC1B,QAAQ,4BAA4B,MAAM,IAAI;AAAA,QAC9C,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,KAAK,EAAE,YAAY,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE,YAAY,EAAE;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/runtime/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
ProtectedModelSettlementError,
|
|
3
3
|
createRouterProtectedModelPort,
|
|
4
4
|
runProtectedRouterTurn
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-LO6VQ35O.js";
|
|
6
6
|
import {
|
|
7
7
|
DURABLE_HOP_BUDGET_MS,
|
|
8
8
|
asksForLanguage,
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
createOpenAICompatStreamTurn,
|
|
14
14
|
createOpenAIResponsesTurn,
|
|
15
15
|
isOpenAIResponsesModel,
|
|
16
|
+
perTurnPrefixBytes,
|
|
16
17
|
placeRouterTurn,
|
|
17
18
|
replyLanguageInstruction,
|
|
18
19
|
routerFunctionName,
|
|
@@ -25,7 +26,7 @@ import {
|
|
|
25
26
|
turnKnowledgeInstructions,
|
|
26
27
|
workspaceKnowledgeForTurn,
|
|
27
28
|
workspaceTurnCheckpoints
|
|
28
|
-
} from "../chunk-
|
|
29
|
+
} from "../chunk-VJBFCNAU.js";
|
|
29
30
|
import "../chunk-UFQM46NV.js";
|
|
30
31
|
import {
|
|
31
32
|
DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR,
|
|
@@ -192,6 +193,7 @@ export {
|
|
|
192
193
|
isTangleExecutionKeyError,
|
|
193
194
|
mergeSurfaceOverlay,
|
|
194
195
|
normalizeModelId,
|
|
196
|
+
perTurnPrefixBytes,
|
|
195
197
|
placeRouterTurn,
|
|
196
198
|
replyLanguageInstruction,
|
|
197
199
|
resolveCatalogModelId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,OAGK;AAkBA,SAAS,wBAAwB,QAAoD;AAC1F,QAAM,SAAS,4BAA4B,MAAM;AACjD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,aAAO,EAAE,GAAG,MAAM,cAAc,MAAM,OAAO,QAAQ,KAAK,YAAY,EAAE;AAAA,IAC1E;AAAA,IACA,SAAS,MAAM,OAAO,QAAQ,EAAE,OAAO,KAAK,CAAC;AAAA,IAC7C,SAAS,OAAO;AAAA,EAClB;AACF;;;ACwCO,SAAS,kBAAwB,MAGR;AAC9B,MAAI,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG;AACnF,UAAM,IAAI,MAAM,mEAAmE,KAAK,UAAU,KAAK,IAAI,CAAC,GAAG;AAAA,EACjH;AACA,MAAI,OAAO,KAAK,UAAU,YAAY;AACpC,UAAM,IAAI,MAAM,iBAAiB,KAAK,IAAI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IAAI,sCAAsC,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAClH;AACA,UAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UAAU;AAC/D,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,8BAA8B,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAC1G;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,gBAAgB,QAAW;AACrC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,WAAW,GAAG;AAC9D,UAAI,EAAE,SAAS,sBAAsB;AACnC,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,GAAG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,OAGK;AAkBA,SAAS,wBAAwB,QAAoD;AAC1F,QAAM,SAAS,4BAA4B,MAAM;AACjD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,aAAO,EAAE,GAAG,MAAM,cAAc,MAAM,OAAO,QAAQ,KAAK,YAAY,EAAE;AAAA,IAC1E;AAAA,IACA,SAAS,MAAM,OAAO,QAAQ,EAAE,OAAO,KAAK,CAAC;AAAA,IAC7C,SAAS,OAAO;AAAA,EAClB;AACF;;;ACwCO,SAAS,kBAAwB,MAGR;AAC9B,MAAI,OAAO,KAAK,SAAS,YAAY,KAA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,GAAG,KAAK,iBAAiB,IAAI,oCAAoC,KAAK,UAAW,OAAmC,SAAS,CAAC,GAAG;AAAA,MACnJ;AACA,UAAI;AACJ,UAAI;AACF,iBAAS,IAAI,IAAI,OAAO,GAAG;AAAA,MAC7B,QAAQ;AACN,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,sCAAsC,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAClH;AACA,UAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UAAU;AAC/D,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,8BAA8B,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAC1G;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,gBAAgB,QAAW;AACrC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,WAAW,GAAG;AAC9D,UAAI,EAAE,SAAS,sBAAsB;AACnC,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,GAAG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -327,7 +327,16 @@ export interface RouterTurnPromptOptions {
|
|
|
327
327
|
files: readonly TurnKnowledgeFile[];
|
|
328
328
|
readTool?: string;
|
|
329
329
|
};
|
|
330
|
+
/** Under a test runner (Vitest, Jest, `NODE_ENV=test`) the composition throws when the prefix carries a per-turn
|
|
331
|
+
* byte ({@link perTurnPrefixBytes}), so an app's own tests fail before a timestamp costs every turn its prompt
|
|
332
|
+
* cache. It never runs outside a test runner. `false` turns the check off for a prefix that is meant to vary. */
|
|
333
|
+
checkStablePrefix?: boolean;
|
|
330
334
|
}
|
|
335
|
+
/**
|
|
336
|
+
* The per-turn bytes in a prompt prefix: a clock to the minute, and any of this turn's `context` sections (or the
|
|
337
|
+
* caller's own per-turn values: ids, the member's message) that also appear there. Empty for a cacheable prefix.
|
|
338
|
+
*/
|
|
339
|
+
export declare function perTurnPrefixBytes(prefix: string, perTurn?: readonly string[]): string[];
|
|
331
340
|
/**
|
|
332
341
|
* The lean system prompt for a Router turn, split where its bytes stop repeating. The prefix holds the profile's
|
|
333
342
|
* system prompt, appended prompt and instructions, the reply-language rule, the caller's `stable` sections and the
|
|
@@ -337,7 +346,8 @@ export interface RouterTurnPromptOptions {
|
|
|
337
346
|
* A provider serves a repeated prompt prefix from its cache: through the Router, Gemini served 38,685 of
|
|
338
347
|
* 40,734 prompt tokens from cache on each repeat of a stable 150 kB prefix, and none when a timestamp came first
|
|
339
348
|
* (2026-10-22). One per-turn byte early in the prompt therefore costs the whole prompt on every turn, so nothing
|
|
340
|
-
* per-turn belongs in `stable` or the profile's prompt
|
|
349
|
+
* per-turn belongs in `stable` or the profile's prompt; under a test runner a clock or a repeated `context` section in
|
|
350
|
+
* the prefix throws (`checkStablePrefix`).
|
|
341
351
|
*/
|
|
342
352
|
export declare function composeRouterTurnPromptSections(profile: {
|
|
343
353
|
prompt?: {
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
budgetTurnKnowledge,
|
|
5
5
|
composeRouterTurnPrompt,
|
|
6
6
|
composeRouterTurnPromptSections,
|
|
7
|
+
perTurnPrefixBytes,
|
|
7
8
|
placeRouterTurn,
|
|
8
9
|
replyLanguageInstruction,
|
|
9
10
|
routerFunctionName,
|
|
@@ -12,7 +13,7 @@ import {
|
|
|
12
13
|
turnKnowledgeInstructions,
|
|
13
14
|
workspaceKnowledgeForTurn,
|
|
14
15
|
workspaceTurnCheckpoints
|
|
15
|
-
} from "../chunk-
|
|
16
|
+
} from "../chunk-VJBFCNAU.js";
|
|
16
17
|
import "../chunk-UFQM46NV.js";
|
|
17
18
|
import "../chunk-D6UJEOZQ.js";
|
|
18
19
|
import "../chunk-AMUXRAUO.js";
|
|
@@ -23,6 +24,7 @@ export {
|
|
|
23
24
|
budgetTurnKnowledge,
|
|
24
25
|
composeRouterTurnPrompt,
|
|
25
26
|
composeRouterTurnPromptSections,
|
|
27
|
+
perTurnPrefixBytes,
|
|
26
28
|
placeRouterTurn,
|
|
27
29
|
replyLanguageInstruction,
|
|
28
30
|
routerFunctionName,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `createChatTurnRoutes` measured for a settled turn, kept in this isolate
|
|
3
|
+
* under the turn's stream id so the rollout timing store can fill the row the
|
|
4
|
+
* product writes from its lifecycle hook. A product's writer that forgot
|
|
5
|
+
* `firstVisibleMs` or `admissionMs` (Legal never wrote first_visible_ms) still
|
|
6
|
+
* records them after a version bump, on every lane.
|
|
7
|
+
*
|
|
8
|
+
* Internal: not exported from a subpath. Values the product passes always win.
|
|
9
|
+
*/
|
|
10
|
+
export interface MeasuredTurnFacts {
|
|
11
|
+
admissionMs?: number;
|
|
12
|
+
firstVisibleMs?: number;
|
|
13
|
+
firstTextMs?: number;
|
|
14
|
+
/** The model that served the turn. */
|
|
15
|
+
model?: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function noteMeasuredTurnFacts(turnStreamId: string, measured: MeasuredTurnFacts): void;
|
|
18
|
+
export declare function measuredTurnFacts(turnStreamId: string): MeasuredTurnFacts | undefined;
|
package/package.json
CHANGED