@dudko.dev/agent-web-ui 0.0.1 → 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 (265) hide show
  1. package/README.md +94 -3
  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-G7LQTOA2.js +1439 -0
  6. package/dist/{chunk-4EHUITGU.js → chunk-S5AHUAFG.js} +6 -1
  7. package/dist/{chunk-7O64ZI6Z.js → chunk-TJBGZM6D.js} +0 -1
  8. package/dist/{chunk-P2F2P3JC.js → chunk-UNIXGP4N.js} +6 -1
  9. package/dist/{chunk-A55Q377T.js → chunk-V33T6VX3.js} +6 -1
  10. package/dist/{chunk-TPK25QGK.js → chunk-VZCQXE3P.js} +6 -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 +1890 -0
  14. package/dist/controller.d.cts +253 -0
  15. package/dist/controller.d.ts +253 -0
  16. package/dist/controller.js +481 -0
  17. package/dist/{en-CcNUz2tN.d.ts → en-Dg2MtzcJ.d.cts} +6 -0
  18. package/dist/{en-CcNUz2tN.d.cts → en-Dg2MtzcJ.d.ts} +6 -0
  19. package/dist/index.cjs +133 -1
  20. package/dist/index.d.cts +82 -4
  21. package/dist/index.d.ts +82 -4
  22. package/dist/index.js +144 -1422
  23. package/dist/{labels-UuWI7wPo.d.ts → labels-CmiTBLWD.d.cts} +68 -100
  24. package/dist/{labels-D5BrHct4.d.cts → labels-DH1ESUtm.d.ts} +68 -100
  25. package/dist/locales/be.cjs +12 -1
  26. package/dist/locales/be.d.cts +4 -2
  27. package/dist/locales/be.d.ts +4 -2
  28. package/dist/locales/be.js +7 -2
  29. package/dist/locales/bg.cjs +12 -1
  30. package/dist/locales/bg.d.cts +4 -2
  31. package/dist/locales/bg.d.ts +4 -2
  32. package/dist/locales/bg.js +7 -2
  33. package/dist/locales/ca.cjs +12 -1
  34. package/dist/locales/ca.d.cts +4 -2
  35. package/dist/locales/ca.d.ts +4 -2
  36. package/dist/locales/ca.js +7 -2
  37. package/dist/locales/cs.cjs +12 -1
  38. package/dist/locales/cs.d.cts +4 -2
  39. package/dist/locales/cs.d.ts +4 -2
  40. package/dist/locales/cs.js +7 -2
  41. package/dist/locales/da.cjs +12 -1
  42. package/dist/locales/da.d.cts +4 -2
  43. package/dist/locales/da.d.ts +4 -2
  44. package/dist/locales/da.js +7 -2
  45. package/dist/locales/de.cjs +12 -1
  46. package/dist/locales/de.d.cts +4 -2
  47. package/dist/locales/de.d.ts +4 -2
  48. package/dist/locales/de.js +7 -2
  49. package/dist/locales/el.cjs +12 -1
  50. package/dist/locales/el.d.cts +4 -2
  51. package/dist/locales/el.d.ts +4 -2
  52. package/dist/locales/el.js +7 -2
  53. package/dist/locales/en.cjs +12 -1
  54. package/dist/locales/en.d.cts +4 -2
  55. package/dist/locales/en.d.ts +4 -2
  56. package/dist/locales/en.js +7 -2
  57. package/dist/locales/es-419.cjs +16 -2
  58. package/dist/locales/es-419.d.cts +4 -2
  59. package/dist/locales/es-419.d.ts +4 -2
  60. package/dist/locales/es-419.js +6 -4
  61. package/dist/locales/es.cjs +12 -1
  62. package/dist/locales/es.d.cts +4 -2
  63. package/dist/locales/es.d.ts +4 -2
  64. package/dist/locales/es.js +2 -3
  65. package/dist/locales/fi.cjs +12 -1
  66. package/dist/locales/fi.d.cts +4 -2
  67. package/dist/locales/fi.d.ts +4 -2
  68. package/dist/locales/fi.js +7 -2
  69. package/dist/locales/fr-CA.cjs +12 -1
  70. package/dist/locales/fr-CA.d.cts +4 -2
  71. package/dist/locales/fr-CA.d.ts +4 -2
  72. package/dist/locales/fr-CA.js +2 -3
  73. package/dist/locales/fr.cjs +12 -1
  74. package/dist/locales/fr.d.cts +4 -2
  75. package/dist/locales/fr.d.ts +4 -2
  76. package/dist/locales/fr.js +2 -3
  77. package/dist/locales/gn.cjs +12 -1
  78. package/dist/locales/gn.d.cts +4 -2
  79. package/dist/locales/gn.d.ts +4 -2
  80. package/dist/locales/gn.js +7 -2
  81. package/dist/locales/hr.cjs +12 -1
  82. package/dist/locales/hr.d.cts +4 -2
  83. package/dist/locales/hr.d.ts +4 -2
  84. package/dist/locales/hr.js +7 -2
  85. package/dist/locales/ht.cjs +12 -1
  86. package/dist/locales/ht.d.cts +4 -2
  87. package/dist/locales/ht.d.ts +4 -2
  88. package/dist/locales/ht.js +7 -2
  89. package/dist/locales/hu.cjs +12 -1
  90. package/dist/locales/hu.d.cts +4 -2
  91. package/dist/locales/hu.d.ts +4 -2
  92. package/dist/locales/hu.js +7 -2
  93. package/dist/locales/index.cjs +6 -1
  94. package/dist/locales/index.d.cts +6 -4
  95. package/dist/locales/index.d.ts +6 -4
  96. package/dist/locales/index.js +1 -2
  97. package/dist/locales/it.cjs +12 -1
  98. package/dist/locales/it.d.cts +4 -2
  99. package/dist/locales/it.d.ts +4 -2
  100. package/dist/locales/it.js +7 -2
  101. package/dist/locales/nb.cjs +12 -1
  102. package/dist/locales/nb.d.cts +4 -2
  103. package/dist/locales/nb.d.ts +4 -2
  104. package/dist/locales/nb.js +7 -2
  105. package/dist/locales/nl.cjs +12 -1
  106. package/dist/locales/nl.d.cts +4 -2
  107. package/dist/locales/nl.d.ts +4 -2
  108. package/dist/locales/nl.js +7 -2
  109. package/dist/locales/pl.cjs +12 -1
  110. package/dist/locales/pl.d.cts +4 -2
  111. package/dist/locales/pl.d.ts +4 -2
  112. package/dist/locales/pl.js +7 -2
  113. package/dist/locales/pt-BR.cjs +12 -1
  114. package/dist/locales/pt-BR.d.cts +4 -2
  115. package/dist/locales/pt-BR.d.ts +4 -2
  116. package/dist/locales/pt-BR.js +7 -2
  117. package/dist/locales/pt.cjs +12 -1
  118. package/dist/locales/pt.d.cts +4 -2
  119. package/dist/locales/pt.d.ts +4 -2
  120. package/dist/locales/pt.js +7 -2
  121. package/dist/locales/qu.cjs +12 -1
  122. package/dist/locales/qu.d.cts +4 -2
  123. package/dist/locales/qu.d.ts +4 -2
  124. package/dist/locales/qu.js +7 -2
  125. package/dist/locales/ro.cjs +12 -1
  126. package/dist/locales/ro.d.cts +4 -2
  127. package/dist/locales/ro.d.ts +4 -2
  128. package/dist/locales/ro.js +7 -2
  129. package/dist/locales/ru.cjs +12 -1
  130. package/dist/locales/ru.d.cts +4 -2
  131. package/dist/locales/ru.d.ts +4 -2
  132. package/dist/locales/ru.js +7 -2
  133. package/dist/locales/sk.cjs +12 -1
  134. package/dist/locales/sk.d.cts +4 -2
  135. package/dist/locales/sk.d.ts +4 -2
  136. package/dist/locales/sk.js +7 -2
  137. package/dist/locales/sq.cjs +12 -1
  138. package/dist/locales/sq.d.cts +4 -2
  139. package/dist/locales/sq.d.ts +4 -2
  140. package/dist/locales/sq.js +7 -2
  141. package/dist/locales/sr-Latn.cjs +12 -1
  142. package/dist/locales/sr-Latn.d.cts +4 -2
  143. package/dist/locales/sr-Latn.d.ts +4 -2
  144. package/dist/locales/sr-Latn.js +2 -3
  145. package/dist/locales/sr.cjs +12 -1
  146. package/dist/locales/sr.d.cts +4 -2
  147. package/dist/locales/sr.d.ts +4 -2
  148. package/dist/locales/sr.js +2 -3
  149. package/dist/locales/sv.cjs +12 -1
  150. package/dist/locales/sv.d.cts +4 -2
  151. package/dist/locales/sv.d.ts +4 -2
  152. package/dist/locales/sv.js +7 -2
  153. package/dist/locales/tr.cjs +12 -1
  154. package/dist/locales/tr.d.cts +4 -2
  155. package/dist/locales/tr.d.ts +4 -2
  156. package/dist/locales/tr.js +7 -2
  157. package/dist/locales/uk.cjs +12 -1
  158. package/dist/locales/uk.d.cts +4 -2
  159. package/dist/locales/uk.d.ts +4 -2
  160. package/dist/locales/uk.js +7 -2
  161. package/dist/markdown.cjs +0 -1
  162. package/dist/markdown.js +1 -2
  163. package/dist/mcp-app-sandbox.cjs +0 -1
  164. package/dist/mcp-app-sandbox.js +1 -2
  165. package/dist/mcp-app.cjs +0 -1
  166. package/dist/mcp-app.d.cts +491 -3
  167. package/dist/mcp-app.d.ts +491 -3
  168. package/dist/mcp-app.js +2 -3
  169. package/dist/pipeline.cjs +0 -1
  170. package/dist/pipeline.js +1 -2
  171. package/dist/questions-Dw--IEjT.d.cts +100 -0
  172. package/dist/questions-Dw--IEjT.d.ts +100 -0
  173. package/dist/{types-BmvgYUzF.d.cts → types-CQquuZpl.d.cts} +1 -1
  174. package/dist/{types-Cr5gmUts.d.ts → types-CXZfZVP5.d.ts} +1 -1
  175. package/dist/{mcp-app-entry-BA-Ca39z.d.ts → types-DnBCok3z.d.cts} +2 -488
  176. package/dist/{mcp-app-entry-tybABaHg.d.cts → types-DnBCok3z.d.ts} +2 -488
  177. package/package.json +13 -3
  178. package/dist/canvas.cjs.map +0 -1
  179. package/dist/canvas.js.map +0 -1
  180. package/dist/chunk-4EHUITGU.js.map +0 -1
  181. package/dist/chunk-7O64ZI6Z.js.map +0 -1
  182. package/dist/chunk-A55Q377T.js.map +0 -1
  183. package/dist/chunk-EL2YCROY.js.map +0 -1
  184. package/dist/chunk-GB7RZJMG.js.map +0 -1
  185. package/dist/chunk-KZQB35LS.js.map +0 -1
  186. package/dist/chunk-P2F2P3JC.js.map +0 -1
  187. package/dist/chunk-TPK25QGK.js.map +0 -1
  188. package/dist/index.cjs.map +0 -1
  189. package/dist/index.js.map +0 -1
  190. package/dist/locales/be.cjs.map +0 -1
  191. package/dist/locales/be.js.map +0 -1
  192. package/dist/locales/bg.cjs.map +0 -1
  193. package/dist/locales/bg.js.map +0 -1
  194. package/dist/locales/ca.cjs.map +0 -1
  195. package/dist/locales/ca.js.map +0 -1
  196. package/dist/locales/cs.cjs.map +0 -1
  197. package/dist/locales/cs.js.map +0 -1
  198. package/dist/locales/da.cjs.map +0 -1
  199. package/dist/locales/da.js.map +0 -1
  200. package/dist/locales/de.cjs.map +0 -1
  201. package/dist/locales/de.js.map +0 -1
  202. package/dist/locales/el.cjs.map +0 -1
  203. package/dist/locales/el.js.map +0 -1
  204. package/dist/locales/en.cjs.map +0 -1
  205. package/dist/locales/en.js.map +0 -1
  206. package/dist/locales/es-419.cjs.map +0 -1
  207. package/dist/locales/es-419.js.map +0 -1
  208. package/dist/locales/es.cjs.map +0 -1
  209. package/dist/locales/es.js.map +0 -1
  210. package/dist/locales/fi.cjs.map +0 -1
  211. package/dist/locales/fi.js.map +0 -1
  212. package/dist/locales/fr-CA.cjs.map +0 -1
  213. package/dist/locales/fr-CA.js.map +0 -1
  214. package/dist/locales/fr.cjs.map +0 -1
  215. package/dist/locales/fr.js.map +0 -1
  216. package/dist/locales/gn.cjs.map +0 -1
  217. package/dist/locales/gn.js.map +0 -1
  218. package/dist/locales/hr.cjs.map +0 -1
  219. package/dist/locales/hr.js.map +0 -1
  220. package/dist/locales/ht.cjs.map +0 -1
  221. package/dist/locales/ht.js.map +0 -1
  222. package/dist/locales/hu.cjs.map +0 -1
  223. package/dist/locales/hu.js.map +0 -1
  224. package/dist/locales/index.cjs.map +0 -1
  225. package/dist/locales/index.js.map +0 -1
  226. package/dist/locales/it.cjs.map +0 -1
  227. package/dist/locales/it.js.map +0 -1
  228. package/dist/locales/nb.cjs.map +0 -1
  229. package/dist/locales/nb.js.map +0 -1
  230. package/dist/locales/nl.cjs.map +0 -1
  231. package/dist/locales/nl.js.map +0 -1
  232. package/dist/locales/pl.cjs.map +0 -1
  233. package/dist/locales/pl.js.map +0 -1
  234. package/dist/locales/pt-BR.cjs.map +0 -1
  235. package/dist/locales/pt-BR.js.map +0 -1
  236. package/dist/locales/pt.cjs.map +0 -1
  237. package/dist/locales/pt.js.map +0 -1
  238. package/dist/locales/qu.cjs.map +0 -1
  239. package/dist/locales/qu.js.map +0 -1
  240. package/dist/locales/ro.cjs.map +0 -1
  241. package/dist/locales/ro.js.map +0 -1
  242. package/dist/locales/ru.cjs.map +0 -1
  243. package/dist/locales/ru.js.map +0 -1
  244. package/dist/locales/sk.cjs.map +0 -1
  245. package/dist/locales/sk.js.map +0 -1
  246. package/dist/locales/sq.cjs.map +0 -1
  247. package/dist/locales/sq.js.map +0 -1
  248. package/dist/locales/sr-Latn.cjs.map +0 -1
  249. package/dist/locales/sr-Latn.js.map +0 -1
  250. package/dist/locales/sr.cjs.map +0 -1
  251. package/dist/locales/sr.js.map +0 -1
  252. package/dist/locales/sv.cjs.map +0 -1
  253. package/dist/locales/sv.js.map +0 -1
  254. package/dist/locales/tr.cjs.map +0 -1
  255. package/dist/locales/tr.js.map +0 -1
  256. package/dist/locales/uk.cjs.map +0 -1
  257. package/dist/locales/uk.js.map +0 -1
  258. package/dist/markdown.cjs.map +0 -1
  259. package/dist/markdown.js.map +0 -1
  260. package/dist/mcp-app-sandbox.cjs.map +0 -1
  261. package/dist/mcp-app-sandbox.js.map +0 -1
  262. package/dist/mcp-app.cjs.map +0 -1
  263. package/dist/mcp-app.js.map +0 -1
  264. package/dist/pipeline.cjs.map +0 -1
  265. package/dist/pipeline.js.map +0 -1
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  tokenizeHtml,
13
13
  withCspFirst,
14
14
  withPolicyFirst
15
- } from "./chunk-EL2YCROY.js";
15
+ } from "./chunk-D64VLIRY.js";
16
16
  import {
17
17
  NAMED_FILES_MAX,
18
18
  NAMED_FILES_SCAN_MAX,
@@ -20,1356 +20,30 @@ import {
20
20
  namedFilesOf,
21
21
  pathsNamedIn,
22
22
  workspacePathOf
23
- } from "./chunk-7O64ZI6Z.js";
24
-
25
- // src/state.ts
23
+ } from "./chunk-TJBGZM6D.js";
26
24
  import {
27
- isReplayedToolOutput
28
- } from "@dudko.dev/agent-web";
29
-
30
- // src/questions.ts
31
- var ASK_USER_TOOL_NAME = "ask_user";
32
- var QUESTION_TIMEOUT_MS = 3e5;
33
- var TIMER_MAX_MS = 2147483647;
34
- var questionTimeoutOf = (askUser) => {
35
- if (!askUser) return void 0;
36
- const raw = askUser === true ? void 0 : askUser.timeoutMs;
37
- if (raw === void 0 || raw === null) return QUESTION_TIMEOUT_MS;
38
- if (typeof raw !== "number" || !(raw > 0) || raw > TIMER_MAX_MS) return void 0;
39
- return Math.max(1, Math.floor(raw));
40
- };
41
- var askUserWith = (askUser, handler) => {
42
- if (!askUser) return askUser;
43
- if (askUser === true) return { onQuestion: handler };
44
- return askUser.onQuestion ? askUser : { ...askUser, onQuestion: handler };
45
- };
46
- var DECLINED = { declined: true };
47
- var createQuestionQueue = (options = {}) => {
48
- const now = options.now ?? Date.now;
49
- const waiting = /* @__PURE__ */ new Map();
50
- let disposed = false;
51
- const list = () => [...waiting.values()].map((w) => w.question);
52
- const changed = () => {
53
- if (!disposed) options.onChange?.(list());
54
- };
55
- const handler = (request, ctx) => new Promise((resolve) => {
56
- const signal = ctx?.signal;
57
- if (disposed || signal?.aborted || waiting.has(request.id)) {
58
- resolve(DECLINED);
59
- return;
60
- }
61
- const onAbort = () => {
62
- if (waiting.get(request.id)?.settle !== settle) return;
63
- settle(DECLINED);
64
- changed();
65
- };
66
- const settle = (answer) => {
67
- waiting.delete(request.id);
68
- signal?.removeEventListener("abort", onAbort);
69
- resolve(answer);
70
- };
71
- signal?.addEventListener("abort", onAbort, { once: true });
72
- const timeoutMs = typeof options.timeoutMs === "function" ? options.timeoutMs() : options.timeoutMs;
73
- waiting.set(request.id, {
74
- question: {
75
- ...request,
76
- options: request.options.map((o) => ({ ...o })),
77
- ...timeoutMs !== void 0 ? { expiresAt: now() + timeoutMs } : {}
78
- },
79
- settle
80
- });
81
- changed();
82
- });
83
- return {
84
- handler,
85
- pending: list,
86
- answer: (id, answer) => {
87
- const entry = waiting.get(id);
88
- if (!entry) return false;
89
- entry.settle(answer);
90
- changed();
91
- return true;
92
- },
93
- cancel: (match) => {
94
- let any = false;
95
- for (const entry of [...waiting.values()]) {
96
- if (match && !match(entry.question)) continue;
97
- entry.settle(DECLINED);
98
- any = true;
99
- }
100
- if (any) changed();
101
- },
102
- dispose: () => {
103
- disposed = true;
104
- for (const entry of [...waiting.values()]) entry.settle(DECLINED);
105
- }
106
- };
107
- };
108
- var questionChoiceOf = (question, picked) => {
109
- const chosen = question.options.map((o) => o.label).filter((label) => picked.includes(label));
110
- if (chosen.length === 0) return void 0;
111
- return { choice: question.multiple ? chosen : chosen.slice(0, 1) };
112
- };
113
- var questionOtherOf = (question, text2) => question.allowOther && typeof text2 === "string" && text2.trim() ? { other: text2.trim() } : void 0;
114
- var LABELS_ONLY = [
115
- "The user chose: ",
116
- "The user chose not to answer.",
117
- "The user did not answer in time.",
118
- "The question could not be put to the user",
119
- "You have already asked the user "
120
- ];
121
- var askUserOutputKept = (output, ok) => (
122
- // A failed call is about the model's own arguments (a bad question): nobody was asked.
123
- !ok || typeof output === "string" && LABELS_ONLY.some((start) => output.startsWith(start))
124
- );
125
- var withoutOutput = (call) => {
126
- if (call.name !== ASK_USER_TOOL_NAME || askUserOutputKept(call.output, call.ok)) return call;
127
- const { output: _dropped, ...rest } = call;
128
- void _dropped;
129
- return rest;
130
- };
131
- var withoutOwnWords = (event) => {
132
- switch (event.type) {
133
- case "step.tool-result": {
134
- const cleaned = withoutOutput(event);
135
- return cleaned === event ? event : { ...cleaned, output: void 0 };
136
- }
137
- case "step.complete": {
138
- const calls = event.result.toolCalls;
139
- const cleaned = calls.map(withoutOutput);
140
- return cleaned.every((c, i) => c === calls[i]) ? event : { ...event, result: { ...event.result, toolCalls: cleaned } };
141
- }
142
- case "subagent.event": {
143
- const inner = withoutOwnWords(event.event);
144
- return inner === event.event ? event : { ...event, event: inner };
145
- }
146
- default:
147
- return event;
148
- }
149
- };
150
-
151
- // src/state.ts
152
- var approxTokens = (value) => {
153
- if (value === void 0) return 0;
154
- let text2;
155
- try {
156
- text2 = typeof value === "string" ? value : JSON.stringify(value) ?? "";
157
- } catch {
158
- text2 = String(value);
159
- }
160
- return Math.ceil(text2.length / 4);
161
- };
162
- var emptyUsage = () => ({
163
- inputTokens: 0,
164
- outputTokens: 0,
165
- totalTokens: 0,
166
- reasoningTokens: 0,
167
- cachedInputTokens: 0,
168
- cacheWriteTokens: 0
169
- });
170
- var USAGE_COUNTS = [
171
- "mediaCalls",
172
- "imagesGenerated",
173
- "speechCharacters",
174
- "transcriptionSeconds",
175
- "decisionCalls"
176
- ];
177
- var addUsage = (a, b) => {
178
- const sum = {
179
- inputTokens: a.inputTokens + b.inputTokens,
180
- outputTokens: a.outputTokens + b.outputTokens,
181
- totalTokens: a.totalTokens + b.totalTokens,
182
- reasoningTokens: (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0),
183
- cachedInputTokens: (a.cachedInputTokens ?? 0) + (b.cachedInputTokens ?? 0),
184
- cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0)
185
- };
186
- for (const key of USAGE_COUNTS) {
187
- const n = (a[key] ?? 0) + (b[key] ?? 0);
188
- if (n) sum[key] = n;
189
- }
190
- return sum;
191
- };
192
- var lessonsOf = (skills) => skills.filter((s) => s.origin?.kind === "learned").map((s) => ({
193
- name: s.name,
194
- description: s.description,
195
- revision: s.origin?.revision ?? 1,
196
- chars: s.content.length,
197
- sources: [...s.origin?.sources ?? [], ...s.origin?.fetched ?? []]
198
- }));
199
- var createInitialAgentState = () => ({
200
- status: "idle",
201
- goal: void 0,
202
- plan: void 0,
203
- planThought: "",
204
- steps: [],
205
- finalText: "",
206
- finalReasoning: "",
207
- totalUsage: emptyUsage(),
208
- runStartedAt: void 0,
209
- runMessageId: void 0,
210
- approvals: [],
211
- subagents: [],
212
- queued: [],
213
- notes: [],
214
- undelivered: [],
215
- skills: [],
216
- learned: [],
217
- learnedNow: [],
218
- fetches: [],
219
- discoveredTools: [],
220
- compactions: [],
221
- budget: void 0,
222
- usage: emptyUsage(),
223
- modelLoad: void 0,
224
- replan: void 0,
225
- error: void 0,
226
- stopped: false,
227
- messages: [],
228
- events: [],
229
- seq: 0
230
- });
231
- var BLOCKER_MARK = "[BLOCKER]";
232
- var resetRun = (state) => ({
233
- ...createInitialAgentState(),
234
- status: state.status,
235
- messages: state.messages,
236
- totalUsage: state.totalUsage,
237
- seq: state.seq,
238
- learned: state.learned,
239
- // An MCP App's request is the user's, not the run's: it waits across runs.
240
- approvals: state.approvals.filter((a) => a.app && a.status === "pending"),
241
- // So is what this tab sent to another tab's run, until that tab answers (a replay that opens
242
- // with the run's start is not an answer).
243
- queued: sentToOtherTab(state.queued)
244
- });
245
- var sentToOtherTab = (queued) => queued.filter((q) => q.sentTo === "another-tab");
246
- var sentEntryOf = (queued, text2) => queued.findIndex(
247
- (q) => q.sentTo === "another-tab" && (q.text === text2 || text2.endsWith("…") && q.text.length > text2.length && q.text.startsWith(text2.slice(0, -1)))
248
- );
249
- var patchStep = (steps, id, fn) => steps.map((s) => s.id === id ? fn(s) : s);
250
- var withoutSkillBody = (a) => {
251
- if (!a.skill || a.skill.body === void 0) return a;
252
- const { body: _body, ...skill } = a.skill;
253
- return { ...a, skill };
254
- };
255
- var patchApproval = (approvals, id, fn) => approvals.map((a) => a.id === id ? fn(a) : a);
256
- var STATUS_OF_ACTION = {
257
- accept: "accepted",
258
- decline: "declined",
259
- cancel: "cancelled"
260
- };
261
- var addElicitation = (state, event, extra) => state.elicitations?.some((e) => e.id === event.id) ? state : {
262
- ...state,
263
- elicitations: [
264
- ...state.elicitations ?? [],
265
- {
266
- id: event.id,
267
- server: event.server,
268
- tool: event.tool,
269
- mode: event.mode,
270
- message: event.message,
271
- ...event.requestedSchema ? { requestedSchema: event.requestedSchema } : {},
272
- ...event.url ? { url: event.url } : {},
273
- ...extra.stepId ? { stepId: extra.stepId } : {},
274
- ...extra.subagent ? { subagent: extra.subagent } : {},
275
- ...extra.remote ? { remote: true } : {},
276
- status: "pending"
277
- }
278
- ]
279
- };
280
- var answerElicitation = (state, event, stepId) => {
281
- const answered = (e) => ({
282
- ...e,
283
- status: STATUS_OF_ACTION[event.action],
284
- automatic: event.automatic,
285
- ...event.reason ? { reason: event.reason } : {},
286
- ...event.fields ? { fields: event.fields } : {}
287
- });
288
- const list = state.elicitations ?? [];
289
- return {
290
- ...state,
291
- elicitations: list.some((e) => e.id === event.id) ? list.map((e) => e.id === event.id ? answered(e) : e) : [
292
- ...list,
293
- answered({
294
- id: event.id,
295
- server: event.server,
296
- tool: event.tool,
297
- message: "",
298
- ...stepId ? { stepId } : {},
299
- status: "pending"
300
- })
301
- ]
302
- };
303
- };
304
- var addQuestion = (state, event, extra) => state.questions?.some((q) => q.id === event.id) ? state : {
305
- ...state,
306
- questions: [
307
- ...state.questions ?? [],
308
- {
309
- id: event.id,
310
- question: event.question,
311
- options: event.options.map((o) => ({ ...o })),
312
- multiple: event.multiple,
313
- allowOther: event.allowOther,
314
- ...extra.stepId ? { stepId: extra.stepId } : {},
315
- ...extra.subagent ? { subagent: extra.subagent } : {},
316
- ...extra.remote ? { remote: true } : {},
317
- status: "pending"
318
- }
319
- ]
320
- };
321
- var answerQuestion = (state, event) => state.questions?.some((q) => q.id === event.id) ? {
322
- ...state,
323
- questions: state.questions.map(
324
- (q) => q.id === event.id ? {
325
- ...q,
326
- status: event.action,
327
- automatic: event.automatic,
328
- ...event.action === "choice" && event.choice ? { choice: [...event.choice] } : {},
329
- ...event.reason ? { reason: event.reason } : {}
330
- } : q
331
- )
332
- } : state;
333
- var patchSubagent = (subagents, id, fn) => subagents.map((s) => s.id === id ? fn(s) : s);
334
- var runningStepId = (steps) => [...steps].reverse().find((s) => s.status === "running")?.id;
335
- var applySubagentEvent = (view, event) => {
336
- switch (event.type) {
337
- case "step.start":
338
- return {
339
- ...view,
340
- steps: view.steps + 1,
341
- activity: `step ${event.index}/${event.total}: ${event.step.description}`,
342
- // Known only when the child runs with model tiers.
343
- ...event.model !== void 0 ? { model: event.model } : {},
344
- ...event.tier !== void 0 ? { tier: event.tier } : {}
345
- };
346
- case "step.escalated":
347
- return { ...view, tier: event.to, ...event.model ? { model: event.model } : {} };
348
- case "step.tool-call":
349
- return { ...view, toolCalls: view.toolCalls + 1, activity: `→ ${event.name}` };
350
- case "final.text-delta":
351
- return { ...view, text: view.text + event.delta, activity: "writing the answer" };
352
- case "final":
353
- return { ...view, text: event.text };
354
- case "usage":
355
- return { ...view, usage: addUsage(view.usage, event.usage) };
356
- default:
357
- return view;
358
- }
359
- };
360
- var ensureSubagent = (state, id, name, ancestors, ctx) => {
361
- if (state.subagents.some((s) => s.id === id)) return state;
362
- const parentId = ancestors[ancestors.length - 1]?.id;
363
- const parent = parentId ? state.subagents.find((s) => s.id === parentId) : void 0;
364
- const stepId = parent ? parent.stepId : runningStepId(state.steps);
365
- const node = {
366
- id,
367
- name,
368
- task: "",
369
- ...parentId ? { parentId } : {},
370
- depth: ancestors.length + 1,
371
- status: "running",
372
- ...stepId ? { stepId } : {},
373
- ...ctx.at !== void 0 ? { startedAt: ctx.at } : {},
374
- activity: "starting",
375
- steps: 0,
376
- toolCalls: 0,
377
- text: "",
378
- usage: emptyUsage()
379
- };
380
- return { ...state, subagents: [...state.subagents, node] };
381
- };
382
- var startSubagent = (state, event, ancestors, ctx) => {
383
- const depth = Math.max(event.depth ?? 1, ancestors.length + 1);
384
- const parentId = ancestors[ancestors.length - 1]?.id ?? (depth > 1 ? event.parentId : void 0);
385
- const told = {
386
- name: event.name,
387
- task: event.task,
388
- depth,
389
- ...parentId ? { parentId } : {},
390
- ...event.profile ? { profile: event.profile } : {},
391
- ...event.dynamic ? { dynamic: true } : {},
392
- ...event.role ? { role: event.role } : {},
393
- ...event.tools ? { tools: event.tools } : {}
394
- };
395
- if (state.subagents.some((s) => s.id === event.id)) {
396
- return {
397
- ...state,
398
- subagents: patchSubagent(state.subagents, event.id, (s) => ({ ...s, ...told }))
399
- };
400
- }
401
- const parent = parentId ? state.subagents.find((s) => s.id === parentId) : void 0;
402
- const stepId = parent ? parent.stepId : runningStepId(state.steps);
403
- const node = {
404
- id: event.id,
405
- ...told,
406
- status: "running",
407
- stepId,
408
- ...ctx.at !== void 0 ? { startedAt: ctx.at } : {},
409
- activity: "starting",
410
- steps: 0,
411
- toolCalls: 0,
412
- text: "",
413
- usage: emptyUsage()
414
- };
415
- return { ...state, subagents: [...state.subagents, node] };
416
- };
417
- var subagentDuration = (s, at) => at !== void 0 && s.startedAt !== void 0 ? { durationMs: Math.max(0, at - s.startedAt) } : {};
418
- var addMedia = (state, view) => ({
419
- ...state,
420
- media: [...state.media ?? [], view],
421
- ...view.stepId ? {
422
- steps: patchStep(state.steps, view.stepId, (s) => ({
423
- ...s,
424
- media: [...s.media ?? [], view]
425
- }))
426
- } : {}
427
- });
428
- var mediaOf = (event, withStep) => ({
429
- kind: event.kind,
430
- path: event.path,
431
- mediaType: event.mediaType,
432
- bytes: event.bytes,
433
- model: event.model,
434
- ...event.references ? {
435
- references: {
436
- used: event.references.used === true,
437
- count: event.references.count,
438
- paths: [...event.references.paths]
439
- }
440
- } : {},
441
- ...withStep && event.step ? { stepId: event.step.id } : {}
442
- });
443
- var addApp = (state, event, by) => {
444
- if (state.apps?.some((a) => a.id === event.id)) return state;
445
- const view = {
446
- id: event.id,
447
- server: event.server,
448
- tool: event.tool,
449
- toolName: event.toolName,
450
- resourceUri: event.resourceUri,
451
- input: event.input,
452
- ...event.result ? { result: event.result } : {},
453
- ...!by && event.step ? { stepId: event.step.id } : {},
454
- ...by ? { by } : {}
455
- };
456
- const steps = !by && event.step ? patchStep(state.steps, event.step.id, (s) => {
457
- let i = s.toolCalls.length - 1;
458
- while (i >= 0 && !(s.toolCalls[i].name === event.tool && !s.toolCalls[i].app)) i -= 1;
459
- if (i < 0) return s;
460
- const toolCalls = s.toolCalls.slice();
461
- toolCalls[i] = { ...toolCalls[i], app: event.id };
462
- return { ...s, toolCalls };
463
- }) : state.steps;
464
- return { ...state, steps, apps: [...state.apps ?? [], view] };
465
- };
466
- var fileWritten = (state, event, by) => {
467
- const files = state.writtenFiles ?? [];
468
- const i = files.findIndex((f) => f.path === event.path);
469
- const view = {
470
- path: event.path,
471
- mediaType: event.mediaType,
472
- bytes: event.bytes,
473
- writes: (i >= 0 ? files[i].writes : 0) + 1,
474
- ...!by && event.step ? { stepId: event.step.id } : {},
475
- ...by ? { by } : {}
476
- };
477
- return {
478
- ...state,
479
- writtenFiles: i >= 0 ? files.map((f, k) => k === i ? view : f) : [...files, view]
480
- };
481
- };
482
- var fileDeleted = (state, path) => state.writtenFiles?.some((f) => f.path === path) ? { ...state, writtenFiles: state.writtenFiles.filter((f) => f.path !== path) } : state;
483
- var transcriptOf = (event) => ({
484
- source: event.source,
485
- name: event.name,
486
- text: event.text,
487
- ...event.language ? { language: event.language } : {},
488
- ...event.durationInSeconds !== void 0 ? { durationInSeconds: event.durationInSeconds } : {},
489
- model: event.model
490
- });
491
- var applySubagent = (state, event, ancestors, ctx) => {
492
- switch (event.type) {
493
- case "subagent.start":
494
- return startSubagent(state, event, ancestors, ctx);
495
- case "subagent.event": {
496
- const known = ensureSubagent(state, event.id, event.name, ancestors, ctx);
497
- const inner = event.event;
498
- switch (inner.type) {
499
- case "subagent.start":
500
- case "subagent.event":
501
- case "subagent.complete":
502
- case "subagent.error":
503
- return applySubagent(known, inner, [...ancestors, { id: event.id }], ctx);
504
- // A helper the model started asks through the run's own consent gate (the event says
505
- // which helper): its request is the user's to answer, like the run's. A subagent with
506
- // a gate of its own (no `subagent` on the event) is its host's business.
507
- case "tool.approval-requested": {
508
- if (!inner.subagent || known.approvals.some((a) => a.id === inner.id)) return known;
509
- const node = known.subagents.find((s) => s.id === inner.subagent.id);
510
- return {
511
- ...known,
512
- approvals: [
513
- ...known.approvals,
514
- {
515
- id: inner.id,
516
- name: inner.name,
517
- input: inner.input,
518
- readOnly: inner.readOnly,
519
- // The helper's own step ids mean nothing here: the step that delegated it does.
520
- stepId: node?.stepId,
521
- subagent: {
522
- id: inner.subagent.id,
523
- depth: inner.subagent.depth,
524
- ...node ? { name: node.name } : {},
525
- ...node?.role ? { role: node.role } : {}
526
- },
527
- ...inner.skill ? { skill: inner.skill } : {},
528
- ...inner.rule ? { rule: inner.rule } : {},
529
- ...ctx.remote ? { remote: true } : {},
530
- status: "pending"
531
- }
532
- ]
533
- };
534
- }
535
- case "tool.approval-resolved":
536
- return known.approvals.some((a) => a.id === inner.id) ? {
537
- ...known,
538
- approvals: patchApproval(
539
- known.approvals,
540
- inner.id,
541
- (a) => withoutSkillBody({
542
- ...a,
543
- status: inner.approved ? "approved" : "denied",
544
- reason: inner.reason,
545
- automatic: inner.automatic
546
- })
547
- )
548
- } : known;
549
- // A server asks the user during a subagent's tool call (the connection lets helpers
550
- // ask): the question is the user's to answer, like the run's own.
551
- case "mcp.elicitation-requested": {
552
- const node = inner.subagent ? known.subagents.find((s) => s.id === inner.subagent.id) : void 0;
553
- return addElicitation(known, inner, {
554
- ...ctx.remote ? { remote: true } : {},
555
- // The subagent's own step ids mean nothing here: the step that delegated it does.
556
- stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,
557
- ...inner.subagent ? {
558
- subagent: {
559
- id: inner.subagent.id,
560
- depth: inner.subagent.depth,
561
- ...node ? { name: node.name } : {},
562
- ...node?.role ? { role: node.role } : {}
563
- }
564
- } : {}
565
- });
566
- }
567
- case "mcp.elicitation-answered":
568
- return answerElicitation(
569
- known,
570
- inner,
571
- known.subagents.find((s) => s.id === event.id)?.stepId
572
- );
573
- // A helper (or a subagent the host defined) asks the person through the run's handler:
574
- // the question is the person's to answer, like the run's own, marked with who asks.
575
- case "user.question-asked": {
576
- const asker = inner.subagent ?? { id: event.id, depth: ancestors.length + 1 };
577
- const node = known.subagents.find((s) => s.id === asker.id);
578
- return addQuestion(known, inner, {
579
- ...ctx.remote ? { remote: true } : {},
580
- // The helper's own step ids mean nothing here: the step that delegated it does.
581
- stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,
582
- subagent: {
583
- id: asker.id,
584
- depth: asker.depth,
585
- ...node ? { name: node.name } : {},
586
- ...node?.role ? { role: node.role } : {}
587
- }
588
- });
589
- }
590
- case "user.question-answered":
591
- return answerQuestion(known, inner);
592
- // What a subagent generated is in the same workspace: it shows in the turn (its step
593
- // ids are its own, so it is tied to no step here).
594
- case "media.generated":
595
- return addMedia(known, mediaOf(inner, false));
596
- case "media.transcribed":
597
- return { ...known, transcripts: [...known.transcripts ?? [], transcriptOf(inner)] };
598
- // A subagent works in the same workspace: what it wrote belongs to the turn, and says
599
- // who wrote it.
600
- case "file.written": {
601
- const node = known.subagents.find((s) => s.id === event.id);
602
- return fileWritten(known, inner, {
603
- id: event.id,
604
- name: node?.name ?? event.name,
605
- ...node?.role ? { role: node.role } : {}
606
- });
607
- }
608
- case "file.deleted":
609
- return fileDeleted(known, inner.path);
610
- // An app a subagent's call came with is shown in the turn too, and says whose call it was.
611
- case "mcp.app": {
612
- if (ctx.remote) return known;
613
- const node = known.subagents.find((s) => s.id === event.id);
614
- return addApp(known, inner, {
615
- id: event.id,
616
- name: node?.name ?? event.name,
617
- ...node?.role ? { role: node.role } : {}
618
- });
619
- }
620
- default:
621
- return {
622
- ...known,
623
- subagents: patchSubagent(
624
- known.subagents,
625
- event.id,
626
- (s) => applySubagentEvent(s, inner)
627
- )
628
- };
629
- }
630
- }
631
- case "subagent.complete": {
632
- const known = ensureSubagent(state, event.id, event.name, ancestors, ctx);
633
- return {
634
- ...known,
635
- subagents: patchSubagent(known.subagents, event.id, (s) => ({
636
- ...s,
637
- status: "done",
638
- activity: "done",
639
- text: event.text,
640
- usage: event.usage,
641
- ...subagentDuration(s, ctx.at)
642
- }))
643
- };
644
- }
645
- case "subagent.error": {
646
- const known = ensureSubagent(state, event.id, event.name, ancestors, ctx);
647
- return {
648
- ...known,
649
- subagents: patchSubagent(known.subagents, event.id, (s) => ({
650
- ...s,
651
- status: event.stopped ? "stopped" : "error",
652
- activity: event.stopped ? "stopped" : "failed",
653
- error: event.error,
654
- // A helper says what it had spent when it ended; a static subagent does not.
655
- ...event.usage ? { usage: event.usage } : {},
656
- ...subagentDuration(s, ctx.at)
657
- }))
658
- };
659
- }
660
- }
661
- };
662
- var subagentTree = (subagents) => {
663
- const nodes = /* @__PURE__ */ new Map();
664
- for (const s of subagents) nodes.set(s.id, { ...s, children: [] });
665
- const loops = (node) => {
666
- let up = node.parentId;
667
- for (let i = 0; up !== void 0 && i <= nodes.size; i++) {
668
- if (up === node.id) return true;
669
- up = nodes.get(up)?.parentId;
670
- }
671
- return false;
672
- };
673
- const roots = [];
674
- for (const node of nodes.values()) {
675
- const parent = node.parentId !== void 0 && !loops(node) ? nodes.get(node.parentId) : void 0;
676
- if (parent) parent.children.push(node);
677
- else roots.push(node);
678
- }
679
- return roots;
680
- };
681
- var finalizeAssistant = (messages, content, extra = {}) => {
682
- for (let i = messages.length - 1; i >= 0; i--) {
683
- const m = messages[i];
684
- if (m.role === "assistant" && m.pending) {
685
- const next = messages.slice();
686
- next[i] = { ...m, content: content || m.content, pending: false, ...extra };
687
- return next;
688
- }
689
- }
690
- return messages;
691
- };
692
- var runDuration = (state, at) => at !== void 0 && state.runStartedAt !== void 0 ? { durationMs: Math.max(0, at - state.runStartedAt) } : {};
693
- var streamAssistant = (messages, content) => {
694
- for (let i = messages.length - 1; i >= 0; i--) {
695
- const m = messages[i];
696
- if (m.role === "assistant" && m.pending) {
697
- const next = messages.slice();
698
- next[i] = { ...m, content };
699
- return next;
700
- }
701
- }
702
- return messages;
703
- };
704
- var WAITING_ID = "waiting-for-session";
705
- var withoutBusy = (state) => {
706
- if (!state.sessionBusy) return state;
707
- const { sessionBusy: _over, ...rest } = state;
708
- void _over;
709
- return { ...rest, queued: rest.queued.filter((q) => q.id !== WAITING_ID) };
710
- };
711
- var withoutSubmitted = (state) => {
712
- if (!state.submitted) return state;
713
- const { submitted, ...rest } = state;
714
- const ids = /* @__PURE__ */ new Set([submitted.userId, submitted.assistantId]);
715
- return { ...rest, messages: rest.messages.filter((m) => !ids.has(m.id)) };
716
- };
717
- var keepSubmitted = (state) => {
718
- if (!state.submitted) return state;
719
- const { submitted: _kept, ...rest } = state;
720
- void _kept;
721
- return rest;
722
- };
723
- var applyEvent = (state, event, ctx) => {
724
- switch (event.type) {
725
- case "run.start": {
726
- const base = resetRun(ctx.remote ? state : withoutSubmitted(state));
727
- const userId = `msg-${base.seq}`;
728
- const assistantId = `msg-${base.seq + 1}`;
729
- const began = ctx.at !== void 0 ? { startedAt: ctx.at } : {};
730
- return {
731
- ...base,
732
- // Another tab's run keeps the view of it; a run of this tab's ends it (and any wait).
733
- ...ctx.remote && state.remote ? { remote: state.remote } : {},
734
- // ...and this tab's sent turn, still waiting for its own run.start (or a session.busy).
735
- ...ctx.remote && state.submitted ? { submitted: state.submitted } : {},
736
- goal: event.goal,
737
- runStartedAt: ctx.at,
738
- runMessageId: assistantId,
739
- messages: [
740
- ...base.messages,
741
- {
742
- id: userId,
743
- role: "user",
744
- content: event.goal,
745
- pending: false,
746
- ...ctx.remote ? { remote: true } : {},
747
- ...began,
748
- ...ctx.attachments?.length ? { attachments: ctx.attachments } : {}
749
- },
750
- {
751
- id: assistantId,
752
- role: "assistant",
753
- content: "",
754
- pending: true,
755
- ...ctx.remote ? { remote: true } : {},
756
- ...began
757
- }
758
- ],
759
- seq: base.seq + 2
760
- };
761
- }
762
- case "model.load":
763
- return { ...state, modelLoad: { progress: event.progress, text: event.text } };
764
- case "plan.thought-delta":
765
- return { ...state, planThought: state.planThought + event.delta };
766
- case "plan.created":
767
- return {
768
- ...state,
769
- plan: event.plan,
770
- planThought: state.planThought || event.plan.thought
771
- };
772
- case "plan.revised":
773
- return {
774
- ...state,
775
- plan: event.plan,
776
- // `replan.decision` came first: keep its "because the user spoke" flag.
777
- replan: {
778
- mode: "revise",
779
- reason: event.reason,
780
- ...state.replan?.byUser ? { byUser: true } : {}
781
- }
782
- };
783
- case "plan.step-added":
784
- return state;
785
- case "step.start": {
786
- const view = {
787
- id: event.step.id,
788
- index: event.index,
789
- total: event.total,
790
- step: event.step,
791
- text: "",
792
- reasoning: "",
793
- toolCalls: [],
794
- status: "running",
795
- blocked: false,
796
- // Only with `config.executorTiers`: without it the view is what it always was.
797
- ...event.tier !== void 0 ? { tier: event.tier } : {},
798
- ...event.model !== void 0 ? { model: event.model } : {},
799
- ...event.tierReason !== void 0 ? { tierReason: event.tierReason } : {}
800
- };
801
- const steps = state.steps.map(
802
- (s) => s.total === event.total ? s : { ...s, total: event.total }
803
- );
804
- return { ...state, steps: [...steps, view] };
805
- }
806
- case "step.escalated":
807
- return {
808
- ...state,
809
- steps: patchStep(state.steps, event.step.id, (s) => {
810
- const attempt = (s.escalations?.length ?? 0) + 1;
811
- return {
812
- ...s,
813
- tier: event.to,
814
- ...event.model ? { model: event.model } : {},
815
- text: "",
816
- reasoning: "",
817
- toolCalls: s.toolCalls.map((c) => c.attempt === void 0 ? { ...c, attempt } : c),
818
- escalations: [
819
- ...s.escalations ?? [],
820
- {
821
- from: event.from,
822
- to: event.to,
823
- reason: event.reason,
824
- ...event.model ? { model: event.model } : {},
825
- ...s.text.trim() ? { text: s.text } : {}
826
- }
827
- ]
828
- };
829
- })
830
- };
831
- case "step.reasoning-delta":
832
- return {
833
- ...state,
834
- steps: patchStep(state.steps, event.step.id, (s) => ({
835
- ...s,
836
- reasoning: s.reasoning + event.delta
837
- }))
838
- };
839
- case "step.text-delta":
840
- return {
841
- ...state,
842
- // "[BLOCKER]" is the executor's signal to the core that a step cannot be completed (the
843
- // core strips it from the step's summary): never a word for the user. Stripped from the
844
- // text as it accumulates, so a marker split across two deltas goes too.
845
- steps: patchStep(state.steps, event.step.id, (s) => ({
846
- ...s,
847
- text: (s.text + event.delta).split(BLOCKER_MARK).join("")
848
- }))
849
- };
850
- case "step.tool-call": {
851
- const tagged = new Set(
852
- state.steps.flatMap((s) => s.toolCalls.map((c) => c.app).filter(Boolean))
853
- );
854
- const early = state.apps?.find(
855
- (a) => a.stepId === event.step.id && a.tool === event.name && !tagged.has(a.id)
856
- );
857
- const call = {
858
- name: event.name,
859
- input: event.input,
860
- status: "calling",
861
- inputTokens: approxTokens(event.input),
862
- ...ctx.at !== void 0 ? { startedAt: ctx.at } : {},
863
- ...early ? { app: early.id } : {}
864
- };
865
- return {
866
- ...state,
867
- steps: patchStep(state.steps, event.step.id, (s) => ({
868
- ...s,
869
- toolCalls: [...s.toolCalls, call]
870
- }))
871
- };
872
- }
873
- case "step.tool-result":
874
- return {
875
- ...state,
876
- steps: patchStep(state.steps, event.step.id, (s) => {
877
- let done = false;
878
- const toolCalls = s.toolCalls.slice().reverse().map((c) => {
879
- if (!done && c.status === "calling" && c.name === event.name) {
880
- done = true;
881
- return {
882
- ...c,
883
- output: event.output,
884
- ok: event.ok,
885
- status: "done",
886
- outputTokens: approxTokens(event.output),
887
- ...isReplayedToolOutput(event.output) ? { replayed: true } : {},
888
- ...ctx.at !== void 0 && c.startedAt !== void 0 ? { durationMs: Math.max(0, ctx.at - c.startedAt) } : {}
889
- };
890
- }
891
- return c;
892
- }).reverse();
893
- return { ...s, toolCalls };
894
- })
895
- };
896
- case "step.complete":
897
- return {
898
- ...state,
899
- steps: patchStep(state.steps, event.step.id, (s) => ({
900
- ...s,
901
- status: "done",
902
- summary: event.result.summary,
903
- // With tiers: where the step finished and how it got there. The result's list is the
904
- // authority; an escalation seen live keeps what only the event told (model, text).
905
- ...event.result.tier !== void 0 ? { tier: event.result.tier } : {},
906
- ...event.result.model !== void 0 ? { model: event.result.model } : {},
907
- ...event.result.escalations?.length ? {
908
- escalations: event.result.escalations.map((e, i) => {
909
- const live = s.escalations?.[i];
910
- return live && live.from === e.from && live.to === e.to ? { ...live, reason: e.reason } : { from: e.from, to: e.to, reason: e.reason };
911
- })
912
- } : {},
913
- blocked: event.result.blocked,
914
- // The result carries the authoritative, ordered tool-call list; keep
915
- // the timing the streamed calls measured (matched in order per name).
916
- toolCalls: (() => {
917
- const seen = /* @__PURE__ */ new Map();
918
- return event.result.toolCalls.map((c) => {
919
- const nth = seen.get(c.name) ?? 0;
920
- seen.set(c.name, nth + 1);
921
- const streamed = s.toolCalls.filter((t) => t.name === c.name)[nth];
922
- return {
923
- name: c.name,
924
- input: c.input,
925
- output: c.output,
926
- ok: c.ok,
927
- status: "done",
928
- inputTokens: approxTokens(c.input),
929
- outputTokens: approxTokens(c.output),
930
- ...streamed?.startedAt !== void 0 ? { startedAt: streamed.startedAt } : {},
931
- ...streamed?.durationMs !== void 0 ? { durationMs: streamed.durationMs } : {},
932
- // With tiers the list holds every attempt's calls, in the order they were made.
933
- ...streamed?.attempt !== void 0 ? { attempt: streamed.attempt } : {},
934
- ...isReplayedToolOutput(c.output) ? { replayed: true } : {},
935
- // The MCP App the call came with (only the stream told it).
936
- ...streamed?.app !== void 0 ? { app: streamed.app } : {}
937
- };
938
- });
939
- })()
940
- }))
941
- };
942
- case "replan.decision": {
943
- if (!event.failed) {
944
- return {
945
- ...state,
946
- replan: {
947
- mode: event.mode,
948
- reason: event.reason,
949
- ...event.byUser ? { byUser: true } : {},
950
- ...event.confidence !== void 0 ? { confidence: event.confidence } : {}
951
- }
952
- };
953
- }
954
- const error = state.replan?.failed ? state.replan.error : void 0;
955
- const last = state.steps[state.steps.length - 1];
956
- return {
957
- ...state,
958
- replan: {
959
- mode: event.mode,
960
- reason: event.reason,
961
- ...event.byUser ? { byUser: true } : {},
962
- failed: true,
963
- ...error ? { error } : {}
964
- },
965
- steps: last ? patchStep(state.steps, last.id, (s) => ({
966
- ...s,
967
- replanFailed: error ?? event.reason
968
- })) : state.steps
969
- };
970
- }
971
- case "decision": {
972
- const view = {
973
- point: event.point,
974
- accepted: event.accepted,
975
- ...event.choice !== void 0 ? { choice: event.choice } : {},
976
- ...event.confidence !== void 0 ? { confidence: event.confidence } : {},
977
- threshold: event.threshold,
978
- ...event.reason ? { reason: event.reason } : {},
979
- durationMs: event.durationMs,
980
- ...event.model ? { model: event.model } : {}
981
- };
982
- const last = state.steps[state.steps.length - 1];
983
- return last ? {
984
- ...state,
985
- steps: patchStep(state.steps, last.id, (s) => ({
986
- ...s,
987
- decisions: [...s.decisions ?? [], view]
988
- }))
989
- } : { ...state, decisions: [...state.decisions ?? [], view] };
990
- }
991
- case "media.generated":
992
- return addMedia(state, mediaOf(event, true));
993
- case "media.transcribed":
994
- return { ...state, transcripts: [...state.transcripts ?? [], transcriptOf(event)] };
995
- case "file.written":
996
- return fileWritten(state, event);
997
- case "file.deleted":
998
- return fileDeleted(state, event.path);
999
- case "mcp.app":
1000
- return ctx.remote ? state : addApp(state, event);
1001
- case "message.queued": {
1002
- if (state.queued.some((q) => q.id === event.id)) return state;
1003
- const entry = {
1004
- id: event.id,
1005
- text: event.text,
1006
- ...event.origin ? { origin: event.origin } : {}
1007
- };
1008
- const mine = ctx.remote && event.origin === "another-tab" ? sentEntryOf(state.queued, event.text) : -1;
1009
- if (mine < 0) return { ...state, queued: [...state.queued, entry] };
1010
- return { ...state, queued: state.queued.map((q, i) => i === mine ? entry : q) };
1011
- }
1012
- case "message.delivered": {
1013
- const anchor = event.at === "round" ? runningStepId(state.steps) : event.at === "step" ? state.steps[state.steps.length - 1]?.id : void 0;
1014
- return {
1015
- ...state,
1016
- queued: state.queued.filter((q) => q.id !== event.id),
1017
- notes: [
1018
- ...state.notes,
1019
- {
1020
- id: event.id,
1021
- text: event.text,
1022
- at: event.at,
1023
- ...anchor ? { stepId: anchor } : {},
1024
- ...event.origin ? { origin: event.origin } : {}
1025
- }
1026
- ]
1027
- };
1028
- }
1029
- case "final.text-delta": {
1030
- const finalText = state.finalText + event.delta;
1031
- return { ...state, finalText, messages: streamAssistant(state.messages, finalText) };
1032
- }
1033
- case "final":
1034
- return {
1035
- ...state,
1036
- finalText: event.text,
1037
- messages: finalizeAssistant(state.messages, event.text, runDuration(state, ctx.at))
1038
- };
1039
- case "final.reasoning-delta":
1040
- return { ...state, finalReasoning: state.finalReasoning + event.delta };
1041
- case "usage":
1042
- if (event.phase === "app") {
1043
- return { ...state, totalUsage: addUsage(state.totalUsage, event.usage) };
1044
- }
1045
- return {
1046
- ...state,
1047
- usage: addUsage(state.usage, event.usage),
1048
- totalUsage: addUsage(state.totalUsage, event.usage)
1049
- };
1050
- case "mcp.elicitation-requested":
1051
- return addElicitation(state, event, {
1052
- // Asked in the tab that runs the tool call: shown here, answered there.
1053
- ...ctx.remote ? { remote: true } : {},
1054
- stepId: event.step?.id,
1055
- ...event.subagent ? { subagent: event.subagent } : {}
1056
- });
1057
- case "mcp.elicitation-answered":
1058
- return answerElicitation(state, event, runningStepId(state.steps));
1059
- case "user.question-asked":
1060
- return addQuestion(state, event, {
1061
- // Asked in the tab that runs the agent: shown here, answered there only.
1062
- ...ctx.remote ? { remote: true } : {},
1063
- stepId: event.step?.id,
1064
- ...event.subagent ? { subagent: event.subagent } : {}
1065
- });
1066
- case "user.question-answered":
1067
- return answerQuestion(state, event);
1068
- case "tool.approval-requested":
1069
- return {
1070
- ...state,
1071
- approvals: [
1072
- ...state.approvals,
1073
- {
1074
- id: event.id,
1075
- name: event.name,
1076
- input: event.input,
1077
- readOnly: event.readOnly,
1078
- stepId: event.step?.id,
1079
- ...event.subagent ? { subagent: event.subagent } : {},
1080
- ...event.app ? { app: event.app } : {},
1081
- ...event.skill ? { skill: event.skill } : {},
1082
- ...event.rule ? { rule: event.rule } : {},
1083
- // Asked in the tab that runs the tool: shown here, answered there.
1084
- ...ctx.remote ? { remote: true } : {},
1085
- status: "pending"
1086
- }
1087
- ]
1088
- };
1089
- case "tool.approval-resolved": {
1090
- const known = state.approvals.some((a) => a.id === event.id);
1091
- const decided = (a) => withoutSkillBody({
1092
- ...a,
1093
- status: event.approved ? "approved" : "denied",
1094
- reason: event.reason,
1095
- automatic: event.automatic
1096
- });
1097
- return {
1098
- ...state,
1099
- approvals: known ? patchApproval(state.approvals, event.id, decided) : (
1100
- // A policy denial arrives without a request: record it too.
1101
- [
1102
- ...state.approvals,
1103
- decided({
1104
- id: event.id,
1105
- name: event.name,
1106
- input: void 0,
1107
- readOnly: false,
1108
- stepId: runningStepId(state.steps),
1109
- status: "pending"
1110
- })
1111
- ]
1112
- )
1113
- };
1114
- }
1115
- case "subagent.start":
1116
- case "subagent.event":
1117
- case "subagent.complete":
1118
- case "subagent.error":
1119
- return applySubagent(state, event, [], ctx);
1120
- case "skill.activated":
1121
- return state.skills.includes(event.name) ? state : { ...state, skills: [...state.skills, event.name] };
1122
- case "skill.learned": {
1123
- const before = state.learned.find((l) => l.name === event.name);
1124
- const lesson = {
1125
- name: event.name,
1126
- description: event.description,
1127
- // A rewrite of a lesson we know goes up one; a lesson we never saw (an event for a store
1128
- // loaded before this view existed) starts at 2 when the core says it is an update.
1129
- revision: event.update ? (before?.revision ?? 1) + 1 : 1,
1130
- chars: event.chars,
1131
- sources: event.sources
1132
- };
1133
- return {
1134
- ...state,
1135
- learned: before ? state.learned.map((l) => l.name === event.name ? lesson : l) : [...state.learned, lesson],
1136
- learnedNow: state.learnedNow.includes(event.name) ? state.learnedNow : [...state.learnedNow, event.name]
1137
- };
1138
- }
1139
- case "skill.forgotten":
1140
- return { ...state, learned: state.learned.filter((l) => l.name !== event.name) };
1141
- case "egress.request":
1142
- return {
1143
- ...state,
1144
- fetches: [
1145
- ...state.fetches,
1146
- {
1147
- url: event.url,
1148
- allowed: event.allowed,
1149
- ...event.status !== void 0 ? { status: event.status } : {},
1150
- ...event.reason ? { reason: event.reason } : {}
1151
- }
1152
- ]
1153
- };
1154
- case "tools.discovered":
1155
- return {
1156
- ...state,
1157
- discoveredTools: [.../* @__PURE__ */ new Set([...state.discoveredTools, ...event.names])]
1158
- };
1159
- case "context.compacted":
1160
- return {
1161
- ...state,
1162
- compactions: [
1163
- ...state.compactions,
1164
- { scope: event.scope, beforeTokens: event.beforeTokens, afterTokens: event.afterTokens }
1165
- ]
1166
- };
1167
- case "budget.exceeded":
1168
- return { ...state, budget: { kind: event.kind, tokens: event.tokens, cap: event.cap } };
1169
- case "session.busy":
1170
- state = withoutSubmitted(state);
1171
- return {
1172
- ...state,
1173
- sessionBusy: { heldBy: event.heldBy, ...ctx.goal ? { goal: ctx.goal } : {} },
1174
- // What the user sent waits with the run: shown as queued, not lost.
1175
- ...ctx.goal ? {
1176
- queued: [
1177
- ...state.queued.filter((q) => q.id !== WAITING_ID),
1178
- { id: WAITING_ID, text: ctx.goal, session: event.heldBy }
1179
- ]
1180
- } : {}
1181
- };
1182
- case "session.acquired":
1183
- return withoutBusy(state);
1184
- case "stopped":
1185
- if (!ctx.remote && state.sessionBusy) return withoutBusy(state);
1186
- if (!ctx.remote && state.submitted) return withoutSubmitted(state);
1187
- return {
1188
- ...withoutBusy(state),
1189
- stopped: true,
1190
- // Nothing of the run is waiting any more once it has stopped (an app's request is not
1191
- // the run's).
1192
- approvals: state.approvals.map(
1193
- (a) => a.status === "pending" && !a.app ? withoutSkillBody({ ...a, status: "denied", reason: "stopped" }) : a
1194
- ),
1195
- ...state.elicitations ? {
1196
- elicitations: state.elicitations.map(
1197
- (e) => e.status === "pending" ? { ...e, status: "cancelled", automatic: true, reason: "stopped" } : e
1198
- )
1199
- } : {},
1200
- // Nobody is asked any more once the run has stopped.
1201
- ...state.questions ? {
1202
- questions: state.questions.map(
1203
- (q) => q.status === "pending" ? { ...q, status: "stopped", automatic: true, reason: "stopped" } : q
1204
- )
1205
- } : {},
1206
- // What it had written, or nothing - the chat says "stopped" through its labels.
1207
- messages: finalizeAssistant(state.messages, state.finalText, {
1208
- ...runDuration(state, ctx.at),
1209
- stopped: true
1210
- })
1211
- };
1212
- case "error":
1213
- if (event.phase === "replan") {
1214
- return {
1215
- ...state,
1216
- replan: { mode: "continue", reason: "", failed: true, error: event.error }
1217
- };
1218
- }
1219
- return event.phase === "run" ? {
1220
- ...withoutBusy(keepSubmitted(state)),
1221
- error: event.error,
1222
- errorCode: event.code,
1223
- messages: finalizeAssistant(
1224
- state.messages,
1225
- state.finalText || `Error: ${event.error}`,
1226
- { ...runDuration(state, ctx.at), error: true }
1227
- )
1228
- } : { ...state, error: event.error };
1229
- case "retry":
1230
- return state;
1231
- default:
1232
- return state;
1233
- }
1234
- };
1235
- var syncRunMessage = (state) => {
1236
- const id = state.runMessageId;
1237
- if (!id) return state;
1238
- const i = state.messages.findIndex((m2) => m2.id === id);
1239
- if (i < 0) return state;
1240
- const m = state.messages[i];
1241
- const decided = state.approvals.filter((a) => a.status !== "pending" && !a.app);
1242
- const patch = {};
1243
- if (m.steps !== state.steps) patch.steps = state.steps;
1244
- if (m.subagents !== state.subagents) patch.subagents = state.subagents;
1245
- if (state.notes.length > 0 && m.notes !== state.notes) patch.notes = state.notes;
1246
- if (m.usage !== state.usage) patch.usage = state.usage;
1247
- if ((m.reasoning ?? "") !== state.finalReasoning) patch.reasoning = state.finalReasoning;
1248
- if (m.skills !== state.skills) patch.skills = state.skills;
1249
- if (state.learnedNow.length > 0 && m.learned !== state.learnedNow)
1250
- patch.learned = state.learnedNow;
1251
- if (state.fetches.length > 0 && m.fetches !== state.fetches) patch.fetches = state.fetches;
1252
- if (state.media && m.media !== state.media) patch.media = state.media;
1253
- if (state.transcripts && m.transcripts !== state.transcripts)
1254
- patch.transcripts = state.transcripts;
1255
- if (state.writtenFiles && m.writtenFiles !== state.writtenFiles)
1256
- patch.writtenFiles = state.writtenFiles;
1257
- if (state.apps && m.apps !== state.apps) patch.apps = state.apps;
1258
- if ((m.approvals?.length ?? 0) !== decided.length || decided.some((a, k) => m.approvals?.[k] !== a)) {
1259
- patch.approvals = decided;
1260
- }
1261
- if (Object.keys(patch).length === 0) return state;
1262
- const messages = state.messages.slice();
1263
- messages[i] = { ...m, ...patch };
1264
- return { ...state, messages };
1265
- };
1266
- var pendingApprovalsOf = (state) => state.approvals.filter((a) => a.status === "pending" && !a.remote);
1267
- var agentStatusOf = (state) => state.remote?.running && (state.status === "ready" || state.status === "idle") ? "running" : state.status;
1268
- var agentStateReducer = (state, action) => {
1269
- switch (action.type) {
1270
- case "reset":
1271
- return {
1272
- ...createInitialAgentState(),
1273
- status: state.status,
1274
- seq: state.seq,
1275
- learned: state.learned
1276
- };
1277
- case "notebook":
1278
- return { ...state, learned: action.lessons };
1279
- case "submitted": {
1280
- if (state.submitted) return state;
1281
- const userId = `msg-${state.seq}`;
1282
- const assistantId = `msg-${state.seq + 1}`;
1283
- return {
1284
- ...state,
1285
- submitted: { userId, assistantId },
1286
- messages: [
1287
- ...state.messages,
1288
- {
1289
- id: userId,
1290
- role: "user",
1291
- content: action.goal,
1292
- pending: false,
1293
- ...action.attachments?.length ? { attachments: action.attachments } : {}
1294
- },
1295
- { id: assistantId, role: "assistant", content: "", pending: true }
1296
- ],
1297
- seq: state.seq + 2
1298
- };
1299
- }
1300
- case "status":
1301
- return {
1302
- ...state,
1303
- status: action.status,
1304
- error: action.status === "error" ? action.error : void 0,
1305
- errorCode: void 0
1306
- };
1307
- case "remote": {
1308
- const remote = action.remote;
1309
- if (!remote) {
1310
- const { remote: _gone, ...rest } = state;
1311
- void _gone;
1312
- return rest;
1313
- }
1314
- if (remote.ended === "gone" && state.remote?.running) {
1315
- return syncRunMessage({
1316
- ...state,
1317
- remote,
1318
- messages: finalizeAssistant(state.messages, state.finalText, { error: true })
1319
- });
1320
- }
1321
- return { ...state, remote };
1322
- }
1323
- case "event": {
1324
- const event = withoutOwnWords(action.event);
1325
- const next = syncRunMessage(
1326
- applyEvent(state, event, {
1327
- at: action.at,
1328
- attachments: action.attachments,
1329
- ...action.remote ? { remote: true } : {},
1330
- ...action.goal ? { goal: action.goal } : {}
1331
- })
1332
- );
1333
- const cap = action.maxEvents ?? 200;
1334
- const events = cap > 0 ? [...state.events, event].slice(-cap) : [...state.events, event];
1335
- return { ...next, events };
1336
- }
1337
- case "undelivered":
1338
- return {
1339
- ...state,
1340
- queued: action.keepQueued ? state.queued : sentToOtherTab(state.queued),
1341
- undelivered: action.texts
1342
- };
1343
- case "remote-send":
1344
- return state.queued.some((q) => q.id === action.id) ? state : {
1345
- ...state,
1346
- queued: [
1347
- ...state.queued,
1348
- { id: action.id, text: action.text, sentTo: "another-tab" }
1349
- ]
1350
- };
1351
- case "remote-answer": {
1352
- const queued = state.queued.filter((q) => q.id !== action.id);
1353
- return action.answer === "refused" ? { ...state, queued, undelivered: [...state.undelivered, action.text] } : { ...state, queued };
1354
- }
1355
- case "load": {
1356
- const maxSeq = action.messages.reduce((n, m) => {
1357
- const k = Number(/^msg-(\d+)$/.exec(m.id)?.[1] ?? -1);
1358
- return Math.max(n, k + 1);
1359
- }, state.seq);
1360
- return {
1361
- ...createInitialAgentState(),
1362
- status: state.status,
1363
- messages: action.messages.map((m) => m.pending ? { ...m, pending: false } : m),
1364
- totalUsage: action.totalUsage ?? emptyUsage(),
1365
- seq: maxSeq,
1366
- learned: state.learned
1367
- };
1368
- }
1369
- default:
1370
- return state;
1371
- }
1372
- };
25
+ ASK_USER_TOOL_NAME,
26
+ QUESTION_TIMEOUT_MS,
27
+ agentStateReducer,
28
+ agentStatusOf,
29
+ askUserOutputKept,
30
+ askUserWith,
31
+ coalesce,
32
+ createApprovalQueue,
33
+ createInitialAgentState,
34
+ createQuestionQueue,
35
+ errMessage,
36
+ followOtherTabs,
37
+ lessonsOf,
38
+ listenToOtherTabs,
39
+ pendingApprovalsOf,
40
+ questionChoiceOf,
41
+ questionOtherOf,
42
+ questionTimeoutOf,
43
+ remoteAnswerOf,
44
+ subagentTree,
45
+ withoutOwnWords
46
+ } from "./chunk-G7LQTOA2.js";
1373
47
 
1374
48
  // src/composer.ts
1375
49
  var parseSlash = (text2) => {
@@ -1383,6 +57,21 @@ var steerIntent = (input) => {
1383
57
  if (parseSlash(input.raw)) return "ignore";
1384
58
  return input.hasAttachments ? "attachments" : "steer";
1385
59
  };
60
+ var notReadyIntent = (input) => {
61
+ if (!input.hasContent) return "ignore";
62
+ if (input.disabled) return "refuse";
63
+ if (input.ready) return "send";
64
+ if (input.status === "initializing") return "wait";
65
+ return "refuse";
66
+ };
67
+ var notReadyReason = (input) => input.disabled ? "disabled" : input.status === "error" ? "failed" : "unavailable";
68
+ var waitingSendStep = (input) => {
69
+ if (input.disabled) return "stop";
70
+ if (input.ready) return "send";
71
+ if (input.status === "initializing" || input.status === "running") return "wait";
72
+ if (input.status === "error") return "failed";
73
+ return "stop";
74
+ };
1386
75
  var filterCommands = (commands, query) => {
1387
76
  const q = query.toLowerCase();
1388
77
  if (!q) return commands;
@@ -1845,6 +534,12 @@ var defaultLabels = {
1845
534
  placeholderBusy: "Tell the agent something while it works…",
1846
535
  steer: "Send to the agent",
1847
536
  noAttachmentsWhileBusy: "Files can’t be added while the agent is working — send them with your next message.",
537
+ sendWhenReady: "Sends when the agent is ready",
538
+ sendWhenReadyButton: "Send when the agent is ready",
539
+ cancelSendWhenReady: "Don’t send",
540
+ notSentFailed: "Not sent: the agent could not start. Your message is still here.",
541
+ notSentUnavailable: "Not sent: the agent isn’t ready. Your message is still here.",
542
+ notSentDisabled: "Not sent: sending is turned off. Your message is still here.",
1848
543
  queuedWaiting: "waiting for the agent’s next step",
1849
544
  queuedForSession: (heldBy) => heldBy === "this-tab" ? "waiting for the other run to finish" : "waiting for the other tab to finish",
1850
545
  queuedForOtherTab: "waiting for the other tab to pick it up",
@@ -2161,6 +856,88 @@ var followsAfterScroll = (following, before, now) => {
2161
856
  };
2162
857
  var followsAfterResize = (following, before, now) => following && !(now.clientHeight === before.clientHeight && now.scrollHeight >= before.scrollHeight && now.scrollTop < reach(before) - FOLLOW_LEAVE_PX);
2163
858
 
859
+ // src/dom-root.ts
860
+ var DOCUMENT_NODE = 9;
861
+ var DOCUMENT_FRAGMENT_NODE = 11;
862
+ var MAX_DEPTH = 64;
863
+ var isShadowRoot = (node) => typeof node === "object" && node !== null && node.nodeType === DOCUMENT_FRAGMENT_NODE && "host" in node && Boolean(node.host);
864
+ var isDocument = (node) => typeof node === "object" && node !== null && node.nodeType === DOCUMENT_NODE;
865
+ var rootOf = (node) => {
866
+ if (isDocument(node)) return node;
867
+ const root = typeof node.getRootNode === "function" ? node.getRootNode() : void 0;
868
+ if (isDocument(root) || isShadowRoot(root)) return root;
869
+ return node.ownerDocument;
870
+ };
871
+ var activeElementOf = (at) => {
872
+ const root = isDocument(at) || isShadowRoot(at) ? at : rootOf(at);
873
+ return root.activeElement ?? null;
874
+ };
875
+ var deepActiveElement = (root) => {
876
+ let active = root.activeElement ?? null;
877
+ for (let i = 0; active && i < MAX_DEPTH; i++) {
878
+ const inner = active.shadowRoot?.activeElement;
879
+ if (!inner || inner === active) break;
880
+ active = inner;
881
+ }
882
+ return active;
883
+ };
884
+ var nothingFocused = (doc) => {
885
+ const active = doc.activeElement;
886
+ return !active || active === doc.body;
887
+ };
888
+ var composedContains = (ancestor, node) => {
889
+ let at = node;
890
+ for (let i = 0; at && i < 1e5; i++) {
891
+ if (at === ancestor) return true;
892
+ at = at.parentNode ?? (isShadowRoot(at) ? at.host : null);
893
+ }
894
+ return false;
895
+ };
896
+ var pathOf = (event) => typeof event.composedPath === "function" ? event.composedPath() : [];
897
+ var eventTargetOf = (event) => pathOf(event)[0] ?? event.target;
898
+ var isEventInside = (event, node) => {
899
+ if (!node) return false;
900
+ const target = event.target;
901
+ const path = pathOf(event);
902
+ if (path.length > 0 && path[0] !== target) return path.includes(node);
903
+ return typeof target?.nodeType === "number" && node.contains(target);
904
+ };
905
+ var deepElementFromPoint = (doc, x, y) => {
906
+ if (typeof doc.elementFromPoint !== "function") return null;
907
+ let hit = doc.elementFromPoint(x, y);
908
+ for (let i = 0; hit && i < MAX_DEPTH; i++) {
909
+ const shadow = hit.shadowRoot;
910
+ if (!shadow || typeof shadow.elementFromPoint !== "function") break;
911
+ const inner = shadow.elementFromPoint(x, y);
912
+ if (!inner || inner === hit || !composedContains(shadow, inner)) break;
913
+ hit = inner;
914
+ }
915
+ return hit;
916
+ };
917
+ var shadowRootsAround = (node) => {
918
+ const roots = [];
919
+ let root = rootOf(node);
920
+ for (let i = 0; isShadowRoot(root) && i < MAX_DEPTH; i++) {
921
+ roots.push(root);
922
+ root = rootOf(root.host);
923
+ }
924
+ return roots;
925
+ };
926
+ var listenScrollAround = (node, listener) => {
927
+ const view = node.ownerDocument?.defaultView ?? globalThis;
928
+ const targets = [view, ...shadowRootsAround(node)];
929
+ for (const t of targets) t.addEventListener("scroll", listener, true);
930
+ return () => {
931
+ for (const t of targets) t.removeEventListener("scroll", listener, true);
932
+ };
933
+ };
934
+ var portalHostOf = (from, selector) => {
935
+ const near = from.closest(selector);
936
+ if (near) return near;
937
+ const root = rootOf(from);
938
+ return isShadowRoot(root) ? root : from.ownerDocument.body;
939
+ };
940
+
2164
941
  // src/file-kinds.ts
2165
942
  import { MEDIA_IMAGE_TYPES, isTextMime } from "@dudko.dev/agent-web";
2166
943
  var CODE = /\.(?:js|mjs|cjs|jsx|ts|tsx|css|scss|py|rb|go|rs|java|kt|c|h|cpp|cs|php|sh|sql|xml|svg|yaml|yml|toml)$/i;
@@ -2376,44 +1153,6 @@ var webSearchOf = (output) => {
2376
1153
  };
2377
1154
  var formatProbability = (p) => String(Math.round(p * 100) / 100);
2378
1155
 
2379
- // src/approval-queue.ts
2380
- var createApprovalQueue = () => {
2381
- const waiting = /* @__PURE__ */ new Map();
2382
- const handler = (req2, ctx) => new Promise((resolve) => {
2383
- const signal = ctx?.signal;
2384
- if (signal?.aborted) {
2385
- resolve({ approved: false, reason: "no longer asked" });
2386
- return;
2387
- }
2388
- const onAbort = () => {
2389
- if (waiting.get(req2.id) !== settle) return;
2390
- settle({ approved: false, reason: "no longer asked" });
2391
- };
2392
- const settle = (decision) => {
2393
- waiting.delete(req2.id);
2394
- signal?.removeEventListener("abort", onAbort);
2395
- resolve(decision);
2396
- };
2397
- signal?.addEventListener("abort", onAbort, { once: true });
2398
- waiting.set(req2.id, settle);
2399
- });
2400
- const answer = (id, decision) => {
2401
- const settle = waiting.get(id);
2402
- if (!settle) return false;
2403
- settle(decision);
2404
- return true;
2405
- };
2406
- return {
2407
- handler,
2408
- approve: (id, options) => answer(id, { approved: true, remember: options?.remember }),
2409
- deny: (id, reason) => answer(id, { approved: false, reason }),
2410
- settleAll: (decision) => {
2411
- for (const settle of [...waiting.values()]) settle(decision);
2412
- },
2413
- pending: () => [...waiting.keys()]
2414
- };
2415
- };
2416
-
2417
1156
  // src/elicitation.ts
2418
1157
  var ELICITATION_TIMEOUT_MS = 3e5;
2419
1158
  var elicitationSettings = (option) => {
@@ -2425,11 +1164,11 @@ var elicitationConnectOptions = (option, handler) => {
2425
1164
  const settings = elicitationSettings(option);
2426
1165
  return settings ? { onElicitation: handler, elicitation: settings } : {};
2427
1166
  };
2428
- var TIMER_MAX_MS2 = 2147483647;
1167
+ var TIMER_MAX_MS = 2147483647;
2429
1168
  var elicitationTimeoutOf = (settings) => {
2430
1169
  const raw = settings.timeoutMs;
2431
1170
  if (raw === void 0 || raw === null) return ELICITATION_TIMEOUT_MS;
2432
- if (typeof raw !== "number" || !(raw > 0) || raw > TIMER_MAX_MS2) return void 0;
1171
+ if (typeof raw !== "number" || !(raw > 0) || raw > TIMER_MAX_MS) return void 0;
2433
1172
  return Math.max(1, Math.floor(raw));
2434
1173
  };
2435
1174
  var createElicitationQueue = (options = {}) => {
@@ -2977,37 +1716,6 @@ var saveChat = async (store, view, base, texts) => {
2977
1716
  return { record, merged };
2978
1717
  };
2979
1718
 
2980
- // src/util.ts
2981
- var errMessage = (err) => err instanceof Error ? err.message : String(err);
2982
- var coalesce = (fn, ms = 100) => {
2983
- let timer;
2984
- return {
2985
- call: () => {
2986
- if (timer !== void 0) clearTimeout(timer);
2987
- timer = setTimeout(() => {
2988
- timer = void 0;
2989
- fn();
2990
- }, ms);
2991
- },
2992
- cancel: () => {
2993
- if (timer !== void 0) clearTimeout(timer);
2994
- timer = void 0;
2995
- }
2996
- };
2997
- };
2998
- var listenToOtherTabs = (core2, dbName, listener) => typeof core2.onStorageChange === "function" && dbName ? core2.onStorageChange(dbName, listener) : () => void 0;
2999
- var followOtherTabs = (core2, dbName, accept, settle, ms = 100) => {
3000
- const later = coalesce(settle, ms);
3001
- const off = listenToOtherTabs(core2, dbName, (change) => {
3002
- if (accept(change)) later.call();
3003
- });
3004
- return () => {
3005
- off();
3006
- later.cancel();
3007
- };
3008
- };
3009
- var remoteAnswerOf = (ok, stillWatching) => ok ? "taken" : stillWatching ? "refused" : "unknown";
3010
-
3011
1719
  // src/voice/record.ts
3012
1720
  var MicError = class extends Error {
3013
1721
  code;
@@ -3653,6 +2361,7 @@ export {
3653
2361
  RECORDING_DEFAULT_MAX_MS,
3654
2362
  RECORDING_TYPES,
3655
2363
  SpeechOutputError,
2364
+ activeElementOf,
3656
2365
  agentStateReducer,
3657
2366
  agentStatusOf,
3658
2367
  askUserOutputKept,
@@ -3671,6 +2380,7 @@ export {
3671
2380
  chatTitle,
3672
2381
  clampFrameHeight,
3673
2382
  coalesce,
2383
+ composedContains,
3674
2384
  createApprovalQueue,
3675
2385
  createAudioSpeaker,
3676
2386
  createBrowserSpeaker,
@@ -3681,6 +2391,8 @@ export {
3681
2391
  createRecordingRecognizer,
3682
2392
  cspMetaTag,
3683
2393
  dataUrlParts,
2394
+ deepActiveElement,
2395
+ deepElementFromPoint,
3684
2396
  defaultLabels,
3685
2397
  defaultNoticeTexts,
3686
2398
  downscaleImage,
@@ -3694,6 +2406,7 @@ export {
3694
2406
  endGap,
3695
2407
  errMessage,
3696
2408
  escapeAttribute,
2409
+ eventTargetOf,
3697
2410
  excerptNote,
3698
2411
  fileKindOf,
3699
2412
  fileNameOf,
@@ -3712,11 +2425,14 @@ export {
3712
2425
  imagesInOutput,
3713
2426
  inputCounterShown,
3714
2427
  insertionFits,
2428
+ isEventInside,
3715
2429
  isOneCharacter,
2430
+ isShadowRoot,
3716
2431
  languageOfText,
3717
2432
  lessonsOf,
3718
2433
  lineCountOf,
3719
2434
  linkedFilesOf,
2435
+ listenScrollAround,
3720
2436
  listenToOtherTabs,
3721
2437
  longTextName,
3722
2438
  longTextRoute,
@@ -3729,6 +2445,9 @@ export {
3729
2445
  micProblemText,
3730
2446
  namedFilesOf,
3731
2447
  newChatId,
2448
+ notReadyIntent,
2449
+ notReadyReason,
2450
+ nothingFocused,
3732
2451
  noticesOf,
3733
2452
  overflowOf,
3734
2453
  ownUnsaved,
@@ -3736,18 +2455,21 @@ export {
3736
2455
  pathsNamedIn,
3737
2456
  pendingApprovalsOf,
3738
2457
  pickRecordingType,
2458
+ portalHostOf,
3739
2459
  previewValue,
3740
2460
  questionChoiceOf,
3741
2461
  questionOtherOf,
3742
2462
  questionTimeoutOf,
3743
2463
  recordingSupported,
3744
2464
  remoteAnswerOf,
2465
+ rootOf,
3745
2466
  sandboxTokens,
3746
2467
  sandboxedCsp,
3747
2468
  saveAttachments,
3748
2469
  saveChat,
3749
2470
  scriptOfLanguage,
3750
2471
  scriptOfText,
2472
+ shadowRootsAround,
3751
2473
  speakableText,
3752
2474
  speechSynthesisSupported,
3753
2475
  splitForSpeech,
@@ -3761,6 +2483,7 @@ export {
3761
2483
  voiceFor,
3762
2484
  voiceMessageName,
3763
2485
  voicesOf,
2486
+ waitingSendStep,
3764
2487
  webSearchOf,
3765
2488
  withAttachments,
3766
2489
  withCspFirst,
@@ -3768,4 +2491,3 @@ export {
3768
2491
  withoutOwnWords,
3769
2492
  workspacePathOf
3770
2493
  };
3771
- //# sourceMappingURL=index.js.map