@dudko.dev/agent-web-ui 0.0.2 → 0.0.3

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 (184) hide show
  1. package/README.md +28 -2
  2. package/dist/canvas.cjs +0 -1
  3. package/dist/canvas.js +1 -2
  4. package/dist/{chunk-EL2YCROY.js → chunk-D64VLIRY.js} +0 -1
  5. package/dist/{chunk-ZBHESK6V.js → chunk-G7LQTOA2.js} +0 -1
  6. package/dist/{chunk-SVYHDLAZ.js → chunk-S5AHUAFG.js} +0 -1
  7. package/dist/{chunk-7O64ZI6Z.js → chunk-TJBGZM6D.js} +0 -1
  8. package/dist/{chunk-WFM6B7CL.js → chunk-UNIXGP4N.js} +0 -1
  9. package/dist/{chunk-VCR7LU7J.js → chunk-V33T6VX3.js} +0 -1
  10. package/dist/{chunk-WZ7K7JIP.js → chunk-VZCQXE3P.js} +0 -1
  11. package/dist/{chunk-GB7RZJMG.js → chunk-WEYQMUKY.js} +0 -1
  12. package/dist/{chunk-KZQB35LS.js → chunk-Y6QYUFSC.js} +0 -1
  13. package/dist/controller.cjs +0 -1
  14. package/dist/controller.js +1 -2
  15. package/dist/index.cjs +0 -1
  16. package/dist/index.js +3 -4
  17. package/dist/locales/be.cjs +0 -1
  18. package/dist/locales/be.js +1 -2
  19. package/dist/locales/bg.cjs +0 -1
  20. package/dist/locales/bg.js +1 -2
  21. package/dist/locales/ca.cjs +0 -1
  22. package/dist/locales/ca.js +1 -2
  23. package/dist/locales/cs.cjs +0 -1
  24. package/dist/locales/cs.js +1 -2
  25. package/dist/locales/da.cjs +0 -1
  26. package/dist/locales/da.js +1 -2
  27. package/dist/locales/de.cjs +0 -1
  28. package/dist/locales/de.js +1 -2
  29. package/dist/locales/el.cjs +0 -1
  30. package/dist/locales/el.js +1 -2
  31. package/dist/locales/en.cjs +0 -1
  32. package/dist/locales/en.js +1 -2
  33. package/dist/locales/es-419.cjs +0 -1
  34. package/dist/locales/es-419.js +2 -3
  35. package/dist/locales/es.cjs +0 -1
  36. package/dist/locales/es.js +2 -3
  37. package/dist/locales/fi.cjs +0 -1
  38. package/dist/locales/fi.js +1 -2
  39. package/dist/locales/fr-CA.cjs +0 -1
  40. package/dist/locales/fr-CA.js +2 -3
  41. package/dist/locales/fr.cjs +0 -1
  42. package/dist/locales/fr.js +2 -3
  43. package/dist/locales/gn.cjs +0 -1
  44. package/dist/locales/gn.js +1 -2
  45. package/dist/locales/hr.cjs +0 -1
  46. package/dist/locales/hr.js +1 -2
  47. package/dist/locales/ht.cjs +0 -1
  48. package/dist/locales/ht.js +1 -2
  49. package/dist/locales/hu.cjs +0 -1
  50. package/dist/locales/hu.js +1 -2
  51. package/dist/locales/index.cjs +0 -1
  52. package/dist/locales/index.js +1 -2
  53. package/dist/locales/it.cjs +0 -1
  54. package/dist/locales/it.js +1 -2
  55. package/dist/locales/nb.cjs +0 -1
  56. package/dist/locales/nb.js +1 -2
  57. package/dist/locales/nl.cjs +0 -1
  58. package/dist/locales/nl.js +1 -2
  59. package/dist/locales/pl.cjs +0 -1
  60. package/dist/locales/pl.js +1 -2
  61. package/dist/locales/pt-BR.cjs +0 -1
  62. package/dist/locales/pt-BR.js +1 -2
  63. package/dist/locales/pt.cjs +0 -1
  64. package/dist/locales/pt.js +1 -2
  65. package/dist/locales/qu.cjs +0 -1
  66. package/dist/locales/qu.js +1 -2
  67. package/dist/locales/ro.cjs +0 -1
  68. package/dist/locales/ro.js +1 -2
  69. package/dist/locales/ru.cjs +0 -1
  70. package/dist/locales/ru.js +1 -2
  71. package/dist/locales/sk.cjs +0 -1
  72. package/dist/locales/sk.js +1 -2
  73. package/dist/locales/sq.cjs +0 -1
  74. package/dist/locales/sq.js +1 -2
  75. package/dist/locales/sr-Latn.cjs +0 -1
  76. package/dist/locales/sr-Latn.js +2 -3
  77. package/dist/locales/sr.cjs +0 -1
  78. package/dist/locales/sr.js +2 -3
  79. package/dist/locales/sv.cjs +0 -1
  80. package/dist/locales/sv.js +1 -2
  81. package/dist/locales/tr.cjs +0 -1
  82. package/dist/locales/tr.js +1 -2
  83. package/dist/locales/uk.cjs +0 -1
  84. package/dist/locales/uk.js +1 -2
  85. package/dist/markdown.cjs +0 -1
  86. package/dist/markdown.js +1 -2
  87. package/dist/mcp-app-sandbox.cjs +0 -1
  88. package/dist/mcp-app-sandbox.js +1 -2
  89. package/dist/mcp-app.cjs +0 -1
  90. package/dist/mcp-app.js +2 -3
  91. package/dist/pipeline.cjs +0 -1
  92. package/dist/pipeline.js +1 -2
  93. package/package.json +2 -2
  94. package/dist/canvas.cjs.map +0 -1
  95. package/dist/canvas.js.map +0 -1
  96. package/dist/chunk-7O64ZI6Z.js.map +0 -1
  97. package/dist/chunk-EL2YCROY.js.map +0 -1
  98. package/dist/chunk-GB7RZJMG.js.map +0 -1
  99. package/dist/chunk-KZQB35LS.js.map +0 -1
  100. package/dist/chunk-SVYHDLAZ.js.map +0 -1
  101. package/dist/chunk-VCR7LU7J.js.map +0 -1
  102. package/dist/chunk-WFM6B7CL.js.map +0 -1
  103. package/dist/chunk-WZ7K7JIP.js.map +0 -1
  104. package/dist/chunk-ZBHESK6V.js.map +0 -1
  105. package/dist/controller.cjs.map +0 -1
  106. package/dist/controller.js.map +0 -1
  107. package/dist/index.cjs.map +0 -1
  108. package/dist/index.js.map +0 -1
  109. package/dist/locales/be.cjs.map +0 -1
  110. package/dist/locales/be.js.map +0 -1
  111. package/dist/locales/bg.cjs.map +0 -1
  112. package/dist/locales/bg.js.map +0 -1
  113. package/dist/locales/ca.cjs.map +0 -1
  114. package/dist/locales/ca.js.map +0 -1
  115. package/dist/locales/cs.cjs.map +0 -1
  116. package/dist/locales/cs.js.map +0 -1
  117. package/dist/locales/da.cjs.map +0 -1
  118. package/dist/locales/da.js.map +0 -1
  119. package/dist/locales/de.cjs.map +0 -1
  120. package/dist/locales/de.js.map +0 -1
  121. package/dist/locales/el.cjs.map +0 -1
  122. package/dist/locales/el.js.map +0 -1
  123. package/dist/locales/en.cjs.map +0 -1
  124. package/dist/locales/en.js.map +0 -1
  125. package/dist/locales/es-419.cjs.map +0 -1
  126. package/dist/locales/es-419.js.map +0 -1
  127. package/dist/locales/es.cjs.map +0 -1
  128. package/dist/locales/es.js.map +0 -1
  129. package/dist/locales/fi.cjs.map +0 -1
  130. package/dist/locales/fi.js.map +0 -1
  131. package/dist/locales/fr-CA.cjs.map +0 -1
  132. package/dist/locales/fr-CA.js.map +0 -1
  133. package/dist/locales/fr.cjs.map +0 -1
  134. package/dist/locales/fr.js.map +0 -1
  135. package/dist/locales/gn.cjs.map +0 -1
  136. package/dist/locales/gn.js.map +0 -1
  137. package/dist/locales/hr.cjs.map +0 -1
  138. package/dist/locales/hr.js.map +0 -1
  139. package/dist/locales/ht.cjs.map +0 -1
  140. package/dist/locales/ht.js.map +0 -1
  141. package/dist/locales/hu.cjs.map +0 -1
  142. package/dist/locales/hu.js.map +0 -1
  143. package/dist/locales/index.cjs.map +0 -1
  144. package/dist/locales/index.js.map +0 -1
  145. package/dist/locales/it.cjs.map +0 -1
  146. package/dist/locales/it.js.map +0 -1
  147. package/dist/locales/nb.cjs.map +0 -1
  148. package/dist/locales/nb.js.map +0 -1
  149. package/dist/locales/nl.cjs.map +0 -1
  150. package/dist/locales/nl.js.map +0 -1
  151. package/dist/locales/pl.cjs.map +0 -1
  152. package/dist/locales/pl.js.map +0 -1
  153. package/dist/locales/pt-BR.cjs.map +0 -1
  154. package/dist/locales/pt-BR.js.map +0 -1
  155. package/dist/locales/pt.cjs.map +0 -1
  156. package/dist/locales/pt.js.map +0 -1
  157. package/dist/locales/qu.cjs.map +0 -1
  158. package/dist/locales/qu.js.map +0 -1
  159. package/dist/locales/ro.cjs.map +0 -1
  160. package/dist/locales/ro.js.map +0 -1
  161. package/dist/locales/ru.cjs.map +0 -1
  162. package/dist/locales/ru.js.map +0 -1
  163. package/dist/locales/sk.cjs.map +0 -1
  164. package/dist/locales/sk.js.map +0 -1
  165. package/dist/locales/sq.cjs.map +0 -1
  166. package/dist/locales/sq.js.map +0 -1
  167. package/dist/locales/sr-Latn.cjs.map +0 -1
  168. package/dist/locales/sr-Latn.js.map +0 -1
  169. package/dist/locales/sr.cjs.map +0 -1
  170. package/dist/locales/sr.js.map +0 -1
  171. package/dist/locales/sv.cjs.map +0 -1
  172. package/dist/locales/sv.js.map +0 -1
  173. package/dist/locales/tr.cjs.map +0 -1
  174. package/dist/locales/tr.js.map +0 -1
  175. package/dist/locales/uk.cjs.map +0 -1
  176. package/dist/locales/uk.js.map +0 -1
  177. package/dist/markdown.cjs.map +0 -1
  178. package/dist/markdown.js.map +0 -1
  179. package/dist/mcp-app-sandbox.cjs.map +0 -1
  180. package/dist/mcp-app-sandbox.js.map +0 -1
  181. package/dist/mcp-app.cjs.map +0 -1
  182. package/dist/mcp-app.js.map +0 -1
  183. package/dist/pipeline.cjs.map +0 -1
  184. package/dist/pipeline.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/controller.ts","../src/approval-queue.ts","../src/questions.ts","../src/state.ts","../src/util.ts"],"sourcesContent":["// The agent's controller: everything `useAgent` did that is not React, as a store any front end\n// can wrap - build the agent, fold its events into `AgentUiState`, run / stop / steer it, the\n// consent and question queues, other tabs, usage. A binding (React's `useAgent`, a web component,\n// Vue / Angular / Svelte) creates one, subscribes to it, renders its snapshot and calls its\n// methods: it never re-implements any of this.\n//\n// Its own entry (`./controller`): it imports the core's `createAgent` and `createRunControl` at\n// run time, which the main entry does not (`tests/entries.test.ts`).\nimport * as core from '@dudko.dev/agent-web'\nimport {\n createAgent,\n createRunControl,\n type IUsage,\n type Agent,\n type AgentEvent,\n type AgentEventHandler,\n type AppSamplingRequest,\n type AppSamplingResult,\n type AppSamplingView,\n type AppToolCallRequest,\n type AskUserAnswer,\n type BrowserAgentConfig,\n type CompactResult,\n type RunControl,\n type RunFile,\n type RunResult,\n type SessionWatch,\n type ToolApprovalContext,\n type ToolApprovalDecision,\n type ToolApprovalMode,\n type ToolApprovalRequest,\n} from '@dudko.dev/agent-web'\nimport { createApprovalQueue } from './approval-queue.js'\nimport {\n askUserWith,\n createQuestionQueue,\n questionTimeoutOf,\n type PendingQuestion,\n} from './questions.js'\nimport {\n agentStateReducer,\n agentStatusOf,\n createInitialAgentState,\n lessonsOf,\n pendingApprovalsOf,\n type AgentAction,\n} from './state.js'\nimport type { AgentUiState, ApprovalView, ChatAttachment, ChatMessage } from './types.js'\nimport { errMessage, followOtherTabs, remoteAnswerOf } from './util.js'\n\n// ── options ──────────────────────────────────────────────────────────────\n\n/** How a controller behaves. `useAgent`'s options are these plus `deps`. */\nexport interface AgentControllerOptions {\n /** Invoked for every raw agent event, after the internal reducer folds it. */\n onEvent?: AgentEventHandler\n /**\n * Build the agent as soon as the controller is created (default `true`). With `false` it waits\n * for `reload()`.\n */\n autoStart?: boolean\n /** Cap the retained raw event log length (default 200; 0 = unbounded). */\n maxEvents?: number\n /**\n * Where \"Always allow\" given to an MCP App's tool is kept (the core's `appGrantKey`: the\n * server's identity on its connection, the tool, the app's resource): handed to the core's\n * `approveAppToolCall`, so a new agent - an `update`, a new controller - keeps the grant. A new\n * connection (the server removed and added again, reconnected, another server under the same\n * name) starts with none, and a rule's 'deny' or 'read-only' still refuses. Default: one set for\n * the page's life (this module's, shared by every controller of the page - and so by every\n * `useAgent`); a reload forgets it, as sampling's \"Always for this app\" is forgotten. Pass your\n * own set to scope it differently.\n */\n appToolGrants?: Set<string>\n /**\n * Route tool-consent requests into the controller (`pendingApprovals`, `approve`, `deny`) when\n * the config has no `toolApproval.onRequest` of its own (default true).\n */\n approvals?: boolean\n /**\n * Route the model's questions (`ask_user`) into the controller (`pendingQuestions`,\n * `answerQuestion`) when the config turns `askUser` on without an `onQuestion` of its own\n * (`askUser: true`, or `{ timeoutMs, maxPerRun }`; default true). A host's own `onQuestion` wins;\n * `askUser` off stays off.\n */\n questions?: boolean\n /**\n * What the run never showed the agent — a message sent while the answer was being\n * written — is sent as the next message, once the run has ended (default true).\n * A run the user stopped never does this: those messages stay in `undelivered`\n * for the UI to offer (`sendUndelivered` / `discardUndelivered`).\n */\n followUp?: boolean\n /**\n * Follow a run of the current conversation that goes on in ANOTHER tab of the site (default\n * true; needs a `memory` the tabs share - `IndexedDBStore` - and `sessionLock` not `'off'`): its\n * steps and answer show here live (`remote`) and `isRunning` is true meanwhile. Writing to it or\n * stopping it is explicit: `sendRemote` / `stopRemote`. Consent requests stay in that tab.\n */\n watch?: boolean\n}\n\nexport interface ApproveOptions {\n /** Also allow this tool for the rest of the agent's life (\"always allow\"). */\n remember?: boolean\n}\n\nexport interface RunGoalOptions {\n /**\n * What the transcript shows for this turn when it differs from what the\n * agent receives — e.g. the typed text without the attached files' contents.\n * `''` with `attachments`: a message of attachments only - the transcript shows them, no text.\n */\n label?: string\n /** Images sent to the model with the goal (vision models; see `agent.capabilities`). */\n images?: RunFile[]\n /** PDFs / files / URLs sent to the model with the goal. */\n files?: RunFile[]\n /** What the transcript shows as attached to this turn (thumbnails, chips). */\n attachments?: ChatAttachment[]\n}\n\n/**\n * A tool call an MCP App asks for, as `approveAppToolCall` takes it: the core's request, plus\n * `frame` - the host's id of the frame that asked (`AppView.id`), put on the request's `app`.\n */\nexport type AppToolCall = AppToolCallRequest & { frame?: string }\n\n/** What `update` does besides taking the new config. */\nexport interface AgentControllerUpdate {\n /** New options (replace the old ones whole). Omitted: the options stay. */\n options?: AgentControllerOptions\n /**\n * Build a new agent from the config (default `true`): what a `deps` change does in `useAgent`.\n * `false` only takes the config (and options) as the latest - read by the next build, the next\n * run, `reset` - and applies what is live: a new `toolApproval.mode`, another `memory` /\n * `sessionLock` / `learning.store` to follow other tabs through. A changed `autoStart` rebuilds\n * either way.\n */\n rebuild?: boolean\n}\n\n// ── the snapshot ─────────────────────────────────────────────────────────\n\n/** Everything a view renders, at one moment. Immutable: a new object on every change. */\nexport interface AgentControllerSnapshot extends AgentUiState {\n /** The memory session runs use (config.sessionId until switched). */\n sessionId: string\n /** This tab's run, or the conversation's run in another tab followed here. */\n isRunning: boolean\n /** The agent is built and nothing runs (here or, for this conversation, in another tab). */\n isReady: boolean\n /** Tool calls waiting for the user's consent (another tab's are answered there, never here). */\n pendingApprovals: ApprovalView[]\n /**\n * The model's questions waiting for the person in THIS tab (`ask_user`, when the controller\n * answers them - see `AgentControllerOptions.questions`), oldest first, each with `expiresAt`\n * when the core stops waiting. Another tab's questions are in `questions` (marked `remote`),\n * never here.\n */\n pendingQuestions: PendingQuestion[]\n /** The consent policy in effect. */\n approvalMode: ToolApprovalMode\n}\n\n// ── the methods ──────────────────────────────────────────────────────────\n\n/** What a view calls. Each keeps its identity for the controller's life. */\nexport interface AgentControllerActions {\n /**\n * Run a goal. Resolves with the RunResult, or `undefined` if it couldn't start. When the\n * conversation is running in another tab, the run waits for it (`sessionBusy`; the core's\n * `sessionLock`) and then goes, with that run's turn in its memory.\n */\n run: (goal: string, options?: RunGoalOptions) => Promise<RunResult | undefined>\n /**\n * Abort the in-flight run of THIS tab (observed between phases and mid-stream), going or waiting\n * for the session. A run followed from another tab is stopped only by `stopRemote`.\n */\n stop: () => void\n /**\n * Stop the conversation's run in another tab (`remote`), when that tab allows it (the core's\n * `sessionRelay`). A no-op when none is followed.\n */\n stopRemote: () => void\n /**\n * Say something to the conversation's run in another tab (`remote`): it reaches that run's\n * model at its next boundary, marked as from another tab. `false` when no such run is followed\n * or the text is empty. Until that tab answers, the text is in `queued` marked\n * `sentTo: 'another-tab'` (shown \"waiting for the other tab to pick it up\") - with no time\n * limit: a tab the browser froze answers when it wakes. Taken, that run's own entry takes its\n * place; refused, or that run ended without it, it comes back in `undelivered`.\n */\n sendRemote: (text: string) => boolean\n /**\n * Say something to the agent while it works. It is shown to the model at the next\n * boundary (between tool calls, or when the step ends — where the replanner then\n * re-checks the plan), never cutting a tool call short. `false` when no run is in\n * flight or the text is empty — then use `run`. Watch `queued` / `notes`. Only this tab's run:\n * for the conversation's run in another tab, `sendRemote`.\n */\n send: (text: string) => boolean\n /** Stop ONE running subagent (`SubagentView.id`); the run and its siblings go on. */\n stopSubagent: (id: string) => boolean\n /**\n * Delete one of the agent's own lessons (`learned`), e.g. one gone stale. Resolves false when\n * there is no such lesson (or no agent yet). Needs `config.learning`.\n */\n forgetSkill: (name: string) => Promise<boolean>\n /** Send the `undelivered` messages (a stopped run's leftovers) as a new message. */\n sendUndelivered: () => void\n /** Drop the `undelivered` messages. */\n discardUndelivered: () => void\n /** Clear the whole conversation — transcript, current run, and the agent's memory. */\n reset: () => void\n /** Rebuild the agent now (e.g. after the user stores a new API key). */\n reload: () => void\n /** Let a pending call run (`remember` → never ask for this tool again). */\n approve: (id: string, options?: ApproveOptions) => void\n /** Refuse a pending call; the model is told and works around it. */\n deny: (id: string, reason?: string) => void\n /**\n * Answer one of `pendingQuestions`: `{ choice: [label] }` (labels as offered; several only when\n * `multiple`), `{ other: text }` (only when `allowOther`) or `{ declined: true }`. False when no\n * such question is waiting (answered, expired, stopped). The answer goes to the core and is not\n * kept here.\n */\n answerQuestion: (id: string, answer: AskUserAnswer) => boolean\n /** Switch the consent policy live — the \"autopilot\" toggle. */\n setApprovalMode: (mode: ToolApprovalMode) => void\n /**\n * Ask the agent's consent gate about a tool call an MCP App wants to make (the core's\n * `Agent.approveAppToolCall`: the same rules and modes as the model's calls - 'autopilot' asks\n * nothing -, \"always allow\" kept apart from the model's and for the page's life, not the\n * agent's: `appToolGrants`). The request joins `pendingApprovals` with `app` set,\n * and waits across runs - a run ending or `stop()` does not answer it; `signal` does (the\n * app's frame going away). `call.frame` (the frame's `AppView.id`) is put on the request's\n * `app`, so it is drawn with THAT frame; `call.serverId` (`McpAppTool.serverId`) scopes the\n * grant to the server's connection. Resolves when the call may go; throws when it may not.\n */\n approveAppToolCall: (call: AppToolCall, signal?: AbortSignal) => Promise<void>\n /**\n * Answer a completion an MCP App asks for (its `sampling/createMessage`) with the agent's model:\n * the core's `Agent.sampleForApp` - checked, rate-limited per app, put to `approve` (shown\n * exactly what the model gets), then sent with no tools and none of the conversation. The\n * tokens count in `totalUsage` (a `usage` event of phase `'app'`, never the run's); the answer\n * is returned to the caller and never reaches the transcript, the memory or the model's context.\n * Throws the core's `AppSamplingError` (its `rpcCode` is what the app is told).\n */\n sampleForApp: (\n request: AppSamplingRequest,\n approve: (view: AppSamplingView) => Promise<boolean>,\n signal?: AbortSignal,\n ) => Promise<AppSamplingResult>\n /** Summarise the stored transcript now (needs `config.memory`). */\n compact: () => Promise<CompactResult | undefined>\n /**\n * Switch to another conversation: its id becomes the memory session of the\n * next runs, and its saved transcript (chat history) is shown.\n */\n loadChat: (chat: { sessionId: string; messages?: ChatMessage[]; totalUsage?: IUsage }) => void\n}\n\n/**\n * The agent as a store: `getSnapshot` + `subscribe` (React's `useSyncExternalStore` contract),\n * the methods a view calls, `update` and `dispose`.\n */\nexport interface AgentController extends AgentControllerActions {\n /** The current snapshot: the same object until something changes, then a new one. */\n getSnapshot: () => AgentControllerSnapshot\n /**\n * Call `listener` after every change (never at once on subscribing). Returns the unsubscribe.\n * After `dispose` nothing is called and subscribing does nothing.\n */\n subscribe: (listener: () => void) => () => void\n /** Take a new config (and options): see {@link AgentControllerUpdate}. */\n update: (config: BrowserAgentConfig, how?: AgentControllerUpdate) => void\n /**\n * Tear everything down: the in-flight run aborted, its consent requests and questions answered\n * (denied / declined: \"the view was closed\"), the build in progress dropped, the other-tab\n * channels closed, pending timers cleared, every listener dropped. The snapshot stays as it was;\n * every method is then a no-op (`run` resolves `undefined`). Idempotent.\n */\n dispose: () => void\n /** The built agent, once ready (`undefined` while building, after a failure or `dispose`). */\n readonly agent: Agent | undefined\n /** Whether `dispose` was called. */\n readonly disposed: boolean\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\n/** The database a store says it lives in (the core's IndexedDB stores do). */\nconst dbNameOf = (store: unknown): string | undefined => {\n const name = (store as { dbName?: unknown } | null | undefined)?.dbName\n return typeof name === 'string' && name ? name : undefined\n}\n\nconst modeOf = (config: BrowserAgentConfig): ToolApprovalMode =>\n config.toolApproval?.mode ?? 'autopilot'\n\n/** \"Always allow\" given to MCP Apps' tools, for the page's life (`appToolGrants`). */\nconst pageAppToolGrants = new Set<string>()\n\nconst snapshotOf = (\n state: AgentUiState,\n extra: { sessionId: string; pendingQuestions: PendingQuestion[]; approvalMode: ToolApprovalMode },\n): AgentControllerSnapshot => {\n // Another tab's run of this conversation counts as running here: the composer steers it, Stop\n // stops it, and nothing else starts the session meanwhile.\n const remoteRunning = state.remote?.running === true\n return Object.freeze({\n ...state,\n // `running` over ready / idle only: a build in progress or an error stays visible.\n status: agentStatusOf(state),\n isRunning: state.status === 'running' || remoteRunning,\n isReady: state.status === 'ready' && !remoteRunning,\n // Another tab's consent requests are answered there, never here.\n pendingApprovals: pendingApprovalsOf(state),\n pendingQuestions: extra.pendingQuestions,\n approvalMode: extra.approvalMode,\n sessionId: extra.sessionId,\n })\n}\n\n/**\n * What a controller's snapshot is before anything happened: what a view renders before it has a\n * controller (React's first render, which must not create one; a server render).\n */\nexport const createInitialAgentSnapshot = (config: BrowserAgentConfig): AgentControllerSnapshot =>\n snapshotOf(createInitialAgentState(), {\n sessionId: config.sessionId ?? 'default',\n pendingQuestions: [],\n approvalMode: modeOf(config),\n })\n\n// ── the controller ───────────────────────────────────────────────────────\n\n/**\n * Build the agent from `config` and keep its UI state: see {@link AgentController}. The agent is\n * built at once (unless `autoStart: false` or the config has no `model` yet), and other tabs are\n * followed from now on - so create it when the view appears and `dispose` it when the view goes.\n *\n * ```js\n * const chat = createAgentController({ model, credentials, toolApproval: { mode: 'ask-writes' } })\n * const off = chat.subscribe(() => render(chat.getSnapshot()))\n * button.onclick = () => chat.run(input.value)\n * // later: off(); chat.dispose()\n * ```\n */\nexport const createAgentController = (\n initialConfig: BrowserAgentConfig,\n initialOptions: AgentControllerOptions = {},\n): AgentController => {\n let config = initialConfig\n let options = initialOptions\n let disposed = false\n\n // ── the store ──\n let state = createInitialAgentState()\n let pendingQuestions: PendingQuestion[] = []\n // The memory session runs go to; a chat-history switch changes it.\n let sessionId = initialConfig.sessionId ?? 'default'\n let approvalMode: ToolApprovalMode = modeOf(initialConfig)\n let snapshot: AgentControllerSnapshot | undefined\n const listeners = new Set<() => void>()\n\n const changed = (): void => {\n snapshot = undefined\n for (const listener of [...listeners]) {\n // A listener that throws must not keep the others from hearing of the change.\n try {\n listener()\n } catch (err) {\n queueMicrotask(() => {\n throw err\n })\n }\n }\n }\n const dispatch = (action: AgentAction): void => {\n if (disposed) return\n const next = agentStateReducer(state, action)\n if (next === state) return\n state = next\n changed()\n }\n\n // ── the agent and its run ──\n let agent: Agent | undefined\n let abort: AbortController | undefined\n // The in-flight run's control: how `send` and `stopSubagent` reach it.\n let control: RunControl | undefined\n let generation = 0\n\n // Consent requests waiting for approve()/deny(), by request id. One the core stops waiting\n // for (its timeoutMs ran out, the run stopped) leaves its queue by its signal. An MCP App's are\n // kept in a queue of their own: they are not the run's, so a run ending (or stopped) does not\n // answer them.\n const approvals = createApprovalQueue()\n const appApprovals = createApprovalQueue()\n // The model's questions waiting for the person (ask_user), by id. One the core stops waiting\n // for (its timeoutMs ran out, the run stopped) leaves by its signal; a run's end takes the rest\n // down. The timeout is read from the latest config, when a question arrives.\n const questionQueue = createQuestionQueue({\n timeoutMs: () => questionTimeoutOf(config.askUser),\n onChange: (pending) => {\n if (disposed) return\n pendingQuestions = pending\n changed()\n },\n })\n const uiOnRequest = (req: ToolApprovalRequest, ctx?: ToolApprovalContext) =>\n (req.app ? appApprovals : approvals).handler(req, ctx)\n const settleAll = (decision: ToolApprovalDecision): void => approvals.settleAll(decision)\n\n // The mode the agent runs with: switched live, and taken by every new agent.\n let mode: ToolApprovalMode = approvalMode\n // The config's mode is the source of truth when IT changes; applied live.\n let configMode: ToolApprovalMode = approvalMode\n\n const setApprovalMode = (next: ToolApprovalMode): void => {\n if (disposed) return\n mode = next\n agent?.setToolApprovalMode(next)\n if (approvalMode === next) return\n approvalMode = next\n changed()\n }\n\n // The build's own status. A rebuild while a run is in flight (a setting changed mid-run) must\n // not flip the view out of 'running': the run keeps the agent it started with, and the new one\n // takes the next run.\n type BuildStatus = { status: 'idle' | 'initializing' | 'ready' | 'error'; error?: string }\n let buildStatus: BuildStatus = { status: 'idle' }\n const setBuildStatus = (next: BuildStatus): void => {\n buildStatus = next\n if (!abort) dispatch({ type: 'status', ...next })\n }\n\n // Build (and rebuild) the agent. Model resolution is async (dynamic provider imports, vault key\n // fetch, WebLLM weight download). A newer build (or dispose) makes an older one's result moot.\n let cancelBuild: (() => void) | undefined\n const build = (): void => {\n cancelBuild?.()\n cancelBuild = undefined\n // Any rebuild invalidates the current agent first.\n agent = undefined\n const cfg = config\n // Skip building until we're asked to (autoStart / reload) and actually have a model — a local\n // WebGPU model may still be downloading (config.model undefined), in which case we sit idle\n // rather than build a broken agent.\n const shouldBuild = (options.autoStart !== false || generation > 0) && Boolean(cfg.model)\n if (!shouldBuild) {\n setBuildStatus({ status: 'idle' })\n return\n }\n // Consent requests come to the controller unless the host handles them itself.\n const routeApprovals = options.approvals !== false && !cfg.toolApproval?.onRequest\n // ...and so do the model's questions, when askUser is on without a handler of the host's.\n const askUser =\n options.questions !== false ? askUserWith(cfg.askUser, questionQueue.handler) : cfg.askUser\n const built: BrowserAgentConfig = {\n ...cfg,\n ...(routeApprovals\n ? { toolApproval: { ...cfg.toolApproval, mode, onRequest: uiOnRequest } }\n : {}),\n ...(askUser !== cfg.askUser ? { askUser } : {}),\n }\n let cancelled = false\n cancelBuild = () => {\n cancelled = true\n }\n setBuildStatus({ status: 'initializing' })\n createAgent(built)\n .then((next) => {\n if (cancelled) return\n next.setToolApprovalMode(mode)\n agent = next\n // The notebook belongs to the agent just built: what its store brought back (or nothing).\n dispatch({ type: 'notebook', lessons: lessonsOf(next.listLearnedSkills()) })\n setBuildStatus({ status: 'ready' })\n })\n .catch((err) => {\n if (cancelled) return\n setBuildStatus({ status: 'error', error: errMessage(err) })\n })\n }\n\n // ── other tabs ──\n // Another tab's run of this conversation: followed here, steered and stopped through the core's\n // watchSession. The session's memory must be one the tabs share (its database names the\n // channel); with `sessionLock: 'off'` nobody relays.\n let watch: SessionWatch | undefined\n // What the watch was opened for (`undefined` db: none opened).\n let watched: { db: string | undefined; sessionId: string } | undefined\n // A run of this tab has started (its `run.start`): it holds the session. While it only WAITS for\n // the session, the other tab's run is still followed.\n let started = false\n const closeWatch = (): void => {\n watch?.close()\n watch = undefined\n }\n const syncWatch = (): void => {\n const db =\n options.watch !== false && config.sessionLock !== 'off' ? dbNameOf(config.memory) : undefined\n if (watched && watched.db === db && watched.sessionId === sessionId) return\n closeWatch()\n watched = { db, sessionId }\n const watchSession = (core as { watchSession?: typeof core.watchSession }).watchSession\n if (!db || typeof watchSession !== 'function') return\n watch = watchSession({\n dbName: db,\n sessionId,\n onEvent: (event) => {\n // A run of this tab holds the session: a late message of the one before it is not ours.\n if (started) return\n dispatch({\n type: 'event',\n event,\n remote: true,\n maxEvents: options.maxEvents,\n at: Date.now(),\n })\n },\n onState: (s) => {\n if (started && s.running) return\n dispatch({\n type: 'remote',\n remote: {\n running: s.running,\n ...(s.runId ? { runId: s.runId } : {}),\n ...(s.ended ? { ended: s.ended } : {}),\n },\n })\n },\n })\n }\n\n // The notebook in another tab changed (its store announces `skills`): read it again.\n let skillsDb: { db: string | undefined } | undefined\n let unfollowSkills: (() => void) | undefined\n const syncSkills = (): void => {\n const db = dbNameOf(typeof config.learning === 'object' ? config.learning.store : undefined)\n if (skillsDb && skillsDb.db === db) return\n unfollowSkills?.()\n skillsDb = { db }\n unfollowSkills = followOtherTabs(\n core,\n db,\n (change) => change.kind === 'skills',\n () => {\n const current = agent\n if (disposed || !current || typeof current.reloadLearnedSkills !== 'function') return\n void current\n .reloadLearnedSkills()\n .then((skills) => dispatch({ type: 'notebook', lessons: lessonsOf(skills) }))\n .catch(() => {})\n },\n )\n }\n\n // ── the methods ──\n const run = async (goal: string, runOptions?: RunGoalOptions): Promise<RunResult | undefined> => {\n const current = agent\n if (disposed || !current || abort) return undefined // not ready, or already running\n const controller = new AbortController()\n abort = controller\n const runControl = createRunControl()\n control = runControl\n // What the run never showed the agent; read once it is over.\n let left: string[] = []\n // Stopped - here, or from another tab (the run's own result says so).\n let stopped = false\n // Whether it began (its run.start): a run stopped while it only waited began nothing.\n let began = false\n const shownGoal = runOptions?.label ?? goal\n dispatch({ type: 'status', status: 'running' })\n // Shown at once: the run's own turn (`run.start`) comes once it has the session.\n // A message of attachments only has no text to show (`label: ''`): its attachments are it.\n const shownAtAll = Boolean(shownGoal.trim() || runOptions?.attachments?.length)\n if (shownAtAll) {\n dispatch({\n type: 'submitted',\n goal: shownGoal,\n ...(runOptions?.attachments?.length ? { attachments: runOptions.attachments } : {}),\n })\n }\n try {\n const result = await current.run(goal, {\n signal: controller.signal,\n control: runControl,\n sessionId,\n ...(runOptions?.images?.length ? { images: runOptions.images } : {}),\n ...(runOptions?.files?.length ? { files: runOptions.files } : {}),\n onEvent: (event) => {\n const start = event.type === 'run.start'\n // From here the session is this run's: whatever the run before it still sends is late.\n if (start) {\n started = true\n began = true\n }\n const shown =\n start && runOptions?.label !== undefined ? { ...event, goal: runOptions.label } : event\n dispatch({\n type: 'event',\n event: shown,\n maxEvents: options.maxEvents,\n at: Date.now(),\n // What the user sent waits with the run: shown as queued meanwhile.\n ...(event.type === 'session.busy' && shownAtAll\n ? {\n goal:\n shownGoal.trim() ||\n (runOptions?.attachments ?? []).map((a) => a.name).join(', '),\n }\n : {}),\n ...(start && runOptions?.attachments?.length\n ? { attachments: runOptions.attachments }\n : {}),\n })\n try {\n options.onEvent?.(event)\n } catch {\n /* a bad host handler must not break the run */\n }\n },\n })\n left = result.undelivered ?? []\n stopped = result.stopped\n return result\n } catch (err) {\n left = runControl.pending()\n dispatch({\n type: 'event',\n event: { type: 'error', phase: 'run', error: errMessage(err) },\n maxEvents: options.maxEvents,\n })\n return undefined\n } finally {\n abort = undefined\n started = false\n control = undefined\n settleAll({ approved: false, reason: 'the run ended' })\n // A question the core still had open is no one's now (the core stopped waiting already).\n questionQueue.cancel()\n // Whatever the agent did meanwhile: rebuilt, still building, or gone.\n dispatch({ type: 'status', ...buildStatus })\n // Stopped while it waited for the session: what the user sent goes back to them.\n if (stopped && !began && shownGoal.trim()) left = [shownGoal, ...left]\n if (left.length > 0) {\n if (!controller.signal.aborted && !stopped && options.followUp !== false) {\n // Said too late for this run: just send it next.\n dispatch({ type: 'undelivered', texts: [] })\n void run(left.join('\\n\\n'))\n } else {\n dispatch({ type: 'undelivered', texts: left })\n }\n } else {\n dispatch({ type: 'undelivered', texts: [] })\n }\n }\n }\n\n const send = (text: string): boolean => control?.send(text) ?? false\n // Ids of what this tab sent to another tab's run, while it waits for that tab's answer.\n let remoteSends = 0\n const sendRemote = (text: string): boolean => {\n const current = watch\n const clean = typeof text === 'string' ? text.trim() : ''\n if (!current?.state.running || !clean) return false\n // Shown as waiting for that tab until it answers - however long: a tab the browser froze in\n // the background answers when it wakes. Taken there, that run's own `message.queued` (marked\n // from another tab) takes the entry's place. Refused, or that run ended without it: the text\n // comes back here, to be sent again or dropped - and only then, so a message never has two\n // runs. The watch closed (another conversation in view, or the view gone): nothing to offer\n // here, and that tab may still take it.\n const id = `to-other-tab-${(remoteSends += 1)}`\n dispatch({ type: 'remote-send', id, text: clean })\n void current.send(clean).then((ok) => {\n const answer = remoteAnswerOf(ok, watch === current)\n dispatch({ type: 'remote-answer', id, text: clean, answer })\n })\n return true\n }\n const stopRemote = (): void => {\n if (watch?.state.running) void watch.stop()\n }\n const stopSubagent = (id: string): boolean => control?.stopSubagent(id) ?? false\n const sendUndelivered = (): void => {\n const texts = state.undelivered\n if (disposed || texts.length === 0) return\n dispatch({ type: 'undelivered', texts: [] })\n void run(texts.join('\\n\\n'))\n }\n const discardUndelivered = (): void => dispatch({ type: 'undelivered', texts: [] })\n\n const stop = (): void => {\n // The run's signal first: the core ends a question's wait as stopped, then nobody is asked.\n abort?.abort()\n settleAll({ approved: false, reason: 'stopped by the user' })\n questionQueue.cancel()\n }\n\n const answerQuestion = (id: string, answer: AskUserAnswer): boolean =>\n questionQueue.answer(id, answer)\n\n const reset = (): void => {\n if (disposed) return\n dispatch({ type: 'reset' })\n // \"New conversation\" means the agent forgets it too, not just the view.\n void config.memory?.clear(sessionId).catch(() => {})\n }\n\n const reload = (): void => {\n if (disposed) return\n generation += 1\n build()\n }\n\n const loadChat = (chat: {\n sessionId: string\n messages?: ChatMessage[]\n totalUsage?: IUsage\n }): void => {\n if (disposed) return\n abort?.abort()\n const switched = chat.sessionId !== sessionId\n sessionId = chat.sessionId\n if (switched) snapshot = undefined\n const before = state\n dispatch({ type: 'load', messages: chat.messages ?? [], totalUsage: chat.totalUsage })\n // The session is part of the snapshot: a switch is a change even when the view is not.\n if (switched && state === before) changed()\n syncWatch()\n }\n\n const forgetSkill = async (name: string): Promise<boolean> => {\n const current = agent\n if (disposed || !current) return false\n return current.forgetSkill(name, (event) =>\n dispatch({ type: 'event', event, maxEvents: options.maxEvents, at: Date.now() }),\n )\n }\n\n // The waiting request with this id - the run's or an app's.\n const approve = (id: string, opts?: ApproveOptions): void => {\n if (!approvals.approve(id, { remember: opts?.remember })) {\n appApprovals.approve(id, { remember: opts?.remember })\n }\n }\n\n const deny = (id: string, reason?: string): void => {\n if (!approvals.deny(id, reason)) appApprovals.deny(id, reason)\n }\n\n const approveAppToolCall = async (\n { frame, ...call }: AppToolCall,\n signal?: AbortSignal,\n ): Promise<void> => {\n const current = agent\n if (!current) throw new Error('The agent is not ready')\n // An older core has no gate for apps: refuse rather than let the call through.\n if (typeof current.approveAppToolCall !== 'function') {\n throw new Error('This version of @dudko.dev/agent-web cannot ask about an app’s calls')\n }\n await current.approveAppToolCall(\n call,\n (event) => {\n // Decided (or given up on): nothing waits on the answer any more. The queue drops a\n // request whose signal aborted; this also covers a core that sends no signal.\n if (event.type === 'tool.approval-resolved') appApprovals.deny(event.id, 'no longer asked')\n dispatch({\n type: 'event',\n // The frame that asked rides on the request's `app`: drawn with that frame.\n event:\n frame !== undefined && event.type === 'tool.approval-requested' && event.app\n ? ({ ...event, app: { ...event.app, frame } } as AgentEvent)\n : event,\n maxEvents: options.maxEvents,\n at: Date.now(),\n })\n },\n signal,\n { remembered: options.appToolGrants ?? pageAppToolGrants },\n )\n }\n\n const sampleForApp = async (\n request: AppSamplingRequest,\n approveView: (view: AppSamplingView) => Promise<boolean>,\n signal?: AbortSignal,\n ): Promise<AppSamplingResult> => {\n const current = agent\n if (!current) throw new Error('The agent is not ready')\n // An older core cannot: refuse rather than answer without the core's checks.\n if (typeof current.sampleForApp !== 'function') {\n throw new Error('This version of @dudko.dev/agent-web cannot answer an app’s sampling')\n }\n return current.sampleForApp(request, {\n approve: approveView,\n ...(signal ? { signal } : {}),\n sessionId,\n // The only event: its tokens (phase 'app'). The answer is never dispatched.\n onEvent: (event) =>\n dispatch({ type: 'event', event, maxEvents: options.maxEvents, at: Date.now() }),\n })\n }\n\n const compact = async (): Promise<CompactResult | undefined> => {\n const current = agent\n if (disposed || !current) return undefined\n const result = await current.compact({ sessionId })\n if (result.compacted) {\n dispatch({\n type: 'event',\n event: {\n type: 'context.compacted',\n scope: 'history',\n beforeTokens: result.beforeTokens,\n afterTokens: result.afterTokens,\n },\n maxEvents: options.maxEvents,\n at: Date.now(),\n })\n }\n return result\n }\n\n // ── update and dispose ──\n const update = (next: BrowserAgentConfig, how: AgentControllerUpdate = {}): void => {\n if (disposed) return\n const autoStartBefore = options.autoStart\n config = next\n if (how.options) options = how.options\n // In the order `useAgent`'s effects ran: the mode, the build, the other tabs.\n const nextMode = modeOf(next)\n if (nextMode !== configMode) {\n configMode = nextMode\n if (nextMode !== mode) setApprovalMode(nextMode)\n }\n if (how.rebuild !== false || !Object.is(options.autoStart, autoStartBefore)) build()\n syncWatch()\n syncSkills()\n }\n\n const dispose = (): void => {\n if (disposed) return\n // Abort any in-flight run, and release waiting consent requests and questions.\n abort?.abort()\n settleAll({ approved: false, reason: 'the view was closed' })\n appApprovals.settleAll({ approved: false, reason: 'the view was closed' })\n questionQueue.dispose()\n disposed = true\n cancelBuild?.()\n cancelBuild = undefined\n agent = undefined\n closeWatch()\n unfollowSkills?.()\n unfollowSkills = undefined\n listeners.clear()\n }\n\n // ── start ──\n build()\n syncWatch()\n syncSkills()\n\n return {\n getSnapshot: () =>\n (snapshot ??= snapshotOf(state, { sessionId, pendingQuestions, approvalMode })),\n subscribe: (listener) => {\n if (disposed) return () => {}\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n update,\n dispose,\n get agent() {\n return agent\n },\n get disposed() {\n return disposed\n },\n run,\n stop,\n stopRemote,\n send,\n sendRemote,\n stopSubagent,\n forgetSkill,\n sendUndelivered,\n discardUndelivered,\n reset,\n reload,\n approve,\n deny,\n answerQuestion,\n setApprovalMode,\n approveAppToolCall,\n sampleForApp,\n compact,\n loadChat,\n }\n}\n","import type {\n ToolApprovalContext,\n ToolApprovalDecision,\n ToolApprovalRequest,\n} from '@dudko.dev/agent-web'\n\n/** The consent requests waiting for a person, by request id. */\nexport interface ApprovalQueue {\n /**\n * The core's `toolApproval.onRequest`: resolves when `approve` / `deny` is called. A request\n * the core stops waiting for (`ctx.signal`: its `timeoutMs` ran out, the run stopped) leaves\n * the queue at once, so no stale answer is kept for it.\n */\n handler: (req: ToolApprovalRequest, ctx?: ToolApprovalContext) => Promise<ToolApprovalDecision>\n /** Allow one. False when no such request is waiting (answered, expired, settled). */\n approve: (id: string, options?: { remember?: boolean }) => boolean\n /** Deny one. False when no such request is waiting. */\n deny: (id: string, reason?: string) => boolean\n /** Answer every waiting request with `decision` (the run ended, the view closed). */\n settleAll: (decision: ToolApprovalDecision) => void\n /** The ids of the requests waiting, oldest first. */\n pending: () => string[]\n}\n\n/**\n * The queue behind `useAgent`'s `approve` / `deny`: `request.id → resolver`. A request leaves it\n * exactly once - answered, settled by `settleAll`, or dropped when the core no longer wants the\n * answer (its signal aborted; the core has already denied the call and said so in its event).\n */\nexport const createApprovalQueue = (): ApprovalQueue => {\n const waiting = new Map<string, (decision: ToolApprovalDecision) => void>()\n\n const handler: ApprovalQueue['handler'] = (req, ctx) =>\n new Promise<ToolApprovalDecision>((resolve) => {\n const signal = ctx?.signal\n if (signal?.aborted) {\n resolve({ approved: false, reason: 'no longer asked' })\n return\n }\n const onAbort = (): void => {\n if (waiting.get(req.id) !== settle) return\n settle({ approved: false, reason: 'no longer asked' })\n }\n // Called only for the request in the map (every caller looks it up first): exactly once.\n const settle = (decision: ToolApprovalDecision): void => {\n waiting.delete(req.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(decision)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n waiting.set(req.id, settle)\n })\n\n const answer = (id: string, decision: ToolApprovalDecision): boolean => {\n const settle = waiting.get(id)\n if (!settle) return false\n settle(decision)\n return true\n }\n\n return {\n handler,\n approve: (id, options) => answer(id, { approved: true, remember: options?.remember }),\n deny: (id, reason) => answer(id, { approved: false, reason }),\n settleAll: (decision) => {\n for (const settle of [...waiting.values()]) settle(decision)\n },\n pending: () => [...waiting.keys()],\n }\n}\n","import type {\n AgentEvent,\n AskUserAnswer,\n AskUserConfig,\n AskUserContext,\n AskUserHandler,\n AskUserRequest,\n} from '@dudko.dev/agent-web'\n\n/**\n * The model asks the person ONE closed question (the core's `ask_user`, `config.askUser`): the\n * part of it that is not React - the queue the hook hands the core as `askUser.onQuestion`, the\n * answer a prompt builds, and what of a question's tool result may be kept.\n *\n * Pure: no React, no clock of its own (the queue takes `now`), no import of the core at run time\n * (types only), so the main entry still loads next to an older core.\n *\n * Nothing here keeps, logs or returns what the person typed (`{ other }`) except to the one caller\n * that hands it to the core: the queue passes an answer straight to the core's resolver, and\n * {@link withoutOwnWords} takes the person's words out of the events before a view keeps them.\n */\n\n/** The core's tool name (`ASK_USER_TOOL`). */\nexport const ASK_USER_TOOL_NAME = 'ask_user'\n\n/** The core's default for `askUser.timeoutMs` (`ASK_USER_TIMEOUT_MS`). */\nexport const QUESTION_TIMEOUT_MS = 300_000\n\n/** The longest wait a timer holds (2^31 - 1 ms); the core takes a longer `timeoutMs` as none. */\nconst TIMER_MAX_MS = 2_147_483_647\n\n// ── a question waiting for the person ────────────────────────────────────\n\n/**\n * A question waiting for the person: the core's request (the question and every option are the\n * MODEL's text, cleaned - show them as plain text), and when the core stops waiting for it.\n */\nexport interface PendingQuestion extends AskUserRequest {\n /** Epoch ms after which the core answers it by itself (\"did not answer in time\"); absent: no limit. */\n expiresAt?: number\n}\n\n/**\n * How long the core waits for an answer with this `askUser`; `undefined` = no limit of its own\n * (`0`, `Infinity`, more than a timer holds - the core's own rules).\n */\nexport const questionTimeoutOf = (\n askUser: boolean | AskUserConfig | undefined,\n): number | undefined => {\n if (!askUser) return undefined\n const raw = askUser === true ? undefined : askUser.timeoutMs\n if (raw === undefined || raw === null) return QUESTION_TIMEOUT_MS\n if (typeof raw !== 'number' || !(raw > 0) || raw > TIMER_MAX_MS) return undefined\n return Math.max(1, Math.floor(raw))\n}\n\n/**\n * `config.askUser` as `useAgent` builds the agent with it: on without a handler of its own\n * (`true`, `{ timeoutMs, maxPerRun }`) it gets `handler`; a host's own `onQuestion` wins, and off\n * (absent, `false`) stays off - nothing is added, so the core mounts no tool.\n */\nexport const askUserWith = (\n askUser: boolean | AskUserConfig | undefined,\n handler: AskUserHandler,\n): boolean | AskUserConfig | undefined => {\n if (!askUser) return askUser\n if (askUser === true) return { onQuestion: handler }\n return askUser.onQuestion ? askUser : { ...askUser, onQuestion: handler }\n}\n\nexport interface QuestionQueueOptions {\n /**\n * How long the core waits (ms), for `expiresAt`; `undefined` = no limit. A function is read when\n * a question arrives (the settings of the agent that asks).\n */\n timeoutMs?: number | (() => number | undefined)\n /** Called whenever the list of waiting questions changed. */\n onChange?: (pending: PendingQuestion[]) => void\n /** The clock (tests). */\n now?: () => number\n}\n\nexport interface QuestionQueue {\n /** The core's `askUser.onQuestion`: resolves when the person answers, or as `{ declined: true }`. */\n handler: (request: AskUserRequest, ctx?: AskUserContext) => Promise<AskUserAnswer>\n /** The questions waiting, oldest first. */\n pending: () => PendingQuestion[]\n /** Answer one. False when no such question is waiting (answered, expired, cancelled). */\n answer: (id: string, answer: AskUserAnswer) => boolean\n /**\n * Take the waiting questions down - all of them, or those `match` picks - as declined (the run\n * ended, it was stopped). The core has usually stopped waiting already; this only makes sure no\n * resolver is left.\n */\n cancel: (match?: (question: PendingQuestion) => boolean) => void\n /** Cancel everything and stop reporting: the owner is gone. A later question is declined at once. */\n dispose: () => void\n}\n\nconst DECLINED: AskUserAnswer = { declined: true }\n\n/**\n * The questions the model is waiting on: `request.id → resolver`. A question leaves the queue\n * exactly once - answered by the person, dropped because the core no longer wants the answer\n * (`ctx.signal`: its time ran out, the run stopped), or cancelled by its owner (the run ended, an\n * unmount) - and the queue never holds an answer: `answer` passes it straight to the resolver.\n */\nexport const createQuestionQueue = (options: QuestionQueueOptions = {}): QuestionQueue => {\n const now = options.now ?? Date.now\n const waiting = new Map<\n string,\n { question: PendingQuestion; settle: (answer: AskUserAnswer) => void }\n >()\n let disposed = false\n\n const list = (): PendingQuestion[] => [...waiting.values()].map((w) => w.question)\n const changed = (): void => {\n if (!disposed) options.onChange?.(list())\n }\n\n const handler: QuestionQueue['handler'] = (request, ctx) =>\n new Promise<AskUserAnswer>((resolve) => {\n const signal = ctx?.signal\n // Nobody to ask, nobody wants the answer any more, or the core asks the same id twice.\n if (disposed || signal?.aborted || waiting.has(request.id)) {\n resolve(DECLINED)\n return\n }\n // The core no longer wants the answer: its time ran out, or the run stopped.\n const onAbort = (): void => {\n if (waiting.get(request.id)?.settle !== settle) return\n settle(DECLINED)\n changed()\n }\n // Called only for the question in the map (every caller looks it up first, and it leaves\n // the map here): exactly once - a second answer finds nothing to resolve.\n const settle = (answer: AskUserAnswer): void => {\n waiting.delete(request.id)\n signal?.removeEventListener('abort', onAbort)\n resolve(answer)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n const timeoutMs =\n typeof options.timeoutMs === 'function' ? options.timeoutMs() : options.timeoutMs\n waiting.set(request.id, {\n question: {\n ...request,\n options: request.options.map((o) => ({ ...o })),\n ...(timeoutMs !== undefined ? { expiresAt: now() + timeoutMs } : {}),\n },\n settle,\n })\n changed()\n })\n\n return {\n handler,\n pending: list,\n answer: (id, answer) => {\n const entry = waiting.get(id)\n if (!entry) return false\n entry.settle(answer)\n changed()\n return true\n },\n cancel: (match) => {\n let any = false\n for (const entry of [...waiting.values()]) {\n if (match && !match(entry.question)) continue\n entry.settle(DECLINED)\n any = true\n }\n if (any) changed()\n },\n dispose: () => {\n disposed = true\n for (const entry of [...waiting.values()]) entry.settle(DECLINED)\n },\n }\n}\n\n/**\n * Why a question ended without the person deciding: the core's `AskUserReason`\n * (`handler-error`, `invalid-answer`, `cannot-park`), or its action (`timeout`, `stopped`).\n */\nexport type QuestionOutcomeReason =\n 'timeout' | 'stopped' | 'handler-error' | 'invalid-answer' | 'cannot-park'\n\n// ── the answer a prompt builds ───────────────────────────────────────────\n\n/**\n * The person's picks as the core's answer: the labels that were offered, in the order they were\n * offered, each once - and one only unless the question allows several. `undefined` when nothing\n * that was offered is picked (Send stays off).\n */\nexport const questionChoiceOf = (\n question: Pick<AskUserRequest, 'options' | 'multiple'>,\n picked: readonly string[],\n): AskUserAnswer | undefined => {\n const chosen = question.options.map((o) => o.label).filter((label) => picked.includes(label))\n if (chosen.length === 0) return undefined\n return { choice: question.multiple ? chosen : chosen.slice(0, 1) }\n}\n\n/**\n * The person's own words as the core's answer, when the question allows them and there is\n * anything but spaces; `undefined` otherwise (Send stays off). The text goes to the caller only.\n */\nexport const questionOtherOf = (\n question: Pick<AskUserRequest, 'allowOther'>,\n text: string,\n): AskUserAnswer | undefined =>\n question.allowOther && typeof text === 'string' && text.trim()\n ? { other: text.trim() }\n : undefined\n\n// ── what of a question's tool result a view may keep ─────────────────────\n\n/**\n * The beginnings of the `ask_user` results that hold no word of the person's: a choice (the\n * labels, which are the model's own text), a decline, no answer in time, not asked, the cap. An\n * answer in the person's own words (\"...answered in their own words: ...\") is none of them - and\n * neither is anything a later core may say: a result that is not one of these is not kept.\n */\nconst LABELS_ONLY = [\n 'The user chose: ',\n 'The user chose not to answer.',\n 'The user did not answer in time.',\n 'The question could not be put to the user',\n 'You have already asked the user ',\n]\n\n/** Whether an `ask_user` result may be kept by a view: it holds no word the person typed. */\nexport const askUserOutputKept = (output: unknown, ok: boolean): boolean =>\n // A failed call is about the model's own arguments (a bad question): nobody was asked.\n !ok || (typeof output === 'string' && LABELS_ONLY.some((start) => output.startsWith(start)))\n\ntype ToolCallLike = { name: string; output?: unknown; ok: boolean }\n\nconst withoutOutput = <T extends ToolCallLike>(call: T): T => {\n if (call.name !== ASK_USER_TOOL_NAME || askUserOutputKept(call.output, call.ok)) return call\n const { output: _dropped, ...rest } = call\n void _dropped\n return rest as T\n}\n\n/**\n * The event with the person's own words taken out: the result of an `ask_user` call that is not\n * known to hold labels only (an answer in their own words) loses its `output` - in\n * `step.tool-result`, in `step.complete`'s tool calls, and in a subagent's events at any depth.\n * Everything else comes back as it was (the same object). The model was given the words; the\n * view, the saved chat and the event log are not.\n */\nexport const withoutOwnWords = (event: AgentEvent): AgentEvent => {\n switch (event.type) {\n case 'step.tool-result': {\n const cleaned = withoutOutput(event)\n return cleaned === event ? event : ({ ...cleaned, output: undefined } as AgentEvent)\n }\n case 'step.complete': {\n const calls = event.result.toolCalls\n const cleaned = calls.map(withoutOutput)\n return cleaned.every((c, i) => c === calls[i])\n ? event\n : { ...event, result: { ...event.result, toolCalls: cleaned } }\n }\n case 'subagent.event': {\n const inner = withoutOwnWords(event.event)\n return inner === event.event ? event : { ...event, event: inner }\n }\n default:\n return event\n }\n}\n","import {\n isReplayedToolOutput,\n type AgentEvent,\n type IUsage,\n type Skill,\n} from '@dudko.dev/agent-web'\nimport type {\n AppView,\n WrittenFileView,\n AgentUiState,\n ApprovalView,\n ElicitationView,\n QuestionView,\n ChatAttachment,\n ChatMessage,\n DecisionView,\n LessonView,\n MediaView,\n QueuedMessageView,\n RemoteRunView,\n StepView,\n SubagentNode,\n SubagentView,\n ToolCallView,\n TranscriptView,\n} from './types.js'\nimport { withoutOwnWords } from './questions.js'\n\n/**\n * The reducer that turns the agent's `AgentEvent` stream into a renderable\n * {@link AgentUiState}. It is a pure function of (state, action) with no React,\n * no clock and no randomness (ids come from a monotonic `seq`; times come in on\n * the action as `at`), so it can be unit-tested in isolation and reused to\n * build a fully custom UI.\n */\nexport type AgentAction =\n /** Clear the whole conversation (transcript + current run), keeping status. */\n | { type: 'reset' }\n /** Set the lifecycle status (owned by the hook). */\n | { type: 'status'; status: AgentUiState['status']; error?: string }\n /**\n * Fold one streamed agent event into the view. `at` (ms epoch, from the\n * hook) times runs and tool calls; `attachments` decorate the user turn a\n * `run.start` opens.\n */\n | {\n type: 'event'\n event: AgentEvent\n maxEvents?: number\n at?: number\n attachments?: ChatAttachment[]\n /** The event is another tab's run of this conversation (`watchSession`), relayed here. */\n remote?: boolean\n /** With `session.busy`: the goal that waits (shown as queued until the run starts). */\n goal?: string\n }\n /**\n * Another tab's run of this conversation, as `watchSession` reports it (or `undefined`: none\n * in view). Ended `gone` - that tab closed before it said so - finishes the answer it left.\n */\n | { type: 'remote'; remote: RemoteRunView | undefined }\n /**\n * The agent's notebook as it is now (the hook sends it when the agent is built: lessons a\n * persistent store brought back). Later `skill.learned` / `skill.forgotten` events keep it current.\n */\n | { type: 'notebook'; lessons: LessonView[] }\n /** Replace the transcript with a saved conversation (chat history). */\n | { type: 'load'; messages: ChatMessage[]; totalUsage?: IUsage }\n /**\n * The run is over and these messages never reached the model (`RunResult.undelivered`,\n * or what was still queued when it was stopped). Clears the queue. An empty list\n * clears `undelivered` too (the follow-up was sent, or the user discarded them).\n */\n | { type: 'undelivered'; texts: string[]; keepQueued?: boolean }\n /**\n * `sendRemote`: the text went to the conversation's run in another tab, which has not answered\n * yet - shown in `queued`, marked `sentTo: 'another-tab'`, until `remote-answer` with this `id`\n * (or that run's own `message.queued` for it, which takes its place).\n */\n | { type: 'remote-send'; id: string; text: string }\n /**\n * That tab's answer to `remote-send` `id`: `taken` (its run has it), `refused` (refused, or its\n * run ended without taking it - the text comes back in `undelivered`, to send again or drop), or\n * `unknown` (the watch that sent it was closed - another conversation is in view: nothing is\n * offered, as that tab may still take it). Either way the waiting entry goes.\n */\n | { type: 'remote-answer'; id: string; text: string; answer: 'taken' | 'refused' | 'unknown' }\n /**\n * The user sent a goal and this tab's run is getting going: its turn is shown at once (a\n * user message and a pending answer), until the run's `run.start` takes its place.\n */\n | { type: 'submitted'; goal: string; attachments?: ChatAttachment[] }\n\ninterface EventContext {\n at?: number\n attachments?: ChatAttachment[]\n remote?: boolean\n /** With `session.busy`: what the user sent, waiting with the run. */\n goal?: string\n}\n\n/** ≈ tokens of a value as the model sees it (chars / 4). */\nconst approxTokens = (value: unknown): number => {\n if (value === undefined) return 0\n let text: string\n try {\n text = typeof value === 'string' ? value : (JSON.stringify(value) ?? '')\n } catch {\n text = String(value)\n }\n return Math.ceil(text.length / 4)\n}\n\nconst emptyUsage = (): IUsage => ({\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n reasoningTokens: 0,\n cachedInputTokens: 0,\n cacheWriteTokens: 0,\n})\n\n// What a usage record counts besides tokens: calls to the media models and to the decision\n// model. Absent until there is one, so a run without them keeps the six-field shape.\nconst USAGE_COUNTS = [\n 'mediaCalls',\n 'imagesGenerated',\n 'speechCharacters',\n 'transcriptionSeconds',\n 'decisionCalls',\n] as const\n\nconst addUsage = (a: IUsage, b: IUsage): IUsage => {\n const sum: IUsage = {\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n totalTokens: a.totalTokens + b.totalTokens,\n reasoningTokens: (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0),\n cachedInputTokens: (a.cachedInputTokens ?? 0) + (b.cachedInputTokens ?? 0),\n cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0),\n }\n for (const key of USAGE_COUNTS) {\n const n = (a[key] ?? 0) + (b[key] ?? 0)\n if (n) sum[key] = n\n }\n return sum\n}\n\n/**\n * The notebook view of the agent's own skills (`agent.listLearnedSkills()`): what the core stored\n * about each lesson, in the shape the UI keeps current from `skill.learned` events.\n */\nexport const lessonsOf = (skills: Skill[]): LessonView[] =>\n skills\n .filter((s) => s.origin?.kind === 'learned')\n .map((s) => ({\n name: s.name,\n description: s.description,\n revision: s.origin?.revision ?? 1,\n chars: s.content.length,\n sources: [...(s.origin?.sources ?? []), ...(s.origin?.fetched ?? [])],\n }))\n\n/** A fresh, empty view. */\nexport const createInitialAgentState = (): AgentUiState => ({\n status: 'idle',\n goal: undefined,\n plan: undefined,\n planThought: '',\n steps: [],\n finalText: '',\n finalReasoning: '',\n totalUsage: emptyUsage(),\n runStartedAt: undefined,\n runMessageId: undefined,\n approvals: [],\n subagents: [],\n queued: [],\n notes: [],\n undelivered: [],\n skills: [],\n learned: [],\n learnedNow: [],\n fetches: [],\n discoveredTools: [],\n compactions: [],\n budget: undefined,\n usage: emptyUsage(),\n modelLoad: undefined,\n replan: undefined,\n error: undefined,\n stopped: false,\n messages: [],\n events: [],\n seq: 0,\n})\n\n/** Clear only the per-run view; keep the transcript, totals, status and seq counter. */\n/** The core's sentinel for a step the executor could not complete (its `BLOCKER`). */\nconst BLOCKER_MARK = '[BLOCKER]'\n\nconst resetRun = (state: AgentUiState): AgentUiState => ({\n ...createInitialAgentState(),\n status: state.status,\n messages: state.messages,\n totalUsage: state.totalUsage,\n seq: state.seq,\n learned: state.learned,\n // An MCP App's request is the user's, not the run's: it waits across runs.\n approvals: state.approvals.filter((a) => a.app && a.status === 'pending'),\n // So is what this tab sent to another tab's run, until that tab answers (a replay that opens\n // with the run's start is not an answer).\n queued: sentToOtherTab(state.queued),\n})\n\n/** The entries of what this tab sent to another tab's run and is still waiting on. */\nconst sentToOtherTab = (queued: QueuedMessageView[]): QueuedMessageView[] =>\n queued.filter((q) => q.sentTo === 'another-tab')\n\n/**\n * The entry of what this tab sent to another tab's run that a `message.queued` of that run is\n * (the oldest waiting one with the same text), or -1. By TEXT, because nothing else is shared:\n * the run there numbers its messages itself (`msg-<n>`) and the request id of `watchSession`\n * never reaches an event. Its own text, trimmed as here, or a copy the relay clipped (ending in\n * `…`, a prefix of this one). The order holds: that tab takes one tab's messages in the order\n * they were sent. A third tab sending the same words at once could be taken for this one - the\n * view only: what this tab offers back (`undelivered`) follows its own answer, never this match.\n */\nconst sentEntryOf = (queued: QueuedMessageView[], text: string): number =>\n queued.findIndex(\n (q) =>\n q.sentTo === 'another-tab' &&\n (q.text === text ||\n (text.endsWith('…') &&\n q.text.length > text.length &&\n q.text.startsWith(text.slice(0, -1)))),\n )\n\n/** Apply `fn` to the step whose id matches, leaving the rest untouched. */\nconst patchStep = (steps: StepView[], id: string, fn: (s: StepView) => StepView): StepView[] =>\n steps.map((s) => (s.id === id ? fn(s) : s))\n\n/**\n * A decided request about an MCP server's skill keeps who and what - not the server's text: the\n * preview was for the decision, and a saved conversation must not hold a server's instructions.\n */\nconst withoutSkillBody = (a: ApprovalView): ApprovalView => {\n if (!a.skill || a.skill.body === undefined) return a\n const { body: _body, ...skill } = a.skill\n return { ...a, skill }\n}\n\nconst patchApproval = (\n approvals: ApprovalView[],\n id: string,\n fn: (a: ApprovalView) => ApprovalView,\n): ApprovalView[] => approvals.map((a) => (a.id === id ? fn(a) : a))\n\nconst STATUS_OF_ACTION = {\n accept: 'accepted',\n decline: 'declined',\n cancel: 'cancelled',\n} as const\n\n/** A server's question (MCP elicitation) joins the run's view, once. */\nconst addElicitation = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'mcp.elicitation-requested' }>,\n extra: Pick<ElicitationView, 'stepId' | 'subagent' | 'remote'>,\n): AgentUiState =>\n state.elicitations?.some((e) => e.id === event.id)\n ? state\n : {\n ...state,\n elicitations: [\n ...(state.elicitations ?? []),\n {\n id: event.id,\n server: event.server,\n tool: event.tool,\n mode: event.mode,\n message: event.message,\n ...(event.requestedSchema ? { requestedSchema: event.requestedSchema } : {}),\n ...(event.url ? { url: event.url } : {}),\n ...(extra.stepId ? { stepId: extra.stepId } : {}),\n ...(extra.subagent ? { subagent: extra.subagent } : {}),\n ...(extra.remote ? { remote: true as const } : {}),\n status: 'pending',\n },\n ],\n }\n\n/** The question was answered; one that was refused before it could be shown is recorded too. */\nconst answerElicitation = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'mcp.elicitation-answered' }>,\n stepId: string | undefined,\n): AgentUiState => {\n const answered = (e: ElicitationView): ElicitationView => ({\n ...e,\n status: STATUS_OF_ACTION[event.action],\n automatic: event.automatic,\n ...(event.reason ? { reason: event.reason } : {}),\n ...(event.fields ? { fields: event.fields } : {}),\n })\n const list = state.elicitations ?? []\n return {\n ...state,\n elicitations: list.some((e) => e.id === event.id)\n ? list.map((e) => (e.id === event.id ? answered(e) : e))\n : [\n ...list,\n answered({\n id: event.id,\n server: event.server,\n tool: event.tool,\n message: '',\n ...(stepId ? { stepId } : {}),\n status: 'pending',\n }),\n ],\n }\n}\n\n/** A question the model put to the person (`ask_user`) joins the run's view, once. */\nconst addQuestion = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'user.question-asked' }>,\n extra: Pick<QuestionView, 'stepId' | 'subagent' | 'remote'>,\n): AgentUiState =>\n state.questions?.some((q) => q.id === event.id)\n ? state\n : {\n ...state,\n questions: [\n ...(state.questions ?? []),\n {\n id: event.id,\n question: event.question,\n options: event.options.map((o) => ({ ...o })),\n multiple: event.multiple,\n allowOther: event.allowOther,\n ...(extra.stepId ? { stepId: extra.stepId } : {}),\n ...(extra.subagent ? { subagent: extra.subagent } : {}),\n ...(extra.remote ? { remote: true as const } : {}),\n status: 'pending',\n },\n ],\n }\n\n/**\n * How the question ended. Only what the event says: the labels of a choice, never anything typed\n * (the core's event never carries it). An answer to a question this view never saw is not kept:\n * there is nothing to show of it.\n */\nconst answerQuestion = (\n state: AgentUiState,\n event: Extract<AgentEvent, { type: 'user.question-answered' }>,\n): AgentUiState =>\n state.questions?.some((q) => q.id === event.id)\n ? {\n ...state,\n questions: state.questions.map((q) =>\n q.id === event.id\n ? {\n ...q,\n status: event.action,\n automatic: event.automatic,\n ...(event.action === 'choice' && event.choice ? { choice: [...event.choice] } : {}),\n ...(event.reason ? { reason: event.reason } : {}),\n }\n : q,\n ),\n }\n : state\n\nconst patchSubagent = (\n subagents: SubagentView[],\n id: string,\n fn: (s: SubagentView) => SubagentView,\n): SubagentView[] => subagents.map((s) => (s.id === id ? fn(s) : s))\n\n/** The step currently executing (the last one still running). */\nconst runningStepId = (steps: StepView[]): string | undefined =>\n [...steps].reverse().find((s) => s.status === 'running')?.id\n\n/** Fold one of a subagent's own events into its compact view. */\nconst applySubagentEvent = (view: SubagentView, event: AgentEvent): SubagentView => {\n switch (event.type) {\n case 'step.start':\n return {\n ...view,\n steps: view.steps + 1,\n activity: `step ${event.index}/${event.total}: ${event.step.description}`,\n // Known only when the child runs with model tiers.\n ...(event.model !== undefined ? { model: event.model } : {}),\n ...(event.tier !== undefined ? { tier: event.tier } : {}),\n }\n case 'step.escalated':\n return { ...view, tier: event.to, ...(event.model ? { model: event.model } : {}) }\n case 'step.tool-call':\n return { ...view, toolCalls: view.toolCalls + 1, activity: `→ ${event.name}` }\n case 'final.text-delta':\n return { ...view, text: view.text + event.delta, activity: 'writing the answer' }\n case 'final':\n return { ...view, text: event.text }\n case 'usage':\n return { ...view, usage: addUsage(view.usage, event.usage) }\n default:\n return view\n }\n}\n\n/** A subagent an event came through on its way up (a `subagent.event` envelope). */\ninterface Ancestor {\n id: string\n}\n\ntype SubagentStart = Extract<AgentEvent, { type: 'subagent.start' }>\n\n/**\n * The node `id`, created when it is not there yet. An event can arrive for a subagent whose\n * `subagent.start` was never seen (a capped log replayed, a host that joined late): it gets a\n * node from what the envelope says - its name, and where in the tree it is.\n */\nconst ensureSubagent = (\n state: AgentUiState,\n id: string,\n name: string,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n if (state.subagents.some((s) => s.id === id)) return state\n const parentId = ancestors[ancestors.length - 1]?.id\n const parent = parentId ? state.subagents.find((s) => s.id === parentId) : undefined\n const stepId = parent ? parent.stepId : runningStepId(state.steps)\n const node: SubagentView = {\n id,\n name,\n task: '',\n ...(parentId ? { parentId } : {}),\n depth: ancestors.length + 1,\n status: 'running',\n ...(stepId ? { stepId } : {}),\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n }\n return { ...state, subagents: [...state.subagents, node] }\n}\n\n/** What a `subagent.start` says about its node (everything but the counters). */\nconst startSubagent = (\n state: AgentUiState,\n event: SubagentStart,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n // The envelopes around an event are its ancestry; a start that came bare says it itself\n // (`parentId` is then a subagent only below depth 1 - at depth 1 it is the run's id).\n const depth = Math.max(event.depth ?? 1, ancestors.length + 1)\n const parentId = ancestors[ancestors.length - 1]?.id ?? (depth > 1 ? event.parentId : undefined)\n const told = {\n name: event.name,\n task: event.task,\n depth,\n ...(parentId ? { parentId } : {}),\n ...(event.profile ? { profile: event.profile } : {}),\n ...(event.dynamic ? { dynamic: true as const } : {}),\n ...(event.role ? { role: event.role } : {}),\n ...(event.tools ? { tools: event.tools } : {}),\n }\n // Already there (its events arrived first): the start fills in what they could not say.\n if (state.subagents.some((s) => s.id === event.id)) {\n return {\n ...state,\n subagents: patchSubagent(state.subagents, event.id, (s) => ({ ...s, ...told })),\n }\n }\n const parent = parentId ? state.subagents.find((s) => s.id === parentId) : undefined\n // A nested one belongs to the step that delegated its top-most ancestor.\n const stepId = parent ? parent.stepId : runningStepId(state.steps)\n const node: SubagentView = {\n id: event.id,\n ...told,\n status: 'running',\n stepId,\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n activity: 'starting',\n steps: 0,\n toolCalls: 0,\n text: '',\n usage: emptyUsage(),\n }\n return { ...state, subagents: [...state.subagents, node] }\n}\n\n/** How long a subagent ran, when both ends were stamped. */\nconst subagentDuration = (s: SubagentView, at?: number): Partial<SubagentView> =>\n at !== undefined && s.startedAt !== undefined ? { durationMs: Math.max(0, at - s.startedAt) } : {}\n\nconst addMedia = (state: AgentUiState, view: MediaView): AgentUiState => ({\n ...state,\n media: [...(state.media ?? []), view],\n ...(view.stepId\n ? {\n steps: patchStep(state.steps, view.stepId, (s) => ({\n ...s,\n media: [...(s.media ?? []), view],\n })),\n }\n : {}),\n})\n\nconst mediaOf = (\n event: Extract<AgentEvent, { type: 'media.generated' }>,\n withStep: boolean,\n): MediaView => ({\n kind: event.kind,\n path: event.path,\n mediaType: event.mediaType,\n bytes: event.bytes,\n model: event.model,\n ...(event.references\n ? {\n references: {\n used: event.references.used === true,\n count: event.references.count,\n paths: [...event.references.paths],\n },\n }\n : {}),\n ...(withStep && event.step ? { stepId: event.step.id } : {}),\n})\n\ntype McpAppEvent = Extract<AgentEvent, { type: 'mcp.app' }>\n\n/**\n * An MCP App joins the run's view, once, and the tool call it came with is tagged. `by` is the\n * subagent the call came through (its step ids are its own: no step then).\n */\nconst addApp = (state: AgentUiState, event: McpAppEvent, by?: AppView['by']): AgentUiState => {\n if (state.apps?.some((a) => a.id === event.id)) return state\n const view: AppView = {\n id: event.id,\n server: event.server,\n tool: event.tool,\n toolName: event.toolName,\n resourceUri: event.resourceUri,\n input: event.input,\n ...(event.result ? { result: event.result } : {}),\n ...(!by && event.step ? { stepId: event.step.id } : {}),\n ...(by ? { by } : {}),\n }\n const steps =\n !by && event.step\n ? patchStep(state.steps, event.step.id, (s) => {\n // The event comes while its call is still running: the newest untagged call of it.\n let i = s.toolCalls.length - 1\n while (i >= 0 && !(s.toolCalls[i].name === event.tool && !s.toolCalls[i].app)) i -= 1\n if (i < 0) return s\n const toolCalls = s.toolCalls.slice()\n toolCalls[i] = { ...toolCalls[i], app: event.id }\n return { ...s, toolCalls }\n })\n : state.steps\n return { ...state, steps, apps: [...(state.apps ?? []), view] }\n}\n\ntype FileWritten = Extract<AgentEvent, { type: 'file.written' }>\n\n/**\n * A file the run wrote: one entry per path (a second write updates it in place), newest size\n * and type. `by` is the subagent it came through; its step ids are its own, so no step then.\n */\nconst fileWritten = (\n state: AgentUiState,\n event: FileWritten,\n by?: WrittenFileView['by'],\n): AgentUiState => {\n const files = state.writtenFiles ?? []\n const i = files.findIndex((f) => f.path === event.path)\n const view: WrittenFileView = {\n path: event.path,\n mediaType: event.mediaType,\n bytes: event.bytes,\n writes: (i >= 0 ? files[i].writes : 0) + 1,\n ...(!by && event.step ? { stepId: event.step.id } : {}),\n ...(by ? { by } : {}),\n }\n return {\n ...state,\n writtenFiles: i >= 0 ? files.map((f, k) => (k === i ? view : f)) : [...files, view],\n }\n}\n\n/** A file deleted later in the run is not one of its files any more. */\nconst fileDeleted = (state: AgentUiState, path: string): AgentUiState =>\n state.writtenFiles?.some((f) => f.path === path)\n ? { ...state, writtenFiles: state.writtenFiles.filter((f) => f.path !== path) }\n : state\n\nconst transcriptOf = (\n event: Extract<AgentEvent, { type: 'media.transcribed' }>,\n): TranscriptView => ({\n source: event.source,\n name: event.name,\n text: event.text,\n ...(event.language ? { language: event.language } : {}),\n ...(event.durationInSeconds !== undefined ? { durationInSeconds: event.durationInSeconds } : {}),\n model: event.model,\n})\n\n/**\n * Fold a `subagent.*` event into the tree. `ancestors` are the subagents it came up through\n * (outermost first): a subagent's own subagents arrive nested,\n * `subagent.event{ A, subagent.event{ G, event } }`, and each level lands on its own node.\n */\nconst applySubagent = (\n state: AgentUiState,\n event: Extract<\n AgentEvent,\n { type: 'subagent.start' | 'subagent.event' | 'subagent.complete' | 'subagent.error' }\n >,\n ancestors: Ancestor[],\n ctx: EventContext,\n): AgentUiState => {\n switch (event.type) {\n case 'subagent.start':\n return startSubagent(state, event, ancestors, ctx)\n\n case 'subagent.event': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n const inner = event.event\n switch (inner.type) {\n case 'subagent.start':\n case 'subagent.event':\n case 'subagent.complete':\n case 'subagent.error':\n return applySubagent(known, inner, [...ancestors, { id: event.id }], ctx)\n\n // A helper the model started asks through the run's own consent gate (the event says\n // which helper): its request is the user's to answer, like the run's. A subagent with\n // a gate of its own (no `subagent` on the event) is its host's business.\n case 'tool.approval-requested': {\n if (!inner.subagent || known.approvals.some((a) => a.id === inner.id)) return known\n const node = known.subagents.find((s) => s.id === inner.subagent!.id)\n return {\n ...known,\n approvals: [\n ...known.approvals,\n {\n id: inner.id,\n name: inner.name,\n input: inner.input,\n readOnly: inner.readOnly,\n // The helper's own step ids mean nothing here: the step that delegated it does.\n stepId: node?.stepId,\n subagent: {\n id: inner.subagent.id,\n depth: inner.subagent.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n ...(inner.skill ? { skill: inner.skill } : {}),\n ...(inner.rule ? { rule: inner.rule } : {}),\n ...(ctx.remote ? { remote: true as const } : {}),\n status: 'pending',\n },\n ],\n }\n }\n case 'tool.approval-resolved':\n return known.approvals.some((a) => a.id === inner.id)\n ? {\n ...known,\n approvals: patchApproval(known.approvals, inner.id, (a) =>\n withoutSkillBody({\n ...a,\n status: inner.approved ? 'approved' : 'denied',\n reason: inner.reason,\n automatic: inner.automatic,\n }),\n ),\n }\n : known\n\n // A server asks the user during a subagent's tool call (the connection lets helpers\n // ask): the question is the user's to answer, like the run's own.\n case 'mcp.elicitation-requested': {\n const node = inner.subagent\n ? known.subagents.find((s) => s.id === inner.subagent!.id)\n : undefined\n return addElicitation(known, inner, {\n ...(ctx.remote ? { remote: true as const } : {}),\n // The subagent's own step ids mean nothing here: the step that delegated it does.\n stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,\n ...(inner.subagent\n ? {\n subagent: {\n id: inner.subagent.id,\n depth: inner.subagent.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n }\n : {}),\n })\n }\n case 'mcp.elicitation-answered':\n return answerElicitation(\n known,\n inner,\n known.subagents.find((s) => s.id === event.id)?.stepId,\n )\n\n // A helper (or a subagent the host defined) asks the person through the run's handler:\n // the question is the person's to answer, like the run's own, marked with who asks.\n case 'user.question-asked': {\n const asker = inner.subagent ?? { id: event.id, depth: ancestors.length + 1 }\n const node = known.subagents.find((s) => s.id === asker.id)\n return addQuestion(known, inner, {\n ...(ctx.remote ? { remote: true as const } : {}),\n // The helper's own step ids mean nothing here: the step that delegated it does.\n stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,\n subagent: {\n id: asker.id,\n depth: asker.depth,\n ...(node ? { name: node.name } : {}),\n ...(node?.role ? { role: node.role } : {}),\n },\n })\n }\n case 'user.question-answered':\n return answerQuestion(known, inner)\n\n // What a subagent generated is in the same workspace: it shows in the turn (its step\n // ids are its own, so it is tied to no step here).\n case 'media.generated':\n return addMedia(known, mediaOf(inner, false))\n case 'media.transcribed':\n return { ...known, transcripts: [...(known.transcripts ?? []), transcriptOf(inner)] }\n\n // A subagent works in the same workspace: what it wrote belongs to the turn, and says\n // who wrote it.\n case 'file.written': {\n const node = known.subagents.find((s) => s.id === event.id)\n return fileWritten(known, inner, {\n id: event.id,\n name: node?.name ?? event.name,\n ...(node?.role ? { role: node.role } : {}),\n })\n }\n case 'file.deleted':\n return fileDeleted(known, inner.path)\n // An app a subagent's call came with is shown in the turn too, and says whose call it was.\n case 'mcp.app': {\n // Another tab's app is that tab's: a frame here would run it a second time.\n if (ctx.remote) return known\n const node = known.subagents.find((s) => s.id === event.id)\n return addApp(known, inner, {\n id: event.id,\n name: node?.name ?? event.name,\n ...(node?.role ? { role: node.role } : {}),\n })\n }\n\n default:\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) =>\n applySubagentEvent(s, inner),\n ),\n }\n }\n }\n\n case 'subagent.complete': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) => ({\n ...s,\n status: 'done',\n activity: 'done',\n text: event.text,\n usage: event.usage,\n ...subagentDuration(s, ctx.at),\n })),\n }\n }\n\n case 'subagent.error': {\n const known = ensureSubagent(state, event.id, event.name, ancestors, ctx)\n return {\n ...known,\n subagents: patchSubagent(known.subagents, event.id, (s) => ({\n ...s,\n status: event.stopped ? 'stopped' : 'error',\n activity: event.stopped ? 'stopped' : 'failed',\n error: event.error,\n // A helper says what it had spent when it ended; a static subagent does not.\n ...(event.usage ? { usage: event.usage } : {}),\n ...subagentDuration(s, ctx.at),\n })),\n }\n }\n }\n}\n\n/**\n * The flat `subagents` list as a tree: each node with the subagents it started, in the order\n * they started. A node whose parent is not in the list (its start was never seen) is a root.\n */\nexport const subagentTree = (subagents: SubagentView[]): SubagentNode[] => {\n const nodes = new Map<string, SubagentNode>()\n for (const s of subagents) nodes.set(s.id, { ...s, children: [] })\n // A parent chain that comes back to the node is not a tree: such a node is a root.\n const loops = (node: SubagentNode): boolean => {\n let up = node.parentId\n for (let i = 0; up !== undefined && i <= nodes.size; i++) {\n if (up === node.id) return true\n up = nodes.get(up)?.parentId\n }\n return false\n }\n const roots: SubagentNode[] = []\n for (const node of nodes.values()) {\n const parent =\n node.parentId !== undefined && !loops(node) ? nodes.get(node.parentId) : undefined\n if (parent) parent.children.push(node)\n else roots.push(node)\n }\n return roots\n}\n\n/** Finalize the trailing pending assistant message with the given content. */\nconst finalizeAssistant = (\n messages: ChatMessage[],\n content: string,\n extra: Partial<ChatMessage> = {},\n): ChatMessage[] => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === 'assistant' && m.pending) {\n const next = messages.slice()\n next[i] = { ...m, content: content || m.content, pending: false, ...extra }\n return next\n }\n }\n return messages\n}\n\n/** Duration of the current run at `at`, when both ends are known. */\nconst runDuration = (state: AgentUiState, at?: number): Partial<ChatMessage> =>\n at !== undefined && state.runStartedAt !== undefined\n ? { durationMs: Math.max(0, at - state.runStartedAt) }\n : {}\n\n/** Update the trailing pending assistant message's streaming content. */\nconst streamAssistant = (messages: ChatMessage[], content: string): ChatMessage[] => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === 'assistant' && m.pending) {\n const next = messages.slice()\n next[i] = { ...m, content }\n return next\n }\n }\n return messages\n}\n\n/** The queue entry of a goal that waits for the session (`session.busy`). */\nconst WAITING_ID = 'waiting-for-session'\n\n/** The state without a wait for the session (the run got it, or will not wait any more). */\nconst withoutBusy = (state: AgentUiState): AgentUiState => {\n if (!state.sessionBusy) return state\n const { sessionBusy: _over, ...rest } = state\n void _over\n return { ...rest, queued: rest.queued.filter((q) => q.id !== WAITING_ID) }\n}\n\n/** The state without the turn shown at submit (`submitted`): the run's own turn replaces it. */\nconst withoutSubmitted = (state: AgentUiState): AgentUiState => {\n if (!state.submitted) return state\n const { submitted, ...rest } = state\n const ids = new Set([submitted.userId, submitted.assistantId])\n return { ...rest, messages: rest.messages.filter((m) => !ids.has(m.id)) }\n}\n\n/** Keep the turn shown at submit, as the run's (it ended before its `run.start`, with an error). */\nconst keepSubmitted = (state: AgentUiState): AgentUiState => {\n if (!state.submitted) return state\n const { submitted: _kept, ...rest } = state\n void _kept\n return rest\n}\n\nconst applyEvent = (state: AgentUiState, event: AgentEvent, ctx: EventContext): AgentUiState => {\n switch (event.type) {\n case 'run.start': {\n // Start a new run: clear the previous run's view but keep the transcript,\n // then push the user turn and a pending assistant turn to stream into (in place of the\n // turn shown when it was sent).\n const base = resetRun(ctx.remote ? state : withoutSubmitted(state))\n const userId = `msg-${base.seq}`\n const assistantId = `msg-${base.seq + 1}`\n // When the turn began: what places it among another tab's turns when both save the chat.\n const began = ctx.at !== undefined ? { startedAt: ctx.at } : {}\n return {\n ...base,\n // Another tab's run keeps the view of it; a run of this tab's ends it (and any wait).\n ...(ctx.remote && state.remote ? { remote: state.remote } : {}),\n // ...and this tab's sent turn, still waiting for its own run.start (or a session.busy).\n ...(ctx.remote && state.submitted ? { submitted: state.submitted } : {}),\n goal: event.goal,\n runStartedAt: ctx.at,\n runMessageId: assistantId,\n messages: [\n ...base.messages,\n {\n id: userId,\n role: 'user',\n content: event.goal,\n pending: false,\n ...(ctx.remote ? { remote: true as const } : {}),\n ...began,\n ...(ctx.attachments?.length ? { attachments: ctx.attachments } : {}),\n },\n {\n id: assistantId,\n role: 'assistant',\n content: '',\n pending: true,\n ...(ctx.remote ? { remote: true as const } : {}),\n ...began,\n },\n ],\n seq: base.seq + 2,\n }\n }\n\n case 'model.load':\n return { ...state, modelLoad: { progress: event.progress, text: event.text } }\n\n case 'plan.thought-delta':\n return { ...state, planThought: state.planThought + event.delta }\n\n case 'plan.created':\n return {\n ...state,\n plan: event.plan,\n planThought: state.planThought || event.plan.thought,\n }\n\n case 'plan.revised':\n return {\n ...state,\n plan: event.plan,\n // `replan.decision` came first: keep its \"because the user spoke\" flag.\n replan: {\n mode: 'revise',\n reason: event.reason,\n ...(state.replan?.byUser ? { byUser: true } : {}),\n },\n }\n\n case 'plan.step-added':\n // Execution is tracked from step.* events; the plan itself already\n // arrived via plan.created. Nothing to fold here.\n return state\n\n case 'step.start': {\n const view: StepView = {\n id: event.step.id,\n index: event.index,\n total: event.total,\n step: event.step,\n text: '',\n reasoning: '',\n toolCalls: [],\n status: 'running',\n blocked: false,\n // Only with `config.executorTiers`: without it the view is what it always was.\n ...(event.tier !== undefined ? { tier: event.tier } : {}),\n ...(event.model !== undefined ? { model: event.model } : {}),\n ...(event.tierReason !== undefined ? { tierReason: event.tierReason } : {}),\n }\n // `total` is the plan's length as this step starts - a replan may have grown or cut it\n // since the earlier steps started: they show the same, so the rows read 1/2, 2/2, not\n // 1/1, 2/2.\n const steps = state.steps.map((s) =>\n s.total === event.total ? s : { ...s, total: event.total },\n )\n return { ...state, steps: [...steps, view] }\n }\n\n case 'step.escalated':\n // The attempt on `from` is over and the step CONTINUES on `to`. What the failed attempt\n // wrote is not the next attempt's text: it moves onto the escalation. Its tool calls\n // happened (the core keeps them in the step's result and shows them to the stronger\n // model), so they stay, marked with the attempt they belong to.\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => {\n const attempt = (s.escalations?.length ?? 0) + 1\n return {\n ...s,\n tier: event.to,\n ...(event.model ? { model: event.model } : {}),\n text: '',\n reasoning: '',\n toolCalls: s.toolCalls.map((c) => (c.attempt === undefined ? { ...c, attempt } : c)),\n escalations: [\n ...(s.escalations ?? []),\n {\n from: event.from,\n to: event.to,\n reason: event.reason,\n ...(event.model ? { model: event.model } : {}),\n ...(s.text.trim() ? { text: s.text } : {}),\n },\n ],\n }\n }),\n }\n\n case 'step.reasoning-delta':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n reasoning: s.reasoning + event.delta,\n })),\n }\n\n case 'step.text-delta':\n return {\n ...state,\n // \"[BLOCKER]\" is the executor's signal to the core that a step cannot be completed (the\n // core strips it from the step's summary): never a word for the user. Stripped from the\n // text as it accumulates, so a marker split across two deltas goes too.\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n text: (s.text + event.delta).split(BLOCKER_MARK).join(''),\n })),\n }\n\n case 'step.tool-call': {\n // An app can be told before its call is (the tool runs while the stream is read): the\n // call then takes the app of this step and tool that no call has yet.\n const tagged = new Set(\n state.steps.flatMap((s) => s.toolCalls.map((c) => c.app).filter(Boolean)),\n )\n const early = state.apps?.find(\n (a) => a.stepId === event.step.id && a.tool === event.name && !tagged.has(a.id),\n )\n const call: ToolCallView = {\n name: event.name,\n input: event.input,\n status: 'calling',\n inputTokens: approxTokens(event.input),\n ...(ctx.at !== undefined ? { startedAt: ctx.at } : {}),\n ...(early ? { app: early.id } : {}),\n }\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n toolCalls: [...s.toolCalls, call],\n })),\n }\n }\n\n case 'step.tool-result':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => {\n // Match the last still-calling entry for this tool name.\n let done = false\n const toolCalls = s.toolCalls\n .slice()\n .reverse()\n .map((c) => {\n if (!done && c.status === 'calling' && c.name === event.name) {\n done = true\n return {\n ...c,\n output: event.output,\n ok: event.ok,\n status: 'done' as const,\n outputTokens: approxTokens(event.output),\n ...(isReplayedToolOutput(event.output) ? { replayed: true } : {}),\n ...(ctx.at !== undefined && c.startedAt !== undefined\n ? { durationMs: Math.max(0, ctx.at - c.startedAt) }\n : {}),\n }\n }\n return c\n })\n .reverse()\n return { ...s, toolCalls }\n }),\n }\n\n case 'step.complete':\n return {\n ...state,\n steps: patchStep(state.steps, event.step.id, (s) => ({\n ...s,\n status: 'done',\n summary: event.result.summary,\n // With tiers: where the step finished and how it got there. The result's list is the\n // authority; an escalation seen live keeps what only the event told (model, text).\n ...(event.result.tier !== undefined ? { tier: event.result.tier } : {}),\n ...(event.result.model !== undefined ? { model: event.result.model } : {}),\n ...(event.result.escalations?.length\n ? {\n escalations: event.result.escalations.map((e, i) => {\n const live = s.escalations?.[i]\n return live && live.from === e.from && live.to === e.to\n ? { ...live, reason: e.reason }\n : { from: e.from, to: e.to, reason: e.reason }\n }),\n }\n : {}),\n blocked: event.result.blocked,\n // The result carries the authoritative, ordered tool-call list; keep\n // the timing the streamed calls measured (matched in order per name).\n toolCalls: (() => {\n const seen = new Map<string, number>()\n return event.result.toolCalls.map((c) => {\n const nth = seen.get(c.name) ?? 0\n seen.set(c.name, nth + 1)\n const streamed = s.toolCalls.filter((t) => t.name === c.name)[nth]\n return {\n name: c.name,\n input: c.input,\n output: c.output,\n ok: c.ok,\n status: 'done' as const,\n inputTokens: approxTokens(c.input),\n outputTokens: approxTokens(c.output),\n ...(streamed?.startedAt !== undefined ? { startedAt: streamed.startedAt } : {}),\n ...(streamed?.durationMs !== undefined ? { durationMs: streamed.durationMs } : {}),\n // With tiers the list holds every attempt's calls, in the order they were made.\n ...(streamed?.attempt !== undefined ? { attempt: streamed.attempt } : {}),\n ...(isReplayedToolOutput(c.output) ? { replayed: true } : {}),\n // The MCP App the call came with (only the stream told it).\n ...(streamed?.app !== undefined ? { app: streamed.app } : {}),\n }\n })\n })(),\n })),\n }\n\n case 'replan.decision': {\n if (!event.failed) {\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n ...(event.confidence !== undefined ? { confidence: event.confidence } : {}),\n },\n }\n }\n // The replanner could not decide: `continue` is the fallback and the run goes on. The\n // failure itself came as the `error` event (phase 'replan') just before; it is pinned to\n // the step the replanner ran after, so the warning stays in that turn's activity.\n const error = state.replan?.failed ? state.replan.error : undefined\n const last = state.steps[state.steps.length - 1]\n return {\n ...state,\n replan: {\n mode: event.mode,\n reason: event.reason,\n ...(event.byUser ? { byUser: true } : {}),\n failed: true,\n ...(error ? { error } : {}),\n },\n steps: last\n ? patchStep(state.steps, last.id, (s) => ({\n ...s,\n replanFailed: error ?? event.reason,\n }))\n : state.steps,\n }\n }\n\n case 'decision': {\n // The decision model is asked after a step (continue / finish): the note belongs to it.\n const view: DecisionView = {\n point: event.point,\n accepted: event.accepted,\n ...(event.choice !== undefined ? { choice: event.choice } : {}),\n ...(event.confidence !== undefined ? { confidence: event.confidence } : {}),\n threshold: event.threshold,\n ...(event.reason ? { reason: event.reason } : {}),\n durationMs: event.durationMs,\n ...(event.model ? { model: event.model } : {}),\n }\n const last = state.steps[state.steps.length - 1]\n return last\n ? {\n ...state,\n steps: patchStep(state.steps, last.id, (s) => ({\n ...s,\n decisions: [...(s.decisions ?? []), view],\n })),\n }\n : { ...state, decisions: [...(state.decisions ?? []), view] }\n }\n\n case 'media.generated':\n return addMedia(state, mediaOf(event, true))\n\n case 'media.transcribed':\n return { ...state, transcripts: [...(state.transcripts ?? []), transcriptOf(event)] }\n\n case 'file.written':\n return fileWritten(state, event)\n\n case 'file.deleted':\n return fileDeleted(state, event.path)\n\n case 'mcp.app':\n // Another tab's app is that tab's: a frame here would load it and run its calls again.\n return ctx.remote ? state : addApp(state, event)\n\n case 'message.queued': {\n if (state.queued.some((q) => q.id === event.id)) return state\n const entry: QueuedMessageView = {\n id: event.id,\n text: event.text,\n ...(event.origin ? { origin: event.origin } : {}),\n }\n // Another tab's run took what THIS tab sent it: its entry takes the place of the one that\n // waited for that tab - shown once, not twice.\n const mine =\n ctx.remote && event.origin === 'another-tab' ? sentEntryOf(state.queued, event.text) : -1\n if (mine < 0) return { ...state, queued: [...state.queued, entry] }\n return { ...state, queued: state.queued.map((q, i) => (i === mine ? entry : q)) }\n }\n\n case 'message.delivered': {\n // Anchored where it landed: inside the executing step (between tool calls),\n // after the step that just ended (a step boundary), or at the end (the answer).\n const anchor =\n event.at === 'round'\n ? runningStepId(state.steps)\n : event.at === 'step'\n ? state.steps[state.steps.length - 1]?.id\n : undefined\n return {\n ...state,\n queued: state.queued.filter((q) => q.id !== event.id),\n notes: [\n ...state.notes,\n {\n id: event.id,\n text: event.text,\n at: event.at,\n ...(anchor ? { stepId: anchor } : {}),\n ...(event.origin ? { origin: event.origin } : {}),\n },\n ],\n }\n }\n\n case 'final.text-delta': {\n const finalText = state.finalText + event.delta\n return { ...state, finalText, messages: streamAssistant(state.messages, finalText) }\n }\n\n case 'final':\n return {\n ...state,\n finalText: event.text,\n messages: finalizeAssistant(state.messages, event.text, runDuration(state, ctx.at)),\n }\n\n case 'final.reasoning-delta':\n return { ...state, finalReasoning: state.finalReasoning + event.delta }\n\n case 'usage':\n // An app's sampling is no run's: it counts in the conversation's total only, never in a\n // run's usage (nor, through it, on an answer).\n if (event.phase === 'app') {\n return { ...state, totalUsage: addUsage(state.totalUsage, event.usage) }\n }\n return {\n ...state,\n usage: addUsage(state.usage, event.usage),\n totalUsage: addUsage(state.totalUsage, event.usage),\n }\n\n case 'mcp.elicitation-requested':\n return addElicitation(state, event, {\n // Asked in the tab that runs the tool call: shown here, answered there.\n ...(ctx.remote ? { remote: true as const } : {}),\n stepId: event.step?.id,\n ...(event.subagent ? { subagent: event.subagent } : {}),\n })\n\n case 'mcp.elicitation-answered':\n return answerElicitation(state, event, runningStepId(state.steps))\n\n case 'user.question-asked':\n return addQuestion(state, event, {\n // Asked in the tab that runs the agent: shown here, answered there only.\n ...(ctx.remote ? { remote: true as const } : {}),\n stepId: event.step?.id,\n ...(event.subagent ? { subagent: event.subagent } : {}),\n })\n\n case 'user.question-answered':\n return answerQuestion(state, event)\n\n case 'tool.approval-requested':\n return {\n ...state,\n approvals: [\n ...state.approvals,\n {\n id: event.id,\n name: event.name,\n input: event.input,\n readOnly: event.readOnly,\n stepId: event.step?.id,\n ...(event.subagent ? { subagent: event.subagent } : {}),\n ...(event.app ? { app: event.app } : {}),\n ...(event.skill ? { skill: event.skill } : {}),\n ...(event.rule ? { rule: event.rule } : {}),\n // Asked in the tab that runs the tool: shown here, answered there.\n ...(ctx.remote ? { remote: true as const } : {}),\n status: 'pending',\n },\n ],\n }\n\n case 'tool.approval-resolved': {\n const known = state.approvals.some((a) => a.id === event.id)\n const decided = (a: ApprovalView): ApprovalView =>\n withoutSkillBody({\n ...a,\n status: event.approved ? 'approved' : 'denied',\n reason: event.reason,\n automatic: event.automatic,\n })\n return {\n ...state,\n approvals: known\n ? patchApproval(state.approvals, event.id, decided)\n : // A policy denial arrives without a request: record it too.\n [\n ...state.approvals,\n decided({\n id: event.id,\n name: event.name,\n input: undefined,\n readOnly: false,\n stepId: runningStepId(state.steps),\n status: 'pending',\n }),\n ],\n }\n }\n\n case 'subagent.start':\n case 'subagent.event':\n case 'subagent.complete':\n case 'subagent.error':\n return applySubagent(state, event, [], ctx)\n\n case 'skill.activated':\n return state.skills.includes(event.name)\n ? state\n : { ...state, skills: [...state.skills, event.name] }\n\n case 'skill.learned': {\n const before = state.learned.find((l) => l.name === event.name)\n const lesson: LessonView = {\n name: event.name,\n description: event.description,\n // A rewrite of a lesson we know goes up one; a lesson we never saw (an event for a store\n // loaded before this view existed) starts at 2 when the core says it is an update.\n revision: event.update ? (before?.revision ?? 1) + 1 : 1,\n chars: event.chars,\n sources: event.sources,\n }\n return {\n ...state,\n learned: before\n ? state.learned.map((l) => (l.name === event.name ? lesson : l))\n : [...state.learned, lesson],\n learnedNow: state.learnedNow.includes(event.name)\n ? state.learnedNow\n : [...state.learnedNow, event.name],\n }\n }\n\n case 'skill.forgotten':\n return { ...state, learned: state.learned.filter((l) => l.name !== event.name) }\n\n case 'egress.request':\n return {\n ...state,\n fetches: [\n ...state.fetches,\n {\n url: event.url,\n allowed: event.allowed,\n ...(event.status !== undefined ? { status: event.status } : {}),\n ...(event.reason ? { reason: event.reason } : {}),\n },\n ],\n }\n\n case 'tools.discovered':\n return {\n ...state,\n discoveredTools: [...new Set([...state.discoveredTools, ...event.names])],\n }\n\n case 'context.compacted':\n return {\n ...state,\n compactions: [\n ...state.compactions,\n { scope: event.scope, beforeTokens: event.beforeTokens, afterTokens: event.afterTokens },\n ],\n }\n\n case 'budget.exceeded':\n return { ...state, budget: { kind: event.kind, tokens: event.tokens, cap: event.cap } }\n\n case 'session.busy':\n // What was shown as sent waits now: a queued item, not a turn of the transcript.\n state = withoutSubmitted(state)\n return {\n ...state,\n sessionBusy: { heldBy: event.heldBy, ...(ctx.goal ? { goal: ctx.goal } : {}) },\n // What the user sent waits with the run: shown as queued, not lost.\n ...(ctx.goal\n ? {\n queued: [\n ...state.queued.filter((q) => q.id !== WAITING_ID),\n { id: WAITING_ID, text: ctx.goal, session: event.heldBy },\n ],\n }\n : {}),\n }\n\n case 'session.acquired':\n return withoutBusy(state)\n\n case 'stopped':\n // A run of this tab stopped while it only waited for the session: nothing of it began, and\n // the run in view (another tab's, followed here) is not the one that stopped.\n if (!ctx.remote && state.sessionBusy) return withoutBusy(state)\n // Stopped before it began: the turn shown at submit goes (the text goes back to the user).\n if (!ctx.remote && state.submitted) return withoutSubmitted(state)\n return {\n ...withoutBusy(state),\n stopped: true,\n // Nothing of the run is waiting any more once it has stopped (an app's request is not\n // the run's).\n approvals: state.approvals.map((a) =>\n a.status === 'pending' && !a.app\n ? withoutSkillBody({ ...a, status: 'denied' as const, reason: 'stopped' })\n : a,\n ),\n ...(state.elicitations\n ? {\n elicitations: state.elicitations.map((e) =>\n e.status === 'pending'\n ? { ...e, status: 'cancelled' as const, automatic: true, reason: 'stopped' }\n : e,\n ),\n }\n : {}),\n // Nobody is asked any more once the run has stopped.\n ...(state.questions\n ? {\n questions: state.questions.map((q) =>\n q.status === 'pending'\n ? { ...q, status: 'stopped' as const, automatic: true, reason: 'stopped' }\n : q,\n ),\n }\n : {}),\n // What it had written, or nothing - the chat says \"stopped\" through its labels.\n messages: finalizeAssistant(state.messages, state.finalText, {\n ...runDuration(state, ctx.at),\n stopped: true,\n }),\n }\n\n case 'error':\n // A per-step ('execute'/'plan'/...) error does not end the run — only a\n // top-level 'run' error does, and it arrives with no trailing `final`.\n // A replanner that failed is not an error of the run at all: the run continues with its\n // plan. It is held for the `replan.decision { failed }` that follows, never in `error`.\n if (event.phase === 'replan') {\n return {\n ...state,\n replan: { mode: 'continue', reason: '', failed: true, error: event.error },\n }\n }\n return event.phase === 'run'\n ? {\n ...withoutBusy(keepSubmitted(state)),\n error: event.error,\n errorCode: event.code,\n messages: finalizeAssistant(\n state.messages,\n state.finalText || `Error: ${event.error}`,\n { ...runDuration(state, ctx.at), error: true },\n ),\n }\n : { ...state, error: event.error }\n\n case 'retry':\n return state\n\n default:\n return state\n }\n}\n\n/**\n * Mirror the current run's activity onto its assistant message, so every turn\n * of the transcript keeps its own tool calls, thoughts, subagents and usage\n * after the next run starts. Only copies what changed (cheap on every event).\n */\nconst syncRunMessage = (state: AgentUiState): AgentUiState => {\n const id = state.runMessageId\n if (!id) return state\n const i = state.messages.findIndex((m) => m.id === id)\n if (i < 0) return state\n const m = state.messages[i]\n // An app's requests are not the run's decisions: they are never kept on its message.\n const decided = state.approvals.filter((a) => a.status !== 'pending' && !a.app)\n const patch: Partial<ChatMessage> = {}\n if (m.steps !== state.steps) patch.steps = state.steps\n if (m.subagents !== state.subagents) patch.subagents = state.subagents\n if (state.notes.length > 0 && m.notes !== state.notes) patch.notes = state.notes\n if (m.usage !== state.usage) patch.usage = state.usage\n if ((m.reasoning ?? '') !== state.finalReasoning) patch.reasoning = state.finalReasoning\n if (m.skills !== state.skills) patch.skills = state.skills\n if (state.learnedNow.length > 0 && m.learned !== state.learnedNow)\n patch.learned = state.learnedNow\n if (state.fetches.length > 0 && m.fetches !== state.fetches) patch.fetches = state.fetches\n if (state.media && m.media !== state.media) patch.media = state.media\n if (state.transcripts && m.transcripts !== state.transcripts)\n patch.transcripts = state.transcripts\n if (state.writtenFiles && m.writtenFiles !== state.writtenFiles)\n patch.writtenFiles = state.writtenFiles\n if (state.apps && m.apps !== state.apps) patch.apps = state.apps\n if (\n (m.approvals?.length ?? 0) !== decided.length ||\n decided.some((a, k) => m.approvals?.[k] !== a)\n ) {\n patch.approvals = decided\n }\n if (Object.keys(patch).length === 0) return state\n const messages = state.messages.slice()\n messages[i] = { ...m, ...patch }\n return { ...state, messages }\n}\n\n/**\n * The consent requests THIS tab can answer: pending, and not asked in another tab (a run of the\n * conversation going on there - those are shown, and answered only there). What `useAgent`\n * returns as `pendingApprovals`.\n */\nexport const pendingApprovalsOf = (state: Pick<AgentUiState, 'approvals'>): ApprovalView[] =>\n state.approvals.filter((a) => a.status === 'pending' && !a.remote)\n\n/**\n * The status to show: `running` while another tab runs this conversation (`remote`) and this\n * tab is otherwise ready or idle - never over `initializing` or `error`, which the host must see.\n */\nexport const agentStatusOf = (\n state: Pick<AgentUiState, 'status' | 'remote'>,\n): AgentUiState['status'] =>\n state.remote?.running && (state.status === 'ready' || state.status === 'idle')\n ? 'running'\n : state.status\n\nexport const agentStateReducer = (state: AgentUiState, action: AgentAction): AgentUiState => {\n switch (action.type) {\n case 'reset':\n // A full \"new conversation\" clear — unlike run.start, this also drops the\n // transcript. Keep status (the agent is still built) and the seq counter\n // (so ids stay unique across resets).\n return {\n ...createInitialAgentState(),\n status: state.status,\n seq: state.seq,\n learned: state.learned,\n }\n case 'notebook':\n return { ...state, learned: action.lessons }\n case 'submitted': {\n if (state.submitted) return state\n const userId = `msg-${state.seq}`\n const assistantId = `msg-${state.seq + 1}`\n return {\n ...state,\n submitted: { userId, assistantId },\n messages: [\n ...state.messages,\n {\n id: userId,\n role: 'user',\n content: action.goal,\n pending: false,\n ...(action.attachments?.length ? { attachments: action.attachments } : {}),\n },\n { id: assistantId, role: 'assistant', content: '', pending: true },\n ],\n seq: state.seq + 2,\n }\n }\n case 'status':\n return {\n ...state,\n status: action.status,\n error: action.status === 'error' ? action.error : undefined,\n errorCode: undefined,\n }\n case 'remote': {\n const remote = action.remote\n if (!remote) {\n const { remote: _gone, ...rest } = state\n void _gone\n return rest\n }\n // That tab went away mid-run: the answer is what had arrived, marked as cut short.\n if (remote.ended === 'gone' && state.remote?.running) {\n return syncRunMessage({\n ...state,\n remote,\n messages: finalizeAssistant(state.messages, state.finalText, { error: true }),\n })\n }\n return { ...state, remote }\n }\n case 'event': {\n // The person's own words (an ask_user answer) reached the model; they are not kept here -\n // not in the steps, the saved transcript or the event log.\n const event = withoutOwnWords(action.event)\n const next = syncRunMessage(\n applyEvent(state, event, {\n at: action.at,\n attachments: action.attachments,\n ...(action.remote ? { remote: true } : {}),\n ...(action.goal ? { goal: action.goal } : {}),\n }),\n )\n const cap = action.maxEvents ?? 200\n const events = cap > 0 ? [...state.events, event].slice(-cap) : [...state.events, event]\n return { ...next, events }\n }\n case 'undelivered':\n // `keepQueued`: a message another tab refused - the run's queue there is not this one's.\n // What this tab sent to another tab's run waits for that tab, not for this run.\n return {\n ...state,\n queued: action.keepQueued ? state.queued : sentToOtherTab(state.queued),\n undelivered: action.texts,\n }\n case 'remote-send':\n return state.queued.some((q) => q.id === action.id)\n ? state\n : {\n ...state,\n queued: [\n ...state.queued,\n { id: action.id, text: action.text, sentTo: 'another-tab' as const },\n ],\n }\n case 'remote-answer': {\n const queued = state.queued.filter((q) => q.id !== action.id)\n // Refused, or that run ended without it: offered back. Taken: that run shows it (its own\n // `message.queued`, then where it arrived). Unknown: not this view's to offer.\n return action.answer === 'refused'\n ? { ...state, queued, undelivered: [...state.undelivered, action.text] }\n : { ...state, queued }\n }\n case 'load': {\n // Ids of the loaded messages must not collide with ones minted later.\n const maxSeq = action.messages.reduce((n, m) => {\n const k = Number(/^msg-(\\d+)$/.exec(m.id)?.[1] ?? -1)\n return Math.max(n, k + 1)\n }, state.seq)\n return {\n ...createInitialAgentState(),\n status: state.status,\n messages: action.messages.map((m) => (m.pending ? { ...m, pending: false } : m)),\n totalUsage: action.totalUsage ?? emptyUsage(),\n seq: maxSeq,\n learned: state.learned,\n }\n }\n default:\n return state\n }\n}\n","/** Normalize any thrown value into a message string. */\nexport const errMessage = (err: unknown): string =>\n err instanceof Error ? err.message : String(err)\n\n/**\n * Calls `fn` once, `ms` after the LAST of a burst of calls (trailing): another tab writing a file\n * per tool call, or a chat per settled run, refreshes a view once, not once per notice. `cancel`\n * drops a pending call (on unmount).\n */\nexport const coalesce = (fn: () => void, ms = 100): { call: () => void; cancel: () => void } => {\n let timer: ReturnType<typeof setTimeout> | undefined\n return {\n call: () => {\n if (timer !== undefined) clearTimeout(timer)\n timer = setTimeout(() => {\n timer = undefined\n fn()\n }, ms)\n },\n cancel: () => {\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n },\n }\n}\n\n/**\n * The core's `onStorageChange`, or a no-op where the core predates it (the hooks then work as\n * before: this tab's own changes only). One place for the guard every hook needs.\n */\nexport const listenToOtherTabs = (\n core: { onStorageChange?: unknown },\n dbName: string | undefined,\n listener: (change: { kind: string; op: string; key?: string; namespace?: string }) => void,\n): (() => void) =>\n typeof core.onStorageChange === 'function' && dbName\n ? (core.onStorageChange as (db: string, l: typeof listener) => () => void)(dbName, listener)\n : () => undefined\n\n/**\n * Follow another tab's writes to one database: `accept` sees every notice (and says whether it\n * matters here), `settle` runs once, ~`ms` after the last accepted one of a burst. What every hook\n * that follows other tabs uses. The returned function unsubscribes and drops a pending settle.\n */\nexport const followOtherTabs = (\n core: { onStorageChange?: unknown },\n dbName: string | undefined,\n accept: (change: { kind: string; op: string; key?: string; namespace?: string }) => boolean,\n settle: () => void,\n ms = 100,\n): (() => void) => {\n const later = coalesce(settle, ms)\n const off = listenToOtherTabs(core, dbName, (change) => {\n if (accept(change)) later.call()\n })\n return () => {\n off()\n later.cancel()\n }\n}\n\n/**\n * What `sendRemote` makes of `watchSession().send`'s answer: `true` - that tab took it; `false`\n * while this view still watches that conversation - refused, or that run ended without it (the text\n * is offered again); `false` after the watch was closed (another conversation, the view gone) -\n * unknown: that tab may still take it, so nothing is offered.\n */\nexport const remoteAnswerOf = (\n ok: boolean,\n stillWatching: boolean,\n): 'taken' | 'refused' | 'unknown' => (ok ? 'taken' : stillWatching ? 'refused' : 'unknown')\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,WAAsB;AACtB,IAAAA,oBAsBO;;;ACFA,IAAM,sBAAsB,MAAqB;AACtD,QAAM,UAAU,oBAAI,IAAsD;AAE1E,QAAM,UAAoC,CAAC,KAAK,QAC9C,IAAI,QAA8B,CAAC,YAAY;AAC7C,UAAM,SAAS,KAAK;AACpB,QAAI,QAAQ,SAAS;AACnB,cAAQ,EAAE,UAAU,OAAO,QAAQ,kBAAkB,CAAC;AACtD;AAAA,IACF;AACA,UAAM,UAAU,MAAY;AAC1B,UAAI,QAAQ,IAAI,IAAI,EAAE,MAAM,OAAQ;AACpC,aAAO,EAAE,UAAU,OAAO,QAAQ,kBAAkB,CAAC;AAAA,IACvD;AAEA,UAAM,SAAS,CAAC,aAAyC;AACvD,cAAQ,OAAO,IAAI,EAAE;AACrB,cAAQ,oBAAoB,SAAS,OAAO;AAC5C,cAAQ,QAAQ;AAAA,IAClB;AACA,YAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AACzD,YAAQ,IAAI,IAAI,IAAI,MAAM;AAAA,EAC5B,CAAC;AAEH,QAAM,SAAS,CAAC,IAAY,aAA4C;AACtE,UAAM,SAAS,QAAQ,IAAI,EAAE;AAC7B,QAAI,CAAC,OAAQ,QAAO;AACpB,WAAO,QAAQ;A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AAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAAA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["import_agent_web","m","core","watchSession","answerQuestion"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/controller.ts"],"sourcesContent":["// The agent's controller: everything `useAgent` did that is not React, as a store any front end\n// can wrap - build the agent, fold its events into `AgentUiState`, run / stop / steer it, the\n// consent and question queues, other tabs, usage. A binding (React's `useAgent`, a web component,\n// Vue / Angular / Svelte) creates one, subscribes to it, renders its snapshot and calls its\n// methods: it never re-implements any of this.\n//\n// Its own entry (`./controller`): it imports the core's `createAgent` and `createRunControl` at\n// run time, which the main entry does not (`tests/entries.test.ts`).\nimport * as core from '@dudko.dev/agent-web'\nimport {\n createAgent,\n createRunControl,\n type IUsage,\n type Agent,\n type AgentEvent,\n type AgentEventHandler,\n type AppSamplingRequest,\n type AppSamplingResult,\n type AppSamplingView,\n type AppToolCallRequest,\n type AskUserAnswer,\n type BrowserAgentConfig,\n type CompactResult,\n type RunControl,\n type RunFile,\n type RunResult,\n type SessionWatch,\n type ToolApprovalContext,\n type ToolApprovalDecision,\n type ToolApprovalMode,\n type ToolApprovalRequest,\n} from '@dudko.dev/agent-web'\nimport { createApprovalQueue } from './approval-queue.js'\nimport {\n askUserWith,\n createQuestionQueue,\n questionTimeoutOf,\n type PendingQuestion,\n} from './questions.js'\nimport {\n agentStateReducer,\n agentStatusOf,\n createInitialAgentState,\n lessonsOf,\n pendingApprovalsOf,\n type AgentAction,\n} from './state.js'\nimport type { AgentUiState, ApprovalView, ChatAttachment, ChatMessage } from './types.js'\nimport { errMessage, followOtherTabs, remoteAnswerOf } from './util.js'\n\n// ── options ──────────────────────────────────────────────────────────────\n\n/** How a controller behaves. `useAgent`'s options are these plus `deps`. */\nexport interface AgentControllerOptions {\n /** Invoked for every raw agent event, after the internal reducer folds it. */\n onEvent?: AgentEventHandler\n /**\n * Build the agent as soon as the controller is created (default `true`). With `false` it waits\n * for `reload()`.\n */\n autoStart?: boolean\n /** Cap the retained raw event log length (default 200; 0 = unbounded). */\n maxEvents?: number\n /**\n * Where \"Always allow\" given to an MCP App's tool is kept (the core's `appGrantKey`: the\n * server's identity on its connection, the tool, the app's resource): handed to the core's\n * `approveAppToolCall`, so a new agent - an `update`, a new controller - keeps the grant. A new\n * connection (the server removed and added again, reconnected, another server under the same\n * name) starts with none, and a rule's 'deny' or 'read-only' still refuses. Default: one set for\n * the page's life (this module's, shared by every controller of the page - and so by every\n * `useAgent`); a reload forgets it, as sampling's \"Always for this app\" is forgotten. Pass your\n * own set to scope it differently.\n */\n appToolGrants?: Set<string>\n /**\n * Route tool-consent requests into the controller (`pendingApprovals`, `approve`, `deny`) when\n * the config has no `toolApproval.onRequest` of its own (default true).\n */\n approvals?: boolean\n /**\n * Route the model's questions (`ask_user`) into the controller (`pendingQuestions`,\n * `answerQuestion`) when the config turns `askUser` on without an `onQuestion` of its own\n * (`askUser: true`, or `{ timeoutMs, maxPerRun }`; default true). A host's own `onQuestion` wins;\n * `askUser` off stays off.\n */\n questions?: boolean\n /**\n * What the run never showed the agent — a message sent while the answer was being\n * written — is sent as the next message, once the run has ended (default true).\n * A run the user stopped never does this: those messages stay in `undelivered`\n * for the UI to offer (`sendUndelivered` / `discardUndelivered`).\n */\n followUp?: boolean\n /**\n * Follow a run of the current conversation that goes on in ANOTHER tab of the site (default\n * true; needs a `memory` the tabs share - `IndexedDBStore` - and `sessionLock` not `'off'`): its\n * steps and answer show here live (`remote`) and `isRunning` is true meanwhile. Writing to it or\n * stopping it is explicit: `sendRemote` / `stopRemote`. Consent requests stay in that tab.\n */\n watch?: boolean\n}\n\nexport interface ApproveOptions {\n /** Also allow this tool for the rest of the agent's life (\"always allow\"). */\n remember?: boolean\n}\n\nexport interface RunGoalOptions {\n /**\n * What the transcript shows for this turn when it differs from what the\n * agent receives — e.g. the typed text without the attached files' contents.\n * `''` with `attachments`: a message of attachments only - the transcript shows them, no text.\n */\n label?: string\n /** Images sent to the model with the goal (vision models; see `agent.capabilities`). */\n images?: RunFile[]\n /** PDFs / files / URLs sent to the model with the goal. */\n files?: RunFile[]\n /** What the transcript shows as attached to this turn (thumbnails, chips). */\n attachments?: ChatAttachment[]\n}\n\n/**\n * A tool call an MCP App asks for, as `approveAppToolCall` takes it: the core's request, plus\n * `frame` - the host's id of the frame that asked (`AppView.id`), put on the request's `app`.\n */\nexport type AppToolCall = AppToolCallRequest & { frame?: string }\n\n/** What `update` does besides taking the new config. */\nexport interface AgentControllerUpdate {\n /** New options (replace the old ones whole). Omitted: the options stay. */\n options?: AgentControllerOptions\n /**\n * Build a new agent from the config (default `true`): what a `deps` change does in `useAgent`.\n * `false` only takes the config (and options) as the latest - read by the next build, the next\n * run, `reset` - and applies what is live: a new `toolApproval.mode`, another `memory` /\n * `sessionLock` / `learning.store` to follow other tabs through. A changed `autoStart` rebuilds\n * either way.\n */\n rebuild?: boolean\n}\n\n// ── the snapshot ─────────────────────────────────────────────────────────\n\n/** Everything a view renders, at one moment. Immutable: a new object on every change. */\nexport interface AgentControllerSnapshot extends AgentUiState {\n /** The memory session runs use (config.sessionId until switched). */\n sessionId: string\n /** This tab's run, or the conversation's run in another tab followed here. */\n isRunning: boolean\n /** The agent is built and nothing runs (here or, for this conversation, in another tab). */\n isReady: boolean\n /** Tool calls waiting for the user's consent (another tab's are answered there, never here). */\n pendingApprovals: ApprovalView[]\n /**\n * The model's questions waiting for the person in THIS tab (`ask_user`, when the controller\n * answers them - see `AgentControllerOptions.questions`), oldest first, each with `expiresAt`\n * when the core stops waiting. Another tab's questions are in `questions` (marked `remote`),\n * never here.\n */\n pendingQuestions: PendingQuestion[]\n /** The consent policy in effect. */\n approvalMode: ToolApprovalMode\n}\n\n// ── the methods ──────────────────────────────────────────────────────────\n\n/** What a view calls. Each keeps its identity for the controller's life. */\nexport interface AgentControllerActions {\n /**\n * Run a goal. Resolves with the RunResult, or `undefined` if it couldn't start. When the\n * conversation is running in another tab, the run waits for it (`sessionBusy`; the core's\n * `sessionLock`) and then goes, with that run's turn in its memory.\n */\n run: (goal: string, options?: RunGoalOptions) => Promise<RunResult | undefined>\n /**\n * Abort the in-flight run of THIS tab (observed between phases and mid-stream), going or waiting\n * for the session. A run followed from another tab is stopped only by `stopRemote`.\n */\n stop: () => void\n /**\n * Stop the conversation's run in another tab (`remote`), when that tab allows it (the core's\n * `sessionRelay`). A no-op when none is followed.\n */\n stopRemote: () => void\n /**\n * Say something to the conversation's run in another tab (`remote`): it reaches that run's\n * model at its next boundary, marked as from another tab. `false` when no such run is followed\n * or the text is empty. Until that tab answers, the text is in `queued` marked\n * `sentTo: 'another-tab'` (shown \"waiting for the other tab to pick it up\") - with no time\n * limit: a tab the browser froze answers when it wakes. Taken, that run's own entry takes its\n * place; refused, or that run ended without it, it comes back in `undelivered`.\n */\n sendRemote: (text: string) => boolean\n /**\n * Say something to the agent while it works. It is shown to the model at the next\n * boundary (between tool calls, or when the step ends — where the replanner then\n * re-checks the plan), never cutting a tool call short. `false` when no run is in\n * flight or the text is empty — then use `run`. Watch `queued` / `notes`. Only this tab's run:\n * for the conversation's run in another tab, `sendRemote`.\n */\n send: (text: string) => boolean\n /** Stop ONE running subagent (`SubagentView.id`); the run and its siblings go on. */\n stopSubagent: (id: string) => boolean\n /**\n * Delete one of the agent's own lessons (`learned`), e.g. one gone stale. Resolves false when\n * there is no such lesson (or no agent yet). Needs `config.learning`.\n */\n forgetSkill: (name: string) => Promise<boolean>\n /** Send the `undelivered` messages (a stopped run's leftovers) as a new message. */\n sendUndelivered: () => void\n /** Drop the `undelivered` messages. */\n discardUndelivered: () => void\n /** Clear the whole conversation — transcript, current run, and the agent's memory. */\n reset: () => void\n /** Rebuild the agent now (e.g. after the user stores a new API key). */\n reload: () => void\n /** Let a pending call run (`remember` → never ask for this tool again). */\n approve: (id: string, options?: ApproveOptions) => void\n /** Refuse a pending call; the model is told and works around it. */\n deny: (id: string, reason?: string) => void\n /**\n * Answer one of `pendingQuestions`: `{ choice: [label] }` (labels as offered; several only when\n * `multiple`), `{ other: text }` (only when `allowOther`) or `{ declined: true }`. False when no\n * such question is waiting (answered, expired, stopped). The answer goes to the core and is not\n * kept here.\n */\n answerQuestion: (id: string, answer: AskUserAnswer) => boolean\n /** Switch the consent policy live — the \"autopilot\" toggle. */\n setApprovalMode: (mode: ToolApprovalMode) => void\n /**\n * Ask the agent's consent gate about a tool call an MCP App wants to make (the core's\n * `Agent.approveAppToolCall`: the same rules and modes as the model's calls - 'autopilot' asks\n * nothing -, \"always allow\" kept apart from the model's and for the page's life, not the\n * agent's: `appToolGrants`). The request joins `pendingApprovals` with `app` set,\n * and waits across runs - a run ending or `stop()` does not answer it; `signal` does (the\n * app's frame going away). `call.frame` (the frame's `AppView.id`) is put on the request's\n * `app`, so it is drawn with THAT frame; `call.serverId` (`McpAppTool.serverId`) scopes the\n * grant to the server's connection. Resolves when the call may go; throws when it may not.\n */\n approveAppToolCall: (call: AppToolCall, signal?: AbortSignal) => Promise<void>\n /**\n * Answer a completion an MCP App asks for (its `sampling/createMessage`) with the agent's model:\n * the core's `Agent.sampleForApp` - checked, rate-limited per app, put to `approve` (shown\n * exactly what the model gets), then sent with no tools and none of the conversation. The\n * tokens count in `totalUsage` (a `usage` event of phase `'app'`, never the run's); the answer\n * is returned to the caller and never reaches the transcript, the memory or the model's context.\n * Throws the core's `AppSamplingError` (its `rpcCode` is what the app is told).\n */\n sampleForApp: (\n request: AppSamplingRequest,\n approve: (view: AppSamplingView) => Promise<boolean>,\n signal?: AbortSignal,\n ) => Promise<AppSamplingResult>\n /** Summarise the stored transcript now (needs `config.memory`). */\n compact: () => Promise<CompactResult | undefined>\n /**\n * Switch to another conversation: its id becomes the memory session of the\n * next runs, and its saved transcript (chat history) is shown.\n */\n loadChat: (chat: { sessionId: string; messages?: ChatMessage[]; totalUsage?: IUsage }) => void\n}\n\n/**\n * The agent as a store: `getSnapshot` + `subscribe` (React's `useSyncExternalStore` contract),\n * the methods a view calls, `update` and `dispose`.\n */\nexport interface AgentController extends AgentControllerActions {\n /** The current snapshot: the same object until something changes, then a new one. */\n getSnapshot: () => AgentControllerSnapshot\n /**\n * Call `listener` after every change (never at once on subscribing). Returns the unsubscribe.\n * After `dispose` nothing is called and subscribing does nothing.\n */\n subscribe: (listener: () => void) => () => void\n /** Take a new config (and options): see {@link AgentControllerUpdate}. */\n update: (config: BrowserAgentConfig, how?: AgentControllerUpdate) => void\n /**\n * Tear everything down: the in-flight run aborted, its consent requests and questions answered\n * (denied / declined: \"the view was closed\"), the build in progress dropped, the other-tab\n * channels closed, pending timers cleared, every listener dropped. The snapshot stays as it was;\n * every method is then a no-op (`run` resolves `undefined`). Idempotent.\n */\n dispose: () => void\n /** The built agent, once ready (`undefined` while building, after a failure or `dispose`). */\n readonly agent: Agent | undefined\n /** Whether `dispose` was called. */\n readonly disposed: boolean\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\n/** The database a store says it lives in (the core's IndexedDB stores do). */\nconst dbNameOf = (store: unknown): string | undefined => {\n const name = (store as { dbName?: unknown } | null | undefined)?.dbName\n return typeof name === 'string' && name ? name : undefined\n}\n\nconst modeOf = (config: BrowserAgentConfig): ToolApprovalMode =>\n config.toolApproval?.mode ?? 'autopilot'\n\n/** \"Always allow\" given to MCP Apps' tools, for the page's life (`appToolGrants`). */\nconst pageAppToolGrants = new Set<string>()\n\nconst snapshotOf = (\n state: AgentUiState,\n extra: { sessionId: string; pendingQuestions: PendingQuestion[]; approvalMode: ToolApprovalMode },\n): AgentControllerSnapshot => {\n // Another tab's run of this conversation counts as running here: the composer steers it, Stop\n // stops it, and nothing else starts the session meanwhile.\n const remoteRunning = state.remote?.running === true\n return Object.freeze({\n ...state,\n // `running` over ready / idle only: a build in progress or an error stays visible.\n status: agentStatusOf(state),\n isRunning: state.status === 'running' || remoteRunning,\n isReady: state.status === 'ready' && !remoteRunning,\n // Another tab's consent requests are answered there, never here.\n pendingApprovals: pendingApprovalsOf(state),\n pendingQuestions: extra.pendingQuestions,\n approvalMode: extra.approvalMode,\n sessionId: extra.sessionId,\n })\n}\n\n/**\n * What a controller's snapshot is before anything happened: what a view renders before it has a\n * controller (React's first render, which must not create one; a server render).\n */\nexport const createInitialAgentSnapshot = (config: BrowserAgentConfig): AgentControllerSnapshot =>\n snapshotOf(createInitialAgentState(), {\n sessionId: config.sessionId ?? 'default',\n pendingQuestions: [],\n approvalMode: modeOf(config),\n })\n\n// ── the controller ───────────────────────────────────────────────────────\n\n/**\n * Build the agent from `config` and keep its UI state: see {@link AgentController}. The agent is\n * built at once (unless `autoStart: false` or the config has no `model` yet), and other tabs are\n * followed from now on - so create it when the view appears and `dispose` it when the view goes.\n *\n * ```js\n * const chat = createAgentController({ model, credentials, toolApproval: { mode: 'ask-writes' } })\n * const off = chat.subscribe(() => render(chat.getSnapshot()))\n * button.onclick = () => chat.run(input.value)\n * // later: off(); chat.dispose()\n * ```\n */\nexport const createAgentController = (\n initialConfig: BrowserAgentConfig,\n initialOptions: AgentControllerOptions = {},\n): AgentController => {\n let config = initialConfig\n let options = initialOptions\n let disposed = false\n\n // ── the store ──\n let state = createInitialAgentState()\n let pendingQuestions: PendingQuestion[] = []\n // The memory session runs go to; a chat-history switch changes it.\n let sessionId = initialConfig.sessionId ?? 'default'\n let approvalMode: ToolApprovalMode = modeOf(initialConfig)\n let snapshot: AgentControllerSnapshot | undefined\n const listeners = new Set<() => void>()\n\n const changed = (): void => {\n snapshot = undefined\n for (const listener of [...listeners]) {\n // A listener that throws must not keep the others from hearing of the change.\n try {\n listener()\n } catch (err) {\n queueMicrotask(() => {\n throw err\n })\n }\n }\n }\n const dispatch = (action: AgentAction): void => {\n if (disposed) return\n const next = agentStateReducer(state, action)\n if (next === state) return\n state = next\n changed()\n }\n\n // ── the agent and its run ──\n let agent: Agent | undefined\n let abort: AbortController | undefined\n // The in-flight run's control: how `send` and `stopSubagent` reach it.\n let control: RunControl | undefined\n let generation = 0\n\n // Consent requests waiting for approve()/deny(), by request id. One the core stops waiting\n // for (its timeoutMs ran out, the run stopped) leaves its queue by its signal. An MCP App's are\n // kept in a queue of their own: they are not the run's, so a run ending (or stopped) does not\n // answer them.\n const approvals = createApprovalQueue()\n const appApprovals = createApprovalQueue()\n // The model's questions waiting for the person (ask_user), by id. One the core stops waiting\n // for (its timeoutMs ran out, the run stopped) leaves by its signal; a run's end takes the rest\n // down. The timeout is read from the latest config, when a question arrives.\n const questionQueue = createQuestionQueue({\n timeoutMs: () => questionTimeoutOf(config.askUser),\n onChange: (pending) => {\n if (disposed) return\n pendingQuestions = pending\n changed()\n },\n })\n const uiOnRequest = (req: ToolApprovalRequest, ctx?: ToolApprovalContext) =>\n (req.app ? appApprovals : approvals).handler(req, ctx)\n const settleAll = (decision: ToolApprovalDecision): void => approvals.settleAll(decision)\n\n // The mode the agent runs with: switched live, and taken by every new agent.\n let mode: ToolApprovalMode = approvalMode\n // The config's mode is the source of truth when IT changes; applied live.\n let configMode: ToolApprovalMode = approvalMode\n\n const setApprovalMode = (next: ToolApprovalMode): void => {\n if (disposed) return\n mode = next\n agent?.setToolApprovalMode(next)\n if (approvalMode === next) return\n approvalMode = next\n changed()\n }\n\n // The build's own status. A rebuild while a run is in flight (a setting changed mid-run) must\n // not flip the view out of 'running': the run keeps the agent it started with, and the new one\n // takes the next run.\n type BuildStatus = { status: 'idle' | 'initializing' | 'ready' | 'error'; error?: string }\n let buildStatus: BuildStatus = { status: 'idle' }\n const setBuildStatus = (next: BuildStatus): void => {\n buildStatus = next\n if (!abort) dispatch({ type: 'status', ...next })\n }\n\n // Build (and rebuild) the agent. Model resolution is async (dynamic provider imports, vault key\n // fetch, WebLLM weight download). A newer build (or dispose) makes an older one's result moot.\n let cancelBuild: (() => void) | undefined\n const build = (): void => {\n cancelBuild?.()\n cancelBuild = undefined\n // Any rebuild invalidates the current agent first.\n agent = undefined\n const cfg = config\n // Skip building until we're asked to (autoStart / reload) and actually have a model — a local\n // WebGPU model may still be downloading (config.model undefined), in which case we sit idle\n // rather than build a broken agent.\n const shouldBuild = (options.autoStart !== false || generation > 0) && Boolean(cfg.model)\n if (!shouldBuild) {\n setBuildStatus({ status: 'idle' })\n return\n }\n // Consent requests come to the controller unless the host handles them itself.\n const routeApprovals = options.approvals !== false && !cfg.toolApproval?.onRequest\n // ...and so do the model's questions, when askUser is on without a handler of the host's.\n const askUser =\n options.questions !== false ? askUserWith(cfg.askUser, questionQueue.handler) : cfg.askUser\n const built: BrowserAgentConfig = {\n ...cfg,\n ...(routeApprovals\n ? { toolApproval: { ...cfg.toolApproval, mode, onRequest: uiOnRequest } }\n : {}),\n ...(askUser !== cfg.askUser ? { askUser } : {}),\n }\n let cancelled = false\n cancelBuild = () => {\n cancelled = true\n }\n setBuildStatus({ status: 'initializing' })\n createAgent(built)\n .then((next) => {\n if (cancelled) return\n next.setToolApprovalMode(mode)\n agent = next\n // The notebook belongs to the agent just built: what its store brought back (or nothing).\n dispatch({ type: 'notebook', lessons: lessonsOf(next.listLearnedSkills()) })\n setBuildStatus({ status: 'ready' })\n })\n .catch((err) => {\n if (cancelled) return\n setBuildStatus({ status: 'error', error: errMessage(err) })\n })\n }\n\n // ── other tabs ──\n // Another tab's run of this conversation: followed here, steered and stopped through the core's\n // watchSession. The session's memory must be one the tabs share (its database names the\n // channel); with `sessionLock: 'off'` nobody relays.\n let watch: SessionWatch | undefined\n // What the watch was opened for (`undefined` db: none opened).\n let watched: { db: string | undefined; sessionId: string } | undefined\n // A run of this tab has started (its `run.start`): it holds the session. While it only WAITS for\n // the session, the other tab's run is still followed.\n let started = false\n const closeWatch = (): void => {\n watch?.close()\n watch = undefined\n }\n const syncWatch = (): void => {\n const db =\n options.watch !== false && config.sessionLock !== 'off' ? dbNameOf(config.memory) : undefined\n if (watched && watched.db === db && watched.sessionId === sessionId) return\n closeWatch()\n watched = { db, sessionId }\n const watchSession = (core as { watchSession?: typeof core.watchSession }).watchSession\n if (!db || typeof watchSession !== 'function') return\n watch = watchSession({\n dbName: db,\n sessionId,\n onEvent: (event) => {\n // A run of this tab holds the session: a late message of the one before it is not ours.\n if (started) return\n dispatch({\n type: 'event',\n event,\n remote: true,\n maxEvents: options.maxEvents,\n at: Date.now(),\n })\n },\n onState: (s) => {\n if (started && s.running) return\n dispatch({\n type: 'remote',\n remote: {\n running: s.running,\n ...(s.runId ? { runId: s.runId } : {}),\n ...(s.ended ? { ended: s.ended } : {}),\n },\n })\n },\n })\n }\n\n // The notebook in another tab changed (its store announces `skills`): read it again.\n let skillsDb: { db: string | undefined } | undefined\n let unfollowSkills: (() => void) | undefined\n const syncSkills = (): void => {\n const db = dbNameOf(typeof config.learning === 'object' ? config.learning.store : undefined)\n if (skillsDb && skillsDb.db === db) return\n unfollowSkills?.()\n skillsDb = { db }\n unfollowSkills = followOtherTabs(\n core,\n db,\n (change) => change.kind === 'skills',\n () => {\n const current = agent\n if (disposed || !current || typeof current.reloadLearnedSkills !== 'function') return\n void current\n .reloadLearnedSkills()\n .then((skills) => dispatch({ type: 'notebook', lessons: lessonsOf(skills) }))\n .catch(() => {})\n },\n )\n }\n\n // ── the methods ──\n const run = async (goal: string, runOptions?: RunGoalOptions): Promise<RunResult | undefined> => {\n const current = agent\n if (disposed || !current || abort) return undefined // not ready, or already running\n const controller = new AbortController()\n abort = controller\n const runControl = createRunControl()\n control = runControl\n // What the run never showed the agent; read once it is over.\n let left: string[] = []\n // Stopped - here, or from another tab (the run's own result says so).\n let stopped = false\n // Whether it began (its run.start): a run stopped while it only waited began nothing.\n let began = false\n const shownGoal = runOptions?.label ?? goal\n dispatch({ type: 'status', status: 'running' })\n // Shown at once: the run's own turn (`run.start`) comes once it has the session.\n // A message of attachments only has no text to show (`label: ''`): its attachments are it.\n const shownAtAll = Boolean(shownGoal.trim() || runOptions?.attachments?.length)\n if (shownAtAll) {\n dispatch({\n type: 'submitted',\n goal: shownGoal,\n ...(runOptions?.attachments?.length ? { attachments: runOptions.attachments } : {}),\n })\n }\n try {\n const result = await current.run(goal, {\n signal: controller.signal,\n control: runControl,\n sessionId,\n ...(runOptions?.images?.length ? { images: runOptions.images } : {}),\n ...(runOptions?.files?.length ? { files: runOptions.files } : {}),\n onEvent: (event) => {\n const start = event.type === 'run.start'\n // From here the session is this run's: whatever the run before it still sends is late.\n if (start) {\n started = true\n began = true\n }\n const shown =\n start && runOptions?.label !== undefined ? { ...event, goal: runOptions.label } : event\n dispatch({\n type: 'event',\n event: shown,\n maxEvents: options.maxEvents,\n at: Date.now(),\n // What the user sent waits with the run: shown as queued meanwhile.\n ...(event.type === 'session.busy' && shownAtAll\n ? {\n goal:\n shownGoal.trim() ||\n (runOptions?.attachments ?? []).map((a) => a.name).join(', '),\n }\n : {}),\n ...(start && runOptions?.attachments?.length\n ? { attachments: runOptions.attachments }\n : {}),\n })\n try {\n options.onEvent?.(event)\n } catch {\n /* a bad host handler must not break the run */\n }\n },\n })\n left = result.undelivered ?? []\n stopped = result.stopped\n return result\n } catch (err) {\n left = runControl.pending()\n dispatch({\n type: 'event',\n event: { type: 'error', phase: 'run', error: errMessage(err) },\n maxEvents: options.maxEvents,\n })\n return undefined\n } finally {\n abort = undefined\n started = false\n control = undefined\n settleAll({ approved: false, reason: 'the run ended' })\n // A question the core still had open is no one's now (the core stopped waiting already).\n questionQueue.cancel()\n // Whatever the agent did meanwhile: rebuilt, still building, or gone.\n dispatch({ type: 'status', ...buildStatus })\n // Stopped while it waited for the session: what the user sent goes back to them.\n if (stopped && !began && shownGoal.trim()) left = [shownGoal, ...left]\n if (left.length > 0) {\n if (!controller.signal.aborted && !stopped && options.followUp !== false) {\n // Said too late for this run: just send it next.\n dispatch({ type: 'undelivered', texts: [] })\n void run(left.join('\\n\\n'))\n } else {\n dispatch({ type: 'undelivered', texts: left })\n }\n } else {\n dispatch({ type: 'undelivered', texts: [] })\n }\n }\n }\n\n const send = (text: string): boolean => control?.send(text) ?? false\n // Ids of what this tab sent to another tab's run, while it waits for that tab's answer.\n let remoteSends = 0\n const sendRemote = (text: string): boolean => {\n const current = watch\n const clean = typeof text === 'string' ? text.trim() : ''\n if (!current?.state.running || !clean) return false\n // Shown as waiting for that tab until it answers - however long: a tab the browser froze in\n // the background answers when it wakes. Taken there, that run's own `message.queued` (marked\n // from another tab) takes the entry's place. Refused, or that run ended without it: the text\n // comes back here, to be sent again or dropped - and only then, so a message never has two\n // runs. The watch closed (another conversation in view, or the view gone): nothing to offer\n // here, and that tab may still take it.\n const id = `to-other-tab-${(remoteSends += 1)}`\n dispatch({ type: 'remote-send', id, text: clean })\n void current.send(clean).then((ok) => {\n const answer = remoteAnswerOf(ok, watch === current)\n dispatch({ type: 'remote-answer', id, text: clean, answer })\n })\n return true\n }\n const stopRemote = (): void => {\n if (watch?.state.running) void watch.stop()\n }\n const stopSubagent = (id: string): boolean => control?.stopSubagent(id) ?? false\n const sendUndelivered = (): void => {\n const texts = state.undelivered\n if (disposed || texts.length === 0) return\n dispatch({ type: 'undelivered', texts: [] })\n void run(texts.join('\\n\\n'))\n }\n const discardUndelivered = (): void => dispatch({ type: 'undelivered', texts: [] })\n\n const stop = (): void => {\n // The run's signal first: the core ends a question's wait as stopped, then nobody is asked.\n abort?.abort()\n settleAll({ approved: false, reason: 'stopped by the user' })\n questionQueue.cancel()\n }\n\n const answerQuestion = (id: string, answer: AskUserAnswer): boolean =>\n questionQueue.answer(id, answer)\n\n const reset = (): void => {\n if (disposed) return\n dispatch({ type: 'reset' })\n // \"New conversation\" means the agent forgets it too, not just the view.\n void config.memory?.clear(sessionId).catch(() => {})\n }\n\n const reload = (): void => {\n if (disposed) return\n generation += 1\n build()\n }\n\n const loadChat = (chat: {\n sessionId: string\n messages?: ChatMessage[]\n totalUsage?: IUsage\n }): void => {\n if (disposed) return\n abort?.abort()\n const switched = chat.sessionId !== sessionId\n sessionId = chat.sessionId\n if (switched) snapshot = undefined\n const before = state\n dispatch({ type: 'load', messages: chat.messages ?? [], totalUsage: chat.totalUsage })\n // The session is part of the snapshot: a switch is a change even when the view is not.\n if (switched && state === before) changed()\n syncWatch()\n }\n\n const forgetSkill = async (name: string): Promise<boolean> => {\n const current = agent\n if (disposed || !current) return false\n return current.forgetSkill(name, (event) =>\n dispatch({ type: 'event', event, maxEvents: options.maxEvents, at: Date.now() }),\n )\n }\n\n // The waiting request with this id - the run's or an app's.\n const approve = (id: string, opts?: ApproveOptions): void => {\n if (!approvals.approve(id, { remember: opts?.remember })) {\n appApprovals.approve(id, { remember: opts?.remember })\n }\n }\n\n const deny = (id: string, reason?: string): void => {\n if (!approvals.deny(id, reason)) appApprovals.deny(id, reason)\n }\n\n const approveAppToolCall = async (\n { frame, ...call }: AppToolCall,\n signal?: AbortSignal,\n ): Promise<void> => {\n const current = agent\n if (!current) throw new Error('The agent is not ready')\n // An older core has no gate for apps: refuse rather than let the call through.\n if (typeof current.approveAppToolCall !== 'function') {\n throw new Error('This version of @dudko.dev/agent-web cannot ask about an app’s calls')\n }\n await current.approveAppToolCall(\n call,\n (event) => {\n // Decided (or given up on): nothing waits on the answer any more. The queue drops a\n // request whose signal aborted; this also covers a core that sends no signal.\n if (event.type === 'tool.approval-resolved') appApprovals.deny(event.id, 'no longer asked')\n dispatch({\n type: 'event',\n // The frame that asked rides on the request's `app`: drawn with that frame.\n event:\n frame !== undefined && event.type === 'tool.approval-requested' && event.app\n ? ({ ...event, app: { ...event.app, frame } } as AgentEvent)\n : event,\n maxEvents: options.maxEvents,\n at: Date.now(),\n })\n },\n signal,\n { remembered: options.appToolGrants ?? pageAppToolGrants },\n )\n }\n\n const sampleForApp = async (\n request: AppSamplingRequest,\n approveView: (view: AppSamplingView) => Promise<boolean>,\n signal?: AbortSignal,\n ): Promise<AppSamplingResult> => {\n const current = agent\n if (!current) throw new Error('The agent is not ready')\n // An older core cannot: refuse rather than answer without the core's checks.\n if (typeof current.sampleForApp !== 'function') {\n throw new Error('This version of @dudko.dev/agent-web cannot answer an app’s sampling')\n }\n return current.sampleForApp(request, {\n approve: approveView,\n ...(signal ? { signal } : {}),\n sessionId,\n // The only event: its tokens (phase 'app'). The answer is never dispatched.\n onEvent: (event) =>\n dispatch({ type: 'event', event, maxEvents: options.maxEvents, at: Date.now() }),\n })\n }\n\n const compact = async (): Promise<CompactResult | undefined> => {\n const current = agent\n if (disposed || !current) return undefined\n const result = await current.compact({ sessionId })\n if (result.compacted) {\n dispatch({\n type: 'event',\n event: {\n type: 'context.compacted',\n scope: 'history',\n beforeTokens: result.beforeTokens,\n afterTokens: result.afterTokens,\n },\n maxEvents: options.maxEvents,\n at: Date.now(),\n })\n }\n return result\n }\n\n // ── update and dispose ──\n const update = (next: BrowserAgentConfig, how: AgentControllerUpdate = {}): void => {\n if (disposed) return\n const autoStartBefore = options.autoStart\n config = next\n if (how.options) options = how.options\n // In the order `useAgent`'s effects ran: the mode, the build, the other tabs.\n const nextMode = modeOf(next)\n if (nextMode !== configMode) {\n configMode = nextMode\n if (nextMode !== mode) setApprovalMode(nextMode)\n }\n if (how.rebuild !== false || !Object.is(options.autoStart, autoStartBefore)) build()\n syncWatch()\n syncSkills()\n }\n\n const dispose = (): void => {\n if (disposed) return\n // Abort any in-flight run, and release waiting consent requests and questions.\n abort?.abort()\n settleAll({ approved: false, reason: 'the view was closed' })\n appApprovals.settleAll({ approved: false, reason: 'the view was closed' })\n questionQueue.dispose()\n disposed = true\n cancelBuild?.()\n cancelBuild = undefined\n agent = undefined\n closeWatch()\n unfollowSkills?.()\n unfollowSkills = undefined\n listeners.clear()\n }\n\n // ── start ──\n build()\n syncWatch()\n syncSkills()\n\n return {\n getSnapshot: () =>\n (snapshot ??= snapshotOf(state, { sessionId, pendingQuestions, approvalMode })),\n subscribe: (listener) => {\n if (disposed) return () => {}\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n update,\n dispose,\n get agent() {\n return agent\n },\n get disposed() {\n return disposed\n },\n run,\n stop,\n stopRemote,\n send,\n sendRemote,\n stopSubagent,\n forgetSkill,\n sendUndelivered,\n discardUndelivered,\n reset,\n reload,\n approve,\n deny,\n answerQuestion,\n setApprovalMode,\n approveAppToolCall,\n sampleForApp,\n compact,\n loadChat,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAQA,YAAY,UAAU;AACtB;AAAA,EACE;AAAA,EACA;AAAA,OAoBK;AAsQP,IAAM,WAAW,CAAC,UAAuC;AACvD,QAAM,OAAQ,OAAmD;AACjE,SAAO,OAAO,SAAS,YAAY,OAAO,OAAO;AACnD;AAEA,IAAM,SAAS,CAAC,WACd,OAAO,cAAc,QAAQ;AAG/B,IAAM,oBAAoB,oBAAI,IAAY;AAE1C,IAAM,aAAa,CACjB,OACA,UAC4B;AAG5B,QAAM,gBAAgB,MAAM,QAAQ,YAAY;AAChD,SAAO,OAAO,OAAO;AAAA,IACnB,GAAG;AAAA;AAAA,IAEH,QAAQ,cAAc,KAAK;AAAA,IAC3B,WAAW,MAAM,WAAW,aAAa;AAAA,IACzC,SAAS,MAAM,WAAW,WAAW,CAAC;AAAA;AAAA,IAEtC,kBAAkB,mBAAmB,KAAK;AAAA,IAC1C,kBAAkB,MAAM;AAAA,IACxB,cAAc,MAAM;AAAA,IACpB,WAAW,MAAM;AAAA,EACnB,CAAC;AACH;AAMO,IAAM,6BAA6B,CAAC,WACzC,WAAW,wBAAwB,GAAG;AAAA,EACpC,WAAW,OAAO,aAAa;AAAA,EAC/B,kBAAkB,CAAC;AAAA,EACnB,cAAc,OAAO,MAAM;AAC7B,CAAC;AAgBI,IAAM,wBAAwB,CACnC,eACA,iBAAyC,CAAC,MACtB;AACpB,MAAI,SAAS;AACb,MAAI,UAAU;AACd,MAAI,WAAW;AAGf,MAAI,QAAQ,wBAAwB;AACpC,MAAI,mBAAsC,CAAC;AAE3C,MAAI,YAAY,cAAc,aAAa;AAC3C,MAAI,eAAiC,OAAO,aAAa;AACzD,MAAI;AACJ,QAAM,YAAY,oBAAI,IAAgB;AAEtC,QAAM,UAAU,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