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

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 (283) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +316 -5
  3. package/dist/canvas.cjs +266 -0
  4. package/dist/canvas.cjs.map +1 -0
  5. package/dist/canvas.d.cts +105 -0
  6. package/dist/canvas.d.ts +105 -0
  7. package/dist/canvas.js +200 -0
  8. package/dist/canvas.js.map +1 -0
  9. package/dist/chunk-7O64ZI6Z.js +125 -0
  10. package/dist/chunk-7O64ZI6Z.js.map +1 -0
  11. package/dist/chunk-EL2YCROY.js +127 -0
  12. package/dist/chunk-EL2YCROY.js.map +1 -0
  13. package/dist/chunk-GB7RZJMG.js +98 -0
  14. package/dist/chunk-GB7RZJMG.js.map +1 -0
  15. package/dist/chunk-KZQB35LS.js +22 -0
  16. package/dist/chunk-KZQB35LS.js.map +1 -0
  17. package/dist/chunk-SVYHDLAZ.js +348 -0
  18. package/dist/chunk-SVYHDLAZ.js.map +1 -0
  19. package/dist/chunk-VCR7LU7J.js +348 -0
  20. package/dist/chunk-VCR7LU7J.js.map +1 -0
  21. package/dist/chunk-WFM6B7CL.js +406 -0
  22. package/dist/chunk-WFM6B7CL.js.map +1 -0
  23. package/dist/chunk-WZ7K7JIP.js +348 -0
  24. package/dist/chunk-WZ7K7JIP.js.map +1 -0
  25. package/dist/chunk-ZBHESK6V.js +1440 -0
  26. package/dist/chunk-ZBHESK6V.js.map +1 -0
  27. package/dist/controller.cjs +1891 -0
  28. package/dist/controller.cjs.map +1 -0
  29. package/dist/controller.d.cts +253 -0
  30. package/dist/controller.d.ts +253 -0
  31. package/dist/controller.js +482 -0
  32. package/dist/controller.js.map +1 -0
  33. package/dist/en-Dg2MtzcJ.d.cts +348 -0
  34. package/dist/en-Dg2MtzcJ.d.ts +348 -0
  35. package/dist/index.cjs +4276 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.d.cts +997 -0
  38. package/dist/index.d.ts +997 -0
  39. package/dist/index.js +2494 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/labels-B5xpIGf_.d.cts +25 -0
  42. package/dist/labels-B5xpIGf_.d.ts +25 -0
  43. package/dist/labels-CmiTBLWD.d.cts +1176 -0
  44. package/dist/labels-DH1ESUtm.d.ts +1176 -0
  45. package/dist/locales/be.cjs +806 -0
  46. package/dist/locales/be.cjs.map +1 -0
  47. package/dist/locales/be.d.cts +16 -0
  48. package/dist/locales/be.d.ts +16 -0
  49. package/dist/locales/be.js +380 -0
  50. package/dist/locales/be.js.map +1 -0
  51. package/dist/locales/bg.cjs +759 -0
  52. package/dist/locales/bg.cjs.map +1 -0
  53. package/dist/locales/bg.d.cts +16 -0
  54. package/dist/locales/bg.d.ts +16 -0
  55. package/dist/locales/bg.js +333 -0
  56. package/dist/locales/bg.js.map +1 -0
  57. package/dist/locales/ca.cjs +785 -0
  58. package/dist/locales/ca.cjs.map +1 -0
  59. package/dist/locales/ca.d.cts +16 -0
  60. package/dist/locales/ca.d.ts +16 -0
  61. package/dist/locales/ca.js +359 -0
  62. package/dist/locales/ca.js.map +1 -0
  63. package/dist/locales/cs.cjs +806 -0
  64. package/dist/locales/cs.cjs.map +1 -0
  65. package/dist/locales/cs.d.cts +16 -0
  66. package/dist/locales/cs.d.ts +16 -0
  67. package/dist/locales/cs.js +380 -0
  68. package/dist/locales/cs.js.map +1 -0
  69. package/dist/locales/da.cjs +759 -0
  70. package/dist/locales/da.cjs.map +1 -0
  71. package/dist/locales/da.d.cts +16 -0
  72. package/dist/locales/da.d.ts +16 -0
  73. package/dist/locales/da.js +333 -0
  74. package/dist/locales/da.js.map +1 -0
  75. package/dist/locales/de.cjs +768 -0
  76. package/dist/locales/de.cjs.map +1 -0
  77. package/dist/locales/de.d.cts +16 -0
  78. package/dist/locales/de.d.ts +16 -0
  79. package/dist/locales/de.js +342 -0
  80. package/dist/locales/de.js.map +1 -0
  81. package/dist/locales/el.cjs +768 -0
  82. package/dist/locales/el.cjs.map +1 -0
  83. package/dist/locales/el.d.cts +16 -0
  84. package/dist/locales/el.d.ts +16 -0
  85. package/dist/locales/el.js +342 -0
  86. package/dist/locales/el.js.map +1 -0
  87. package/dist/locales/en.cjs +765 -0
  88. package/dist/locales/en.cjs.map +1 -0
  89. package/dist/locales/en.d.cts +12 -0
  90. package/dist/locales/en.d.ts +12 -0
  91. package/dist/locales/en.js +339 -0
  92. package/dist/locales/en.js.map +1 -0
  93. package/dist/locales/es-419.cjs +793 -0
  94. package/dist/locales/es-419.cjs.map +1 -0
  95. package/dist/locales/es-419.d.cts +18 -0
  96. package/dist/locales/es-419.d.ts +18 -0
  97. package/dist/locales/es-419.js +26 -0
  98. package/dist/locales/es-419.js.map +1 -0
  99. package/dist/locales/es.cjs +781 -0
  100. package/dist/locales/es.cjs.map +1 -0
  101. package/dist/locales/es.d.cts +16 -0
  102. package/dist/locales/es.d.ts +16 -0
  103. package/dist/locales/es.js +14 -0
  104. package/dist/locales/es.js.map +1 -0
  105. package/dist/locales/fi.cjs +765 -0
  106. package/dist/locales/fi.cjs.map +1 -0
  107. package/dist/locales/fi.d.cts +16 -0
  108. package/dist/locales/fi.d.ts +16 -0
  109. package/dist/locales/fi.js +339 -0
  110. package/dist/locales/fi.js.map +1 -0
  111. package/dist/locales/fr-CA.cjs +789 -0
  112. package/dist/locales/fr-CA.cjs.map +1 -0
  113. package/dist/locales/fr-CA.d.cts +19 -0
  114. package/dist/locales/fr-CA.d.ts +19 -0
  115. package/dist/locales/fr-CA.js +22 -0
  116. package/dist/locales/fr-CA.js.map +1 -0
  117. package/dist/locales/fr.cjs +781 -0
  118. package/dist/locales/fr.cjs.map +1 -0
  119. package/dist/locales/fr.d.cts +16 -0
  120. package/dist/locales/fr.d.ts +16 -0
  121. package/dist/locales/fr.js +14 -0
  122. package/dist/locales/fr.js.map +1 -0
  123. package/dist/locales/gn.cjs +762 -0
  124. package/dist/locales/gn.cjs.map +1 -0
  125. package/dist/locales/gn.d.cts +18 -0
  126. package/dist/locales/gn.d.ts +18 -0
  127. package/dist/locales/gn.js +336 -0
  128. package/dist/locales/gn.js.map +1 -0
  129. package/dist/locales/hr.cjs +781 -0
  130. package/dist/locales/hr.cjs.map +1 -0
  131. package/dist/locales/hr.d.cts +16 -0
  132. package/dist/locales/hr.d.ts +16 -0
  133. package/dist/locales/hr.js +355 -0
  134. package/dist/locales/hr.js.map +1 -0
  135. package/dist/locales/ht.cjs +762 -0
  136. package/dist/locales/ht.cjs.map +1 -0
  137. package/dist/locales/ht.d.cts +18 -0
  138. package/dist/locales/ht.d.ts +18 -0
  139. package/dist/locales/ht.js +336 -0
  140. package/dist/locales/ht.js.map +1 -0
  141. package/dist/locales/hu.cjs +765 -0
  142. package/dist/locales/hu.cjs.map +1 -0
  143. package/dist/locales/hu.d.cts +16 -0
  144. package/dist/locales/hu.d.ts +16 -0
  145. package/dist/locales/hu.js +339 -0
  146. package/dist/locales/hu.js.map +1 -0
  147. package/dist/locales/index.cjs +543 -0
  148. package/dist/locales/index.cjs.map +1 -0
  149. package/dist/locales/index.d.cts +40 -0
  150. package/dist/locales/index.d.ts +40 -0
  151. package/dist/locales/index.js +105 -0
  152. package/dist/locales/index.js.map +1 -0
  153. package/dist/locales/it.cjs +789 -0
  154. package/dist/locales/it.cjs.map +1 -0
  155. package/dist/locales/it.d.cts +16 -0
  156. package/dist/locales/it.d.ts +16 -0
  157. package/dist/locales/it.js +363 -0
  158. package/dist/locales/it.js.map +1 -0
  159. package/dist/locales/nb.cjs +759 -0
  160. package/dist/locales/nb.cjs.map +1 -0
  161. package/dist/locales/nb.d.cts +16 -0
  162. package/dist/locales/nb.d.ts +16 -0
  163. package/dist/locales/nb.js +333 -0
  164. package/dist/locales/nb.js.map +1 -0
  165. package/dist/locales/nl.cjs +765 -0
  166. package/dist/locales/nl.cjs.map +1 -0
  167. package/dist/locales/nl.d.cts +16 -0
  168. package/dist/locales/nl.d.ts +16 -0
  169. package/dist/locales/nl.js +339 -0
  170. package/dist/locales/nl.js.map +1 -0
  171. package/dist/locales/pl.cjs +806 -0
  172. package/dist/locales/pl.cjs.map +1 -0
  173. package/dist/locales/pl.d.cts +16 -0
  174. package/dist/locales/pl.d.ts +16 -0
  175. package/dist/locales/pl.js +380 -0
  176. package/dist/locales/pl.js.map +1 -0
  177. package/dist/locales/pt-BR.cjs +785 -0
  178. package/dist/locales/pt-BR.cjs.map +1 -0
  179. package/dist/locales/pt-BR.d.cts +16 -0
  180. package/dist/locales/pt-BR.d.ts +16 -0
  181. package/dist/locales/pt-BR.js +359 -0
  182. package/dist/locales/pt-BR.js.map +1 -0
  183. package/dist/locales/pt.cjs +789 -0
  184. package/dist/locales/pt.cjs.map +1 -0
  185. package/dist/locales/pt.d.cts +16 -0
  186. package/dist/locales/pt.d.ts +16 -0
  187. package/dist/locales/pt.js +363 -0
  188. package/dist/locales/pt.js.map +1 -0
  189. package/dist/locales/qu.cjs +768 -0
  190. package/dist/locales/qu.cjs.map +1 -0
  191. package/dist/locales/qu.d.cts +18 -0
  192. package/dist/locales/qu.d.ts +18 -0
  193. package/dist/locales/qu.js +342 -0
  194. package/dist/locales/qu.js.map +1 -0
  195. package/dist/locales/ro.cjs +781 -0
  196. package/dist/locales/ro.cjs.map +1 -0
  197. package/dist/locales/ro.d.cts +16 -0
  198. package/dist/locales/ro.d.ts +16 -0
  199. package/dist/locales/ro.js +355 -0
  200. package/dist/locales/ro.js.map +1 -0
  201. package/dist/locales/ru.cjs +801 -0
  202. package/dist/locales/ru.cjs.map +1 -0
  203. package/dist/locales/ru.d.cts +16 -0
  204. package/dist/locales/ru.d.ts +16 -0
  205. package/dist/locales/ru.js +375 -0
  206. package/dist/locales/ru.js.map +1 -0
  207. package/dist/locales/sk.cjs +806 -0
  208. package/dist/locales/sk.cjs.map +1 -0
  209. package/dist/locales/sk.d.cts +16 -0
  210. package/dist/locales/sk.d.ts +16 -0
  211. package/dist/locales/sk.js +380 -0
  212. package/dist/locales/sk.js.map +1 -0
  213. package/dist/locales/sq.cjs +765 -0
  214. package/dist/locales/sq.cjs.map +1 -0
  215. package/dist/locales/sq.d.cts +16 -0
  216. package/dist/locales/sq.d.ts +16 -0
  217. package/dist/locales/sq.js +339 -0
  218. package/dist/locales/sq.js.map +1 -0
  219. package/dist/locales/sr-Latn.cjs +853 -0
  220. package/dist/locales/sr-Latn.cjs.map +1 -0
  221. package/dist/locales/sr-Latn.d.cts +19 -0
  222. package/dist/locales/sr-Latn.d.ts +19 -0
  223. package/dist/locales/sr-Latn.js +86 -0
  224. package/dist/locales/sr-Latn.js.map +1 -0
  225. package/dist/locales/sr.cjs +781 -0
  226. package/dist/locales/sr.cjs.map +1 -0
  227. package/dist/locales/sr.d.cts +16 -0
  228. package/dist/locales/sr.d.ts +16 -0
  229. package/dist/locales/sr.js +14 -0
  230. package/dist/locales/sr.js.map +1 -0
  231. package/dist/locales/sv.cjs +765 -0
  232. package/dist/locales/sv.cjs.map +1 -0
  233. package/dist/locales/sv.d.cts +16 -0
  234. package/dist/locales/sv.d.ts +16 -0
  235. package/dist/locales/sv.js +339 -0
  236. package/dist/locales/sv.js.map +1 -0
  237. package/dist/locales/tr.cjs +762 -0
  238. package/dist/locales/tr.cjs.map +1 -0
  239. package/dist/locales/tr.d.cts +16 -0
  240. package/dist/locales/tr.d.ts +16 -0
  241. package/dist/locales/tr.js +336 -0
  242. package/dist/locales/tr.js.map +1 -0
  243. package/dist/locales/uk.cjs +806 -0
  244. package/dist/locales/uk.cjs.map +1 -0
  245. package/dist/locales/uk.d.cts +16 -0
  246. package/dist/locales/uk.d.ts +16 -0
  247. package/dist/locales/uk.js +380 -0
  248. package/dist/locales/uk.js.map +1 -0
  249. package/dist/markdown.cjs +620 -0
  250. package/dist/markdown.cjs.map +1 -0
  251. package/dist/markdown.d.cts +153 -0
  252. package/dist/markdown.d.ts +153 -0
  253. package/dist/markdown.js +573 -0
  254. package/dist/markdown.js.map +1 -0
  255. package/dist/mcp-app-policy-DXKQ2jjM.d.cts +73 -0
  256. package/dist/mcp-app-policy-DXKQ2jjM.d.ts +73 -0
  257. package/dist/mcp-app-sandbox.cjs +323 -0
  258. package/dist/mcp-app-sandbox.cjs.map +1 -0
  259. package/dist/mcp-app-sandbox.d.cts +70 -0
  260. package/dist/mcp-app-sandbox.d.ts +70 -0
  261. package/dist/mcp-app-sandbox.js +209 -0
  262. package/dist/mcp-app-sandbox.js.map +1 -0
  263. package/dist/mcp-app.cjs +980 -0
  264. package/dist/mcp-app.cjs.map +1 -0
  265. package/dist/mcp-app.d.cts +491 -0
  266. package/dist/mcp-app.d.ts +491 -0
  267. package/dist/mcp-app.js +816 -0
  268. package/dist/mcp-app.js.map +1 -0
  269. package/dist/pipeline.cjs +845 -0
  270. package/dist/pipeline.cjs.map +1 -0
  271. package/dist/pipeline.css +1407 -0
  272. package/dist/pipeline.d.cts +348 -0
  273. package/dist/pipeline.d.ts +348 -0
  274. package/dist/pipeline.js +778 -0
  275. package/dist/pipeline.js.map +1 -0
  276. package/dist/questions-Dw--IEjT.d.cts +100 -0
  277. package/dist/questions-Dw--IEjT.d.ts +100 -0
  278. package/dist/styles.css +4109 -0
  279. package/dist/types-CQquuZpl.d.cts +19 -0
  280. package/dist/types-CXZfZVP5.d.ts +19 -0
  281. package/dist/types-DnBCok3z.d.cts +994 -0
  282. package/dist/types-DnBCok3z.d.ts +994 -0
  283. package/package.json +165 -8
@@ -0,0 +1,482 @@
1
+ import {
2
+ agentStateReducer,
3
+ agentStatusOf,
4
+ askUserWith,
5
+ createApprovalQueue,
6
+ createInitialAgentState,
7
+ createQuestionQueue,
8
+ errMessage,
9
+ followOtherTabs,
10
+ lessonsOf,
11
+ pendingApprovalsOf,
12
+ questionTimeoutOf,
13
+ remoteAnswerOf
14
+ } from "./chunk-ZBHESK6V.js";
15
+
16
+ // src/controller.ts
17
+ import * as core from "@dudko.dev/agent-web";
18
+ import {
19
+ createAgent,
20
+ createRunControl
21
+ } from "@dudko.dev/agent-web";
22
+ var dbNameOf = (store) => {
23
+ const name = store?.dbName;
24
+ return typeof name === "string" && name ? name : void 0;
25
+ };
26
+ var modeOf = (config) => config.toolApproval?.mode ?? "autopilot";
27
+ var pageAppToolGrants = /* @__PURE__ */ new Set();
28
+ var snapshotOf = (state, extra) => {
29
+ const remoteRunning = state.remote?.running === true;
30
+ return Object.freeze({
31
+ ...state,
32
+ // `running` over ready / idle only: a build in progress or an error stays visible.
33
+ status: agentStatusOf(state),
34
+ isRunning: state.status === "running" || remoteRunning,
35
+ isReady: state.status === "ready" && !remoteRunning,
36
+ // Another tab's consent requests are answered there, never here.
37
+ pendingApprovals: pendingApprovalsOf(state),
38
+ pendingQuestions: extra.pendingQuestions,
39
+ approvalMode: extra.approvalMode,
40
+ sessionId: extra.sessionId
41
+ });
42
+ };
43
+ var createInitialAgentSnapshot = (config) => snapshotOf(createInitialAgentState(), {
44
+ sessionId: config.sessionId ?? "default",
45
+ pendingQuestions: [],
46
+ approvalMode: modeOf(config)
47
+ });
48
+ var createAgentController = (initialConfig, initialOptions = {}) => {
49
+ let config = initialConfig;
50
+ let options = initialOptions;
51
+ let disposed = false;
52
+ let state = createInitialAgentState();
53
+ let pendingQuestions = [];
54
+ let sessionId = initialConfig.sessionId ?? "default";
55
+ let approvalMode = modeOf(initialConfig);
56
+ let snapshot;
57
+ const listeners = /* @__PURE__ */ new Set();
58
+ const changed = () => {
59
+ snapshot = void 0;
60
+ for (const listener of [...listeners]) {
61
+ try {
62
+ listener();
63
+ } catch (err) {
64
+ queueMicrotask(() => {
65
+ throw err;
66
+ });
67
+ }
68
+ }
69
+ };
70
+ const dispatch = (action) => {
71
+ if (disposed) return;
72
+ const next = agentStateReducer(state, action);
73
+ if (next === state) return;
74
+ state = next;
75
+ changed();
76
+ };
77
+ let agent;
78
+ let abort;
79
+ let control;
80
+ let generation = 0;
81
+ const approvals = createApprovalQueue();
82
+ const appApprovals = createApprovalQueue();
83
+ const questionQueue = createQuestionQueue({
84
+ timeoutMs: () => questionTimeoutOf(config.askUser),
85
+ onChange: (pending) => {
86
+ if (disposed) return;
87
+ pendingQuestions = pending;
88
+ changed();
89
+ }
90
+ });
91
+ const uiOnRequest = (req, ctx) => (req.app ? appApprovals : approvals).handler(req, ctx);
92
+ const settleAll = (decision) => approvals.settleAll(decision);
93
+ let mode = approvalMode;
94
+ let configMode = approvalMode;
95
+ const setApprovalMode = (next) => {
96
+ if (disposed) return;
97
+ mode = next;
98
+ agent?.setToolApprovalMode(next);
99
+ if (approvalMode === next) return;
100
+ approvalMode = next;
101
+ changed();
102
+ };
103
+ let buildStatus = { status: "idle" };
104
+ const setBuildStatus = (next) => {
105
+ buildStatus = next;
106
+ if (!abort) dispatch({ type: "status", ...next });
107
+ };
108
+ let cancelBuild;
109
+ const build = () => {
110
+ cancelBuild?.();
111
+ cancelBuild = void 0;
112
+ agent = void 0;
113
+ const cfg = config;
114
+ const shouldBuild = (options.autoStart !== false || generation > 0) && Boolean(cfg.model);
115
+ if (!shouldBuild) {
116
+ setBuildStatus({ status: "idle" });
117
+ return;
118
+ }
119
+ const routeApprovals = options.approvals !== false && !cfg.toolApproval?.onRequest;
120
+ const askUser = options.questions !== false ? askUserWith(cfg.askUser, questionQueue.handler) : cfg.askUser;
121
+ const built = {
122
+ ...cfg,
123
+ ...routeApprovals ? { toolApproval: { ...cfg.toolApproval, mode, onRequest: uiOnRequest } } : {},
124
+ ...askUser !== cfg.askUser ? { askUser } : {}
125
+ };
126
+ let cancelled = false;
127
+ cancelBuild = () => {
128
+ cancelled = true;
129
+ };
130
+ setBuildStatus({ status: "initializing" });
131
+ createAgent(built).then((next) => {
132
+ if (cancelled) return;
133
+ next.setToolApprovalMode(mode);
134
+ agent = next;
135
+ dispatch({ type: "notebook", lessons: lessonsOf(next.listLearnedSkills()) });
136
+ setBuildStatus({ status: "ready" });
137
+ }).catch((err) => {
138
+ if (cancelled) return;
139
+ setBuildStatus({ status: "error", error: errMessage(err) });
140
+ });
141
+ };
142
+ let watch;
143
+ let watched;
144
+ let started = false;
145
+ const closeWatch = () => {
146
+ watch?.close();
147
+ watch = void 0;
148
+ };
149
+ const syncWatch = () => {
150
+ const db = options.watch !== false && config.sessionLock !== "off" ? dbNameOf(config.memory) : void 0;
151
+ if (watched && watched.db === db && watched.sessionId === sessionId) return;
152
+ closeWatch();
153
+ watched = { db, sessionId };
154
+ const watchSession2 = core.watchSession;
155
+ if (!db || typeof watchSession2 !== "function") return;
156
+ watch = watchSession2({
157
+ dbName: db,
158
+ sessionId,
159
+ onEvent: (event) => {
160
+ if (started) return;
161
+ dispatch({
162
+ type: "event",
163
+ event,
164
+ remote: true,
165
+ maxEvents: options.maxEvents,
166
+ at: Date.now()
167
+ });
168
+ },
169
+ onState: (s) => {
170
+ if (started && s.running) return;
171
+ dispatch({
172
+ type: "remote",
173
+ remote: {
174
+ running: s.running,
175
+ ...s.runId ? { runId: s.runId } : {},
176
+ ...s.ended ? { ended: s.ended } : {}
177
+ }
178
+ });
179
+ }
180
+ });
181
+ };
182
+ let skillsDb;
183
+ let unfollowSkills;
184
+ const syncSkills = () => {
185
+ const db = dbNameOf(typeof config.learning === "object" ? config.learning.store : void 0);
186
+ if (skillsDb && skillsDb.db === db) return;
187
+ unfollowSkills?.();
188
+ skillsDb = { db };
189
+ unfollowSkills = followOtherTabs(
190
+ core,
191
+ db,
192
+ (change) => change.kind === "skills",
193
+ () => {
194
+ const current = agent;
195
+ if (disposed || !current || typeof current.reloadLearnedSkills !== "function") return;
196
+ void current.reloadLearnedSkills().then((skills) => dispatch({ type: "notebook", lessons: lessonsOf(skills) })).catch(() => {
197
+ });
198
+ }
199
+ );
200
+ };
201
+ const run = async (goal, runOptions) => {
202
+ const current = agent;
203
+ if (disposed || !current || abort) return void 0;
204
+ const controller = new AbortController();
205
+ abort = controller;
206
+ const runControl = createRunControl();
207
+ control = runControl;
208
+ let left = [];
209
+ let stopped = false;
210
+ let began = false;
211
+ const shownGoal = runOptions?.label ?? goal;
212
+ dispatch({ type: "status", status: "running" });
213
+ const shownAtAll = Boolean(shownGoal.trim() || runOptions?.attachments?.length);
214
+ if (shownAtAll) {
215
+ dispatch({
216
+ type: "submitted",
217
+ goal: shownGoal,
218
+ ...runOptions?.attachments?.length ? { attachments: runOptions.attachments } : {}
219
+ });
220
+ }
221
+ try {
222
+ const result = await current.run(goal, {
223
+ signal: controller.signal,
224
+ control: runControl,
225
+ sessionId,
226
+ ...runOptions?.images?.length ? { images: runOptions.images } : {},
227
+ ...runOptions?.files?.length ? { files: runOptions.files } : {},
228
+ onEvent: (event) => {
229
+ const start = event.type === "run.start";
230
+ if (start) {
231
+ started = true;
232
+ began = true;
233
+ }
234
+ const shown = start && runOptions?.label !== void 0 ? { ...event, goal: runOptions.label } : event;
235
+ dispatch({
236
+ type: "event",
237
+ event: shown,
238
+ maxEvents: options.maxEvents,
239
+ at: Date.now(),
240
+ // What the user sent waits with the run: shown as queued meanwhile.
241
+ ...event.type === "session.busy" && shownAtAll ? {
242
+ goal: shownGoal.trim() || (runOptions?.attachments ?? []).map((a) => a.name).join(", ")
243
+ } : {},
244
+ ...start && runOptions?.attachments?.length ? { attachments: runOptions.attachments } : {}
245
+ });
246
+ try {
247
+ options.onEvent?.(event);
248
+ } catch {
249
+ }
250
+ }
251
+ });
252
+ left = result.undelivered ?? [];
253
+ stopped = result.stopped;
254
+ return result;
255
+ } catch (err) {
256
+ left = runControl.pending();
257
+ dispatch({
258
+ type: "event",
259
+ event: { type: "error", phase: "run", error: errMessage(err) },
260
+ maxEvents: options.maxEvents
261
+ });
262
+ return void 0;
263
+ } finally {
264
+ abort = void 0;
265
+ started = false;
266
+ control = void 0;
267
+ settleAll({ approved: false, reason: "the run ended" });
268
+ questionQueue.cancel();
269
+ dispatch({ type: "status", ...buildStatus });
270
+ if (stopped && !began && shownGoal.trim()) left = [shownGoal, ...left];
271
+ if (left.length > 0) {
272
+ if (!controller.signal.aborted && !stopped && options.followUp !== false) {
273
+ dispatch({ type: "undelivered", texts: [] });
274
+ void run(left.join("\n\n"));
275
+ } else {
276
+ dispatch({ type: "undelivered", texts: left });
277
+ }
278
+ } else {
279
+ dispatch({ type: "undelivered", texts: [] });
280
+ }
281
+ }
282
+ };
283
+ const send = (text) => control?.send(text) ?? false;
284
+ let remoteSends = 0;
285
+ const sendRemote = (text) => {
286
+ const current = watch;
287
+ const clean = typeof text === "string" ? text.trim() : "";
288
+ if (!current?.state.running || !clean) return false;
289
+ const id = `to-other-tab-${remoteSends += 1}`;
290
+ dispatch({ type: "remote-send", id, text: clean });
291
+ void current.send(clean).then((ok) => {
292
+ const answer = remoteAnswerOf(ok, watch === current);
293
+ dispatch({ type: "remote-answer", id, text: clean, answer });
294
+ });
295
+ return true;
296
+ };
297
+ const stopRemote = () => {
298
+ if (watch?.state.running) void watch.stop();
299
+ };
300
+ const stopSubagent = (id) => control?.stopSubagent(id) ?? false;
301
+ const sendUndelivered = () => {
302
+ const texts = state.undelivered;
303
+ if (disposed || texts.length === 0) return;
304
+ dispatch({ type: "undelivered", texts: [] });
305
+ void run(texts.join("\n\n"));
306
+ };
307
+ const discardUndelivered = () => dispatch({ type: "undelivered", texts: [] });
308
+ const stop = () => {
309
+ abort?.abort();
310
+ settleAll({ approved: false, reason: "stopped by the user" });
311
+ questionQueue.cancel();
312
+ };
313
+ const answerQuestion = (id, answer) => questionQueue.answer(id, answer);
314
+ const reset = () => {
315
+ if (disposed) return;
316
+ dispatch({ type: "reset" });
317
+ void config.memory?.clear(sessionId).catch(() => {
318
+ });
319
+ };
320
+ const reload = () => {
321
+ if (disposed) return;
322
+ generation += 1;
323
+ build();
324
+ };
325
+ const loadChat = (chat) => {
326
+ if (disposed) return;
327
+ abort?.abort();
328
+ const switched = chat.sessionId !== sessionId;
329
+ sessionId = chat.sessionId;
330
+ if (switched) snapshot = void 0;
331
+ const before = state;
332
+ dispatch({ type: "load", messages: chat.messages ?? [], totalUsage: chat.totalUsage });
333
+ if (switched && state === before) changed();
334
+ syncWatch();
335
+ };
336
+ const forgetSkill = async (name) => {
337
+ const current = agent;
338
+ if (disposed || !current) return false;
339
+ return current.forgetSkill(
340
+ name,
341
+ (event) => dispatch({ type: "event", event, maxEvents: options.maxEvents, at: Date.now() })
342
+ );
343
+ };
344
+ const approve = (id, opts) => {
345
+ if (!approvals.approve(id, { remember: opts?.remember })) {
346
+ appApprovals.approve(id, { remember: opts?.remember });
347
+ }
348
+ };
349
+ const deny = (id, reason) => {
350
+ if (!approvals.deny(id, reason)) appApprovals.deny(id, reason);
351
+ };
352
+ const approveAppToolCall = async ({ frame, ...call }, signal) => {
353
+ const current = agent;
354
+ if (!current) throw new Error("The agent is not ready");
355
+ if (typeof current.approveAppToolCall !== "function") {
356
+ throw new Error("This version of @dudko.dev/agent-web cannot ask about an app’s calls");
357
+ }
358
+ await current.approveAppToolCall(
359
+ call,
360
+ (event) => {
361
+ if (event.type === "tool.approval-resolved") appApprovals.deny(event.id, "no longer asked");
362
+ dispatch({
363
+ type: "event",
364
+ // The frame that asked rides on the request's `app`: drawn with that frame.
365
+ event: frame !== void 0 && event.type === "tool.approval-requested" && event.app ? { ...event, app: { ...event.app, frame } } : event,
366
+ maxEvents: options.maxEvents,
367
+ at: Date.now()
368
+ });
369
+ },
370
+ signal,
371
+ { remembered: options.appToolGrants ?? pageAppToolGrants }
372
+ );
373
+ };
374
+ const sampleForApp = async (request, approveView, signal) => {
375
+ const current = agent;
376
+ if (!current) throw new Error("The agent is not ready");
377
+ if (typeof current.sampleForApp !== "function") {
378
+ throw new Error("This version of @dudko.dev/agent-web cannot answer an app’s sampling");
379
+ }
380
+ return current.sampleForApp(request, {
381
+ approve: approveView,
382
+ ...signal ? { signal } : {},
383
+ sessionId,
384
+ // The only event: its tokens (phase 'app'). The answer is never dispatched.
385
+ onEvent: (event) => dispatch({ type: "event", event, maxEvents: options.maxEvents, at: Date.now() })
386
+ });
387
+ };
388
+ const compact = async () => {
389
+ const current = agent;
390
+ if (disposed || !current) return void 0;
391
+ const result = await current.compact({ sessionId });
392
+ if (result.compacted) {
393
+ dispatch({
394
+ type: "event",
395
+ event: {
396
+ type: "context.compacted",
397
+ scope: "history",
398
+ beforeTokens: result.beforeTokens,
399
+ afterTokens: result.afterTokens
400
+ },
401
+ maxEvents: options.maxEvents,
402
+ at: Date.now()
403
+ });
404
+ }
405
+ return result;
406
+ };
407
+ const update = (next, how = {}) => {
408
+ if (disposed) return;
409
+ const autoStartBefore = options.autoStart;
410
+ config = next;
411
+ if (how.options) options = how.options;
412
+ const nextMode = modeOf(next);
413
+ if (nextMode !== configMode) {
414
+ configMode = nextMode;
415
+ if (nextMode !== mode) setApprovalMode(nextMode);
416
+ }
417
+ if (how.rebuild !== false || !Object.is(options.autoStart, autoStartBefore)) build();
418
+ syncWatch();
419
+ syncSkills();
420
+ };
421
+ const dispose = () => {
422
+ if (disposed) return;
423
+ abort?.abort();
424
+ settleAll({ approved: false, reason: "the view was closed" });
425
+ appApprovals.settleAll({ approved: false, reason: "the view was closed" });
426
+ questionQueue.dispose();
427
+ disposed = true;
428
+ cancelBuild?.();
429
+ cancelBuild = void 0;
430
+ agent = void 0;
431
+ closeWatch();
432
+ unfollowSkills?.();
433
+ unfollowSkills = void 0;
434
+ listeners.clear();
435
+ };
436
+ build();
437
+ syncWatch();
438
+ syncSkills();
439
+ return {
440
+ getSnapshot: () => snapshot ??= snapshotOf(state, { sessionId, pendingQuestions, approvalMode }),
441
+ subscribe: (listener) => {
442
+ if (disposed) return () => {
443
+ };
444
+ listeners.add(listener);
445
+ return () => {
446
+ listeners.delete(listener);
447
+ };
448
+ },
449
+ update,
450
+ dispose,
451
+ get agent() {
452
+ return agent;
453
+ },
454
+ get disposed() {
455
+ return disposed;
456
+ },
457
+ run,
458
+ stop,
459
+ stopRemote,
460
+ send,
461
+ sendRemote,
462
+ stopSubagent,
463
+ forgetSkill,
464
+ sendUndelivered,
465
+ discardUndelivered,
466
+ reset,
467
+ reload,
468
+ approve,
469
+ deny,
470
+ answerQuestion,
471
+ setApprovalMode,
472
+ approveAppToolCall,
473
+ sampleForApp,
474
+ compact,
475
+ loadChat
476
+ };
477
+ };
478
+ export {
479
+ createAgentController,
480
+ createInitialAgentSnapshot
481
+ };
482
+ //# sourceMappingURL=controller.js.map
@@ -0,0 +1 @@
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 loadCh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