@tangle-network/agent-app 0.60.250 → 0.60.251

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 (222) hide show
  1. package/dist/DesignCanvas-L6J72JQ2.js +15 -0
  2. package/dist/DesignCanvasEditor-QFQD63MR.js +18 -0
  3. package/dist/agent-enrollment/drizzle.js +3 -3
  4. package/dist/agent-enrollment/index.js +3 -3
  5. package/dist/app-auth/drizzle.d.ts +561 -0
  6. package/dist/app-auth/drizzle.js +72 -0
  7. package/dist/app-auth/drizzle.js.map +1 -0
  8. package/dist/app-auth/index.js +5 -3
  9. package/dist/app-auth/index.js.map +1 -1
  10. package/dist/app-oauth/drizzle.d.ts +2080 -0
  11. package/dist/app-oauth/drizzle.js +161 -0
  12. package/dist/app-oauth/drizzle.js.map +1 -0
  13. package/dist/app-oauth/index.d.ts +4 -0
  14. package/dist/app-oauth/index.js +8 -222
  15. package/dist/app-oauth/index.js.map +1 -1
  16. package/dist/app-oauth/issuer.d.ts +133 -0
  17. package/dist/app-oauth/issuer.js +247 -0
  18. package/dist/app-oauth/issuer.js.map +1 -0
  19. package/dist/assistant/index.js +13 -13
  20. package/dist/chat-react/index.js +4 -4
  21. package/dist/chat-routes/index.js +37 -67
  22. package/dist/chat-routes/index.js.map +1 -1
  23. package/dist/chat-routes/promote-file-part.d.ts +2 -3
  24. package/dist/chat-store/index.js +4 -4
  25. package/dist/{chunk-MY3EJJ6Y.js → chunk-4FEH6266.js} +2 -2
  26. package/dist/{chunk-5Y7Z5G3Y.js → chunk-4GCPADYG.js} +20 -336
  27. package/dist/chunk-4GCPADYG.js.map +1 -0
  28. package/dist/{chunk-X556WVBG.js → chunk-4ZSLX3LY.js} +2 -2
  29. package/dist/chunk-57XPEL7X.js +26 -0
  30. package/dist/chunk-57XPEL7X.js.map +1 -0
  31. package/dist/chunk-6Z7TZVKZ.js +26 -0
  32. package/dist/chunk-6Z7TZVKZ.js.map +1 -0
  33. package/dist/{chunk-7KKOFMLD.js → chunk-AWIQQEFP.js} +1 -1
  34. package/dist/chunk-AWIQQEFP.js.map +1 -0
  35. package/dist/{chunk-VBKP2NLI.js → chunk-BTKI4XMM.js} +2 -2
  36. package/dist/{chunk-63QAQP7I.js → chunk-CNBVWPQC.js} +7 -7
  37. package/dist/{chunk-FENBDSIW.js → chunk-CQGEGPY7.js} +75 -3
  38. package/dist/chunk-CQGEGPY7.js.map +1 -0
  39. package/dist/chunk-CTREXL3O.js +335 -0
  40. package/dist/chunk-CTREXL3O.js.map +1 -0
  41. package/dist/chunk-DLWO3J7D.js +238 -0
  42. package/dist/chunk-DLWO3J7D.js.map +1 -0
  43. package/dist/{chunk-LWSJK546.js → chunk-DSMGS4IV.js} +5 -5
  44. package/dist/{chunk-LWSJK546.js.map → chunk-DSMGS4IV.js.map} +1 -1
  45. package/dist/{chunk-A3KPDLSF.js → chunk-EFPIHR6F.js} +18 -18
  46. package/dist/chunk-FRAICFTZ.js +191 -0
  47. package/dist/chunk-FRAICFTZ.js.map +1 -0
  48. package/dist/chunk-GS7VWV26.js +61 -0
  49. package/dist/chunk-GS7VWV26.js.map +1 -0
  50. package/dist/{chunk-NMSAZFRL.js → chunk-H5GQMLHA.js} +2 -2
  51. package/dist/{chunk-OQE6WMDP.js → chunk-HN6MZ2XL.js} +5 -5
  52. package/dist/chunk-HY57QRRW.js +11 -0
  53. package/dist/chunk-HY57QRRW.js.map +1 -0
  54. package/dist/{chunk-TCGZFSN5.js → chunk-KH4QSBNI.js} +2 -2
  55. package/dist/{chunk-JH3CKHF4.js → chunk-KJODHPWM.js} +8 -8
  56. package/dist/chunk-LSBI5MWS.js +66 -0
  57. package/dist/chunk-LSBI5MWS.js.map +1 -0
  58. package/dist/chunk-MDRH3SDA.js +106 -0
  59. package/dist/chunk-MDRH3SDA.js.map +1 -0
  60. package/dist/{chunk-VBWYH7UZ.js → chunk-NHYRIM4I.js} +3 -3
  61. package/dist/{chunk-BYP54FMI.js → chunk-O2RCDK5D.js} +30 -15
  62. package/dist/{chunk-BYP54FMI.js.map → chunk-O2RCDK5D.js.map} +1 -1
  63. package/dist/{chunk-EWOJATDS.js → chunk-PDD5A43Y.js} +3 -3
  64. package/dist/{chunk-23JUSUUB.js → chunk-RZLCBWGG.js} +2 -2
  65. package/dist/chunk-SFZELD6V.js +52 -0
  66. package/dist/chunk-SFZELD6V.js.map +1 -0
  67. package/dist/{chunk-Y4W6GK5X.js → chunk-UGFCLD32.js} +2 -2
  68. package/dist/{chunk-ZGUXI5SI.js → chunk-VUBJZEZB.js} +2 -2
  69. package/dist/{chunk-LQYIBL3G.js → chunk-WL7PZK7Q.js} +71 -1
  70. package/dist/chunk-WL7PZK7Q.js.map +1 -0
  71. package/dist/{chunk-7HZCFG2A.js → chunk-WP2GYFZ4.js} +38 -1
  72. package/dist/chunk-WP2GYFZ4.js.map +1 -0
  73. package/dist/{chunk-JK7R7BZQ.js → chunk-ZWJ3SZ2G.js} +2 -2
  74. package/dist/crypto/digest.d.ts +2 -0
  75. package/dist/crypto/index.d.ts +1 -0
  76. package/dist/crypto/index.js +6 -2
  77. package/dist/design-canvas/index.js +5 -3
  78. package/dist/design-canvas/index.js.map +1 -1
  79. package/dist/design-canvas-react/engine.js +7 -5
  80. package/dist/design-canvas-react/index.js +14 -12
  81. package/dist/design-canvas-react/index.js.map +1 -1
  82. package/dist/design-canvas-react/lazy.js +1 -1
  83. package/dist/eval/index.d.ts +4 -0
  84. package/dist/eval/index.js +125 -0
  85. package/dist/eval/index.js.map +1 -1
  86. package/dist/eval/persona-driver.d.ts +37 -0
  87. package/dist/eval/research-plan.d.ts +25 -0
  88. package/dist/eval/research-plan.js +55 -0
  89. package/dist/eval/research-plan.js.map +1 -0
  90. package/dist/eval/scorecard.d.ts +38 -0
  91. package/dist/forms/blank.d.ts +2 -2
  92. package/dist/forms/index.js +4 -5
  93. package/dist/forms/index.js.map +1 -1
  94. package/dist/hosted-agent/application.js +2 -2
  95. package/dist/interactions/index.js +3 -3
  96. package/dist/knowledge/prelaunch-audit.d.ts +17 -0
  97. package/dist/knowledge/prelaunch-audit.js +67 -0
  98. package/dist/knowledge/prelaunch-audit.js.map +1 -0
  99. package/dist/media/drizzle.d.ts +207 -0
  100. package/dist/media/drizzle.js +26 -0
  101. package/dist/media/drizzle.js.map +1 -0
  102. package/dist/media/generate-request.d.ts +53 -0
  103. package/dist/media/generation-record.d.ts +68 -0
  104. package/dist/media/index.d.ts +13 -0
  105. package/dist/media/index.js +653 -0
  106. package/dist/media/index.js.map +1 -0
  107. package/dist/media/model-catalog.d.ts +109 -0
  108. package/dist/media/router-client.d.ts +40 -0
  109. package/dist/media/router-generation.d.ts +44 -0
  110. package/dist/media/speech-script.d.ts +20 -0
  111. package/dist/openui/index.js +1 -1
  112. package/dist/operator/index.js +4 -5
  113. package/dist/operator/index.js.map +1 -1
  114. package/dist/plans/decision.d.ts +48 -0
  115. package/dist/plans/drizzle.d.ts +25 -0
  116. package/dist/plans/drizzle.js +97 -0
  117. package/dist/plans/drizzle.js.map +1 -0
  118. package/dist/plans/index.d.ts +1 -1
  119. package/dist/plans/index.js +11 -3
  120. package/dist/platform/billing-config.d.ts +22 -0
  121. package/dist/platform/billing-config.js +36 -0
  122. package/dist/platform/billing-config.js.map +1 -0
  123. package/dist/platform/index.js +13 -11
  124. package/dist/platform/index.js.map +1 -1
  125. package/dist/preset-cloudflare/index.js +2 -1
  126. package/dist/preset-cloudflare/index.js.map +1 -1
  127. package/dist/profile/index.js +4 -5
  128. package/dist/profile/index.js.map +1 -1
  129. package/dist/public-consultation/index.d.ts +1 -1
  130. package/dist/public-consultation/index.js +13 -11
  131. package/dist/public-consultation/index.js.map +1 -1
  132. package/dist/runtime/telemetry-cap.d.ts +24 -0
  133. package/dist/runtime/telemetry-cap.js +36 -0
  134. package/dist/runtime/telemetry-cap.js.map +1 -0
  135. package/dist/sandbox/index.js +12 -9
  136. package/dist/sequences/index.js +4 -2
  137. package/dist/sequences/index.js.map +1 -1
  138. package/dist/skills-placement/box.d.ts +50 -0
  139. package/dist/skills-placement/box.js +204 -0
  140. package/dist/skills-placement/box.js.map +1 -0
  141. package/dist/skills-placement/index.js +8 -96
  142. package/dist/skills-placement/index.js.map +1 -1
  143. package/dist/spend/budget.d.ts +13 -0
  144. package/dist/spend/drizzle.d.ts +55 -0
  145. package/dist/spend/drizzle.js +131 -0
  146. package/dist/spend/drizzle.js.map +1 -0
  147. package/dist/spend/index.d.ts +2 -1
  148. package/dist/spend/index.js +77 -58
  149. package/dist/spend/index.js.map +1 -1
  150. package/dist/spend/platform-settlements.d.ts +46 -0
  151. package/dist/stream/index.js +19 -19
  152. package/dist/studio/generated-media/index.d.ts +6 -0
  153. package/dist/studio/generated-media/index.js +590 -0
  154. package/dist/studio/generated-media/index.js.map +1 -0
  155. package/dist/studio/generated-media/output.d.ts +27 -0
  156. package/dist/studio/generated-media/store.d.ts +175 -0
  157. package/dist/studio-react/download-generations.d.ts +7 -0
  158. package/dist/studio-react/index.d.ts +1 -0
  159. package/dist/studio-react/index.js +85 -0
  160. package/dist/studio-react/index.js.map +1 -1
  161. package/dist/studio-react/use-studio-route.d.ts +44 -0
  162. package/dist/teams/invitations-api.d.ts +4 -0
  163. package/dist/teams/invitations-api.js +44 -32
  164. package/dist/teams/invitations-api.js.map +1 -1
  165. package/dist/theme/dom.d.ts +22 -0
  166. package/dist/theme/dom.js +18 -0
  167. package/dist/theme/dom.js.map +1 -0
  168. package/dist/vault/collaboration.d.ts +83 -0
  169. package/dist/vault/collaboration.js +215 -0
  170. package/dist/vault/collaboration.js.map +1 -0
  171. package/dist/vault/server.js +6 -53
  172. package/dist/vault/server.js.map +1 -1
  173. package/dist/vault/store/coordinator.d.ts +64 -0
  174. package/dist/vault/store/index.d.ts +12 -0
  175. package/dist/vault/store/index.js +1202 -0
  176. package/dist/vault/store/index.js.map +1 -0
  177. package/dist/vault/store/paths.d.ts +65 -0
  178. package/dist/vault/store/revisions.d.ts +211 -0
  179. package/dist/vault/store/sandbox-sync.d.ts +74 -0
  180. package/dist/vault/store/store.d.ts +161 -0
  181. package/dist/vault/store/tree.d.ts +11 -0
  182. package/dist/web/entry-server.d.ts +7 -0
  183. package/dist/web/entry-server.js +29 -0
  184. package/dist/web/entry-server.js.map +1 -0
  185. package/dist/web/fetch-guard.d.ts +6 -0
  186. package/dist/web/index.d.ts +3 -0
  187. package/dist/web/index.js +20 -4
  188. package/dist/web/mime.d.ts +16 -0
  189. package/dist/web/rate-limit.d.ts +25 -0
  190. package/dist/web/timeout.d.ts +9 -0
  191. package/dist/web-react/agent-profile-editor.js +3 -3
  192. package/dist/web-react/api-access-panel.d.ts +4 -2
  193. package/dist/web-react/document.d.ts +41 -0
  194. package/dist/web-react/document.js +103 -0
  195. package/dist/web-react/document.js.map +1 -0
  196. package/dist/web-react/index.js +31 -31
  197. package/dist/workspace-react/index.js +5 -5
  198. package/package.json +95 -4
  199. package/dist/DesignCanvas-OW3W2QXW.js +0 -13
  200. package/dist/DesignCanvasEditor-TCHZF25W.js +0 -16
  201. package/dist/chunk-5Y7Z5G3Y.js.map +0 -1
  202. package/dist/chunk-7HZCFG2A.js.map +0 -1
  203. package/dist/chunk-7KKOFMLD.js.map +0 -1
  204. package/dist/chunk-FENBDSIW.js.map +0 -1
  205. package/dist/chunk-LQYIBL3G.js.map +0 -1
  206. /package/dist/{DesignCanvas-OW3W2QXW.js.map → DesignCanvas-L6J72JQ2.js.map} +0 -0
  207. /package/dist/{DesignCanvasEditor-TCHZF25W.js.map → DesignCanvasEditor-QFQD63MR.js.map} +0 -0
  208. /package/dist/{chunk-MY3EJJ6Y.js.map → chunk-4FEH6266.js.map} +0 -0
  209. /package/dist/{chunk-X556WVBG.js.map → chunk-4ZSLX3LY.js.map} +0 -0
  210. /package/dist/{chunk-VBKP2NLI.js.map → chunk-BTKI4XMM.js.map} +0 -0
  211. /package/dist/{chunk-63QAQP7I.js.map → chunk-CNBVWPQC.js.map} +0 -0
  212. /package/dist/{chunk-A3KPDLSF.js.map → chunk-EFPIHR6F.js.map} +0 -0
  213. /package/dist/{chunk-NMSAZFRL.js.map → chunk-H5GQMLHA.js.map} +0 -0
  214. /package/dist/{chunk-OQE6WMDP.js.map → chunk-HN6MZ2XL.js.map} +0 -0
  215. /package/dist/{chunk-TCGZFSN5.js.map → chunk-KH4QSBNI.js.map} +0 -0
  216. /package/dist/{chunk-JH3CKHF4.js.map → chunk-KJODHPWM.js.map} +0 -0
  217. /package/dist/{chunk-VBWYH7UZ.js.map → chunk-NHYRIM4I.js.map} +0 -0
  218. /package/dist/{chunk-EWOJATDS.js.map → chunk-PDD5A43Y.js.map} +0 -0
  219. /package/dist/{chunk-23JUSUUB.js.map → chunk-RZLCBWGG.js.map} +0 -0
  220. /package/dist/{chunk-Y4W6GK5X.js.map → chunk-UGFCLD32.js.map} +0 -0
  221. /package/dist/{chunk-ZGUXI5SI.js.map → chunk-VUBJZEZB.js.map} +0 -0
  222. /package/dist/{chunk-JK7R7BZQ.js.map → chunk-ZWJ3SZ2G.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sandbox/exec-failure.ts","../src/sandbox/outcome.ts","../src/sandbox/profile-files.ts","../src/sandbox/shell-path.ts","../src/sandbox/binary-read.ts"],"sourcesContent":["\n\n// Sentinel cause for a client-side per-exec timeout (a hung/wedged proxy exec).\n// Carried as the `.cause` of the fail-loud Outcome so callers see the wedged\n// command instead of an opaque infinite hang.\nexport class ProfileWriteExecTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`exec exceeded ${timeoutMs}ms (proxy hang/wedge)`)\n this.name = 'ProfileWriteExecTimeoutError'\n }\n}\n\nconst TRANSIENT_EXEC_STATUS_CODES = new Set([408, 409, 425, 429, 500, 502, 503, 504])\n\nconst TRANSIENT_EXEC_CODE_RE = /^(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ECONNABORTED)$/i\n\nconst TRANSIENT_EXEC_MESSAGE_RE =\n /\\b(408|409|425|429|500|502|503|504)\\b|rate.?limit|too many requests|\\bfetch failed\\b|network error|connection reset|socket hang up|timed? out|service unavailable|bad gateway|gateway timeout|internal server error|\\b(?:sidecar|runtime|exec(?:ution)?|terminal|sandbox|service|command(?:s)?|proxy)\\b.{0,80}\\bnot ready\\b|\\bnot ready\\b.{0,80}\\b(?:sidecar|runtime|exec(?:ution)?|terminal|sandbox|service|command(?:s)?|proxy)\\b/i\n\nfunction errorStatus(err: { status?: unknown; statusCode?: unknown; response?: unknown }): number | undefined {\n const rawStatus = err.status ?? err.statusCode ?? (\n err.response && typeof err.response === 'object'\n ? (err.response as { status?: unknown }).status\n : undefined\n )\n if (typeof rawStatus === 'number') return rawStatus\n if (typeof rawStatus === 'string' && /^\\d+$/.test(rawStatus)) return Number(rawStatus)\n return undefined\n}\n\nfunction retryAfterMs(err: unknown, seen = new Set<object>()): number | undefined {\n if (!err || typeof err !== 'object') return undefined\n if (seen.has(err)) return undefined\n seen.add(err)\n const e = err as { retryAfterMs?: unknown; cause?: unknown }\n if (typeof e.retryAfterMs === 'number') return e.retryAfterMs\n return retryAfterMs(e.cause, seen)\n}\n\nfunction isTransientExecError(err: unknown, seen = new Set<object>()): boolean {\n if (!err || typeof err !== 'object') return false\n if (seen.has(err)) return false\n seen.add(err)\n const e = err as {\n status?: unknown\n statusCode?: unknown\n response?: unknown\n code?: unknown\n message?: unknown\n cause?: unknown\n }\n const status = errorStatus(e)\n if (status !== undefined && TRANSIENT_EXEC_STATUS_CODES.has(status)) return true\n if (typeof e.code === 'string') {\n if (TRANSIENT_EXEC_CODE_RE.test(e.code)) return true\n if (/rate.?limit|too.?many.?requests|429|server.?error|service.?unavailable/i.test(e.code)) return true\n }\n if (typeof e.message === 'string' && TRANSIENT_EXEC_MESSAGE_RE.test(e.message)) return true\n return isTransientExecError(e.cause, seen)\n}\n\nexport function isRuntimeExecAuthError(err: unknown, seen = new Set<object>()): boolean {\n if (!err || typeof err !== 'object') return false\n if (seen.has(err)) return false\n seen.add(err)\n const e = err as {\n status?: unknown\n statusCode?: unknown\n response?: unknown\n code?: unknown\n name?: unknown\n message?: unknown\n cause?: unknown\n }\n if (errorStatus(e) === 401) return true\n if (\n typeof e.code === 'string' &&\n /^(AUTH_ERROR|AUTHENTICATION_ERROR|UNAUTHORIZED|UNAUTHENTICATED|ERR_UNAUTHORIZED|ERR_UNAUTHENTICATED|401)$/i.test(e.code)\n ) {\n return true\n }\n if (\n typeof e.name === 'string' &&\n /^(AuthError|AuthenticationError|UnauthorizedError|UnauthenticatedError|SandboxAuthError)$/i.test(e.name)\n ) {\n return true\n }\n return isRuntimeExecAuthError(e.cause, seen)\n}\n\nexport function isRuntimeAuthRefreshDenied(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false\n return (\n isRuntimeExecAuthError(err) ||\n errorStatus(err as { status?: unknown; statusCode?: unknown; response?: unknown }) === 403\n )\n}\n\n// Classify an exec failure as transient-retryable. Retryable shapes share the\n// same backoff path: rate-limit (HTTP 429 + retryAfterMs), client-side timeout,\n// and transient sidecar/transport/readiness failures surfaced as SandboxError-\n// shaped objects, fetch errors, network resets, or 5xx-ish messages. Everything\n// else fails loud. Non-zero shell exits never reach this classifier.\nexport function transientExecError(err: unknown): { retryable: boolean; retryAfterMs?: number } {\n if (err instanceof ProfileWriteExecTimeoutError) return { retryable: true }\n if (isTransientExecError(err)) return { retryable: true, retryAfterMs: retryAfterMs(err) }\n return { retryable: false }\n}\n","// Shared Outcome triple for the sandbox modules. Lives in a dependency-free\n// leaf so helpers can use it without importing the substrate-bound index.\n/** Represent success or failure of an operation with corresponding value or error information */\nexport type Outcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: Error }\n\nexport const ok = <T>(value: T): Outcome<T> => ({ succeeded: true, value })\nexport const fail = (error: unknown): Outcome<never> => ({\n succeeded: false,\n error: error instanceof Error ? error : new Error(String(error)),\n})\n","import type { AgentProfile, AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { ExecResult } from '@tangle-network/sandbox/core'\nimport { ProfileWriteExecTimeoutError, transientExecError } from './exec-failure'\nimport { type Outcome, fail, ok } from './outcome'\nimport { createHash } from 'node:crypto'\nimport { shellPath, shellSingleQuote } from './shell-path'\n\n// Split a profile's `resources.files` into the inline mounts that can be\n// written into a running box and the rest (non-inline refs that the\n// orchestrator must resolve, so they stay in the create payload). Returns the\n// inline set to defer and a profile copy with those inline files removed.\n/** Split profile files into inline deferred files and a lean profile without them */\nexport function splitDeferredProfileFiles(\n profile: AgentProfile,\n): { leanProfile: AgentProfile; deferredFiles: AgentProfileFileMount[] } {\n const files = profile.resources?.files ?? []\n const deferredFiles: AgentProfileFileMount[] = []\n const keptFiles: AgentProfileFileMount[] = []\n for (const mount of files) {\n if (mount.resource.kind === 'inline') deferredFiles.push(mount)\n else keptFiles.push(mount)\n }\n if (deferredFiles.length === 0) return { leanProfile: profile, deferredFiles }\n const leanProfile: AgentProfile = {\n ...profile,\n resources: { ...(profile.resources ?? {}), files: keptFiles },\n }\n return { leanProfile, deferredFiles }\n}\n\n// The runtime exec proxy (`box.exec` → /terminals/commands) hangs (30s\n// timeout) on any request whose body crosses ~4096 bytes, and one oversized\n// exec wedges the channel so every later exec on the box hangs too. We slice\n// each file's base64 into appends whose full command string stays well under\n// that cap. 3000 chars of base64 leaves ~1000 bytes of headroom for the\n// surrounding `printf '%s' '<slice>' >> <path>.b64` command plus the proxy's\n// JSON request envelope — comfortably below 4096.\nconst PROFILE_WRITE_B64_CHUNK_CHARS = 3000\n\n// gtm's corpus is ~135 small execs; on a cold box the runtime exec proxy\n// hard-throttles (HTTP 429 after ~21 execs in ~34s) and, under sustained load,\n// SILENTLY HANGS instead of returning 429 — one parked exec wedges the channel\n// and `writeProfileFilesToBox` never returns, so `ensureWorkspaceSandbox`\n// parks the worker (~140s, no exception). These failures plus sidecar exec-plane\n// readiness/transport failures (5xx, reset, fetch/network errors) are transient:\n// retry the SAME exec with exponential backoff before failing loud. A non-zero\n// exit is a real command failure, never retried.\nconst PROFILE_WRITE_MAX_RETRIES = 4\n\nconst PROFILE_WRITE_RETRY_BASE_MS = 250\n\nconst PROFILE_WRITE_RETRY_MAX_MS = 2000\n\n// Client-side hard ceiling per exec. The proxy's own 30s timeout is unreliable\n// once the channel wedges (it can hang past it), so we race each exec against an\n// independent timer we control: a wedged exec is abandoned here and retried as a\n// transient transport error, never silently parked. We also pass timeoutMs to\n// the SDK as defense-in-depth, but the race is the guarantee.\nconst PROFILE_WRITE_EXEC_TIMEOUT_MS = 30_000\n\n// Pacing between execs to stay under the proxy throttle that triggers the hang.\n// The drill saw throttling at ~0.6 exec/s bursts; ~150ms between ~135 execs\n// adds well under a minute total and keeps the burst rate below the trip point.\n// On by default for the deferred path; overridable for tests/tuning.\nconst PROFILE_WRITE_PACE_MS = 150\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\n// A mount whose path sits in a bin directory is made executable. Shared so the\n// file-API eligibility check and the exec branch agree on \"executable by dir\".\nconst PROFILE_BIN_DIR_RE = /(^|\\/)(s?bin)\\//\n\n// Run a box.exec, abandoning it if it does not settle within timeoutMs. The\n// returned promise rejects with ProfileWriteExecTimeoutError on timeout so the\n// retry loop treats a hang exactly like a transient transport error. We also\n// forward timeoutMs to the SDK so the underlying request is cancelled when the\n// SDK honors it; the race covers the case where it does not.\nfunction execWithTimeout(\n box: SandboxInstance,\n cmd: string,\n timeoutMs: number,\n): Promise<ExecResult> {\n return new Promise<ExecResult>((resolve, reject) => {\n let settled = false\n const timer = setTimeout(() => {\n if (settled) return\n settled = true\n reject(new ProfileWriteExecTimeoutError(timeoutMs))\n }, timeoutMs)\n box.exec(cmd, { timeoutMs }).then(\n (res) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n resolve(res)\n },\n (err) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n reject(err)\n },\n )\n })\n}\n\n// Materialize inline profile files into a running box via `box.exec`. Uses a\n// base64 pipe so arbitrary content (scripts, unicode, special chars) lands\n// byte-exact, and writes to ANY absolute path (e.g. /usr/local/bin) or a\n// `~`-relative path — the exec runs as the sidecar, which is not bound by the\n// safe-prefix allow-list the /files/write API enforces. Sets the executable\n// bit when the mount declares it OR the target is a bin directory.\n//\n// Each file is written in several small execs (mkdir, one append per base64\n// chunk, then a decode+cleanup) so no single exec request body trips the\n// ~4 KiB proxy cap. Writes are sequential; a single bad mount stops the batch\n// and the first failure is returned (fail-loud), the rest are not attempted.\n//\n// Each exec is bounded by a client-side hard timeout and retried with backoff\n// on transient rate-limit/readiness/transport failures, so one wedged or early\n// exec-plane request can never park the caller (and thus never park provisioning).\n// A small pace between execs keeps the burst rate below the proxy throttle that\n// triggers the hang.\n/** Define options to control execution timeout, pacing, and retry behavior when writing profile files */\nexport interface WriteProfileFilesOptions {\n // Hard ceiling per exec (ms). A hung/wedged exec is abandoned and retried.\n execTimeoutMs?: number\n // Delay between execs (ms) to stay under the proxy throttle. 0 disables it.\n paceMs?: number\n // Max retries for a transient exec before failing loud.\n maxRetries?: number\n}\n\n// The workspace-relative target for a deferred inline mount when it can be\n// materialized through the sidecar file API (`box.fs.writeMany` — FILES rate\n// group, 300/min, whole-file, auto-mkdir) instead of the chunked terminal-exec\n// path (50/min); null when it must stay on exec. The file API resolves relative\n// paths from the workspace root, so eligibility is: inline and a path that\n// resolves under the workspace root with no `..`/`.sidecar` segment. `~/…` and\n// `/home/agent/…` are home-relative; agent sandboxes set $HOME to the workspace\n// root, so both map to the same relative target. Other absolute (`/…`) and bare\n// `~`/`~user` mounts stay on exec.\nfunction fileApiTarget(mount: AgentProfileFileMount): string | null {\n if (mount.resource.kind !== 'inline') return null\n let rel: string\n if (mount.path.startsWith('~/')) rel = mount.path.slice(2)\n else if (mount.path.startsWith('/home/agent/')) rel = mount.path.slice('/home/agent/'.length)\n else if (mount.path.startsWith('/') || mount.path.startsWith('~')) return null\n else rel = mount.path\n if (rel.length === 0 || rel.startsWith('/') || rel.split('/').some((seg) => seg === '..' || seg === '.sidecar')) {\n return null\n }\n return rel\n}\n\nfunction isExecutableProfileFile(mount: AgentProfileFileMount): boolean {\n return mount.executable ?? PROFILE_BIN_DIR_RE.test(mount.path)\n}\n\nfunction profileFileMode(mount: AgentProfileFileMount): number | undefined {\n return isExecutableProfileFile(mount) ? 0o755 : undefined\n}\n\n// The sandbox gateway rejects request bodies over 1 MiB, and `writeMany` sends\n// each file as one JSON string, so a file larger than one request can never\n// land through it — the SDK splits batches but not files. Such a file goes\n// through the chunked `fs.uploadData` when the SDK has it and the chunked exec\n// path otherwise: the rule the SDK's `materializeProfileFileMounts` applies.\nconst PROFILE_FILE_API_MAX_JSON_BYTES = 1024 * 1024 - 16 * 1024\n\nfunction fitsProfileFileApi(content: string): boolean {\n const encoder = new TextEncoder()\n // JSON escaping grows one byte to at most six (`\\u001f`).\n if (encoder.encode(content).byteLength * 6 <= PROFILE_FILE_API_MAX_JSON_BYTES) return true\n return encoder.encode(JSON.stringify(content)).byteLength <= PROFILE_FILE_API_MAX_JSON_BYTES\n}\n\ntype ProfileFileUpload = (remotePath: string, data: string, options?: { mode?: number }) => Promise<unknown>\n\nfunction fileApiSupportsMode(box: SandboxInstance): boolean {\n const fs = box.fs as (SandboxInstance['fs'] & { supportsWriteMode?: boolean }) | undefined\n return fs?.supportsWriteMode === true\n}\n\n/** Write profile files to a sandbox with pacing, retries, and optional execution timeout handling */\nexport async function writeProfileFilesToBox(\n box: SandboxInstance,\n files: AgentProfileFileMount[],\n options: WriteProfileFilesOptions = {},\n): Promise<Outcome<void>> {\n const execTimeoutMs = options.execTimeoutMs ?? PROFILE_WRITE_EXEC_TIMEOUT_MS\n const paceMs = options.paceMs ?? PROFILE_WRITE_PACE_MS\n const maxRetries = options.maxRetries ?? PROFILE_WRITE_MAX_RETRIES\n // The bulk of a profile corpus (skills, `~/.claude/skills/…`, config) is\n // inline and workspace-relative — write it in ONE paced,\n // retry-aware batch via the SDK's file API (`box.fs.writeMany`, FILES rate\n // group 300/min). The SDK owns the pacing + transient-retry this module used\n // to hand-roll. Absolute / bare-`~` paths can't use the file API\n // (prefix-restricted), so they stay on the chunked exec path.\n // Capability-guarded: SDKs without `writeMany` route everything through\n // exec; SDKs before @tangle-network/sandbox 0.9.4 keep executable files on\n // exec because they do not expose `supportsWriteMode` or forward file modes.\n const fileApiAvailable = typeof box.fs?.writeMany === 'function'\n const modeAwareFileApi = fileApiSupportsMode(box)\n const uploadData = (box.fs as { uploadData?: ProfileFileUpload } | undefined)?.uploadData\n const viaFileApi: { path: string; content: string; mode?: number }[] = []\n const viaUpload: { path: string; content: string; mode?: number }[] = []\n const viaExec: AgentProfileFileMount[] = []\n for (const mount of files) {\n if (mount.resource.kind !== 'inline') continue\n const fileApiPath = fileApiAvailable ? fileApiTarget(mount) : null\n const executable = isExecutableProfileFile(mount)\n if (fileApiPath !== null && (!executable || modeAwareFileApi)) {\n const mode = profileFileMode(mount)\n const content = mount.resource.content ?? ''\n const write = { path: fileApiPath, content, ...(mode !== undefined ? { mode } : {}) }\n if (fitsProfileFileApi(content)) viaFileApi.push(write)\n else if (typeof uploadData === 'function') viaUpload.push(write)\n else viaExec.push(mount)\n }\n else viaExec.push(mount)\n }\n if (viaFileApi.length > 0) {\n // `writeMany` is fail-loud on the first file it can't write. Preserve the\n // cause so the runtime-auth-refresh wrapper still detects a 401 — it\n // recurses `.cause` for an AuthError/401 shape (see isRuntimeExecAuthError).\n try {\n await box.fs.writeMany(viaFileApi, { paceMs, maxRetries })\n } catch (err) {\n return fail(new Error('writeProfileFilesToBox: file-API batch write failed', { cause: err }))\n }\n }\n for (const upload of viaUpload) {\n // The SDK paces, retries, and checksums each chunked upload session.\n try {\n await uploadData!.call(box.fs, upload.path, upload.content, upload.mode !== undefined ? { mode: upload.mode } : undefined)\n } catch (err) {\n return fail(new Error(`writeProfileFilesToBox: chunked upload failed for ${upload.path}`, { cause: err }))\n }\n }\n\n // Pace BETWEEN execs, not before the first or after the last. Shared across\n // the exec mounts so the (now smaller) executable/edge-case set stays paced.\n let execStarted = false\n\n // Pace + transient-retry ONE exec attempt: backoff/pace/fail-loud in one place.\n // `run` must be idempotent under unknown-outcome retries (exec writes\n // deterministic parts). A transient error retries with backoff up to\n // maxRetries (honoring a server Retry-After); anything else, or exhausting\n // retries, fails loud with the cause.\n const paceAndRetry = async <T>(run: () => Promise<T>, path: string): Promise<Outcome<T>> => {\n for (let attempt = 0; ; attempt++) {\n if (execStarted && paceMs > 0) await sleep(paceMs)\n execStarted = true\n try {\n return ok(await run())\n } catch (err) {\n const { retryable, retryAfterMs } = transientExecError(err)\n if (retryable && attempt < maxRetries) {\n const backoff = Math.min(PROFILE_WRITE_RETRY_BASE_MS * 2 ** attempt, PROFILE_WRITE_RETRY_MAX_MS)\n await sleep(retryAfterMs ?? backoff)\n continue\n }\n return fail(new Error(`writeProfileFilesToBox: exec failed for ${path}`, { cause: err }))\n }\n }\n }\n\n for (const mount of viaExec) {\n if (mount.resource.kind !== 'inline') continue // always true (viaExec is inline) — narrows for TS\n const content = mount.resource.content ?? ''\n const path = mount.path\n\n const b64 = Buffer.from(content, 'utf8').toString('base64')\n const b64Chunks: string[] = []\n for (let i = 0; i < b64.length; i += PROFILE_WRITE_B64_CHUNK_CHARS) {\n b64Chunks.push(b64.slice(i, i + PROFILE_WRITE_B64_CHUNK_CHARS))\n }\n const expectedSha256 = createHash('sha256').update(content, 'utf8').digest('hex')\n const dir = path.replace(/\\/[^/]*$/, '')\n const executable = isExecutableProfileFile(mount)\n const q = shellPath(path)\n const qb64 = shellPath(`${path}.b64`)\n const qtmp = shellPath(`${path}.tmp`)\n const qpartPrefix = shellPath(`${path}.b64.part.`)\n\n // Run one exec step. Transport errors (incl. a wedged-proxy timeout) are\n // paced + retried by paceAndRetry; a non-zero exit is a REAL command failure\n // — surfaced immediately, never retried.\n const step = async (cmd: string): Promise<Outcome<void>> => {\n const res = await paceAndRetry(() => execWithTimeout(box, cmd, execTimeoutMs), path)\n if (!res.succeeded) return res\n const exec = res.value\n if (exec.exitCode !== 0) {\n return fail(\n new Error(\n `writeProfileFilesToBox: failed to write ${path} (exit ${exec.exitCode}): ${exec.stderr.slice(0, 500)}`,\n ),\n )\n }\n return ok(undefined)\n }\n\n // Ensure the target directory exists. Chunk/final commands below are\n // idempotent under unknown-outcome transport retries; this no-op/mkdir is too.\n const mkdir = dir && dir !== path ? `mkdir -p ${shellPath(dir)}` : ':'\n let res = await step(mkdir)\n if (!res.succeeded) return res\n\n // Write each deterministic part with overwrite, not append. If the server\n // writes a part but the HTTP response is lost, retrying the same step lands\n // the same bytes instead of duplicating them.\n for (let i = 0; i < b64Chunks.length; i++) {\n const slice = b64Chunks[i]!\n res = await step(`printf '%s' '${slice}' > ${shellPath(`${path}.b64.part.${i}`)}`)\n if (!res.succeeded) return res\n }\n\n // Materialize from deterministic parts into a temp file, verify its content\n // hash, then atomically move into place. If the final exec succeeds but its\n // response is lost, a retry first accepts an already-correct target and only\n // re-runs idempotent chmod/cleanup. Parts are cleaned only after the target\n // hash is known-good, so a retried final step can always reconstruct.\n const chmod = executable ? `chmod +x ${q} || exit 1; ` : ''\n const checksumMismatch = shellSingleQuote(`writeProfileFilesToBox: checksum mismatch for ${path}`)\n const finalCmd =\n `expected='${expectedSha256}'; ` +\n `if [ -f ${q} ] && [ \"$(sha256sum ${q} | awk '{print $1}')\" = \"$expected\" ]; then ` +\n `${chmod}rm -f ${qb64} ${qtmp}; i=0; while [ \"$i\" -lt ${b64Chunks.length} ]; do rm -f ${qpartPrefix}$i; i=$((i+1)); done; exit 0; fi; ` +\n `: > ${qb64} && ` +\n `i=0; while [ \"$i\" -lt ${b64Chunks.length} ]; do cat ${qpartPrefix}$i >> ${qb64} || exit 1; i=$((i+1)); done && ` +\n `base64 -d < ${qb64} > ${qtmp} && ` +\n `[ \"$(sha256sum ${qtmp} | awk '{print $1}')\" = \"$expected\" ] || { echo ${checksumMismatch} >&2; exit 1; }; ` +\n `mv ${qtmp} ${q} && ` +\n `${executable ? `chmod +x ${q} && ` : ''}` +\n `[ \"$(sha256sum ${q} | awk '{print $1}')\" = \"$expected\" ] || { echo ${checksumMismatch} >&2; exit 1; }; ` +\n `rm -f ${qb64} ${qtmp}; i=0; while [ \"$i\" -lt ${b64Chunks.length} ]; do rm -f ${qpartPrefix}$i; i=$((i+1)); done`\n res = await step(finalCmd)\n if (!res.succeeded) return res\n }\n return ok(undefined)\n}\n","\n\n// Single-quote a string for safe interpolation into a shell command.\nexport function shellSingleQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`\n}\n\n// Build a shell-safe path token that preserves tilde-home semantics. A path\n// beginning `~/` (or a bare `~`) must resolve to the box user's real `$HOME`,\n// but single-quoting the whole path suppresses shell `~` expansion and lands\n// the file in a literal directory named `~`. Expand the leading `~` to an\n// UNQUOTED `\"$HOME\"` (so the shell expands it) and single-quote only the\n// remainder. Absolute and relative paths are single-quoted unchanged.\nexport function shellPath(path: string): string {\n if (path === '~') return '\"$HOME\"'\n if (path.startsWith('~/')) {\n const rest = path.slice(2)\n return rest ? `\"$HOME\"/${shellSingleQuote(rest)}` : '\"$HOME\"'\n }\n return shellSingleQuote(path)\n}\n","/**\n * Reading arbitrary bytes out of a sandbox over an exec channel that only\n * speaks text.\n *\n * `box.exec` returns stdout as a string, so a binary file has to be encoded to\n * survive the trip: `wc -c` gives the on-disk length, `base64` gives the\n * payload, and the decoded byte count is checked against the stat. That last\n * check is the point of the module — an exec channel that caps or clips its\n * output still reports `exitCode: 0` with a short buffer, which decodes into a\n * perfectly valid but TRUNCATED file. Verifying the length turns that silent\n * corruption into a loud failure at the boundary.\n *\n * Both helpers return typed outcomes; callers must inspect `succeeded` before\n * touching `value`.\n */\n\n/** The `box.exec` surface these helpers use — structural, so a caller can pass\n * the sandbox SDK's `SandboxInstance` directly or a narrower test double. */\nexport interface SandboxExecChannel {\n exec(\n command: string,\n options?: { sessionId?: string },\n ): Promise<{ stdout: string; stderr: string; exitCode: number }>\n}\n\n/** Define options to execute code within a sandbox environment with optional session control */\nexport interface SandboxExecOptions {\n /** Run inside a named session rather than the box's default one. */\n sessionId?: string\n}\n\n/** Resolve the outcome of a sandbox file size check with success status and value or error message */\nexport type SandboxFileSizeOutcome =\n | { succeeded: true; value: number }\n | { succeeded: false; error: string }\n\n/** Represent the outcome of reading sandbox file bytes with success status and corresponding data or error */\nexport type SandboxFileBytesOutcome =\n | { succeeded: true; value: { bytes: Uint8Array; size: number } }\n | { succeeded: false; error: string }\n\n/** Wraps a value in single quotes for `sh`, closing and reopening the quote\n * around each embedded quote (`'` → `'\"'\"'`). Every path these helpers\n * interpolate into a command goes through this — in-box filenames are\n * arbitrary, so spaces, quotes and `$` are ordinary content, not syntax. */\nexport function shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`\n}\n\n/** Decodes with `atob` rather than `Buffer.from(s, 'base64')`: Buffer SKIPS\n * characters outside the alphabet, so a corrupted payload would decode to\n * something plausible instead of throwing. */\nfunction base64ToBytes(base64: string): Uint8Array {\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n\nfunction execInSandbox(box: SandboxExecChannel, command: string, options?: SandboxExecOptions) {\n return options?.sessionId ? box.exec(command, { sessionId: options.sessionId }) : box.exec(command)\n}\n\n/** Stats a sandbox file's byte length via `wc -c`. A caller enforcing a size\n * cap must check this BEFORE {@link readSandboxBinaryBytes}, so an oversize\n * file is rejected without paying for a base64 round trip of it. */\nexport async function statSandboxFileSize(\n box: SandboxExecChannel,\n absolutePath: string,\n options?: SandboxExecOptions,\n): Promise<SandboxFileSizeOutcome> {\n const quotedPath = shellQuote(absolutePath)\n let result\n try {\n result = await execInSandbox(box, `wc -c < ${quotedPath}`, options)\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n if (result.exitCode !== 0) {\n return { succeeded: false, error: result.stderr || 'unknown error' }\n }\n const size = Number.parseInt(result.stdout.trim(), 10)\n if (!Number.isFinite(size)) {\n return { succeeded: false, error: `could not parse file size from \"${result.stdout.trim()}\"` }\n }\n return { succeeded: true, value: size }\n}\n\n/** Reads a sandbox file as base64 and decodes it, verifying the decoded byte\n * length against `expectedSize` (from a prior {@link statSandboxFileSize}). A\n * mismatch is reported, never returned as a short buffer. */\nexport async function readSandboxBinaryBytes(\n box: SandboxExecChannel,\n absolutePath: string,\n expectedSize: number,\n options?: SandboxExecOptions,\n): Promise<SandboxFileBytesOutcome> {\n const quotedPath = shellQuote(absolutePath)\n let result\n try {\n result = await execInSandbox(box, `base64 ${quotedPath}`, options)\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n if (result.exitCode !== 0) {\n return { succeeded: false, error: result.stderr || 'unknown error' }\n }\n // GNU coreutils wraps base64 output at 76 columns; BusyBox may not wrap at\n // all. Stripping all whitespace makes both shapes decode identically.\n const cleaned = result.stdout.replace(/\\s+/g, '')\n let bytes: Uint8Array\n try {\n bytes = base64ToBytes(cleaned)\n } catch (err) {\n return {\n succeeded: false,\n error: `could not decode file contents: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (bytes.byteLength !== expectedSize) {\n return {\n succeeded: false,\n error: `read returned ${bytes.byteLength} bytes, expected ${expectedSize} — output truncated in transit`,\n }\n }\n return { succeeded: true, value: { bytes, size: expectedSize } }\n}\n"],"mappings":";AAKO,IAAM,+BAAN,cAA2C,MAAM;AAAA,EACtD,YAAY,WAAmB;AAC7B,UAAM,iBAAiB,SAAS,uBAAuB;AACvD,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,8BAA8B,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAEpF,IAAM,yBAAyB;AAE/B,IAAM,4BACJ;AAEF,SAAS,YAAY,KAAyF;AAC5G,QAAM,YAAY,IAAI,UAAU,IAAI,eAClC,IAAI,YAAY,OAAO,IAAI,aAAa,WACnC,IAAI,SAAkC,S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AK;AACZ,WAAO;AAAA,MACL,WAAW;AAAA,MACX,OAAO,mCAAmC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAC5F;AAAA,EACF;AACA,MAAI,MAAM,eAAe,cAAc;AACrC,WAAO;AAAA,MACL,WAAW;AAAA,MACX,OAAO,iBAAiB,MAAM,UAAU,oBAAoB,YAAY;AAAA,IAC1E;AAAA,EACF;AACA,SAAO,EAAE,WAAW,MAAM,OAAO,EAAE,OAAO,MAAM,aAAa,EAAE;AACjE;","names":["retryAfterMs","res"]}
@@ -0,0 +1,238 @@
1
+ // src/app-oauth/index.ts
2
+ import { oauthProvider } from "@better-auth/oauth-provider";
3
+ import { oauthProviderResourceClient } from "@better-auth/oauth-provider/resource-client";
4
+ import { APIError } from "better-auth/api";
5
+ import { verifyJwsAccessToken } from "better-auth/oauth2";
6
+ var ASYMMETRIC_ALGORITHMS = ["EdDSA", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512", "RS256", "RS384", "RS512"];
7
+ var OPERATIONAL_ERROR = /* @__PURE__ */ Symbol("appOAuthOperational");
8
+ var RESERVED_CONSENT_CLAIMS = /* @__PURE__ */ new Set([
9
+ "iss",
10
+ "sub",
11
+ "aud",
12
+ "exp",
13
+ "iat",
14
+ "jti",
15
+ "client_id",
16
+ "scope",
17
+ "auth_time",
18
+ "acr",
19
+ "amr",
20
+ "cnf",
21
+ "sid",
22
+ "nbf",
23
+ "azp"
24
+ ]);
25
+ var STANDARD_SCOPES = ["openid", "profile", "email", "offline_access"];
26
+ function list(value) {
27
+ if (Array.isArray(value)) return value.every((item) => typeof item === "string") ? [...value] : null;
28
+ if (typeof value !== "string") return null;
29
+ try {
30
+ const parsed = JSON.parse(value);
31
+ return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+ function validate(config) {
37
+ const issuer = new URL(config.issuer);
38
+ const resource = new URL(config.resource);
39
+ if (!config.issuer || !config.resource || !/^[a-z][a-z0-9_]*$/.test(config.consentClaim) || RESERVED_CONSENT_CLAIMS.has(config.consentClaim) || !config.scopes.length || !config.scopes.includes(config.defaultClientScope) || issuer.hash || issuer.search || resource.hash || resource.search || issuer.username || issuer.password || resource.username || resource.password || !["https:", "http:"].includes(issuer.protocol) || !["https:", "http:"].includes(resource.protocol) || issuer.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(issuer.hostname) || resource.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(resource.hostname)) {
40
+ throw new Error("app-oauth: invalid issuer, resource, scopes or consent claim");
41
+ }
42
+ }
43
+ function consentFromRows(config, rows, scopes) {
44
+ if (!Array.isArray(rows)) return null;
45
+ if (rows.length !== 1) return null;
46
+ const consent = rows[0];
47
+ if (!consent?.id) return null;
48
+ const resources = list(consent.resources);
49
+ const granted = list(consent.scopes);
50
+ if (!resources?.includes(config.resource) || !granted) return null;
51
+ return scopes.every((scope) => granted.includes(scope)) ? consent : null;
52
+ }
53
+ async function activeAppOAuthConsent(config, clientId, userId, scopes) {
54
+ return consentFromRows(config, await config.authority.findConsents(clientId, userId), scopes);
55
+ }
56
+ function invalidGrant(description) {
57
+ throw new APIError("BAD_REQUEST", { error: "invalid_grant", error_description: description });
58
+ }
59
+ function createAppOAuthProvider(config) {
60
+ validate(config);
61
+ return oauthProvider({
62
+ loginPage: config.loginPage,
63
+ consentPage: config.consentPage,
64
+ accessTokenExpiresIn: 900,
65
+ refreshTokenExpiresIn: 604800,
66
+ codeExpiresIn: 600,
67
+ grantTypes: ["authorization_code", "refresh_token"],
68
+ dpop: { signingAlgorithms: [] },
69
+ scopes: [...STANDARD_SCOPES, ...config.scopes],
70
+ defaultScope: "openid profile email",
71
+ allowPublicClientPrelogin: true,
72
+ allowDynamicClientRegistration: true,
73
+ allowUnauthenticatedClientRegistration: true,
74
+ clientRegistrationDefaultScopes: [config.defaultClientScope],
75
+ clientRegistrationAllowedScopes: [...STANDARD_SCOPES, ...config.scopes],
76
+ clientRegistrationDefaultResources: [config.resource],
77
+ clientRegistrationAllowedResources: [config.resource],
78
+ resources: [{ identifier: config.resource, accessTokenTtl: 900, allowedScopes: [...config.scopes] }],
79
+ resourceSeedMode: "insertOnly",
80
+ enforcePerClientResources: true,
81
+ extensions: [{ claims: { accessToken: async ({ user, client, scopes, resources, grantType, referenceId }) => {
82
+ if (!user?.id || !resources?.includes(config.resource)) invalidGrant("Resource consent is required");
83
+ const consent = await activeAppOAuthConsent(config, client.clientId, user.id, scopes);
84
+ if (!consent || grantType === "refresh_token" && referenceId !== consent.id) {
85
+ invalidGrant("Resource consent changed");
86
+ }
87
+ return { [config.consentClaim]: consent.id };
88
+ } } }],
89
+ customTokenResponseFields: async ({ grantType, user }) => {
90
+ if (grantType === "client_credentials" || !user?.id) invalidGrant("Human identity is required");
91
+ if (!await config.humanUserEligible(user.id)) invalidGrant("Verified identity is required");
92
+ return {};
93
+ }
94
+ });
95
+ }
96
+ async function refreshHash(token) {
97
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)));
98
+ return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
99
+ }
100
+ function issuedClaims(token) {
101
+ const payload = token.split(".")[1];
102
+ if (!payload) return null;
103
+ try {
104
+ const decoded = JSON.parse(atob(payload.replaceAll("-", "+").replaceAll("_", "/")));
105
+ return decoded && typeof decoded === "object" && !Array.isArray(decoded) ? decoded : null;
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+ function rejectedTokenResponse() {
111
+ return Response.json({ error: "invalid_grant" }, { status: 400, headers: { "cache-control": "no-store" } });
112
+ }
113
+ async function appOAuthTokenResponse(request, config) {
114
+ validate(config);
115
+ let grantType = null;
116
+ try {
117
+ grantType = String((await request.clone().formData()).get("grant_type") ?? "");
118
+ } catch {
119
+ }
120
+ const response = await config.handler(request);
121
+ if (!response.ok) return response;
122
+ if (grantType !== "authorization_code" && grantType !== "refresh_token") return rejectedTokenResponse();
123
+ const issued = await response.clone().json();
124
+ const claims = typeof issued.access_token === "string" ? issuedClaims(issued.access_token) : null;
125
+ if (!claims || typeof claims.sub !== "string" || typeof claims.client_id !== "string" || typeof claims[config.consentClaim] !== "string") return rejectedTokenResponse();
126
+ const scopes = typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
127
+ const consent = await activeAppOAuthConsent(config, claims.client_id, claims.sub, scopes);
128
+ if (!consent || consent.id !== claims[config.consentClaim]) return rejectedTokenResponse();
129
+ if (typeof issued.refresh_token === "string") {
130
+ const row = await config.refreshStore.findByHash(await refreshHash(issued.refresh_token));
131
+ if (!row || row.clientId !== claims.client_id || row.userId !== claims.sub) return rejectedTokenResponse();
132
+ if (grantType === "authorization_code") {
133
+ if (!await config.refreshStore.bindIfUnbound(row.id, consent.id)) return rejectedTokenResponse();
134
+ } else if (row.referenceId !== consent.id) return rejectedTokenResponse();
135
+ }
136
+ return response;
137
+ }
138
+ function createAppOAuthResourceVerifier(config) {
139
+ validate(config);
140
+ const jwksCacheKey = {};
141
+ return async (request) => {
142
+ if (request.headers.has("dpop")) return null;
143
+ const token = /^Bearer ([^\s]+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
144
+ if (!token || /^(sk-|gak_|svc_)/.test(token)) return null;
145
+ let claims;
146
+ try {
147
+ claims = await verifyJwsAccessToken(token, {
148
+ jwksCacheKey,
149
+ jwksFetch: async () => {
150
+ try {
151
+ const jwks = await config.jwksFetch();
152
+ if (!jwks || !Array.isArray(jwks.keys)) throw new Error("Invalid JWKS response");
153
+ return jwks;
154
+ } catch (cause) {
155
+ const error = new Error("App OAuth JWKS unavailable", { cause });
156
+ Object.defineProperty(error, OPERATIONAL_ERROR, { value: true });
157
+ throw error;
158
+ }
159
+ },
160
+ verifyOptions: {
161
+ issuer: config.issuer,
162
+ audience: config.resource,
163
+ algorithms: ASYMMETRIC_ALGORITHMS,
164
+ requiredClaims: ["exp"]
165
+ }
166
+ });
167
+ } catch (error) {
168
+ if (typeof error === "object" && error !== null && error[OPERATIONAL_ERROR]) throw error;
169
+ return null;
170
+ }
171
+ if (!claims || typeof claims.sub !== "string" || !claims.sub || claims.cnf !== void 0 || typeof claims.client_id !== "string" || !claims.client_id || typeof claims.sid !== "string" || !claims.sid) return null;
172
+ const consentId = claims[config.consentClaim];
173
+ if (typeof consentId !== "string" || !consentId) return null;
174
+ const clientId = claims.client_id;
175
+ const userId = claims.sub;
176
+ const tokenScopes = typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
177
+ const authority = config.authority;
178
+ if ("readSnapshot" in authority) {
179
+ const snapshot = await authority.readSnapshot({
180
+ clientId,
181
+ userId,
182
+ sessionId: claims.sid,
183
+ consentId,
184
+ resource: config.resource,
185
+ scopes: tokenScopes,
186
+ claims: { ...claims }
187
+ });
188
+ if (!snapshot?.active || !snapshot.clientActive || !snapshot.resourceActive || !snapshot.clientResourceLinked || !snapshot.sessionActive || !snapshot.userActive || consentFromRows(config, snapshot.consents, tokenScopes)?.id !== consentId) return null;
189
+ } else {
190
+ if (!await authority.clientActive(clientId) || !await authority.resourceActive(config.resource) || !await authority.clientResourceLinked(clientId, config.resource)) return null;
191
+ const consent = await activeAppOAuthConsent({ ...config, authority }, clientId, userId, tokenScopes);
192
+ if (!consent || consent.id !== consentId) return null;
193
+ if (!await authority.sessionActive(claims.sid, userId) || !await authority.userActive(userId)) return null;
194
+ }
195
+ return {
196
+ userId,
197
+ clientId,
198
+ scopes: tokenScopes.filter((scope) => config.scopes.includes(scope)),
199
+ consentId,
200
+ sessionId: claims.sid
201
+ };
202
+ };
203
+ }
204
+ function withoutDpop(metadata) {
205
+ const bearerOnly = { ...metadata };
206
+ delete bearerOnly.dpop_signing_alg_values_supported;
207
+ return bearerOnly;
208
+ }
209
+ async function appOAuthMetadataResponse(request, handler) {
210
+ const response = await handler(request);
211
+ if (!response.ok) return response;
212
+ const metadata = await response.json();
213
+ const headers = new Headers(response.headers);
214
+ headers.delete("content-length");
215
+ return Response.json(withoutDpop(metadata), { status: response.status, headers });
216
+ }
217
+ async function appOAuthProtectedResourceMetadata(config, auth) {
218
+ validate(config);
219
+ const overrides = {
220
+ resource: config.resource,
221
+ authorization_servers: [config.issuer],
222
+ scopes_supported: [...config.scopes, "offline_access"]
223
+ };
224
+ const metadata = auth ? await oauthProviderResourceClient(auth).getActions().getProtectedResourceMetadata(overrides) : await oauthProviderResourceClient().getActions().getProtectedResourceMetadata(overrides, {
225
+ externalScopes: overrides.scopes_supported
226
+ });
227
+ return withoutDpop(metadata);
228
+ }
229
+
230
+ export {
231
+ activeAppOAuthConsent,
232
+ createAppOAuthProvider,
233
+ appOAuthTokenResponse,
234
+ createAppOAuthResourceVerifier,
235
+ appOAuthMetadataResponse,
236
+ appOAuthProtectedResourceMetadata
237
+ };
238
+ //# sourceMappingURL=chunk-DLWO3J7D.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/app-oauth/index.ts"],"sourcesContent":["/** OAuth for an application's MCP resource. The host owns identity, tables and grants. */\nimport { oauthProvider } from '@better-auth/oauth-provider'\nimport { oauthProviderResourceClient } from '@better-auth/oauth-provider/resource-client'\nimport { APIError } from 'better-auth/api'\nimport { verifyJwsAccessToken } from 'better-auth/oauth2'\n\nconst ASYMMETRIC_ALGORITHMS = ['EdDSA', 'ES256', 'ES384', 'ES512', 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512']\nconst OPERATIONAL_ERROR = Symbol('appOAuthOperational')\n// Better Auth 1.7.2 strips these AS-owned access-token claims at issuance.\nconst RESERVED_CONSENT_CLAIMS = new Set(['iss', 'sub', 'aud', 'exp', 'iat', 'jti', 'client_id', 'scope',\n 'auth_time', 'acr', 'amr', 'cnf', 'sid', 'nbf', 'azp'])\nconst STANDARD_SCOPES = ['openid', 'profile', 'email', 'offline_access']\n\nexport interface AppOAuthConsent {\n id: string\n /** JSON string or string array, as returned by the host's persistence adapter. */\n scopes: string | readonly string[] | null\n resources: string | readonly string[] | null\n}\n\n/** The issuer reads current consent before minting a token. A lookup outage must throw. */\nexport interface AppOAuthConsentAuthority {\n findConsents(clientId: string, userId: string): Promise<readonly AppOAuthConsent[]>\n}\n\n/** Each callback reads current host authority. A lookup outage must throw. */\nexport interface AppOAuthAuthority extends AppOAuthConsentAuthority {\n clientActive(clientId: string): Promise<boolean>\n resourceActive(resource: string): Promise<boolean>\n clientResourceLinked(clientId: string, resource: string): Promise<boolean>\n sessionActive(sessionId: string, userId: string): Promise<boolean>\n userActive(userId: string): Promise<boolean>\n}\n\nexport interface AppOAuthAuthoritySnapshotInput {\n clientId: string\n userId: string\n sessionId: string\n consentId: string\n resource: string\n scopes: readonly string[]\n /** Claims from a verified JWS. The host can forward its own grant generation. */\n claims: Readonly<Record<string, unknown>>\n}\n\nexport interface AppOAuthAuthoritySnapshot {\n active: boolean\n clientActive: boolean\n resourceActive: boolean\n clientResourceLinked: boolean\n consents: readonly AppOAuthConsent[]\n sessionActive: boolean\n userActive: boolean\n}\n\n/** Read one uncached, current authority view after JWS verification. */\nexport interface AppOAuthSnapshotAuthority {\n readSnapshot(input: AppOAuthAuthoritySnapshotInput): Promise<AppOAuthAuthoritySnapshot>\n}\n\nexport interface AppOAuthConfig {\n /** Exact RFC 8707 audience. The host owns the URL and its route. */\n resource: string\n /** Exact issuer, including Better Auth's /api/auth base path. */\n issuer: string\n /** OAuth permissions the application offers for this resource. */\n scopes: readonly string[]\n /** Scope granted to a dynamically registered client by default. */\n defaultClientScope: string\n /** Claim containing the current consent row ID. */\n consentClaim: string\n}\n\nexport type AppOAuthIssuerConfig = AppOAuthConfig & { authority: AppOAuthConsentAuthority }\nexport type AppOAuthResourceConfig = AppOAuthConfig & {\n authority: AppOAuthAuthority | AppOAuthSnapshotAuthority\n}\n\nexport type AppOAuthJwksFetch = Extract<Parameters<typeof verifyJwsAccessToken>[1]['jwksFetch'], (...args: never[]) => unknown>\n\nfunction list(value: AppOAuthConsent['scopes']): string[] | null {\n if (Array.isArray(value)) return value.every(item => typeof item === 'string') ? [...value] : null\n if (typeof value !== 'string') return null\n try {\n const parsed: unknown = JSON.parse(value)\n return Array.isArray(parsed) && parsed.every(item => typeof item === 'string') ? parsed : null\n } catch { return null }\n}\n\nfunction validate(config: AppOAuthConfig): void {\n const issuer = new URL(config.issuer)\n const resource = new URL(config.resource)\n if (!config.issuer || !config.resource || !/^[a-z][a-z0-9_]*$/.test(config.consentClaim)\n || RESERVED_CONSENT_CLAIMS.has(config.consentClaim)\n || !config.scopes.length\n || !config.scopes.includes(config.defaultClientScope)\n || issuer.hash || issuer.search || resource.hash || resource.search\n || issuer.username || issuer.password || resource.username || resource.password\n || !['https:', 'http:'].includes(issuer.protocol) || !['https:', 'http:'].includes(resource.protocol)\n || (issuer.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(issuer.hostname))\n || (resource.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(resource.hostname))) {\n throw new Error('app-oauth: invalid issuer, resource, scopes or consent claim')\n }\n}\n\n/** Require exactly one current consent; malformed grants cannot widen authority. */\nfunction consentFromRows(config: AppOAuthConfig, rows: readonly AppOAuthConsent[],\n scopes: readonly string[]): AppOAuthConsent | null {\n if (!Array.isArray(rows)) return null\n if (rows.length !== 1) return null\n const consent = rows[0]\n if (!consent?.id) return null\n const resources = list(consent.resources)\n const granted = list(consent.scopes)\n if (!resources?.includes(config.resource) || !granted) return null\n return scopes.every(scope => granted.includes(scope)) ? consent : null\n}\n\nexport async function activeAppOAuthConsent(config: AppOAuthIssuerConfig, clientId: string, userId: string,\n scopes: readonly string[]): Promise<AppOAuthConsent | null> {\n return consentFromRows(config, await config.authority.findConsents(clientId, userId), scopes)\n}\n\nfunction invalidGrant(description: string): never {\n throw new APIError('BAD_REQUEST', { error: 'invalid_grant', error_description: description })\n}\n\n/** Compose the maintained Better Auth provider with one host's live authority. */\nexport function createAppOAuthProvider(config: AppOAuthIssuerConfig & {\n loginPage: string\n consentPage: string\n /** The host must reject deleted, disabled or unverified users at token mint. */\n humanUserEligible(userId: string): Promise<boolean>\n}): ReturnType<typeof oauthProvider> {\n validate(config)\n return oauthProvider({\n loginPage: config.loginPage,\n consentPage: config.consentPage,\n accessTokenExpiresIn: 900,\n refreshTokenExpiresIn: 604800,\n codeExpiresIn: 600,\n grantTypes: ['authorization_code', 'refresh_token'],\n dpop: { signingAlgorithms: [] },\n scopes: [...STANDARD_SCOPES, ...config.scopes],\n defaultScope: 'openid profile email',\n allowPublicClientPrelogin: true,\n allowDynamicClientRegistration: true,\n allowUnauthenticatedClientRegistration: true,\n clientRegistrationDefaultScopes: [config.defaultClientScope],\n clientRegistrationAllowedScopes: [...STANDARD_SCOPES, ...config.scopes],\n clientRegistrationDefaultResources: [config.resource],\n clientRegistrationAllowedResources: [config.resource],\n resources: [{ identifier: config.resource, accessTokenTtl: 900, allowedScopes: [...config.scopes] }],\n resourceSeedMode: 'insertOnly',\n enforcePerClientResources: true,\n extensions: [{ claims: { accessToken: async ({ user, client, scopes, resources, grantType, referenceId }) => {\n if (!user?.id || !resources?.includes(config.resource)) invalidGrant('Resource consent is required')\n const consent = await activeAppOAuthConsent(config, client.clientId, user.id, scopes)\n if (!consent || (grantType === 'refresh_token' && referenceId !== consent.id)) {\n invalidGrant('Resource consent changed')\n }\n return { [config.consentClaim]: consent.id }\n } } }],\n customTokenResponseFields: async ({ grantType, user }) => {\n if (grantType === 'client_credentials' || !user?.id) invalidGrant('Human identity is required')\n if (!await config.humanUserEligible(user.id)) invalidGrant('Verified identity is required')\n return {}\n },\n })\n}\n\nexport interface AppOAuthRefreshToken {\n id: string\n clientId: string\n userId: string\n referenceId: string | null\n}\n\nexport interface AppOAuthRefreshStore {\n findByHash(hash: string): Promise<AppOAuthRefreshToken | null>\n /** Atomically set referenceId only when it is NULL. */\n bindIfUnbound(id: string, consentId: string): Promise<boolean>\n}\n\nasync function refreshHash(token: string): Promise<string> {\n const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)))\n return btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')\n}\n\nfunction issuedClaims(token: string): Record<string, unknown> | null {\n const payload = token.split('.')[1]\n if (!payload) return null\n try {\n const decoded: unknown = JSON.parse(atob(payload.replaceAll('-', '+').replaceAll('_', '/')))\n return decoded && typeof decoded === 'object' && !Array.isArray(decoded)\n ? decoded as Record<string, unknown> : null\n } catch { return null }\n}\n\nfunction rejectedTokenResponse(): Response {\n return Response.json({ error: 'invalid_grant' }, { status: 400, headers: { 'cache-control': 'no-store' } })\n}\n\n/** Bind refresh rows to the current consent before their secret leaves the host. */\nexport async function appOAuthTokenResponse(request: Request, config: AppOAuthIssuerConfig & {\n handler(request: Request): Promise<Response>\n refreshStore: AppOAuthRefreshStore\n}): Promise<Response> {\n validate(config)\n let grantType: string | null = null\n try { grantType = String((await request.clone().formData()).get('grant_type') ?? '') }\n catch { /* The provider owns malformed-request responses. */ }\n const response = await config.handler(request)\n if (!response.ok) return response\n if (grantType !== 'authorization_code' && grantType !== 'refresh_token') return rejectedTokenResponse()\n const issued = await response.clone().json() as { access_token?: unknown; refresh_token?: unknown }\n const claims = typeof issued.access_token === 'string' ? issuedClaims(issued.access_token) : null\n if (!claims || typeof claims.sub !== 'string' || typeof claims.client_id !== 'string'\n || typeof claims[config.consentClaim] !== 'string') return rejectedTokenResponse()\n const scopes = typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : []\n const consent = await activeAppOAuthConsent(config, claims.client_id, claims.sub, scopes)\n if (!consent || consent.id !== claims[config.consentClaim]) return rejectedTokenResponse()\n if (typeof issued.refresh_token === 'string') {\n const row = await config.refreshStore.findByHash(await refreshHash(issued.refresh_token))\n if (!row || row.clientId !== claims.client_id || row.userId !== claims.sub) return rejectedTokenResponse()\n if (grantType === 'authorization_code') {\n if (!await config.refreshStore.bindIfUnbound(row.id, consent.id)) return rejectedTokenResponse()\n } else if (row.referenceId !== consent.id) return rejectedTokenResponse()\n }\n return response\n}\n\nexport interface AppOAuthPrincipal {\n userId: string\n clientId: string\n scopes: readonly string[]\n /** The consent row the token was minted under. */\n consentId: string\n /** The issuer session (`sid`) the token was minted in. */\n sessionId: string\n}\n\n/** Verify bearer tokens and current host grants before any private tool is listed. */\nexport function createAppOAuthResourceVerifier(config: AppOAuthResourceConfig & {\n jwksFetch: AppOAuthJwksFetch\n}) {\n validate(config)\n const jwksCacheKey = {}\n return async (request: Request): Promise<AppOAuthPrincipal | null> => {\n if (request.headers.has('dpop')) return null\n const token = /^Bearer ([^\\s]+)$/i.exec(request.headers.get('authorization') ?? '')?.[1]\n if (!token || /^(sk-|gak_|svc_)/.test(token)) return null\n let claims: Awaited<ReturnType<typeof verifyJwsAccessToken>>\n try {\n claims = await verifyJwsAccessToken(token, {\n jwksCacheKey,\n jwksFetch: async () => {\n try {\n const jwks = await config.jwksFetch()\n if (!jwks || !Array.isArray(jwks.keys)) throw new Error('Invalid JWKS response')\n return jwks\n }\n catch (cause) {\n const error = new Error('App OAuth JWKS unavailable', { cause })\n Object.defineProperty(error, OPERATIONAL_ERROR, { value: true })\n throw error\n }\n },\n verifyOptions: { issuer: config.issuer, audience: config.resource,\n algorithms: ASYMMETRIC_ALGORITHMS, requiredClaims: ['exp'] },\n })\n } catch (error) {\n if (typeof error === 'object' && error !== null && (error as Record<PropertyKey, unknown>)[OPERATIONAL_ERROR]) throw error\n return null\n }\n if (!claims || typeof claims.sub !== 'string' || !claims.sub || claims.cnf !== undefined\n || typeof claims.client_id !== 'string' || !claims.client_id\n || typeof claims.sid !== 'string' || !claims.sid) return null\n const consentId = claims[config.consentClaim]\n if (typeof consentId !== 'string' || !consentId) return null\n const clientId = claims.client_id\n const userId = claims.sub\n const tokenScopes = typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : []\n const authority = config.authority\n if ('readSnapshot' in authority) {\n const snapshot = await authority.readSnapshot({ clientId, userId, sessionId: claims.sid,\n consentId, resource: config.resource, scopes: tokenScopes, claims: { ...claims } })\n if (!snapshot?.active || !snapshot.clientActive || !snapshot.resourceActive\n || !snapshot.clientResourceLinked || !snapshot.sessionActive || !snapshot.userActive\n || consentFromRows(config, snapshot.consents, tokenScopes)?.id !== consentId) return null\n } else {\n if (!await authority.clientActive(clientId)\n || !await authority.resourceActive(config.resource)\n || !await authority.clientResourceLinked(clientId, config.resource)) return null\n const consent = await activeAppOAuthConsent({ ...config, authority }, clientId, userId, tokenScopes)\n if (!consent || consent.id !== consentId) return null\n if (!await authority.sessionActive(claims.sid, userId)\n || !await authority.userActive(userId)) return null\n }\n return { userId, clientId, scopes: tokenScopes.filter(scope => config.scopes.includes(scope)),\n consentId, sessionId: claims.sid }\n }\n}\n\nfunction withoutDpop(metadata: object): Record<string, unknown> {\n const bearerOnly = { ...metadata } as Record<string, unknown>\n delete bearerOnly.dpop_signing_alg_values_supported\n return bearerOnly\n}\n\n/** Strip unsupported DPoP advertisement from Better Auth's issuer metadata. */\nexport async function appOAuthMetadataResponse(request: Request, handler: (request: Request) => Promise<Response>): Promise<Response> {\n const response = await handler(request)\n if (!response.ok) return response\n const metadata = await response.json() as Record<string, unknown>\n const headers = new Headers(response.headers)\n headers.delete('content-length')\n return Response.json(withoutDpop(metadata), { status: response.status, headers })\n}\n\n/** RFC 9728 metadata for an issuer-hosted or separate protected resource. */\nexport async function appOAuthProtectedResourceMetadata(\n config: AppOAuthConfig, auth?: NonNullable<Parameters<typeof oauthProviderResourceClient>[0]>,\n) {\n validate(config)\n const overrides = {\n resource: config.resource,\n authorization_servers: [config.issuer],\n scopes_supported: [...config.scopes, 'offline_access'],\n }\n const metadata = auth\n ? await oauthProviderResourceClient(auth).getActions().getProtectedResourceMetadata(overrides)\n : await oauthProviderResourceClient().getActions().getProtectedResourceMetadata(overrides, {\n externalScopes: overrides.scopes_supported,\n })\n return withoutDpop(metadata)\n}\n"],"mappings":";AACA,SAAS,qBAAqB;AAC9B,SAAS,mCAAmC;AAC5C,SAAS,gB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AA6B,WAAW;AAAA,IACzF,gBAAgB,UAAU;AAAA,EAC5B,CAAC;AACH,SAAO,YAAY,QAAQ;AAC7B;","names":[]}
@@ -1,3 +1,7 @@
1
+ import {
2
+ sha256Hex
3
+ } from "./chunk-HY57QRRW.js";
4
+
1
5
  // src/profile/budget.ts
2
6
  var DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 4e4;
3
7
  function assertBudgetPolicy(budget) {
@@ -52,10 +56,6 @@ function assertProfilePromptWithinBudget(profile, budget = {}, origin = "profile
52
56
  }
53
57
 
54
58
  // src/profile/fingerprint.ts
55
- async function sha256Hex(text) {
56
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
57
- return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
58
- }
59
59
  async function fingerprintAgentProfile(profile, context) {
60
60
  const systemPrompt = profile.prompt?.systemPrompt ?? "";
61
61
  const promptSha = await sha256Hex(systemPrompt);
@@ -126,4 +126,4 @@ export {
126
126
  diffProfileFingerprints,
127
127
  formatProfileDrift
128
128
  };
129
- //# sourceMappingURL=chunk-LWSJK546.js.map
129
+ //# sourceMappingURL=chunk-DSMGS4IV.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/profile/budget.ts","../src/profile/fingerprint.ts"],"sourcesContent":["/**\n * The composed-system-prompt byte budget, split out of `./index` so it imports\n * NOTHING.\n *\n * `./index` pulls `@tangle-network/agent-eval` (the evolvable-section seam), so\n * `/sandbox` — which has no agent-eval import and must not gain one — could not\n * enforce the budget from there. The gate is the same function either way; only\n * its module home moved. `./index` re-exports every symbol below, so the\n * published `/profile` surface is byte-identical.\n *\n * Why the gate belongs at more than one call site: `composeAgentProfile` is\n * OPT-IN. A product may hand-build its `AgentProfile`, and one does —\n * creative-agent's create-time profile is deliberately minimal and its full\n * system prompt rides the PER-TURN backend (`buildPromptBackend`), which never\n * touches the composer. `/sandbox` therefore runs this gate at the three points\n * where the profile that actually executes exists.\n */\n\n/** Byte budget on the FINAL composed `prompt.systemPrompt`. Past this the\n * model degrades sharply (a 122,659-byte prompt shipped once and the model\n * returned empty answers), so the default gate throws well before that. */\nexport const DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 40_000\n\n/** Budget config for the composed system prompt. */\nexport interface ComposeProfileBudget {\n /** Byte cap on the composed `prompt.systemPrompt`.\n * Default {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES}. */\n maxSystemPromptBytes?: number\n /** Downgrade the over-budget throw to a `console.warn` — the escape hatch\n * for a product with a known-big prompt that must still ship (it yells on\n * every compose instead of blocking). */\n warnOnly?: boolean\n /** Required to raise {@link maxSystemPromptBytes} above\n * {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES} or to set {@link warnOnly}: a\n * written reason naming what stays inline and why it cannot be mounted.\n * Weakening the cap is a product decision that outlives the person making\n * it, and the usual cause is reference material concatenated into the prompt\n * that belongs in `resources.files`; demanding the sentence here keeps that\n * from happening by accident. */\n overBudgetReason?: string\n}\n\n/** Reject a budget that weakens the cap without stating why. Runs before the\n * size check so it fires on every compose, not only once a prompt has already\n * grown past the raised ceiling. */\nfunction assertBudgetPolicy(budget: ComposeProfileBudget): void {\n const raisedCap =\n budget.maxSystemPromptBytes !== undefined &&\n budget.maxSystemPromptBytes > DEFAULT_MAX_SYSTEM_PROMPT_BYTES\n if (!raisedCap && !budget.warnOnly) return\n if ((budget.overBudgetReason ?? '').trim() !== '') return\n const weakened = raisedCap\n ? `maxSystemPromptBytes ${budget.maxSystemPromptBytes} exceeds the ${DEFAULT_MAX_SYSTEM_PROMPT_BYTES}-byte default`\n : 'warnOnly downgrades the over-budget throw to a warning'\n throw new Error(\n `${weakened} without an overBudgetReason. Oversized system prompts degrade toward empty answers, so the cap is not a formality. ` +\n 'Before raising it: rank the prompt with largestPromptSections() — reference material (playbooks, checklists, corpora) belongs in resources.files ' +\n \"via corpusSkills()/userSkillMounts() or composeSkills({ mode: 'mounted' }), which puts the bodies on disk in the sandbox and leaves a short index in the prompt. \" +\n 'Only content the agent must obey without a tool call should stay inline. If the prompt is genuinely irreducible, set overBudgetReason to the sentence that says so.',\n )\n}\n\n/** Largest markdown-heading-delimited sections of a prompt, by UTF-8 bytes.\n * Cheap heuristic: split on `#`-heading lines; the preamble before the first\n * heading reports as \"(preamble)\". */\nexport function largestPromptSections(\n prompt: string,\n top = 3,\n): Array<{ title: string; bytes: number }> {\n const encoder = new TextEncoder()\n const sections: Array<{ title: string; bytes: number }> = []\n let title = '(preamble)'\n let start = 0\n const flush = (end: number) => {\n const body = prompt.slice(start, end)\n if (body.trim()) sections.push({ title, bytes: encoder.encode(body).byteLength })\n }\n const headingRe = /^#{1,6}\\s+(.+)$/gm\n for (const match of prompt.matchAll(headingRe)) {\n flush(match.index)\n title = (match[1] ?? '').trim() || '(untitled section)'\n start = match.index\n }\n flush(prompt.length)\n return sections.sort((a, b) => b.bytes - a.bytes).slice(0, top)\n}\n\n/** Enforce {@link ComposeProfileBudget} on a composed system prompt: over\n * budget throws (or warns with `warnOnly`) with the actual size and the\n * top-3 largest sections. Exported so a product assembling its prompt\n * outside `composeAgentProfile` (e.g. via the `/prompt` assembler) can\n * run the same gate at its own final-composition point. */\nexport function assertSystemPromptWithinBudget(\n systemPrompt: string,\n budget: ComposeProfileBudget = {},\n /** Prefixed to the message so a throw from a turn/provision choke point says\n * WHERE it fired — \"composed systemPrompt\" alone reads like a compose-time\n * error even when it fired on `driveSandboxTurn`. */\n origin = 'composed systemPrompt',\n): void {\n assertBudgetPolicy(budget)\n const max = budget.maxSystemPromptBytes ?? DEFAULT_MAX_SYSTEM_PROMPT_BYTES\n const bytes = new TextEncoder().encode(systemPrompt).byteLength\n if (bytes <= max) return\n const sections = largestPromptSections(systemPrompt)\n .map((s) => `\"${s.title}\" (${s.bytes}B)`)\n .join(', ')\n const message =\n `${origin} is ${bytes} bytes — over the ${max}-byte budget ` +\n `(oversized prompts degrade to empty answers). ` +\n (sections ? `Largest sections: ${sections}. ` : '') +\n `Move reference material to resources.files (corpusSkills/userSkillMounts, or composeSkills({ mode: 'mounted' })) so the bodies land on disk in the sandbox ` +\n `and the prompt keeps only an index; keep inline only what the agent must obey without a tool call. Raising maxSystemPromptBytes requires an overBudgetReason.`\n if (budget.warnOnly) {\n console.warn(`[profile] ${message}`)\n return\n }\n throw new Error(message)\n}\n\n/** Run {@link assertSystemPromptWithinBudget} over a profile-shaped object's\n * `prompt.systemPrompt`. Structural on purpose: `/sandbox` calls this on the\n * SDK's `AgentProfile` and on the product-supplied seam result without either\n * module importing the other's types. A profile with no string systemPrompt\n * is a no-op — there is nothing to measure.\n *\n * The `hint` exists because this gate can fire on a product that ALREADY made\n * a deliberate budget decision somewhere else. gtm-agent composes with\n * `{ maxSystemPromptBytes: 50_000 }`; without the hint, the shell's 40 KB\n * default reads as the gate contradicting a choice the product already made\n * rather than as \"declare the same number here too\". */\nexport function assertProfilePromptWithinBudget(\n profile: { prompt?: { systemPrompt?: unknown } } | undefined,\n budget: ComposeProfileBudget = {},\n origin = 'profile systemPrompt',\n hint = '',\n): void {\n const systemPrompt = profile?.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string') return\n try {\n assertSystemPromptWithinBudget(systemPrompt, budget, origin)\n } catch (err) {\n if (!hint) throw err\n throw new Error(`${(err as Error).message} ${hint}`, { cause: err })\n }\n}\n","/**\n * Profile fingerprinting — prove WHICH profile a turn actually executed.\n *\n * The backtest invariant this exists to enforce: an eval's score is only worth\n * publishing if the benchmarked profile IS the shipped profile. The failure\n * mode is structural, not hypothetical — a product's eval composed the\n * production profile in one module, executed a hand-rolled stub in another,\n * and stamped the composed profile's identity onto the stub's scorecard.\n * Nothing compared the two, so nothing could notice.\n *\n * A `ProfileFingerprint` is a channelled identity of the profile handed to the\n * sandbox SDK: the system-prompt digest plus the names of every capability\n * surface (MCP servers, subagents, file mounts, hub connections) and the\n * model/harness the turn dispatched at. It is deliberately NOT a byte-exhaustive\n * serialization — channels are what drift in practice, and a channelled diff\n * names the surface that moved instead of reporting \"bytes differ\".\n *\n * The write half of the seam is `StreamSandboxPromptOptions.onProfileResolved`\n * (`/sandbox`): the one place the final profile exists is inside\n * `streamSandboxPrompt` after the system-prompt override, the MCP merge, and\n * reasoning-effort attachment, so that is where the fingerprint is taken. A\n * caller re-deriving a profile to fingerprint it would reintroduce the exact\n * gap this closes.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\n\n/** The dispatch context a profile cannot see but a turn's identity includes. */\nexport interface ProfileFingerprintContext {\n model?: string\n harness?: string\n}\n\n/** Channelled identity of one executed (or composed) profile. */\nexport interface ProfileFingerprint {\n /** sha256 over every channel below — one value to log/compare. */\n hash: string\n /** sha256 of `prompt.systemPrompt` ('' when absent). */\n promptSha: string\n /** UTF-8 byte length of `prompt.systemPrompt`. */\n promptBytes: number\n /** Sorted MCP server keys. */\n mcpKeys: string[]\n /** Sorted subagent names. */\n subagentNames: string[]\n /** Sorted `resources.files[].path` mounts. */\n fileMountPaths: string[]\n /** Sorted hub connection ids (alias-qualified when present). */\n connectionIds: string[]\n model?: string\n harness?: string\n}\n\nasync function sha256Hex(text: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/** Fingerprint a profile as the SDK would receive it. */\nexport async function fingerprintAgentProfile(\n profile: AgentProfile,\n context?: ProfileFingerprintContext,\n): Promise<ProfileFingerprint> {\n const systemPrompt = profile.prompt?.systemPrompt ?? ''\n const promptSha = await sha256Hex(systemPrompt)\n const mcpKeys = Object.keys(profile.mcp ?? {}).sort()\n const subagentNames = Object.keys(profile.subagents ?? {}).sort()\n const fileMountPaths = (profile.resources?.files ?? []).map((mount) => mount.path).sort()\n const connectionIds = (profile.connections ?? [])\n .map((connection) => (connection.alias ? `${connection.connectionId}:${connection.alias}` : connection.connectionId))\n .sort()\n const hash = await sha256Hex(\n JSON.stringify([\n promptSha,\n mcpKeys,\n subagentNames,\n fileMountPaths,\n connectionIds,\n context?.model ?? null,\n context?.harness ?? null,\n ]),\n )\n return {\n hash,\n promptSha,\n promptBytes: new TextEncoder().encode(systemPrompt).length,\n mcpKeys,\n subagentNames,\n fileMountPaths,\n connectionIds,\n model: context?.model,\n harness: context?.harness,\n }\n}\n\n/** One drifted channel between two fingerprints, rendered as comparable strings. */\nexport interface ProfileDriftEntry {\n channel: 'promptSha' | 'promptBytes' | 'mcpKeys' | 'subagentNames' | 'fileMountPaths' | 'connectionIds' | 'model' | 'harness'\n a: string\n b: string\n}\n\nexport interface ProfileDrift {\n equal: boolean\n drift: ProfileDriftEntry[]\n}\n\nfunction channelValue(fingerprint: ProfileFingerprint, channel: ProfileDriftEntry['channel']): string {\n const value = fingerprint[channel]\n if (Array.isArray(value)) return value.length === 0 ? '(none)' : value.join(',')\n return String(value ?? '(unset)')\n}\n\nconst DRIFT_CHANNELS: ProfileDriftEntry['channel'][] = [\n 'promptSha',\n 'promptBytes',\n 'mcpKeys',\n 'subagentNames',\n 'fileMountPaths',\n 'connectionIds',\n 'model',\n 'harness',\n]\n\n/** Channel-by-channel comparison of two fingerprints. */\nexport function diffProfileFingerprints(a: ProfileFingerprint, b: ProfileFingerprint): ProfileDrift {\n const drift: ProfileDriftEntry[] = []\n for (const channel of DRIFT_CHANNELS) {\n const left = channelValue(a, channel)\n const right = channelValue(b, channel)\n if (left !== right) drift.push({ channel, a: left, b: right })\n }\n return { equal: drift.length === 0, drift }\n}\n\n/** Human-readable drift report; exactly 'profiles identical' when equal. */\nexport function formatProfileDrift(drift: ProfileDrift): string {\n if (drift.equal) return 'profiles identical'\n const lines = drift.drift.map((entry) => ` ${entry.channel}: ${entry.a} != ${entry.b}`)\n return `profile drift on ${drift.drift.length} channel(s):\\n${lines.join('\\n')}`\n}\n"],"mappings":";AAqBO,IAAM,kCAAkC;AAwB/C,SAAS,mBAAmB,QAAoC;AAC9D,QAAM,YACJ,OAAO,yBAAyB,UAChC,OAAO,uB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int.ts"],"sourcesContent":["/**\n * The composed-system-prompt byte budget, split out of `./index` so it imports\n * NOTHING.\n *\n * `./index` pulls `@tangle-network/agent-eval` (the evolvable-section seam), so\n * `/sandbox` — which has no agent-eval import and must not gain one — could not\n * enforce the budget from there. The gate is the same function either way; only\n * its module home moved. `./index` re-exports every symbol below, so the\n * published `/profile` surface is byte-identical.\n *\n * Why the gate belongs at more than one call site: `composeAgentProfile` is\n * OPT-IN. A product may hand-build its `AgentProfile`, and one does —\n * creative-agent's create-time profile is deliberately minimal and its full\n * system prompt rides the PER-TURN backend (`buildPromptBackend`), which never\n * touches the composer. `/sandbox` therefore runs this gate at the three points\n * where the profile that actually executes exists.\n */\n\n/** Byte budget on the FINAL composed `prompt.systemPrompt`. Past this the\n * model degrades sharply (a 122,659-byte prompt shipped once and the model\n * returned empty answers), so the default gate throws well before that. */\nexport const DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 40_000\n\n/** Budget config for the composed system prompt. */\nexport interface ComposeProfileBudget {\n /** Byte cap on the composed `prompt.systemPrompt`.\n * Default {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES}. */\n maxSystemPromptBytes?: number\n /** Downgrade the over-budget throw to a `console.warn` — the escape hatch\n * for a product with a known-big prompt that must still ship (it yells on\n * every compose instead of blocking). */\n warnOnly?: boolean\n /** Required to raise {@link maxSystemPromptBytes} above\n * {@link DEFAULT_MAX_SYSTEM_PROMPT_BYTES} or to set {@link warnOnly}: a\n * written reason naming what stays inline and why it cannot be mounted.\n * Weakening the cap is a product decision that outlives the person making\n * it, and the usual cause is reference material concatenated into the prompt\n * that belongs in `resources.files`; demanding the sentence here keeps that\n * from happening by accident. */\n overBudgetReason?: string\n}\n\n/** Reject a budget that weakens the cap without stating why. Runs before the\n * size check so it fires on every compose, not only once a prompt has already\n * grown past the raised ceiling. */\nfunction assertBudgetPolicy(budget: ComposeProfileBudget): void {\n const raisedCap =\n budget.maxSystemPromptBytes !== undefined &&\n budget.maxSystemPromptBytes > DEFAULT_MAX_SYSTEM_PROMPT_BYTES\n if (!raisedCap && !budget.warnOnly) return\n if ((budget.overBudgetReason ?? '').trim() !== '') return\n const weakened = raisedCap\n ? `maxSystemPromptBytes ${budget.maxSystemPromptBytes} exceeds the ${DEFAULT_MAX_SYSTEM_PROMPT_BYTES}-byte default`\n : 'warnOnly downgrades the over-budget throw to a warning'\n throw new Error(\n `${weakened} without an overBudgetReason. Oversized system prompts degrade toward empty answers, so the cap is not a formality. ` +\n 'Before raising it: rank the prompt with largestPromptSections() — reference material (playbooks, checklists, corpora) belongs in resources.files ' +\n \"via corpusSkills()/userSkillMounts() or composeSkills({ mode: 'mounted' }), which puts the bodies on disk in the sandbox and leaves a short index in the prompt. \" +\n 'Only content the agent must obey without a tool call should stay inline. If the prompt is genuinely irreducible, set overBudgetReason to the sentence that says so.',\n )\n}\n\n/** Largest markdown-heading-delimited sections of a prompt, by UTF-8 bytes.\n * Cheap heuristic: split on `#`-heading lines; the preamble before the first\n * heading reports as \"(preamble)\". */\nexport function largestPromptSections(\n prompt: string,\n top = 3,\n): Array<{ title: string; bytes: number }> {\n const encoder = new TextEncoder()\n const sections: Array<{ title: string; bytes: number }> = []\n let title = '(preamble)'\n let start = 0\n const flush = (end: number) => {\n const body = prompt.slice(start, end)\n if (body.trim()) sections.push({ title, bytes: encoder.encode(body).byteLength })\n }\n const headingRe = /^#{1,6}\\s+(.+)$/gm\n for (const match of prompt.matchAll(headingRe)) {\n flush(match.index)\n title = (match[1] ?? '').trim() || '(untitled section)'\n start = match.index\n }\n flush(prompt.length)\n return sections.sort((a, b) => b.bytes - a.bytes).slice(0, top)\n}\n\n/** Enforce {@link ComposeProfileBudget} on a composed system prompt: over\n * budget throws (or warns with `warnOnly`) with the actual size and the\n * top-3 largest sections. Exported so a product assembling its prompt\n * outside `composeAgentProfile` (e.g. via the `/prompt` assembler) can\n * run the same gate at its own final-composition point. */\nexport function assertSystemPromptWithinBudget(\n systemPrompt: string,\n budget: ComposeProfileBudget = {},\n /** Prefixed to the message so a throw from a turn/provision choke point says\n * WHERE it fired — \"composed systemPrompt\" alone reads like a compose-time\n * error even when it fired on `driveSandboxTurn`. */\n origin = 'composed systemPrompt',\n): void {\n assertBudgetPolicy(budget)\n const max = budget.maxSystemPromptBytes ?? DEFAULT_MAX_SYSTEM_PROMPT_BYTES\n const bytes = new TextEncoder().encode(systemPrompt).byteLength\n if (bytes <= max) return\n const sections = largestPromptSections(systemPrompt)\n .map((s) => `\"${s.title}\" (${s.bytes}B)`)\n .join(', ')\n const message =\n `${origin} is ${bytes} bytes — over the ${max}-byte budget ` +\n `(oversized prompts degrade to empty answers). ` +\n (sections ? `Largest sections: ${sections}. ` : '') +\n `Move reference material to resources.files (corpusSkills/userSkillMounts, or composeSkills({ mode: 'mounted' })) so the bodies land on disk in the sandbox ` +\n `and the prompt keeps only an index; keep inline only what the agent must obey without a tool call. Raising maxSystemPromptBytes requires an overBudgetReason.`\n if (budget.warnOnly) {\n console.warn(`[profile] ${message}`)\n return\n }\n throw new Error(message)\n}\n\n/** Run {@link assertSystemPromptWithinBudget} over a profile-shaped object's\n * `prompt.systemPrompt`. Structural on purpose: `/sandbox` calls this on the\n * SDK's `AgentProfile` and on the product-supplied seam result without either\n * module importing the other's types. A profile with no string systemPrompt\n * is a no-op — there is nothing to measure.\n *\n * The `hint` exists because this gate can fire on a product that ALREADY made\n * a deliberate budget decision somewhere else. gtm-agent composes with\n * `{ maxSystemPromptBytes: 50_000 }`; without the hint, the shell's 40 KB\n * default reads as the gate contradicting a choice the product already made\n * rather than as \"declare the same number here too\". */\nexport function assertProfilePromptWithinBudget(\n profile: { prompt?: { systemPrompt?: unknown } } | undefined,\n budget: ComposeProfileBudget = {},\n origin = 'profile systemPrompt',\n hint = '',\n): void {\n const systemPrompt = profile?.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string') return\n try {\n assertSystemPromptWithinBudget(systemPrompt, budget, origin)\n } catch (err) {\n if (!hint) throw err\n throw new Error(`${(err as Error).message} ${hint}`, { cause: err })\n }\n}\n","/**\n * Profile fingerprinting — prove WHICH profile a turn actually executed.\n *\n * The backtest invariant this exists to enforce: an eval's score is only worth\n * publishing if the benchmarked profile IS the shipped profile. The failure\n * mode is structural, not hypothetical — a product's eval composed the\n * production profile in one module, executed a hand-rolled stub in another,\n * and stamped the composed profile's identity onto the stub's scorecard.\n * Nothing compared the two, so nothing could notice.\n *\n * A `ProfileFingerprint` is a channelled identity of the profile handed to the\n * sandbox SDK: the system-prompt digest plus the names of every capability\n * surface (MCP servers, subagents, file mounts, hub connections) and the\n * model/harness the turn dispatched at. It is deliberately NOT a byte-exhaustive\n * serialization — channels are what drift in practice, and a channelled diff\n * names the surface that moved instead of reporting \"bytes differ\".\n *\n * The write half of the seam is `StreamSandboxPromptOptions.onProfileResolved`\n * (`/sandbox`): the one place the final profile exists is inside\n * `streamSandboxPrompt` after the system-prompt override, the MCP merge, and\n * reasoning-effort attachment, so that is where the fingerprint is taken. A\n * caller re-deriving a profile to fingerprint it would reintroduce the exact\n * gap this closes.\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { sha256Hex } from '../crypto/digest'\n\n/** The dispatch context a profile cannot see but a turn's identity includes. */\nexport interface ProfileFingerprintContext {\n model?: string\n harness?: string\n}\n\n/** Channelled identity of one executed (or composed) profile. */\nexport interface ProfileFingerprint {\n /** sha256 over every channel below — one value to log/compare. */\n hash: string\n /** sha256 of `prompt.systemPrompt` ('' when absent). */\n promptSha: string\n /** UTF-8 byte length of `prompt.systemPrompt`. */\n promptBytes: number\n /** Sorted MCP server keys. */\n mcpKeys: string[]\n /** Sorted subagent names. */\n subagentNames: string[]\n /** Sorted `resources.files[].path` mounts. */\n fileMountPaths: string[]\n /** Sorted hub connection ids (alias-qualified when present). */\n connectionIds: string[]\n model?: string\n harness?: string\n}\n\n/** Fingerprint a profile as the SDK would receive it. */\nexport async function fingerprintAgentProfile(\n profile: AgentProfile,\n context?: ProfileFingerprintContext,\n): Promise<ProfileFingerprint> {\n const systemPrompt = profile.prompt?.systemPrompt ?? ''\n const promptSha = await sha256Hex(systemPrompt)\n const mcpKeys = Object.keys(profile.mcp ?? {}).sort()\n const subagentNames = Object.keys(profile.subagents ?? {}).sort()\n const fileMountPaths = (profile.resources?.files ?? []).map((mount) => mount.path).sort()\n const connectionIds = (profile.connections ?? [])\n .map((connection) => (connection.alias ? `${connection.connectionId}:${connection.alias}` : connection.connectionId))\n .sort()\n const hash = await sha256Hex(\n JSON.stringify([\n promptSha,\n mcpKeys,\n subagentNames,\n fileMountPaths,\n connectionIds,\n context?.model ?? null,\n context?.harness ?? null,\n ]),\n )\n return {\n hash,\n promptSha,\n promptBytes: new TextEncoder().encode(systemPrompt).length,\n mcpKeys,\n subagentNames,\n fileMountPaths,\n connectionIds,\n model: context?.model,\n harness: context?.harness,\n }\n}\n\n/** One drifted channel between two fingerprints, rendered as comparable strings. */\nexport interface ProfileDriftEntry {\n channel: 'promptSha' | 'promptBytes' | 'mcpKeys' | 'subagentNames' | 'fileMountPaths' | 'connectionIds' | 'model' | 'harness'\n a: string\n b: string\n}\n\nexport interface ProfileDrift {\n equal: boolean\n drift: ProfileDriftEntry[]\n}\n\nfunction channelValue(fingerprint: ProfileFingerprint, channel: ProfileDriftEntry['channel']): string {\n const value = fingerprint[channel]\n if (Array.isArray(value)) return value.length === 0 ? '(none)' : value.join(',')\n return String(value ?? '(unset)')\n}\n\nconst DRIFT_CHANNELS: ProfileDriftEntry['channel'][] = [\n 'promptSha',\n 'promptBytes',\n 'mcpKeys',\n 'subagentNames',\n 'fileMountPaths',\n 'connectionIds',\n 'model',\n 'harness',\n]\n\n/** Channel-by-channel comparison of two fingerprints. */\nexport function diffProfileFingerprints(a: ProfileFingerprint, b: ProfileFingerprint): ProfileDrift {\n const drift: ProfileDriftEntry[] = []\n for (const channel of DRIFT_CHANNELS) {\n const left = channelValue(a, channel)\n const right = channelValue(b, channel)\n if (left !== right) drift.push({ channel, a: left, b: right })\n }\n return { equal: drift.length === 0, drift }\n}\n\n/** Human-readable drift report; exactly 'profiles identical' when equal. */\nexport function formatProfileDrift(drift: ProfileDrift): string {\n if (drift.equal) return 'profiles identical'\n const lines = drift.drift.map((entry) => ` ${entry.channel}: ${entry.a} != ${entry.b}`)\n return `profile drift on ${drift.drift.length} channel(s):\\n${lines.join('\\n')}`\n}\n"],"mappings":";;;;;AAqBO,IAAM,kCAAkC;AAwB/C,SAAS,mBAAmB,QAAoC;AAC9D,QAAM,YACJ,OAAO,yBAAyB,UAChC,OAAO,uBAAuB;AAChC,MAAI,CAAC,aAAa,CAAC,OAAO,SAAU;AACpC,OAAK,OAAO,oBAAoB,IAAI,KAAK,MAAM,GAAI;AACnD,QAAM,WAAW,YACb,wBAAwB,OAAO,oBAAoB,gBAAgB,+BAA+B,kBAClG;AACJ,QAAM,IAAI;AAAA,IACR,GAAG,QAAQ;AAAA,EAIb;AACF;AAKO,SAAS,sBACd,QACA,MAAM,GACmC;AACzC,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,WAAoD,CAAC;AAC3D,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,QAAM,QAAQ,CAAC,QAAgB;AAC7B,UAAM,OAAO,OAAO,MAAM,OAAO,GAAG;AACpC,QAAI,KAAK,KAAK,EAAG,UAAS,KAAK,EAAE,OAAO,OAAO,QAAQ,OAAO,IAAI,EAAE,WAAW,CAAC;AAAA,EAClF;AACA,QAAM,YAAY;AAClB,aAAW,SAAS,OAAO,SAAS,SAAS,GAAG;AAC9C,UAAM,MAAM,KAAK;AACjB,aAAS,MAAM,CAAC,KAAK,IAAI,KAAK,KAAK;AACnC,YAAQ,MAAM;AAAA,EAChB;AACA,QAAM,OAAO,MAAM;AACnB,SAAO,SAAS,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG;AAChE;AAOO,SAAS,+BACd,cACA,SAA+B,CAAC,GAIhC,SAAS,yBACH;AACN,qBAAmB,MAAM;AACzB,Q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AAI,CAAC;AAChF;","names":[]}
@@ -1,27 +1,13 @@
1
1
  import {
2
2
  createInteractionAnswerRoute
3
- } from "./chunk-TCGZFSN5.js";
3
+ } from "./chunk-KH4QSBNI.js";
4
4
  import {
5
5
  parseJsonObjectBody
6
- } from "./chunk-7HZCFG2A.js";
7
- import {
8
- normalizeClientTurnId,
9
- resolveChatTurn
10
- } from "./chunk-YG66IHDU.js";
11
- import {
12
- coalesceDeltas,
13
- createBufferedTurnTap,
14
- replayTurnEvents,
15
- stampReplaySeq
16
- } from "./chunk-ISP6ZH3G.js";
17
- import {
18
- currentD1QueryCounter,
19
- withD1QueryCount
20
- } from "./chunk-MM6RLOXF.js";
6
+ } from "./chunk-WP2GYFZ4.js";
21
7
  import {
22
8
  mentionInputToPart,
23
9
  toChatMessageParts
24
- } from "./chunk-23JUSUUB.js";
10
+ } from "./chunk-RZLCBWGG.js";
25
11
  import {
26
12
  ChatTurnInputError,
27
13
  TURN_INTENT_EVENT,
@@ -35,6 +21,20 @@ import {
35
21
  parseFileMentions,
36
22
  turnResponseEventFor
37
23
  } from "./chunk-5TSRFF5W.js";
24
+ import {
25
+ normalizeClientTurnId,
26
+ resolveChatTurn
27
+ } from "./chunk-YG66IHDU.js";
28
+ import {
29
+ coalesceDeltas,
30
+ createBufferedTurnTap,
31
+ replayTurnEvents,
32
+ stampReplaySeq
33
+ } from "./chunk-ISP6ZH3G.js";
34
+ import {
35
+ currentD1QueryCounter,
36
+ withD1QueryCount
37
+ } from "./chunk-MM6RLOXF.js";
38
38
  import {
39
39
  checkModelPolicy
40
40
  } from "./chunk-XELWWXJJ.js";
@@ -1634,4 +1634,4 @@ export {
1634
1634
  createChatTurnRoutes,
1635
1635
  streamChatRouteAsSandboxEvents
1636
1636
  };
1637
- //# sourceMappingURL=chunk-A3KPDLSF.js.map
1637
+ //# sourceMappingURL=chunk-EFPIHR6F.js.map