@tangle-network/agent-app 0.63.29 → 0.63.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/dist/{DesignCanvas-3DGZQOD7.js → DesignCanvas-VKZ7Y3JU.js} +2 -3
  2. package/dist/{DesignCanvasEditor-OG4QY5WJ.js → DesignCanvasEditor-3V53YLLZ.js} +2 -3
  3. package/dist/agent-profiles/d1.js +4 -3
  4. package/dist/agent-profiles/d1.js.map +1 -1
  5. package/dist/agent-profiles/index.js +4 -3
  6. package/dist/alerting/github.d.ts +33 -0
  7. package/dist/alerting/index.d.ts +1 -0
  8. package/dist/alerting/index.js +47 -0
  9. package/dist/alerting/index.js.map +1 -1
  10. package/dist/app-auth/index.js +1 -2
  11. package/dist/app-auth/index.js.map +1 -1
  12. package/dist/assistant/index.js +4 -4
  13. package/dist/billing/index.d.ts +15 -0
  14. package/dist/billing/index.js +5 -3
  15. package/dist/chat-routes/default-backend.d.ts +19 -2
  16. package/dist/chat-routes/hybrid-producer.d.ts +7 -2
  17. package/dist/chat-routes/index.js +16 -15
  18. package/dist/chat-routes/index.js.map +1 -1
  19. package/dist/chat-routes/route-storage.d.ts +1 -1
  20. package/dist/chat-routes/router-producer.d.ts +2 -1
  21. package/dist/chat-routes/turn-route-contracts.d.ts +1 -1
  22. package/dist/chat-store/index.js +34 -4
  23. package/dist/chat-store/index.js.map +1 -1
  24. package/dist/chat-store/schema.d.ts +286 -0
  25. package/dist/{chunk-6JEDSKFH.js → chunk-2SDX3OC4.js} +32 -24
  26. package/dist/{chunk-6JEDSKFH.js.map → chunk-2SDX3OC4.js.map} +1 -1
  27. package/dist/{chunk-DCJCZ7EP.js → chunk-4CEIZZTH.js} +44 -26
  28. package/dist/chunk-4CEIZZTH.js.map +1 -0
  29. package/dist/{chunk-WL7PZK7Q.js → chunk-4PIN6QYQ.js} +43 -1
  30. package/dist/chunk-4PIN6QYQ.js.map +1 -0
  31. package/dist/{chunk-6UMIOEDR.js → chunk-AZRPDSRQ.js} +3 -3
  32. package/dist/{chunk-6LMM3OVX.js → chunk-BMCC2BUP.js} +3 -3
  33. package/dist/{chunk-36HSG7HU.js → chunk-CRZXEKCX.js} +2 -2
  34. package/dist/chunk-F4XBNR5L.js +16 -0
  35. package/dist/chunk-F4XBNR5L.js.map +1 -0
  36. package/dist/chunk-GY4IPYG4.js +40 -0
  37. package/dist/chunk-GY4IPYG4.js.map +1 -0
  38. package/dist/{chunk-QUT3T2IN.js → chunk-L3QR274L.js} +11 -3
  39. package/dist/chunk-L3QR274L.js.map +1 -0
  40. package/dist/{chunk-6OG4244Y.js → chunk-MTKD2FN5.js} +2 -251
  41. package/dist/chunk-MTKD2FN5.js.map +1 -0
  42. package/dist/{chunk-56JUV4DK.js → chunk-NDXQFEZQ.js} +3332 -3014
  43. package/dist/chunk-NDXQFEZQ.js.map +1 -0
  44. package/dist/chunk-NSWLZTJX.js +645 -0
  45. package/dist/chunk-NSWLZTJX.js.map +1 -0
  46. package/dist/chunk-PU6AWIRE.js +252 -0
  47. package/dist/chunk-PU6AWIRE.js.map +1 -0
  48. package/dist/{chunk-JKECSYDB.js → chunk-PV3GSLUY.js} +3 -3
  49. package/dist/{chunk-7Y7U7U7X.js → chunk-Q7RSHLEV.js} +5 -3
  50. package/dist/{chunk-7Y7U7U7X.js.map → chunk-Q7RSHLEV.js.map} +1 -1
  51. package/dist/{chunk-HRBF4B5L.js → chunk-TUJ4277Q.js} +1 -14
  52. package/dist/chunk-TUJ4277Q.js.map +1 -0
  53. package/dist/{chunk-57XPEL7X.js → chunk-V42C72V5.js} +25 -2
  54. package/dist/chunk-V42C72V5.js.map +1 -0
  55. package/dist/{chunk-FCYHDENJ.js → chunk-VOIVDEAV.js} +2 -2
  56. package/dist/{chunk-ACB7KOQ6.js → chunk-WSQSKYXP.js} +4 -4
  57. package/dist/{chunk-F6J5J4H6.js → chunk-WYQTPFPI.js} +26 -2
  58. package/dist/chunk-WYQTPFPI.js.map +1 -0
  59. package/dist/{chunk-PFTOGTHH.js → chunk-Z3IJ7XEW.js} +3 -3
  60. package/dist/{chunk-ZD2AUFIT.js → chunk-ZGGEYYEQ.js} +3 -3
  61. package/dist/{chunk-O5AUJQIA.js → chunk-ZNWJJRHP.js} +2 -2
  62. package/dist/design-canvas/index.js +1 -2
  63. package/dist/design-canvas/index.js.map +1 -1
  64. package/dist/design-canvas-react/engine.js +1 -2
  65. package/dist/design-canvas-react/index.js +2 -3
  66. package/dist/design-canvas-react/index.js.map +1 -1
  67. package/dist/design-canvas-react/lazy.js +1 -1
  68. package/dist/media/generate-request.d.ts +27 -1
  69. package/dist/media/index.js +36 -426
  70. package/dist/media/index.js.map +1 -1
  71. package/dist/media/router-generation.d.ts +7 -0
  72. package/dist/model-resolution/index.js +1 -1
  73. package/dist/operator/gateway-keys.d.ts +44 -0
  74. package/dist/operator/index.d.ts +1 -0
  75. package/dist/operator/index.js +55 -1
  76. package/dist/operator/index.js.map +1 -1
  77. package/dist/plans/decision.d.ts +31 -0
  78. package/dist/plans/drizzle.js +1 -1
  79. package/dist/plans/index.js +5 -1
  80. package/dist/platform/billing.d.ts +3 -2
  81. package/dist/platform/deployment.d.ts +21 -0
  82. package/dist/platform/index.d.ts +1 -0
  83. package/dist/platform/index.js +30 -10
  84. package/dist/platform/index.js.map +1 -1
  85. package/dist/preset-cloudflare/index.js +9 -8
  86. package/dist/preset-cloudflare/index.js.map +1 -1
  87. package/dist/public-consultation/index.d.ts +1 -1
  88. package/dist/public-consultation/index.js +14 -13
  89. package/dist/public-consultation/index.js.map +1 -1
  90. package/dist/sandbox/computer-files.d.ts +67 -0
  91. package/dist/sandbox/computer-receipts.d.ts +46 -0
  92. package/dist/sandbox/computer-step.d.ts +78 -0
  93. package/dist/sandbox/index.d.ts +5 -0
  94. package/dist/sandbox/index.js +34 -5
  95. package/dist/sandbox/router-model-policy.d.ts +31 -0
  96. package/dist/sandbox/router-models.d.ts +26 -0
  97. package/dist/sandbox/sandbox-run-tool.d.ts +5 -4
  98. package/dist/sequences/index.js +1 -2
  99. package/dist/sequences/index.js.map +1 -1
  100. package/dist/spend/drizzle.d.ts +195 -0
  101. package/dist/spend/drizzle.js +22 -0
  102. package/dist/spend/drizzle.js.map +1 -1
  103. package/dist/stream/index.js +2 -2
  104. package/dist/studio/generated-media/flows.d.ts +240 -0
  105. package/dist/studio/generated-media/index.d.ts +3 -1
  106. package/dist/studio/generated-media/index.js +357 -138
  107. package/dist/studio/generated-media/index.js.map +1 -1
  108. package/dist/studio/index.js +18 -16
  109. package/dist/studio-react/index.js +28 -26
  110. package/dist/studio-react/index.js.map +1 -1
  111. package/dist/teams/index.d.ts +1 -0
  112. package/dist/teams/index.js +16 -0
  113. package/dist/teams/index.js.map +1 -1
  114. package/dist/teams/invitations-api.js +1 -1
  115. package/dist/teams/members-api.d.ts +5 -3
  116. package/dist/teams/members-api.js +1 -1
  117. package/dist/teams/thread-access.d.ts +22 -0
  118. package/dist/tools/index.js +5 -4
  119. package/dist/web/index.js +4 -6
  120. package/dist/web-react/index.js +4 -4
  121. package/dist/work-product/index.js +3 -2
  122. package/dist/work-product/index.js.map +1 -1
  123. package/dist/workspace-export/d1.d.ts +1 -1
  124. package/dist/workspace-export/index.js +9 -2
  125. package/dist/workspace-export/index.js.map +1 -1
  126. package/package.json +1 -1
  127. package/dist/chunk-56JUV4DK.js.map +0 -1
  128. package/dist/chunk-57XPEL7X.js.map +0 -1
  129. package/dist/chunk-6OG4244Y.js.map +0 -1
  130. package/dist/chunk-6Z7TZVKZ.js +0 -26
  131. package/dist/chunk-6Z7TZVKZ.js.map +0 -1
  132. package/dist/chunk-DCJCZ7EP.js.map +0 -1
  133. package/dist/chunk-F6J5J4H6.js.map +0 -1
  134. package/dist/chunk-HRBF4B5L.js.map +0 -1
  135. package/dist/chunk-QUT3T2IN.js.map +0 -1
  136. package/dist/chunk-WL7PZK7Q.js.map +0 -1
  137. /package/dist/{DesignCanvas-3DGZQOD7.js.map → DesignCanvas-VKZ7Y3JU.js.map} +0 -0
  138. /package/dist/{DesignCanvasEditor-OG4QY5WJ.js.map → DesignCanvasEditor-3V53YLLZ.js.map} +0 -0
  139. /package/dist/{chunk-6UMIOEDR.js.map → chunk-AZRPDSRQ.js.map} +0 -0
  140. /package/dist/{chunk-6LMM3OVX.js.map → chunk-BMCC2BUP.js.map} +0 -0
  141. /package/dist/{chunk-36HSG7HU.js.map → chunk-CRZXEKCX.js.map} +0 -0
  142. /package/dist/{chunk-JKECSYDB.js.map → chunk-PV3GSLUY.js.map} +0 -0
  143. /package/dist/{chunk-FCYHDENJ.js.map → chunk-VOIVDEAV.js.map} +0 -0
  144. /package/dist/{chunk-ACB7KOQ6.js.map → chunk-WSQSKYXP.js.map} +0 -0
  145. /package/dist/{chunk-PFTOGTHH.js.map → chunk-Z3IJ7XEW.js.map} +0 -0
  146. /package/dist/{chunk-ZD2AUFIT.js.map → chunk-ZGGEYYEQ.js.map} +0 -0
  147. /package/dist/{chunk-O5AUJQIA.js.map → chunk-ZNWJJRHP.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"],"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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,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;AACA,QAAM,QAAwB,EAAE,MAAM,IAAI,aAAa,IAAI,SAAS,CAAC,GAAG,OAAO,OAAO,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,EAAE,EAAE;AAC/G,QAAM,aAAa,CAAC,SAClB,OAAO,OAAO,EAAE,IAAI,KAAK,IAAI,OAAO,KAAK,OAAO,MAAM,KAAK,KA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AEA,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"]}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The files a computer step leaves in the workspace, and what the model may
3
+ * truthfully tell the member about them.
4
+ *
5
+ * A box keeps workspace files under one directory; the app's Vault is a
6
+ * different store, and a file the box agent saves proves nothing about it.
7
+ * So the step lists the box's tree before and after the run, saves each new or
8
+ * changed file through the app's `save`, and appends one receipt line to the
9
+ * answer. That line is the only statement about Vault contents the model may
10
+ * relay ({@link COMPUTER_FILES_GUIDANCE}). Legal learned this in production:
11
+ * a child saved a file outside the Vault and the model said it was saved (#547).
12
+ */
13
+ import type { SandboxInstance } from '@tangle-network/sandbox';
14
+ /** One file the step wrote, at its path relative to the Vault root. */
15
+ export interface ComputerVaultFile {
16
+ path: string;
17
+ content: string;
18
+ size: number;
19
+ }
20
+ /** The app's Vault, as a computer step sees it. */
21
+ export interface ComputerVault {
22
+ /** Absolute directory on the box that holds the workspace's files. */
23
+ root: string;
24
+ /** Store one file the step wrote. A throw leaves it on the computer only, named in the receipt. */
25
+ save(file: ComputerVaultFile, step: {
26
+ executionId: string;
27
+ }): Promise<void>;
28
+ /** Why the Vault cannot hold this file, or null when it can. Default: text kinds up to 512 KB. */
29
+ refuse?(path: string, size: number): string | null;
30
+ /** Most files one step saves. Default 20. */
31
+ maxFiles?: number;
32
+ }
33
+ /** Path relative to the root, mapped to the file's size and modification time. */
34
+ export type ComputerFileListing = {
35
+ succeeded: true;
36
+ files: Record<string, {
37
+ size: number;
38
+ mtime: number;
39
+ }>;
40
+ } | {
41
+ succeeded: false;
42
+ error: string;
43
+ };
44
+ /** What one step saved, and what it left on the computer only (with the reason). */
45
+ export interface ComputerFileReceipt {
46
+ checked: boolean;
47
+ saved: string[];
48
+ computerOnly: Array<{
49
+ path: string;
50
+ reason: string;
51
+ }>;
52
+ /** The receipt line appended to the step's answer. */
53
+ text: string;
54
+ }
55
+ /** Appended to the Router model's prompt whenever a computer step copies files into the Vault. */
56
+ export declare const COMPUTER_FILES_GUIDANCE: string;
57
+ /** Appended to the task the box agent receives, so a member's relative path lands under the Vault root. */
58
+ export declare function computerFileContract(root: string, task: string): string;
59
+ /** The box's tree under `root`. A tree the box cannot list completely is a failure, never a partial listing. */
60
+ export declare function listComputerFiles(box: SandboxInstance, root: string): Promise<ComputerFileListing>;
61
+ /** Save what the step wrote since `before` into the Vault and return its receipt. */
62
+ export declare function saveComputerFiles(input: {
63
+ box: SandboxInstance;
64
+ vault: ComputerVault;
65
+ before: ComputerFileListing;
66
+ executionId: string;
67
+ }): Promise<ComputerFileReceipt>;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Computer-step receipts: the durable record of one `sandbox_run` call, keyed
3
+ * by its step id (the turn's execution, the session and the tool call).
4
+ *
5
+ * `prepared` is written before the task is sent and holds the Vault listing
6
+ * taken then, so a repeated call after a lost request still copies the files
7
+ * the first send wrote. `settled` holds the answer the model read, the model
8
+ * that ran and the file receipt; a repeated call returns it and sends nothing.
9
+ * A receipt holds no credential.
10
+ */
11
+ import type { ComputerFileListing, ComputerFileReceipt } from './computer-files';
12
+ export interface ComputerStepReceipt {
13
+ stepId: string;
14
+ state: 'prepared' | 'settled';
15
+ sessionId: string;
16
+ model?: string;
17
+ /** The Vault listing before the first send, while `prepared`. */
18
+ before?: ComputerFileListing;
19
+ /** The answer the model read, file receipt line included, once `settled`. */
20
+ answer?: string;
21
+ files?: ComputerFileReceipt;
22
+ updatedAt: number;
23
+ }
24
+ export interface ComputerStepReceipts {
25
+ read(stepId: string): Promise<ComputerStepReceipt | null>;
26
+ /** A `settled` receipt is final: a later `prepared` write for the same step never replaces it. */
27
+ write(receipt: ComputerStepReceipt): Promise<void>;
28
+ }
29
+ /** The D1 surface the store uses. A real `D1Database` satisfies it. */
30
+ export interface ComputerStepReceiptD1Like {
31
+ prepare(query: string): {
32
+ bind(...values: unknown[]): {
33
+ first<T = Record<string, unknown>>(): Promise<T | null>;
34
+ run(): Promise<unknown>;
35
+ };
36
+ };
37
+ }
38
+ export declare const DEFAULT_COMPUTER_STEP_RECEIPT_TABLE = "computer_step_receipts";
39
+ /** Paste into a product migration; the store never runs DDL. Times are epoch ms. */
40
+ export declare const COMPUTER_STEP_RECEIPT_TABLE_DDL = "CREATE TABLE IF NOT EXISTS computer_step_receipts (\n step_id TEXT PRIMARY KEY,\n state TEXT NOT NULL,\n receipt TEXT NOT NULL,\n updated_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS computer_step_receipts_by_age ON computer_step_receipts (updated_at);";
41
+ /** Receipts in one D1 table, shared by every isolate. Rows older than `retentionMs` (default 30 days) are pruned. */
42
+ export declare function createD1ComputerStepReceipts(db: ComputerStepReceiptD1Like, options?: {
43
+ table?: string;
44
+ retentionMs?: number;
45
+ now?: () => number;
46
+ }): ComputerStepReceipts;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * `createComputerStep`: what one `sandbox_run` call does on the workspace box,
3
+ * owned once for every app. GTM, Creative and Legal each wrote this step, and
4
+ * each break on 2026-10-24 was in one of those copies (agent-app-lessons.md,
5
+ * "Computer steps"). The step:
6
+ *
7
+ * - runs the first of the turn's models the box key allows: the box calls the
8
+ * Router on its own key, whose models are the payer's sandbox policy
9
+ * (`readSandboxRouterModels`), so a model outside it is refused before a token;
10
+ * a run that ends refused for its model (`provider_disabled`, quota) moves to the
11
+ * next allowed one under its own execution id;
12
+ * - takes its session as one value, `{ id, isolated }`, which sets both
13
+ * `secretProfileIsolation` and the send witness;
14
+ * - sends under a step id derived from the turn, the session and the tool call,
15
+ * so a repeated call attaches to its run instead of sending a second one;
16
+ * - keeps a durable receipt (`receipts`): a repeated call returns it and sends nothing;
17
+ * - copies what the box agent wrote under the Vault root into the app's Vault
18
+ * (`files`) and appends the receipt line the model may relay.
19
+ *
20
+ * The product keeps the prompt path when it has its own (`run`); otherwise the
21
+ * step uses agent-app's `runSandboxPrompt` over the product's shell.
22
+ */
23
+ import type { SandboxInstance } from '@tangle-network/sandbox';
24
+ import type { SandboxRuntimeConfig } from './configuration';
25
+ import type { StreamSandboxPromptOptions } from './prompt-options';
26
+ import { type ComputerVault } from './computer-files';
27
+ import type { ComputerStepReceipts } from './computer-receipts';
28
+ import type { Outcome } from './outcome';
29
+ import type { SandboxRunToolOptions, SandboxTaskOptions } from './sandbox-run-tool';
30
+ /** The box session one computer step runs in. */
31
+ export interface ComputerStepSession {
32
+ id: string;
33
+ /** A secret-isolated native session the product prepared before the send. */
34
+ isolated?: boolean;
35
+ }
36
+ /** What a product's own prompt path receives for one step. */
37
+ export interface ComputerStepRun extends SandboxTaskOptions {
38
+ /** Stable for the turn, the session and the tool call: send under it as both execution and turn id. */
39
+ executionId?: string;
40
+ session?: ComputerStepSession;
41
+ /** Set only when the box key's policy constrains the turn's models; otherwise run the product's model. */
42
+ model?: string;
43
+ /** The send witness: pass it as the prompt's `onDispatch`, or call it exactly at the send. */
44
+ onDispatch(): void;
45
+ }
46
+ export interface ComputerStepOptions {
47
+ /** agent-app's prompt path over the product's shell. */
48
+ shell?: SandboxRuntimeConfig;
49
+ /** That path's options, other than the ones the step owns. `onDispatch` here observes the step's own witness. */
50
+ prompt?: Omit<StreamSandboxPromptOptions, 'sessionId' | 'executionId' | 'turnId' | 'secretProfileIsolation' | 'signal' | 'timeoutMs' | 'trace' | 'traceParent' | 'disallowQuestions' | 'history'>;
51
+ /** The product's own prompt path, instead of `shell`. Returns the box agent's final answer. */
52
+ run?(box: SandboxInstance, task: string, step: ComputerStepRun): Promise<string>;
53
+ /** `run` passes `step.onDispatch` to a send that calls it (agent-app's `streamSandboxPrompt`, `runSandboxPrompt`
54
+ * and `driveSandboxTurn` do), so a failure before it fired was never sent. Without it, every `run` failure is
55
+ * unconfirmed. The `shell` path always witnesses. */
56
+ runWitnessesDispatch?: boolean;
57
+ /** The turn's execution id; with the tool call id it makes the step id. Without it each call sends fresh. */
58
+ parentExecutionId?: string;
59
+ /** The session: one value, or prepared per box (a secret-isolated session). A failure there is never sent. */
60
+ session?: ComputerStepSession | ((box: SandboxInstance, signal: AbortSignal) => Promise<ComputerStepSession>);
61
+ /** The turn's models in preference order and the box key's allow-list (`readSandboxRouterModels`). */
62
+ models?: {
63
+ preferred: readonly string[];
64
+ allowed(signal: AbortSignal): Promise<Outcome<readonly string[] | null>>;
65
+ };
66
+ /** Copy each file the step wrote under the Vault root into the product's Vault. */
67
+ files?: ComputerVault;
68
+ /** The product's filesystem contract, applied to every task. */
69
+ frame?(task: string): string;
70
+ /** Durable step receipts (`createD1ComputerStepReceipts`). */
71
+ receipts?: ComputerStepReceipts;
72
+ }
73
+ export interface ComputerStep {
74
+ runTask: SandboxRunToolOptions['runTask'];
75
+ /** What the Router model must be told about this step's answers. */
76
+ guidance?: string;
77
+ }
78
+ export declare function createComputerStep(options: ComputerStepOptions): ComputerStep;
@@ -14,6 +14,10 @@ export * from './workspace-sandbox-manager';
14
14
  export * from './terminal-connection';
15
15
  export * from './prewarm';
16
16
  export * from './sandbox-run-tool';
17
+ export * from './computer-step';
18
+ export * from './computer-files';
19
+ export * from './computer-receipts';
20
+ export * from './router-models';
17
21
  export * from './sandbox-exec-tool';
18
22
  export * from './prewarm-claim-d1';
19
23
  export * from './prewarm-route';
@@ -27,6 +31,7 @@ export type { SandboxClientCredentials, SandboxCredentialEnvironment, ResolveSan
27
31
  export { DEFAULT_SANDBOX_RESOURCES } from './configuration';
28
32
  export type { SandboxResourceConfig, SandboxBuildContext, SandboxScope, SandboxRestoreSpec, StoppedSandboxResumeFailure, MissingSandboxFailure, StoppedSandboxResumeRecovery, LivenessProbeConfig, ProfileComposeOptions, SandboxRuntimeConfig, EnsureWorkspaceSandboxOptions, SandboxProvisionedObservation, SandboxSpendHooks, } from './configuration';
29
33
  export { PYPI_EGRESS_DOMAINS, buildProductEgressPolicy } from './product-egress';
34
+ export { readSandboxModelPolicy, sandboxModelWithinPolicy, type SandboxModelPolicy } from './router-model-policy';
30
35
  export { dropTrustedBox, getClient, resetClientCache } from './runtime-cache';
31
36
  export { buildAppToolMcpServers, sandboxToolRootDir, sandboxToolBinDir, sandboxToolPath, buildSandboxToolFileMounts, buildSandboxToolBinDirsEnv, buildSandboxToolBinDirScript, buildSandboxToolPathSetupScript, ensureSandboxToolBinDir, runSandboxToolPathSetup, } from './app-tools';
32
37
  export type { AppToolDescriptor, BuildAppToolMcpServersOptions, SandboxToolSpec, SandboxToolPathOptions, BuildSandboxToolFileMountsOptions, } from './app-tools';
@@ -1,4 +1,5 @@
1
1
  import {
2
+ COMPUTER_FILES_GUIDANCE,
2
3
  DEFAULT_ESCALATION_TOOLS,
3
4
  DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,
4
5
  DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS,
@@ -43,7 +44,9 @@ import {
43
44
  buildSandboxToolPathSetupScript,
44
45
  classifySeveredStream,
45
46
  collectSandboxPromptText,
47
+ computerFileContract,
46
48
  createCacheReuseStore,
49
+ createComputerStep,
47
50
  createD1PrewarmClaimStore,
48
51
  createD1WarmLeaseStore,
49
52
  createD1WarmReceiptStore,
@@ -69,11 +72,15 @@ import {
69
72
  getClient,
70
73
  isAutomatedPrewarmRequest,
71
74
  isTerminalPromptEvent,
75
+ listComputerFiles,
72
76
  mergeExtraMcp,
73
77
  mergeHistoryIntoParts,
74
78
  mintSandboxScopedToken,
79
+ modelWithinAllowList,
75
80
  peekWorkspaceSandbox,
76
81
  predictColdArrival,
82
+ readSandboxModelPolicy,
83
+ readSandboxRouterModels,
77
84
  requireTransportableModel,
78
85
  resetClientCache,
79
86
  resolveModel,
@@ -84,6 +91,7 @@ import {
84
91
  runForegroundSandboxSingleFlight,
85
92
  runSandboxPrompt,
86
93
  runSandboxToolPathSetup,
94
+ sandboxModelWithinPolicy,
87
95
  sandboxPrewarmClaimKey,
88
96
  sandboxPromptExecutionOptions,
89
97
  sandboxPromptRunner,
@@ -91,6 +99,7 @@ import {
91
99
  sandboxToolBinDir,
92
100
  sandboxToolPath,
93
101
  sandboxToolRootDir,
102
+ saveComputerFiles,
94
103
  secretStoreFromClient,
95
104
  storeSecret,
96
105
  streamSandboxPrompt,
@@ -103,11 +112,16 @@ import {
103
112
  warmKey,
104
113
  warmReceiptId,
105
114
  warmWeekdayOf
106
- } from "../chunk-56JUV4DK.js";
115
+ } from "../chunk-NDXQFEZQ.js";
107
116
  import {
108
117
  createWarmCache
109
118
  } from "../chunk-F4TUZYMX.js";
110
119
  import "../chunk-MH74DY2I.js";
120
+ import {
121
+ COMPUTER_STEP_RECEIPT_TABLE_DDL,
122
+ DEFAULT_COMPUTER_STEP_RECEIPT_TABLE,
123
+ createD1ComputerStepReceipts
124
+ } from "../chunk-GY4IPYG4.js";
111
125
  import {
112
126
  EGRESS_PROXY_RECOVERY_PHASE,
113
127
  EGRESS_PROXY_RECOVERY_REQUIRED,
@@ -152,15 +166,17 @@ import "../chunk-ALIWB2P3.js";
152
166
  import "../chunk-N5RWYR5N.js";
153
167
  import "../chunk-3Q3UEWKK.js";
154
168
  import "../chunk-QGJOT6R6.js";
169
+ import "../chunk-L3QR274L.js";
170
+ import "../chunk-XELWWXJJ.js";
155
171
  import "../chunk-DSMGS4IV.js";
156
- import "../chunk-ACB7KOQ6.js";
172
+ import "../chunk-WSQSKYXP.js";
157
173
  import "../chunk-6A7MYOUI.js";
158
174
  import "../chunk-O7UX55EU.js";
159
- import "../chunk-7Y7U7U7X.js";
175
+ import "../chunk-Q7RSHLEV.js";
160
176
  import "../chunk-S5SRJJQG.js";
161
- import "../chunk-FCYHDENJ.js";
177
+ import "../chunk-VOIVDEAV.js";
162
178
  import "../chunk-UGWQLQDS.js";
163
- import "../chunk-HRBF4B5L.js";
179
+ import "../chunk-TUJ4277Q.js";
164
180
  import "../chunk-D6UJEOZQ.js";
165
181
  import "../chunk-W6G2HF6M.js";
166
182
  import {
@@ -172,8 +188,12 @@ import {
172
188
  } from "../chunk-CTREXL3O.js";
173
189
  import "../chunk-ELX5YITO.js";
174
190
  import "../chunk-HY57QRRW.js";
191
+ import "../chunk-F4XBNR5L.js";
175
192
  import "../chunk-TXD5HXLE.js";
176
193
  export {
194
+ COMPUTER_FILES_GUIDANCE,
195
+ COMPUTER_STEP_RECEIPT_TABLE_DDL,
196
+ DEFAULT_COMPUTER_STEP_RECEIPT_TABLE,
177
197
  DEFAULT_ESCALATION_TOOLS,
178
198
  DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,
179
199
  DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS,
@@ -232,7 +252,10 @@ export {
232
252
  classifySandboxTransientFailure,
233
253
  classifySeveredStream,
234
254
  collectSandboxPromptText,
255
+ computerFileContract,
235
256
  createCacheReuseStore,
257
+ createComputerStep,
258
+ createD1ComputerStepReceipts,
236
259
  createD1PrewarmClaimStore,
237
260
  createD1WarmLeaseStore,
238
261
  createD1WarmReceiptStore,
@@ -272,15 +295,19 @@ export {
272
295
  isWorkspaceSandboxRecoveryCode,
273
296
  isWorkspaceSandboxRecoveryState,
274
297
  isWorkspaceSandboxSnapshotRestoreError,
298
+ listComputerFiles,
275
299
  mergeExtraMcp,
276
300
  mergeHistoryIntoParts,
277
301
  mintSandboxScopedToken,
302
+ modelWithinAllowList,
278
303
  peekWorkspaceSandbox,
279
304
  plannedHostRestart,
280
305
  predictColdArrival,
281
306
  preferredWorkspaceSandboxRecoveryBoxKey,
282
307
  readDuringPlannedHostRestart,
283
308
  readSandboxBinaryBytes,
309
+ readSandboxModelPolicy,
310
+ readSandboxRouterModels,
284
311
  requireTransportableModel,
285
312
  resetClientCache,
286
313
  resolveModel,
@@ -292,6 +319,7 @@ export {
292
319
  runForegroundSandboxSingleFlight,
293
320
  runSandboxPrompt,
294
321
  runSandboxToolPathSetup,
322
+ sandboxModelWithinPolicy,
295
323
  sandboxPrewarmClaimKey,
296
324
  sandboxPromptExecutionOptions,
297
325
  sandboxPromptRunner,
@@ -300,6 +328,7 @@ export {
300
328
  sandboxToolPath,
301
329
  sandboxToolRootDir,
302
330
  sandboxTransientBackoffMs,
331
+ saveComputerFiles,
303
332
  secretStoreFromClient,
304
333
  serializeSandboxProvisioningError,
305
334
  shellQuote,
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The models a workspace box may call. Platform mints every box's Router key
3
+ * (`auto:sandbox:router:<box>`) under the payer's sandbox policy, and the
4
+ * Sandbox API sends that key with every run in place of any per-turn key. A
5
+ * paying customer's policy names no models; a company account's (operator,
6
+ * smoke, acceptance, staff) names only the flat-plan models and the Router's
7
+ * synthetic model, so a box asked for any other model is refused before it
8
+ * produces a token. `GET /v1/keys/sandbox-router-models` reports that policy
9
+ * for the calling key without returning key material.
10
+ */
11
+ export type SandboxModelPolicy = {
12
+ ok: true;
13
+ allowedModels: string[] | null;
14
+ } | {
15
+ ok: false;
16
+ error: string;
17
+ };
18
+ /**
19
+ * Platform's model policy for a box minted under the payer of `apiKey`, cached
20
+ * per key for ten minutes. A missing Platform URL, a failed request or an
21
+ * invalid answer is a refusal, never an open policy.
22
+ */
23
+ export declare function readSandboxModelPolicy(apiKey: string, options: {
24
+ platformUrl: string | undefined;
25
+ signal?: AbortSignal;
26
+ }): Promise<SandboxModelPolicy>;
27
+ /**
28
+ * The first preferred model the policy allows, else the policy's own first
29
+ * model. A policy that names none allows the first preference.
30
+ */
31
+ export declare function sandboxModelWithinPolicy(preferred: readonly string[], allowedModels: readonly string[] | null): string | undefined;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The models a workspace box may call. Platform mints every box's Router key
3
+ * (`auto:sandbox:router:<box>`) under the payer's sandbox policy, and the
4
+ * Sandbox API sends that key with every run in place of any per-turn key. A
5
+ * paying customer's policy names no models (`null`); a company account's
6
+ * (operator, smoke, acceptance, staff) names only its flat-plan models, so a
7
+ * box asked for any other model is refused before it writes a token.
8
+ * `GET /v1/keys/sandbox-router-models` reports that policy for the calling key
9
+ * without returning key material.
10
+ *
11
+ * Creative #739, Legal #546 and GTM each kept a copy of this read; a computer
12
+ * step asked for a model its box key refuses failed every call.
13
+ */
14
+ import { type Outcome } from './outcome';
15
+ export interface ReadSandboxRouterModelsOptions {
16
+ /** Platform's origin (`TANGLE_PLATFORM_URL`); any path on it is ignored. */
17
+ platformUrl: string;
18
+ /** A key of the payer whose sandbox policy applies: the member's linked key, or the owner's sandbox key. */
19
+ apiKey: string;
20
+ signal?: AbortSignal;
21
+ fetch?: typeof fetch;
22
+ }
23
+ /** Platform's model policy for a box minted under the payer of `apiKey`: the allowed models, or `null` for any. */
24
+ export declare function readSandboxRouterModels(options: ReadSandboxRouterModelsOptions): Promise<Outcome<string[] | null>>;
25
+ /** The first preferred model the policy allows, else the policy's own first model; `null` allows the first preference. */
26
+ export declare function modelWithinAllowList(preferred: readonly string[], allowedModels: readonly string[] | null): string | undefined;
@@ -20,7 +20,8 @@
20
20
  */
21
21
  import type { SandboxInstance } from '@tangle-network/sandbox';
22
22
  import type { TurnSpan, TurnTrace } from '../turn-trace/recorder';
23
- import { type SandboxRuntimeConfig, type StreamSandboxPromptOptions } from './index';
23
+ import type { SandboxRuntimeConfig } from './configuration';
24
+ import type { StreamSandboxPromptOptions } from './prompt-options';
24
25
  import { SandboxRunError } from './sandbox-run-error';
25
26
  export { SandboxRunError, type SandboxRunFailureCode } from './sandbox-run-error';
26
27
  /** The engine's per-call tool context (`RouterTurnToolContext`), kept structural so this module does not import the engine. */
@@ -91,9 +92,9 @@ export declare const SANDBOX_RUN_DESCRIPTION: string;
91
92
  /** The redacted cause chain of a computer-step failure, one line, for a durable record: each cause's name, code,
92
93
  * status and message, outermost first, credentials and signed URLs removed. */
93
94
  export declare function sandboxRunFailureDetail(error: unknown): string;
94
- /** The shell's unattended runner. A supplied execution/turn id seeds child
95
- * identity with the actual tool callId: different calls stay separate and a
96
- * retry of that exact call stays idempotent. Without callId, use a fresh child.
95
+ /** The shell's unattended runner: {@link createComputerStep} over the shell, with the session and isolation the
96
+ * prompt names. A supplied execution/turn id seeds the step id with the actual tool callId: different calls stay
97
+ * separate and a retry of that exact call stays idempotent. Without callId, each call sends fresh.
97
98
  *
98
99
  * Its failure follows the send witness, in a shared and an isolated session alike: a failure before the prompt
99
100
  * was handed to the SDK is `sandbox_unavailable` (nothing runs on the box, so the turn may use it again); after
@@ -29,9 +29,8 @@ import {
29
29
  buildScopedMcpServerEntry,
30
30
  createMcpToolHandler
31
31
  } from "../chunk-6A7MYOUI.js";
32
+ import "../chunk-V42C72V5.js";
32
33
  import "../chunk-TXD5HXLE.js";
33
- import "../chunk-6Z7TZVKZ.js";
34
- import "../chunk-57XPEL7X.js";
35
34
 
36
35
  // src/sequences/operations.ts
37
36
  var SEQUENCE_OPERATION_TYPES = [