@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
package/dist/index.cjs ADDED
@@ -0,0 +1,4276 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ ASK_USER_TOOL_NAME: () => ASK_USER_TOOL_NAME,
34
+ ATTACHMENT_BOUNDS: () => ATTACHMENT_BOUNDS,
35
+ ChatHistoryStore: () => ChatHistoryStore,
36
+ ELICITATION_MAX_OPTIONS: () => ELICITATION_MAX_OPTIONS,
37
+ ELICITATION_TIMEOUT_MS: () => ELICITATION_TIMEOUT_MS,
38
+ ELICITATION_VALUE_MAX_CHARS: () => ELICITATION_VALUE_MAX_CHARS,
39
+ FOLLOW_LEAVE_PX: () => FOLLOW_LEAVE_PX,
40
+ FOLLOW_REJOIN_PX: () => FOLLOW_REJOIN_PX,
41
+ FRAME_MAX_HEIGHT: () => FRAME_MAX_HEIGHT,
42
+ FRAME_MIN_HEIGHT: () => FRAME_MIN_HEIGHT,
43
+ HTML_PREVIEW_MAX_CHARS: () => HTML_PREVIEW_MAX_CHARS,
44
+ INPUT_COUNTER_FROM: () => INPUT_COUNTER_FROM,
45
+ MicError: () => MicError,
46
+ NAMED_FILES_MAX: () => NAMED_FILES_MAX,
47
+ NAMED_FILES_SCAN_MAX: () => NAMED_FILES_SCAN_MAX,
48
+ NAMED_FILES_TEXT_MAX: () => NAMED_FILES_TEXT_MAX,
49
+ PROMPT_ARM_MS: () => PROMPT_ARM_MS,
50
+ QUESTION_TIMEOUT_MS: () => QUESTION_TIMEOUT_MS,
51
+ RECORDING_DEFAULT_MAX_MS: () => RECORDING_DEFAULT_MAX_MS,
52
+ RECORDING_TYPES: () => RECORDING_TYPES,
53
+ SpeechOutputError: () => SpeechOutputError,
54
+ activeElementOf: () => activeElementOf,
55
+ agentStateReducer: () => agentStateReducer,
56
+ agentStatusOf: () => agentStatusOf,
57
+ askUserOutputKept: () => askUserOutputKept,
58
+ askUserWith: () => askUserWith,
59
+ attachmentFileName: () => attachmentFileName,
60
+ attachmentKindOf: () => attachmentKindOf,
61
+ attachmentLabel: () => attachmentLabel,
62
+ attachmentOverLimit: () => attachmentOverLimit,
63
+ attachmentRefusal: () => attachmentRefusal,
64
+ attachmentTransformOf: () => attachmentTransformOf,
65
+ attachmentsText: () => attachmentsText,
66
+ audioExtensionOf: () => audioExtensionOf,
67
+ audioTypeOf: () => audioTypeOf,
68
+ boxLength: () => boxLength,
69
+ buildSandboxedDocument: () => buildSandboxedDocument,
70
+ chatTitle: () => chatTitle,
71
+ clampFrameHeight: () => clampFrameHeight,
72
+ coalesce: () => coalesce,
73
+ composedContains: () => composedContains,
74
+ createApprovalQueue: () => createApprovalQueue,
75
+ createAudioSpeaker: () => createAudioSpeaker,
76
+ createBrowserSpeaker: () => createBrowserSpeaker,
77
+ createElicitationQueue: () => createElicitationQueue,
78
+ createInitialAgentState: () => createInitialAgentState,
79
+ createPromptArming: () => createPromptArming,
80
+ createQuestionQueue: () => createQuestionQueue,
81
+ createRecordingRecognizer: () => createRecordingRecognizer,
82
+ cspMetaTag: () => cspMetaTag,
83
+ dataUrlParts: () => dataUrlParts,
84
+ deepActiveElement: () => deepActiveElement,
85
+ deepElementFromPoint: () => deepElementFromPoint,
86
+ defaultLabels: () => defaultLabels,
87
+ defaultNoticeTexts: () => defaultNoticeTexts,
88
+ downscaleImage: () => downscaleImage,
89
+ elicitationConnectOptions: () => elicitationConnectOptions,
90
+ elicitationFields: () => elicitationFields,
91
+ elicitationFormAnswer: () => elicitationFormAnswer,
92
+ elicitationInitialDraft: () => elicitationInitialDraft,
93
+ elicitationLink: () => elicitationLink,
94
+ elicitationSettings: () => elicitationSettings,
95
+ elicitationTimeoutOf: () => elicitationTimeoutOf,
96
+ endGap: () => endGap,
97
+ errMessage: () => errMessage,
98
+ escapeAttribute: () => escapeAttribute,
99
+ eventTargetOf: () => eventTargetOf,
100
+ excerptNote: () => excerptNote,
101
+ fileKindOf: () => fileKindOf,
102
+ fileNameOf: () => fileNameOf,
103
+ filterCommands: () => filterCommands,
104
+ followOtherTabs: () => followOtherTabs,
105
+ followsAfterResize: () => followsAfterResize,
106
+ followsAfterScroll: () => followsAfterScroll,
107
+ formatClock: () => formatClock,
108
+ formatCountdown: () => formatCountdown,
109
+ formatDuration: () => formatDuration,
110
+ formatElapsed: () => formatElapsed,
111
+ formatProbability: () => formatProbability,
112
+ formatTokens: () => formatTokens,
113
+ freeAttachmentPath: () => freeAttachmentPath,
114
+ imageSizeOf: () => imageSizeOf,
115
+ imagesInOutput: () => imagesInOutput,
116
+ inputCounterShown: () => inputCounterShown,
117
+ insertionFits: () => insertionFits,
118
+ isEventInside: () => isEventInside,
119
+ isOneCharacter: () => isOneCharacter,
120
+ isShadowRoot: () => isShadowRoot,
121
+ languageOfText: () => languageOfText,
122
+ lessonsOf: () => lessonsOf,
123
+ lineCountOf: () => lineCountOf,
124
+ linkedFilesOf: () => linkedFilesOf,
125
+ listenScrollAround: () => listenScrollAround,
126
+ listenToOtherTabs: () => listenToOtherTabs,
127
+ longTextName: () => longTextName,
128
+ longTextRoute: () => longTextRoute,
129
+ menuKeyTarget: () => menuKeyTarget,
130
+ menuSections: () => menuSections,
131
+ mergeChatRecord: () => mergeChatRecord,
132
+ mergeLabels: () => mergeLabels,
133
+ messageOverLimit: () => messageOverLimit,
134
+ micProblemOf: () => micProblemOf,
135
+ micProblemText: () => micProblemText,
136
+ namedFilesOf: () => namedFilesOf,
137
+ newChatId: () => newChatId,
138
+ notReadyIntent: () => notReadyIntent,
139
+ notReadyReason: () => notReadyReason,
140
+ nothingFocused: () => nothingFocused,
141
+ noticesOf: () => noticesOf,
142
+ overflowOf: () => overflowOf,
143
+ ownUnsaved: () => ownUnsaved,
144
+ parseSlash: () => parseSlash,
145
+ pathsNamedIn: () => pathsNamedIn,
146
+ pendingApprovalsOf: () => pendingApprovalsOf,
147
+ pickRecordingType: () => pickRecordingType,
148
+ portalHostOf: () => portalHostOf,
149
+ previewValue: () => previewValue,
150
+ questionChoiceOf: () => questionChoiceOf,
151
+ questionOtherOf: () => questionOtherOf,
152
+ questionTimeoutOf: () => questionTimeoutOf,
153
+ recordingSupported: () => recordingSupported,
154
+ remoteAnswerOf: () => remoteAnswerOf,
155
+ rootOf: () => rootOf,
156
+ sandboxTokens: () => sandboxTokens,
157
+ sandboxedCsp: () => sandboxedCsp,
158
+ saveAttachments: () => saveAttachments,
159
+ saveChat: () => saveChat,
160
+ scriptOfLanguage: () => scriptOfLanguage,
161
+ scriptOfText: () => scriptOfText,
162
+ shadowRootsAround: () => shadowRootsAround,
163
+ speakableText: () => speakableText,
164
+ speechSynthesisSupported: () => speechSynthesisSupported,
165
+ splitForSpeech: () => splitForSpeech,
166
+ startRecording: () => startRecording,
167
+ steerIntent: () => steerIntent,
168
+ stopTracks: () => stopTracks,
169
+ subagentTree: () => subagentTree,
170
+ textExcerpt: () => textExcerpt,
171
+ tokenizeHtml: () => tokenizeHtml,
172
+ unchangedSince: () => unchangedSince,
173
+ voiceFor: () => voiceFor,
174
+ voiceMessageName: () => voiceMessageName,
175
+ voicesOf: () => voicesOf,
176
+ waitingSendStep: () => waitingSendStep,
177
+ webSearchOf: () => webSearchOf,
178
+ withAttachments: () => withAttachments,
179
+ withCspFirst: () => withCspFirst,
180
+ withPolicyFirst: () => withPolicyFirst,
181
+ withoutOwnWords: () => withoutOwnWords,
182
+ workspacePathOf: () => workspacePathOf
183
+ });
184
+ module.exports = __toCommonJS(src_exports);
185
+
186
+ // src/state.ts
187
+ var import_agent_web = require("@dudko.dev/agent-web");
188
+
189
+ // src/questions.ts
190
+ var ASK_USER_TOOL_NAME = "ask_user";
191
+ var QUESTION_TIMEOUT_MS = 3e5;
192
+ var TIMER_MAX_MS = 2147483647;
193
+ var questionTimeoutOf = (askUser) => {
194
+ if (!askUser) return void 0;
195
+ const raw = askUser === true ? void 0 : askUser.timeoutMs;
196
+ if (raw === void 0 || raw === null) return QUESTION_TIMEOUT_MS;
197
+ if (typeof raw !== "number" || !(raw > 0) || raw > TIMER_MAX_MS) return void 0;
198
+ return Math.max(1, Math.floor(raw));
199
+ };
200
+ var askUserWith = (askUser, handler) => {
201
+ if (!askUser) return askUser;
202
+ if (askUser === true) return { onQuestion: handler };
203
+ return askUser.onQuestion ? askUser : { ...askUser, onQuestion: handler };
204
+ };
205
+ var DECLINED = { declined: true };
206
+ var createQuestionQueue = (options = {}) => {
207
+ const now = options.now ?? Date.now;
208
+ const waiting = /* @__PURE__ */ new Map();
209
+ let disposed = false;
210
+ const list = () => [...waiting.values()].map((w) => w.question);
211
+ const changed = () => {
212
+ if (!disposed) options.onChange?.(list());
213
+ };
214
+ const handler = (request, ctx) => new Promise((resolve) => {
215
+ const signal = ctx?.signal;
216
+ if (disposed || signal?.aborted || waiting.has(request.id)) {
217
+ resolve(DECLINED);
218
+ return;
219
+ }
220
+ const onAbort = () => {
221
+ if (waiting.get(request.id)?.settle !== settle) return;
222
+ settle(DECLINED);
223
+ changed();
224
+ };
225
+ const settle = (answer) => {
226
+ waiting.delete(request.id);
227
+ signal?.removeEventListener("abort", onAbort);
228
+ resolve(answer);
229
+ };
230
+ signal?.addEventListener("abort", onAbort, { once: true });
231
+ const timeoutMs = typeof options.timeoutMs === "function" ? options.timeoutMs() : options.timeoutMs;
232
+ waiting.set(request.id, {
233
+ question: {
234
+ ...request,
235
+ options: request.options.map((o) => ({ ...o })),
236
+ ...timeoutMs !== void 0 ? { expiresAt: now() + timeoutMs } : {}
237
+ },
238
+ settle
239
+ });
240
+ changed();
241
+ });
242
+ return {
243
+ handler,
244
+ pending: list,
245
+ answer: (id, answer) => {
246
+ const entry = waiting.get(id);
247
+ if (!entry) return false;
248
+ entry.settle(answer);
249
+ changed();
250
+ return true;
251
+ },
252
+ cancel: (match) => {
253
+ let any = false;
254
+ for (const entry of [...waiting.values()]) {
255
+ if (match && !match(entry.question)) continue;
256
+ entry.settle(DECLINED);
257
+ any = true;
258
+ }
259
+ if (any) changed();
260
+ },
261
+ dispose: () => {
262
+ disposed = true;
263
+ for (const entry of [...waiting.values()]) entry.settle(DECLINED);
264
+ }
265
+ };
266
+ };
267
+ var questionChoiceOf = (question, picked) => {
268
+ const chosen = question.options.map((o) => o.label).filter((label) => picked.includes(label));
269
+ if (chosen.length === 0) return void 0;
270
+ return { choice: question.multiple ? chosen : chosen.slice(0, 1) };
271
+ };
272
+ var questionOtherOf = (question, text2) => question.allowOther && typeof text2 === "string" && text2.trim() ? { other: text2.trim() } : void 0;
273
+ var LABELS_ONLY = [
274
+ "The user chose: ",
275
+ "The user chose not to answer.",
276
+ "The user did not answer in time.",
277
+ "The question could not be put to the user",
278
+ "You have already asked the user "
279
+ ];
280
+ var askUserOutputKept = (output, ok) => (
281
+ // A failed call is about the model's own arguments (a bad question): nobody was asked.
282
+ !ok || typeof output === "string" && LABELS_ONLY.some((start) => output.startsWith(start))
283
+ );
284
+ var withoutOutput = (call) => {
285
+ if (call.name !== ASK_USER_TOOL_NAME || askUserOutputKept(call.output, call.ok)) return call;
286
+ const { output: _dropped, ...rest } = call;
287
+ void _dropped;
288
+ return rest;
289
+ };
290
+ var withoutOwnWords = (event) => {
291
+ switch (event.type) {
292
+ case "step.tool-result": {
293
+ const cleaned = withoutOutput(event);
294
+ return cleaned === event ? event : { ...cleaned, output: void 0 };
295
+ }
296
+ case "step.complete": {
297
+ const calls = event.result.toolCalls;
298
+ const cleaned = calls.map(withoutOutput);
299
+ return cleaned.every((c, i) => c === calls[i]) ? event : { ...event, result: { ...event.result, toolCalls: cleaned } };
300
+ }
301
+ case "subagent.event": {
302
+ const inner = withoutOwnWords(event.event);
303
+ return inner === event.event ? event : { ...event, event: inner };
304
+ }
305
+ default:
306
+ return event;
307
+ }
308
+ };
309
+
310
+ // src/state.ts
311
+ var approxTokens = (value) => {
312
+ if (value === void 0) return 0;
313
+ let text2;
314
+ try {
315
+ text2 = typeof value === "string" ? value : JSON.stringify(value) ?? "";
316
+ } catch {
317
+ text2 = String(value);
318
+ }
319
+ return Math.ceil(text2.length / 4);
320
+ };
321
+ var emptyUsage = () => ({
322
+ inputTokens: 0,
323
+ outputTokens: 0,
324
+ totalTokens: 0,
325
+ reasoningTokens: 0,
326
+ cachedInputTokens: 0,
327
+ cacheWriteTokens: 0
328
+ });
329
+ var USAGE_COUNTS = [
330
+ "mediaCalls",
331
+ "imagesGenerated",
332
+ "speechCharacters",
333
+ "transcriptionSeconds",
334
+ "decisionCalls"
335
+ ];
336
+ var addUsage = (a, b) => {
337
+ const sum = {
338
+ inputTokens: a.inputTokens + b.inputTokens,
339
+ outputTokens: a.outputTokens + b.outputTokens,
340
+ totalTokens: a.totalTokens + b.totalTokens,
341
+ reasoningTokens: (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0),
342
+ cachedInputTokens: (a.cachedInputTokens ?? 0) + (b.cachedInputTokens ?? 0),
343
+ cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0)
344
+ };
345
+ for (const key of USAGE_COUNTS) {
346
+ const n = (a[key] ?? 0) + (b[key] ?? 0);
347
+ if (n) sum[key] = n;
348
+ }
349
+ return sum;
350
+ };
351
+ var lessonsOf = (skills) => skills.filter((s) => s.origin?.kind === "learned").map((s) => ({
352
+ name: s.name,
353
+ description: s.description,
354
+ revision: s.origin?.revision ?? 1,
355
+ chars: s.content.length,
356
+ sources: [...s.origin?.sources ?? [], ...s.origin?.fetched ?? []]
357
+ }));
358
+ var createInitialAgentState = () => ({
359
+ status: "idle",
360
+ goal: void 0,
361
+ plan: void 0,
362
+ planThought: "",
363
+ steps: [],
364
+ finalText: "",
365
+ finalReasoning: "",
366
+ totalUsage: emptyUsage(),
367
+ runStartedAt: void 0,
368
+ runMessageId: void 0,
369
+ approvals: [],
370
+ subagents: [],
371
+ queued: [],
372
+ notes: [],
373
+ undelivered: [],
374
+ skills: [],
375
+ learned: [],
376
+ learnedNow: [],
377
+ fetches: [],
378
+ discoveredTools: [],
379
+ compactions: [],
380
+ budget: void 0,
381
+ usage: emptyUsage(),
382
+ modelLoad: void 0,
383
+ replan: void 0,
384
+ error: void 0,
385
+ stopped: false,
386
+ messages: [],
387
+ events: [],
388
+ seq: 0
389
+ });
390
+ var BLOCKER_MARK = "[BLOCKER]";
391
+ var resetRun = (state) => ({
392
+ ...createInitialAgentState(),
393
+ status: state.status,
394
+ messages: state.messages,
395
+ totalUsage: state.totalUsage,
396
+ seq: state.seq,
397
+ learned: state.learned,
398
+ // An MCP App's request is the user's, not the run's: it waits across runs.
399
+ approvals: state.approvals.filter((a) => a.app && a.status === "pending"),
400
+ // So is what this tab sent to another tab's run, until that tab answers (a replay that opens
401
+ // with the run's start is not an answer).
402
+ queued: sentToOtherTab(state.queued)
403
+ });
404
+ var sentToOtherTab = (queued) => queued.filter((q) => q.sentTo === "another-tab");
405
+ var sentEntryOf = (queued, text2) => queued.findIndex(
406
+ (q) => q.sentTo === "another-tab" && (q.text === text2 || text2.endsWith("…") && q.text.length > text2.length && q.text.startsWith(text2.slice(0, -1)))
407
+ );
408
+ var patchStep = (steps, id, fn) => steps.map((s) => s.id === id ? fn(s) : s);
409
+ var withoutSkillBody = (a) => {
410
+ if (!a.skill || a.skill.body === void 0) return a;
411
+ const { body: _body, ...skill } = a.skill;
412
+ return { ...a, skill };
413
+ };
414
+ var patchApproval = (approvals, id, fn) => approvals.map((a) => a.id === id ? fn(a) : a);
415
+ var STATUS_OF_ACTION = {
416
+ accept: "accepted",
417
+ decline: "declined",
418
+ cancel: "cancelled"
419
+ };
420
+ var addElicitation = (state, event, extra) => state.elicitations?.some((e) => e.id === event.id) ? state : {
421
+ ...state,
422
+ elicitations: [
423
+ ...state.elicitations ?? [],
424
+ {
425
+ id: event.id,
426
+ server: event.server,
427
+ tool: event.tool,
428
+ mode: event.mode,
429
+ message: event.message,
430
+ ...event.requestedSchema ? { requestedSchema: event.requestedSchema } : {},
431
+ ...event.url ? { url: event.url } : {},
432
+ ...extra.stepId ? { stepId: extra.stepId } : {},
433
+ ...extra.subagent ? { subagent: extra.subagent } : {},
434
+ ...extra.remote ? { remote: true } : {},
435
+ status: "pending"
436
+ }
437
+ ]
438
+ };
439
+ var answerElicitation = (state, event, stepId) => {
440
+ const answered = (e) => ({
441
+ ...e,
442
+ status: STATUS_OF_ACTION[event.action],
443
+ automatic: event.automatic,
444
+ ...event.reason ? { reason: event.reason } : {},
445
+ ...event.fields ? { fields: event.fields } : {}
446
+ });
447
+ const list = state.elicitations ?? [];
448
+ return {
449
+ ...state,
450
+ elicitations: list.some((e) => e.id === event.id) ? list.map((e) => e.id === event.id ? answered(e) : e) : [
451
+ ...list,
452
+ answered({
453
+ id: event.id,
454
+ server: event.server,
455
+ tool: event.tool,
456
+ message: "",
457
+ ...stepId ? { stepId } : {},
458
+ status: "pending"
459
+ })
460
+ ]
461
+ };
462
+ };
463
+ var addQuestion = (state, event, extra) => state.questions?.some((q) => q.id === event.id) ? state : {
464
+ ...state,
465
+ questions: [
466
+ ...state.questions ?? [],
467
+ {
468
+ id: event.id,
469
+ question: event.question,
470
+ options: event.options.map((o) => ({ ...o })),
471
+ multiple: event.multiple,
472
+ allowOther: event.allowOther,
473
+ ...extra.stepId ? { stepId: extra.stepId } : {},
474
+ ...extra.subagent ? { subagent: extra.subagent } : {},
475
+ ...extra.remote ? { remote: true } : {},
476
+ status: "pending"
477
+ }
478
+ ]
479
+ };
480
+ var answerQuestion = (state, event) => state.questions?.some((q) => q.id === event.id) ? {
481
+ ...state,
482
+ questions: state.questions.map(
483
+ (q) => q.id === event.id ? {
484
+ ...q,
485
+ status: event.action,
486
+ automatic: event.automatic,
487
+ ...event.action === "choice" && event.choice ? { choice: [...event.choice] } : {},
488
+ ...event.reason ? { reason: event.reason } : {}
489
+ } : q
490
+ )
491
+ } : state;
492
+ var patchSubagent = (subagents, id, fn) => subagents.map((s) => s.id === id ? fn(s) : s);
493
+ var runningStepId = (steps) => [...steps].reverse().find((s) => s.status === "running")?.id;
494
+ var applySubagentEvent = (view, event) => {
495
+ switch (event.type) {
496
+ case "step.start":
497
+ return {
498
+ ...view,
499
+ steps: view.steps + 1,
500
+ activity: `step ${event.index}/${event.total}: ${event.step.description}`,
501
+ // Known only when the child runs with model tiers.
502
+ ...event.model !== void 0 ? { model: event.model } : {},
503
+ ...event.tier !== void 0 ? { tier: event.tier } : {}
504
+ };
505
+ case "step.escalated":
506
+ return { ...view, tier: event.to, ...event.model ? { model: event.model } : {} };
507
+ case "step.tool-call":
508
+ return { ...view, toolCalls: view.toolCalls + 1, activity: `→ ${event.name}` };
509
+ case "final.text-delta":
510
+ return { ...view, text: view.text + event.delta, activity: "writing the answer" };
511
+ case "final":
512
+ return { ...view, text: event.text };
513
+ case "usage":
514
+ return { ...view, usage: addUsage(view.usage, event.usage) };
515
+ default:
516
+ return view;
517
+ }
518
+ };
519
+ var ensureSubagent = (state, id, name, ancestors, ctx) => {
520
+ if (state.subagents.some((s) => s.id === id)) return state;
521
+ const parentId = ancestors[ancestors.length - 1]?.id;
522
+ const parent = parentId ? state.subagents.find((s) => s.id === parentId) : void 0;
523
+ const stepId = parent ? parent.stepId : runningStepId(state.steps);
524
+ const node = {
525
+ id,
526
+ name,
527
+ task: "",
528
+ ...parentId ? { parentId } : {},
529
+ depth: ancestors.length + 1,
530
+ status: "running",
531
+ ...stepId ? { stepId } : {},
532
+ ...ctx.at !== void 0 ? { startedAt: ctx.at } : {},
533
+ activity: "starting",
534
+ steps: 0,
535
+ toolCalls: 0,
536
+ text: "",
537
+ usage: emptyUsage()
538
+ };
539
+ return { ...state, subagents: [...state.subagents, node] };
540
+ };
541
+ var startSubagent = (state, event, ancestors, ctx) => {
542
+ const depth = Math.max(event.depth ?? 1, ancestors.length + 1);
543
+ const parentId = ancestors[ancestors.length - 1]?.id ?? (depth > 1 ? event.parentId : void 0);
544
+ const told = {
545
+ name: event.name,
546
+ task: event.task,
547
+ depth,
548
+ ...parentId ? { parentId } : {},
549
+ ...event.profile ? { profile: event.profile } : {},
550
+ ...event.dynamic ? { dynamic: true } : {},
551
+ ...event.role ? { role: event.role } : {},
552
+ ...event.tools ? { tools: event.tools } : {}
553
+ };
554
+ if (state.subagents.some((s) => s.id === event.id)) {
555
+ return {
556
+ ...state,
557
+ subagents: patchSubagent(state.subagents, event.id, (s) => ({ ...s, ...told }))
558
+ };
559
+ }
560
+ const parent = parentId ? state.subagents.find((s) => s.id === parentId) : void 0;
561
+ const stepId = parent ? parent.stepId : runningStepId(state.steps);
562
+ const node = {
563
+ id: event.id,
564
+ ...told,
565
+ status: "running",
566
+ stepId,
567
+ ...ctx.at !== void 0 ? { startedAt: ctx.at } : {},
568
+ activity: "starting",
569
+ steps: 0,
570
+ toolCalls: 0,
571
+ text: "",
572
+ usage: emptyUsage()
573
+ };
574
+ return { ...state, subagents: [...state.subagents, node] };
575
+ };
576
+ var subagentDuration = (s, at) => at !== void 0 && s.startedAt !== void 0 ? { durationMs: Math.max(0, at - s.startedAt) } : {};
577
+ var addMedia = (state, view) => ({
578
+ ...state,
579
+ media: [...state.media ?? [], view],
580
+ ...view.stepId ? {
581
+ steps: patchStep(state.steps, view.stepId, (s) => ({
582
+ ...s,
583
+ media: [...s.media ?? [], view]
584
+ }))
585
+ } : {}
586
+ });
587
+ var mediaOf = (event, withStep) => ({
588
+ kind: event.kind,
589
+ path: event.path,
590
+ mediaType: event.mediaType,
591
+ bytes: event.bytes,
592
+ model: event.model,
593
+ ...event.references ? {
594
+ references: {
595
+ used: event.references.used === true,
596
+ count: event.references.count,
597
+ paths: [...event.references.paths]
598
+ }
599
+ } : {},
600
+ ...withStep && event.step ? { stepId: event.step.id } : {}
601
+ });
602
+ var addApp = (state, event, by) => {
603
+ if (state.apps?.some((a) => a.id === event.id)) return state;
604
+ const view = {
605
+ id: event.id,
606
+ server: event.server,
607
+ tool: event.tool,
608
+ toolName: event.toolName,
609
+ resourceUri: event.resourceUri,
610
+ input: event.input,
611
+ ...event.result ? { result: event.result } : {},
612
+ ...!by && event.step ? { stepId: event.step.id } : {},
613
+ ...by ? { by } : {}
614
+ };
615
+ const steps = !by && event.step ? patchStep(state.steps, event.step.id, (s) => {
616
+ let i = s.toolCalls.length - 1;
617
+ while (i >= 0 && !(s.toolCalls[i].name === event.tool && !s.toolCalls[i].app)) i -= 1;
618
+ if (i < 0) return s;
619
+ const toolCalls = s.toolCalls.slice();
620
+ toolCalls[i] = { ...toolCalls[i], app: event.id };
621
+ return { ...s, toolCalls };
622
+ }) : state.steps;
623
+ return { ...state, steps, apps: [...state.apps ?? [], view] };
624
+ };
625
+ var fileWritten = (state, event, by) => {
626
+ const files = state.writtenFiles ?? [];
627
+ const i = files.findIndex((f) => f.path === event.path);
628
+ const view = {
629
+ path: event.path,
630
+ mediaType: event.mediaType,
631
+ bytes: event.bytes,
632
+ writes: (i >= 0 ? files[i].writes : 0) + 1,
633
+ ...!by && event.step ? { stepId: event.step.id } : {},
634
+ ...by ? { by } : {}
635
+ };
636
+ return {
637
+ ...state,
638
+ writtenFiles: i >= 0 ? files.map((f, k) => k === i ? view : f) : [...files, view]
639
+ };
640
+ };
641
+ var fileDeleted = (state, path) => state.writtenFiles?.some((f) => f.path === path) ? { ...state, writtenFiles: state.writtenFiles.filter((f) => f.path !== path) } : state;
642
+ var transcriptOf = (event) => ({
643
+ source: event.source,
644
+ name: event.name,
645
+ text: event.text,
646
+ ...event.language ? { language: event.language } : {},
647
+ ...event.durationInSeconds !== void 0 ? { durationInSeconds: event.durationInSeconds } : {},
648
+ model: event.model
649
+ });
650
+ var applySubagent = (state, event, ancestors, ctx) => {
651
+ switch (event.type) {
652
+ case "subagent.start":
653
+ return startSubagent(state, event, ancestors, ctx);
654
+ case "subagent.event": {
655
+ const known = ensureSubagent(state, event.id, event.name, ancestors, ctx);
656
+ const inner = event.event;
657
+ switch (inner.type) {
658
+ case "subagent.start":
659
+ case "subagent.event":
660
+ case "subagent.complete":
661
+ case "subagent.error":
662
+ return applySubagent(known, inner, [...ancestors, { id: event.id }], ctx);
663
+ // A helper the model started asks through the run's own consent gate (the event says
664
+ // which helper): its request is the user's to answer, like the run's. A subagent with
665
+ // a gate of its own (no `subagent` on the event) is its host's business.
666
+ case "tool.approval-requested": {
667
+ if (!inner.subagent || known.approvals.some((a) => a.id === inner.id)) return known;
668
+ const node = known.subagents.find((s) => s.id === inner.subagent.id);
669
+ return {
670
+ ...known,
671
+ approvals: [
672
+ ...known.approvals,
673
+ {
674
+ id: inner.id,
675
+ name: inner.name,
676
+ input: inner.input,
677
+ readOnly: inner.readOnly,
678
+ // The helper's own step ids mean nothing here: the step that delegated it does.
679
+ stepId: node?.stepId,
680
+ subagent: {
681
+ id: inner.subagent.id,
682
+ depth: inner.subagent.depth,
683
+ ...node ? { name: node.name } : {},
684
+ ...node?.role ? { role: node.role } : {}
685
+ },
686
+ ...inner.skill ? { skill: inner.skill } : {},
687
+ ...inner.rule ? { rule: inner.rule } : {},
688
+ ...ctx.remote ? { remote: true } : {},
689
+ status: "pending"
690
+ }
691
+ ]
692
+ };
693
+ }
694
+ case "tool.approval-resolved":
695
+ return known.approvals.some((a) => a.id === inner.id) ? {
696
+ ...known,
697
+ approvals: patchApproval(
698
+ known.approvals,
699
+ inner.id,
700
+ (a) => withoutSkillBody({
701
+ ...a,
702
+ status: inner.approved ? "approved" : "denied",
703
+ reason: inner.reason,
704
+ automatic: inner.automatic
705
+ })
706
+ )
707
+ } : known;
708
+ // A server asks the user during a subagent's tool call (the connection lets helpers
709
+ // ask): the question is the user's to answer, like the run's own.
710
+ case "mcp.elicitation-requested": {
711
+ const node = inner.subagent ? known.subagents.find((s) => s.id === inner.subagent.id) : void 0;
712
+ return addElicitation(known, inner, {
713
+ ...ctx.remote ? { remote: true } : {},
714
+ // The subagent's own step ids mean nothing here: the step that delegated it does.
715
+ stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,
716
+ ...inner.subagent ? {
717
+ subagent: {
718
+ id: inner.subagent.id,
719
+ depth: inner.subagent.depth,
720
+ ...node ? { name: node.name } : {},
721
+ ...node?.role ? { role: node.role } : {}
722
+ }
723
+ } : {}
724
+ });
725
+ }
726
+ case "mcp.elicitation-answered":
727
+ return answerElicitation(
728
+ known,
729
+ inner,
730
+ known.subagents.find((s) => s.id === event.id)?.stepId
731
+ );
732
+ // A helper (or a subagent the host defined) asks the person through the run's handler:
733
+ // the question is the person's to answer, like the run's own, marked with who asks.
734
+ case "user.question-asked": {
735
+ const asker = inner.subagent ?? { id: event.id, depth: ancestors.length + 1 };
736
+ const node = known.subagents.find((s) => s.id === asker.id);
737
+ return addQuestion(known, inner, {
738
+ ...ctx.remote ? { remote: true } : {},
739
+ // The helper's own step ids mean nothing here: the step that delegated it does.
740
+ stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,
741
+ subagent: {
742
+ id: asker.id,
743
+ depth: asker.depth,
744
+ ...node ? { name: node.name } : {},
745
+ ...node?.role ? { role: node.role } : {}
746
+ }
747
+ });
748
+ }
749
+ case "user.question-answered":
750
+ return answerQuestion(known, inner);
751
+ // What a subagent generated is in the same workspace: it shows in the turn (its step
752
+ // ids are its own, so it is tied to no step here).
753
+ case "media.generated":
754
+ return addMedia(known, mediaOf(inner, false));
755
+ case "media.transcribed":
756
+ return { ...known, transcripts: [...known.transcripts ?? [], transcriptOf(inner)] };
757
+ // A subagent works in the same workspace: what it wrote belongs to the turn, and says
758
+ // who wrote it.
759
+ case "file.written": {
760
+ const node = known.subagents.find((s) => s.id === event.id);
761
+ return fileWritten(known, inner, {
762
+ id: event.id,
763
+ name: node?.name ?? event.name,
764
+ ...node?.role ? { role: node.role } : {}
765
+ });
766
+ }
767
+ case "file.deleted":
768
+ return fileDeleted(known, inner.path);
769
+ // An app a subagent's call came with is shown in the turn too, and says whose call it was.
770
+ case "mcp.app": {
771
+ if (ctx.remote) return known;
772
+ const node = known.subagents.find((s) => s.id === event.id);
773
+ return addApp(known, inner, {
774
+ id: event.id,
775
+ name: node?.name ?? event.name,
776
+ ...node?.role ? { role: node.role } : {}
777
+ });
778
+ }
779
+ default:
780
+ return {
781
+ ...known,
782
+ subagents: patchSubagent(
783
+ known.subagents,
784
+ event.id,
785
+ (s) => applySubagentEvent(s, inner)
786
+ )
787
+ };
788
+ }
789
+ }
790
+ case "subagent.complete": {
791
+ const known = ensureSubagent(state, event.id, event.name, ancestors, ctx);
792
+ return {
793
+ ...known,
794
+ subagents: patchSubagent(known.subagents, event.id, (s) => ({
795
+ ...s,
796
+ status: "done",
797
+ activity: "done",
798
+ text: event.text,
799
+ usage: event.usage,
800
+ ...subagentDuration(s, ctx.at)
801
+ }))
802
+ };
803
+ }
804
+ case "subagent.error": {
805
+ const known = ensureSubagent(state, event.id, event.name, ancestors, ctx);
806
+ return {
807
+ ...known,
808
+ subagents: patchSubagent(known.subagents, event.id, (s) => ({
809
+ ...s,
810
+ status: event.stopped ? "stopped" : "error",
811
+ activity: event.stopped ? "stopped" : "failed",
812
+ error: event.error,
813
+ // A helper says what it had spent when it ended; a static subagent does not.
814
+ ...event.usage ? { usage: event.usage } : {},
815
+ ...subagentDuration(s, ctx.at)
816
+ }))
817
+ };
818
+ }
819
+ }
820
+ };
821
+ var subagentTree = (subagents) => {
822
+ const nodes = /* @__PURE__ */ new Map();
823
+ for (const s of subagents) nodes.set(s.id, { ...s, children: [] });
824
+ const loops = (node) => {
825
+ let up = node.parentId;
826
+ for (let i = 0; up !== void 0 && i <= nodes.size; i++) {
827
+ if (up === node.id) return true;
828
+ up = nodes.get(up)?.parentId;
829
+ }
830
+ return false;
831
+ };
832
+ const roots = [];
833
+ for (const node of nodes.values()) {
834
+ const parent = node.parentId !== void 0 && !loops(node) ? nodes.get(node.parentId) : void 0;
835
+ if (parent) parent.children.push(node);
836
+ else roots.push(node);
837
+ }
838
+ return roots;
839
+ };
840
+ var finalizeAssistant = (messages, content, extra = {}) => {
841
+ for (let i = messages.length - 1; i >= 0; i--) {
842
+ const m = messages[i];
843
+ if (m.role === "assistant" && m.pending) {
844
+ const next = messages.slice();
845
+ next[i] = { ...m, content: content || m.content, pending: false, ...extra };
846
+ return next;
847
+ }
848
+ }
849
+ return messages;
850
+ };
851
+ var runDuration = (state, at) => at !== void 0 && state.runStartedAt !== void 0 ? { durationMs: Math.max(0, at - state.runStartedAt) } : {};
852
+ var streamAssistant = (messages, content) => {
853
+ for (let i = messages.length - 1; i >= 0; i--) {
854
+ const m = messages[i];
855
+ if (m.role === "assistant" && m.pending) {
856
+ const next = messages.slice();
857
+ next[i] = { ...m, content };
858
+ return next;
859
+ }
860
+ }
861
+ return messages;
862
+ };
863
+ var WAITING_ID = "waiting-for-session";
864
+ var withoutBusy = (state) => {
865
+ if (!state.sessionBusy) return state;
866
+ const { sessionBusy: _over, ...rest } = state;
867
+ void _over;
868
+ return { ...rest, queued: rest.queued.filter((q) => q.id !== WAITING_ID) };
869
+ };
870
+ var withoutSubmitted = (state) => {
871
+ if (!state.submitted) return state;
872
+ const { submitted, ...rest } = state;
873
+ const ids = /* @__PURE__ */ new Set([submitted.userId, submitted.assistantId]);
874
+ return { ...rest, messages: rest.messages.filter((m) => !ids.has(m.id)) };
875
+ };
876
+ var keepSubmitted = (state) => {
877
+ if (!state.submitted) return state;
878
+ const { submitted: _kept, ...rest } = state;
879
+ void _kept;
880
+ return rest;
881
+ };
882
+ var applyEvent = (state, event, ctx) => {
883
+ switch (event.type) {
884
+ case "run.start": {
885
+ const base = resetRun(ctx.remote ? state : withoutSubmitted(state));
886
+ const userId = `msg-${base.seq}`;
887
+ const assistantId = `msg-${base.seq + 1}`;
888
+ const began = ctx.at !== void 0 ? { startedAt: ctx.at } : {};
889
+ return {
890
+ ...base,
891
+ // Another tab's run keeps the view of it; a run of this tab's ends it (and any wait).
892
+ ...ctx.remote && state.remote ? { remote: state.remote } : {},
893
+ // ...and this tab's sent turn, still waiting for its own run.start (or a session.busy).
894
+ ...ctx.remote && state.submitted ? { submitted: state.submitted } : {},
895
+ goal: event.goal,
896
+ runStartedAt: ctx.at,
897
+ runMessageId: assistantId,
898
+ messages: [
899
+ ...base.messages,
900
+ {
901
+ id: userId,
902
+ role: "user",
903
+ content: event.goal,
904
+ pending: false,
905
+ ...ctx.remote ? { remote: true } : {},
906
+ ...began,
907
+ ...ctx.attachments?.length ? { attachments: ctx.attachments } : {}
908
+ },
909
+ {
910
+ id: assistantId,
911
+ role: "assistant",
912
+ content: "",
913
+ pending: true,
914
+ ...ctx.remote ? { remote: true } : {},
915
+ ...began
916
+ }
917
+ ],
918
+ seq: base.seq + 2
919
+ };
920
+ }
921
+ case "model.load":
922
+ return { ...state, modelLoad: { progress: event.progress, text: event.text } };
923
+ case "plan.thought-delta":
924
+ return { ...state, planThought: state.planThought + event.delta };
925
+ case "plan.created":
926
+ return {
927
+ ...state,
928
+ plan: event.plan,
929
+ planThought: state.planThought || event.plan.thought
930
+ };
931
+ case "plan.revised":
932
+ return {
933
+ ...state,
934
+ plan: event.plan,
935
+ // `replan.decision` came first: keep its "because the user spoke" flag.
936
+ replan: {
937
+ mode: "revise",
938
+ reason: event.reason,
939
+ ...state.replan?.byUser ? { byUser: true } : {}
940
+ }
941
+ };
942
+ case "plan.step-added":
943
+ return state;
944
+ case "step.start": {
945
+ const view = {
946
+ id: event.step.id,
947
+ index: event.index,
948
+ total: event.total,
949
+ step: event.step,
950
+ text: "",
951
+ reasoning: "",
952
+ toolCalls: [],
953
+ status: "running",
954
+ blocked: false,
955
+ // Only with `config.executorTiers`: without it the view is what it always was.
956
+ ...event.tier !== void 0 ? { tier: event.tier } : {},
957
+ ...event.model !== void 0 ? { model: event.model } : {},
958
+ ...event.tierReason !== void 0 ? { tierReason: event.tierReason } : {}
959
+ };
960
+ const steps = state.steps.map(
961
+ (s) => s.total === event.total ? s : { ...s, total: event.total }
962
+ );
963
+ return { ...state, steps: [...steps, view] };
964
+ }
965
+ case "step.escalated":
966
+ return {
967
+ ...state,
968
+ steps: patchStep(state.steps, event.step.id, (s) => {
969
+ const attempt = (s.escalations?.length ?? 0) + 1;
970
+ return {
971
+ ...s,
972
+ tier: event.to,
973
+ ...event.model ? { model: event.model } : {},
974
+ text: "",
975
+ reasoning: "",
976
+ toolCalls: s.toolCalls.map((c) => c.attempt === void 0 ? { ...c, attempt } : c),
977
+ escalations: [
978
+ ...s.escalations ?? [],
979
+ {
980
+ from: event.from,
981
+ to: event.to,
982
+ reason: event.reason,
983
+ ...event.model ? { model: event.model } : {},
984
+ ...s.text.trim() ? { text: s.text } : {}
985
+ }
986
+ ]
987
+ };
988
+ })
989
+ };
990
+ case "step.reasoning-delta":
991
+ return {
992
+ ...state,
993
+ steps: patchStep(state.steps, event.step.id, (s) => ({
994
+ ...s,
995
+ reasoning: s.reasoning + event.delta
996
+ }))
997
+ };
998
+ case "step.text-delta":
999
+ return {
1000
+ ...state,
1001
+ // "[BLOCKER]" is the executor's signal to the core that a step cannot be completed (the
1002
+ // core strips it from the step's summary): never a word for the user. Stripped from the
1003
+ // text as it accumulates, so a marker split across two deltas goes too.
1004
+ steps: patchStep(state.steps, event.step.id, (s) => ({
1005
+ ...s,
1006
+ text: (s.text + event.delta).split(BLOCKER_MARK).join("")
1007
+ }))
1008
+ };
1009
+ case "step.tool-call": {
1010
+ const tagged = new Set(
1011
+ state.steps.flatMap((s) => s.toolCalls.map((c) => c.app).filter(Boolean))
1012
+ );
1013
+ const early = state.apps?.find(
1014
+ (a) => a.stepId === event.step.id && a.tool === event.name && !tagged.has(a.id)
1015
+ );
1016
+ const call = {
1017
+ name: event.name,
1018
+ input: event.input,
1019
+ status: "calling",
1020
+ inputTokens: approxTokens(event.input),
1021
+ ...ctx.at !== void 0 ? { startedAt: ctx.at } : {},
1022
+ ...early ? { app: early.id } : {}
1023
+ };
1024
+ return {
1025
+ ...state,
1026
+ steps: patchStep(state.steps, event.step.id, (s) => ({
1027
+ ...s,
1028
+ toolCalls: [...s.toolCalls, call]
1029
+ }))
1030
+ };
1031
+ }
1032
+ case "step.tool-result":
1033
+ return {
1034
+ ...state,
1035
+ steps: patchStep(state.steps, event.step.id, (s) => {
1036
+ let done = false;
1037
+ const toolCalls = s.toolCalls.slice().reverse().map((c) => {
1038
+ if (!done && c.status === "calling" && c.name === event.name) {
1039
+ done = true;
1040
+ return {
1041
+ ...c,
1042
+ output: event.output,
1043
+ ok: event.ok,
1044
+ status: "done",
1045
+ outputTokens: approxTokens(event.output),
1046
+ ...(0, import_agent_web.isReplayedToolOutput)(event.output) ? { replayed: true } : {},
1047
+ ...ctx.at !== void 0 && c.startedAt !== void 0 ? { durationMs: Math.max(0, ctx.at - c.startedAt) } : {}
1048
+ };
1049
+ }
1050
+ return c;
1051
+ }).reverse();
1052
+ return { ...s, toolCalls };
1053
+ })
1054
+ };
1055
+ case "step.complete":
1056
+ return {
1057
+ ...state,
1058
+ steps: patchStep(state.steps, event.step.id, (s) => ({
1059
+ ...s,
1060
+ status: "done",
1061
+ summary: event.result.summary,
1062
+ // With tiers: where the step finished and how it got there. The result's list is the
1063
+ // authority; an escalation seen live keeps what only the event told (model, text).
1064
+ ...event.result.tier !== void 0 ? { tier: event.result.tier } : {},
1065
+ ...event.result.model !== void 0 ? { model: event.result.model } : {},
1066
+ ...event.result.escalations?.length ? {
1067
+ escalations: event.result.escalations.map((e, i) => {
1068
+ const live = s.escalations?.[i];
1069
+ return live && live.from === e.from && live.to === e.to ? { ...live, reason: e.reason } : { from: e.from, to: e.to, reason: e.reason };
1070
+ })
1071
+ } : {},
1072
+ blocked: event.result.blocked,
1073
+ // The result carries the authoritative, ordered tool-call list; keep
1074
+ // the timing the streamed calls measured (matched in order per name).
1075
+ toolCalls: (() => {
1076
+ const seen = /* @__PURE__ */ new Map();
1077
+ return event.result.toolCalls.map((c) => {
1078
+ const nth = seen.get(c.name) ?? 0;
1079
+ seen.set(c.name, nth + 1);
1080
+ const streamed = s.toolCalls.filter((t) => t.name === c.name)[nth];
1081
+ return {
1082
+ name: c.name,
1083
+ input: c.input,
1084
+ output: c.output,
1085
+ ok: c.ok,
1086
+ status: "done",
1087
+ inputTokens: approxTokens(c.input),
1088
+ outputTokens: approxTokens(c.output),
1089
+ ...streamed?.startedAt !== void 0 ? { startedAt: streamed.startedAt } : {},
1090
+ ...streamed?.durationMs !== void 0 ? { durationMs: streamed.durationMs } : {},
1091
+ // With tiers the list holds every attempt's calls, in the order they were made.
1092
+ ...streamed?.attempt !== void 0 ? { attempt: streamed.attempt } : {},
1093
+ ...(0, import_agent_web.isReplayedToolOutput)(c.output) ? { replayed: true } : {},
1094
+ // The MCP App the call came with (only the stream told it).
1095
+ ...streamed?.app !== void 0 ? { app: streamed.app } : {}
1096
+ };
1097
+ });
1098
+ })()
1099
+ }))
1100
+ };
1101
+ case "replan.decision": {
1102
+ if (!event.failed) {
1103
+ return {
1104
+ ...state,
1105
+ replan: {
1106
+ mode: event.mode,
1107
+ reason: event.reason,
1108
+ ...event.byUser ? { byUser: true } : {},
1109
+ ...event.confidence !== void 0 ? { confidence: event.confidence } : {}
1110
+ }
1111
+ };
1112
+ }
1113
+ const error = state.replan?.failed ? state.replan.error : void 0;
1114
+ const last = state.steps[state.steps.length - 1];
1115
+ return {
1116
+ ...state,
1117
+ replan: {
1118
+ mode: event.mode,
1119
+ reason: event.reason,
1120
+ ...event.byUser ? { byUser: true } : {},
1121
+ failed: true,
1122
+ ...error ? { error } : {}
1123
+ },
1124
+ steps: last ? patchStep(state.steps, last.id, (s) => ({
1125
+ ...s,
1126
+ replanFailed: error ?? event.reason
1127
+ })) : state.steps
1128
+ };
1129
+ }
1130
+ case "decision": {
1131
+ const view = {
1132
+ point: event.point,
1133
+ accepted: event.accepted,
1134
+ ...event.choice !== void 0 ? { choice: event.choice } : {},
1135
+ ...event.confidence !== void 0 ? { confidence: event.confidence } : {},
1136
+ threshold: event.threshold,
1137
+ ...event.reason ? { reason: event.reason } : {},
1138
+ durationMs: event.durationMs,
1139
+ ...event.model ? { model: event.model } : {}
1140
+ };
1141
+ const last = state.steps[state.steps.length - 1];
1142
+ return last ? {
1143
+ ...state,
1144
+ steps: patchStep(state.steps, last.id, (s) => ({
1145
+ ...s,
1146
+ decisions: [...s.decisions ?? [], view]
1147
+ }))
1148
+ } : { ...state, decisions: [...state.decisions ?? [], view] };
1149
+ }
1150
+ case "media.generated":
1151
+ return addMedia(state, mediaOf(event, true));
1152
+ case "media.transcribed":
1153
+ return { ...state, transcripts: [...state.transcripts ?? [], transcriptOf(event)] };
1154
+ case "file.written":
1155
+ return fileWritten(state, event);
1156
+ case "file.deleted":
1157
+ return fileDeleted(state, event.path);
1158
+ case "mcp.app":
1159
+ return ctx.remote ? state : addApp(state, event);
1160
+ case "message.queued": {
1161
+ if (state.queued.some((q) => q.id === event.id)) return state;
1162
+ const entry = {
1163
+ id: event.id,
1164
+ text: event.text,
1165
+ ...event.origin ? { origin: event.origin } : {}
1166
+ };
1167
+ const mine = ctx.remote && event.origin === "another-tab" ? sentEntryOf(state.queued, event.text) : -1;
1168
+ if (mine < 0) return { ...state, queued: [...state.queued, entry] };
1169
+ return { ...state, queued: state.queued.map((q, i) => i === mine ? entry : q) };
1170
+ }
1171
+ case "message.delivered": {
1172
+ const anchor = event.at === "round" ? runningStepId(state.steps) : event.at === "step" ? state.steps[state.steps.length - 1]?.id : void 0;
1173
+ return {
1174
+ ...state,
1175
+ queued: state.queued.filter((q) => q.id !== event.id),
1176
+ notes: [
1177
+ ...state.notes,
1178
+ {
1179
+ id: event.id,
1180
+ text: event.text,
1181
+ at: event.at,
1182
+ ...anchor ? { stepId: anchor } : {},
1183
+ ...event.origin ? { origin: event.origin } : {}
1184
+ }
1185
+ ]
1186
+ };
1187
+ }
1188
+ case "final.text-delta": {
1189
+ const finalText = state.finalText + event.delta;
1190
+ return { ...state, finalText, messages: streamAssistant(state.messages, finalText) };
1191
+ }
1192
+ case "final":
1193
+ return {
1194
+ ...state,
1195
+ finalText: event.text,
1196
+ messages: finalizeAssistant(state.messages, event.text, runDuration(state, ctx.at))
1197
+ };
1198
+ case "final.reasoning-delta":
1199
+ return { ...state, finalReasoning: state.finalReasoning + event.delta };
1200
+ case "usage":
1201
+ if (event.phase === "app") {
1202
+ return { ...state, totalUsage: addUsage(state.totalUsage, event.usage) };
1203
+ }
1204
+ return {
1205
+ ...state,
1206
+ usage: addUsage(state.usage, event.usage),
1207
+ totalUsage: addUsage(state.totalUsage, event.usage)
1208
+ };
1209
+ case "mcp.elicitation-requested":
1210
+ return addElicitation(state, event, {
1211
+ // Asked in the tab that runs the tool call: shown here, answered there.
1212
+ ...ctx.remote ? { remote: true } : {},
1213
+ stepId: event.step?.id,
1214
+ ...event.subagent ? { subagent: event.subagent } : {}
1215
+ });
1216
+ case "mcp.elicitation-answered":
1217
+ return answerElicitation(state, event, runningStepId(state.steps));
1218
+ case "user.question-asked":
1219
+ return addQuestion(state, event, {
1220
+ // Asked in the tab that runs the agent: shown here, answered there only.
1221
+ ...ctx.remote ? { remote: true } : {},
1222
+ stepId: event.step?.id,
1223
+ ...event.subagent ? { subagent: event.subagent } : {}
1224
+ });
1225
+ case "user.question-answered":
1226
+ return answerQuestion(state, event);
1227
+ case "tool.approval-requested":
1228
+ return {
1229
+ ...state,
1230
+ approvals: [
1231
+ ...state.approvals,
1232
+ {
1233
+ id: event.id,
1234
+ name: event.name,
1235
+ input: event.input,
1236
+ readOnly: event.readOnly,
1237
+ stepId: event.step?.id,
1238
+ ...event.subagent ? { subagent: event.subagent } : {},
1239
+ ...event.app ? { app: event.app } : {},
1240
+ ...event.skill ? { skill: event.skill } : {},
1241
+ ...event.rule ? { rule: event.rule } : {},
1242
+ // Asked in the tab that runs the tool: shown here, answered there.
1243
+ ...ctx.remote ? { remote: true } : {},
1244
+ status: "pending"
1245
+ }
1246
+ ]
1247
+ };
1248
+ case "tool.approval-resolved": {
1249
+ const known = state.approvals.some((a) => a.id === event.id);
1250
+ const decided = (a) => withoutSkillBody({
1251
+ ...a,
1252
+ status: event.approved ? "approved" : "denied",
1253
+ reason: event.reason,
1254
+ automatic: event.automatic
1255
+ });
1256
+ return {
1257
+ ...state,
1258
+ approvals: known ? patchApproval(state.approvals, event.id, decided) : (
1259
+ // A policy denial arrives without a request: record it too.
1260
+ [
1261
+ ...state.approvals,
1262
+ decided({
1263
+ id: event.id,
1264
+ name: event.name,
1265
+ input: void 0,
1266
+ readOnly: false,
1267
+ stepId: runningStepId(state.steps),
1268
+ status: "pending"
1269
+ })
1270
+ ]
1271
+ )
1272
+ };
1273
+ }
1274
+ case "subagent.start":
1275
+ case "subagent.event":
1276
+ case "subagent.complete":
1277
+ case "subagent.error":
1278
+ return applySubagent(state, event, [], ctx);
1279
+ case "skill.activated":
1280
+ return state.skills.includes(event.name) ? state : { ...state, skills: [...state.skills, event.name] };
1281
+ case "skill.learned": {
1282
+ const before = state.learned.find((l) => l.name === event.name);
1283
+ const lesson = {
1284
+ name: event.name,
1285
+ description: event.description,
1286
+ // A rewrite of a lesson we know goes up one; a lesson we never saw (an event for a store
1287
+ // loaded before this view existed) starts at 2 when the core says it is an update.
1288
+ revision: event.update ? (before?.revision ?? 1) + 1 : 1,
1289
+ chars: event.chars,
1290
+ sources: event.sources
1291
+ };
1292
+ return {
1293
+ ...state,
1294
+ learned: before ? state.learned.map((l) => l.name === event.name ? lesson : l) : [...state.learned, lesson],
1295
+ learnedNow: state.learnedNow.includes(event.name) ? state.learnedNow : [...state.learnedNow, event.name]
1296
+ };
1297
+ }
1298
+ case "skill.forgotten":
1299
+ return { ...state, learned: state.learned.filter((l) => l.name !== event.name) };
1300
+ case "egress.request":
1301
+ return {
1302
+ ...state,
1303
+ fetches: [
1304
+ ...state.fetches,
1305
+ {
1306
+ url: event.url,
1307
+ allowed: event.allowed,
1308
+ ...event.status !== void 0 ? { status: event.status } : {},
1309
+ ...event.reason ? { reason: event.reason } : {}
1310
+ }
1311
+ ]
1312
+ };
1313
+ case "tools.discovered":
1314
+ return {
1315
+ ...state,
1316
+ discoveredTools: [.../* @__PURE__ */ new Set([...state.discoveredTools, ...event.names])]
1317
+ };
1318
+ case "context.compacted":
1319
+ return {
1320
+ ...state,
1321
+ compactions: [
1322
+ ...state.compactions,
1323
+ { scope: event.scope, beforeTokens: event.beforeTokens, afterTokens: event.afterTokens }
1324
+ ]
1325
+ };
1326
+ case "budget.exceeded":
1327
+ return { ...state, budget: { kind: event.kind, tokens: event.tokens, cap: event.cap } };
1328
+ case "session.busy":
1329
+ state = withoutSubmitted(state);
1330
+ return {
1331
+ ...state,
1332
+ sessionBusy: { heldBy: event.heldBy, ...ctx.goal ? { goal: ctx.goal } : {} },
1333
+ // What the user sent waits with the run: shown as queued, not lost.
1334
+ ...ctx.goal ? {
1335
+ queued: [
1336
+ ...state.queued.filter((q) => q.id !== WAITING_ID),
1337
+ { id: WAITING_ID, text: ctx.goal, session: event.heldBy }
1338
+ ]
1339
+ } : {}
1340
+ };
1341
+ case "session.acquired":
1342
+ return withoutBusy(state);
1343
+ case "stopped":
1344
+ if (!ctx.remote && state.sessionBusy) return withoutBusy(state);
1345
+ if (!ctx.remote && state.submitted) return withoutSubmitted(state);
1346
+ return {
1347
+ ...withoutBusy(state),
1348
+ stopped: true,
1349
+ // Nothing of the run is waiting any more once it has stopped (an app's request is not
1350
+ // the run's).
1351
+ approvals: state.approvals.map(
1352
+ (a) => a.status === "pending" && !a.app ? withoutSkillBody({ ...a, status: "denied", reason: "stopped" }) : a
1353
+ ),
1354
+ ...state.elicitations ? {
1355
+ elicitations: state.elicitations.map(
1356
+ (e) => e.status === "pending" ? { ...e, status: "cancelled", automatic: true, reason: "stopped" } : e
1357
+ )
1358
+ } : {},
1359
+ // Nobody is asked any more once the run has stopped.
1360
+ ...state.questions ? {
1361
+ questions: state.questions.map(
1362
+ (q) => q.status === "pending" ? { ...q, status: "stopped", automatic: true, reason: "stopped" } : q
1363
+ )
1364
+ } : {},
1365
+ // What it had written, or nothing - the chat says "stopped" through its labels.
1366
+ messages: finalizeAssistant(state.messages, state.finalText, {
1367
+ ...runDuration(state, ctx.at),
1368
+ stopped: true
1369
+ })
1370
+ };
1371
+ case "error":
1372
+ if (event.phase === "replan") {
1373
+ return {
1374
+ ...state,
1375
+ replan: { mode: "continue", reason: "", failed: true, error: event.error }
1376
+ };
1377
+ }
1378
+ return event.phase === "run" ? {
1379
+ ...withoutBusy(keepSubmitted(state)),
1380
+ error: event.error,
1381
+ errorCode: event.code,
1382
+ messages: finalizeAssistant(
1383
+ state.messages,
1384
+ state.finalText || `Error: ${event.error}`,
1385
+ { ...runDuration(state, ctx.at), error: true }
1386
+ )
1387
+ } : { ...state, error: event.error };
1388
+ case "retry":
1389
+ return state;
1390
+ default:
1391
+ return state;
1392
+ }
1393
+ };
1394
+ var syncRunMessage = (state) => {
1395
+ const id = state.runMessageId;
1396
+ if (!id) return state;
1397
+ const i = state.messages.findIndex((m2) => m2.id === id);
1398
+ if (i < 0) return state;
1399
+ const m = state.messages[i];
1400
+ const decided = state.approvals.filter((a) => a.status !== "pending" && !a.app);
1401
+ const patch = {};
1402
+ if (m.steps !== state.steps) patch.steps = state.steps;
1403
+ if (m.subagents !== state.subagents) patch.subagents = state.subagents;
1404
+ if (state.notes.length > 0 && m.notes !== state.notes) patch.notes = state.notes;
1405
+ if (m.usage !== state.usage) patch.usage = state.usage;
1406
+ if ((m.reasoning ?? "") !== state.finalReasoning) patch.reasoning = state.finalReasoning;
1407
+ if (m.skills !== state.skills) patch.skills = state.skills;
1408
+ if (state.learnedNow.length > 0 && m.learned !== state.learnedNow)
1409
+ patch.learned = state.learnedNow;
1410
+ if (state.fetches.length > 0 && m.fetches !== state.fetches) patch.fetches = state.fetches;
1411
+ if (state.media && m.media !== state.media) patch.media = state.media;
1412
+ if (state.transcripts && m.transcripts !== state.transcripts)
1413
+ patch.transcripts = state.transcripts;
1414
+ if (state.writtenFiles && m.writtenFiles !== state.writtenFiles)
1415
+ patch.writtenFiles = state.writtenFiles;
1416
+ if (state.apps && m.apps !== state.apps) patch.apps = state.apps;
1417
+ if ((m.approvals?.length ?? 0) !== decided.length || decided.some((a, k) => m.approvals?.[k] !== a)) {
1418
+ patch.approvals = decided;
1419
+ }
1420
+ if (Object.keys(patch).length === 0) return state;
1421
+ const messages = state.messages.slice();
1422
+ messages[i] = { ...m, ...patch };
1423
+ return { ...state, messages };
1424
+ };
1425
+ var pendingApprovalsOf = (state) => state.approvals.filter((a) => a.status === "pending" && !a.remote);
1426
+ var agentStatusOf = (state) => state.remote?.running && (state.status === "ready" || state.status === "idle") ? "running" : state.status;
1427
+ var agentStateReducer = (state, action) => {
1428
+ switch (action.type) {
1429
+ case "reset":
1430
+ return {
1431
+ ...createInitialAgentState(),
1432
+ status: state.status,
1433
+ seq: state.seq,
1434
+ learned: state.learned
1435
+ };
1436
+ case "notebook":
1437
+ return { ...state, learned: action.lessons };
1438
+ case "submitted": {
1439
+ if (state.submitted) return state;
1440
+ const userId = `msg-${state.seq}`;
1441
+ const assistantId = `msg-${state.seq + 1}`;
1442
+ return {
1443
+ ...state,
1444
+ submitted: { userId, assistantId },
1445
+ messages: [
1446
+ ...state.messages,
1447
+ {
1448
+ id: userId,
1449
+ role: "user",
1450
+ content: action.goal,
1451
+ pending: false,
1452
+ ...action.attachments?.length ? { attachments: action.attachments } : {}
1453
+ },
1454
+ { id: assistantId, role: "assistant", content: "", pending: true }
1455
+ ],
1456
+ seq: state.seq + 2
1457
+ };
1458
+ }
1459
+ case "status":
1460
+ return {
1461
+ ...state,
1462
+ status: action.status,
1463
+ error: action.status === "error" ? action.error : void 0,
1464
+ errorCode: void 0
1465
+ };
1466
+ case "remote": {
1467
+ const remote = action.remote;
1468
+ if (!remote) {
1469
+ const { remote: _gone, ...rest } = state;
1470
+ void _gone;
1471
+ return rest;
1472
+ }
1473
+ if (remote.ended === "gone" && state.remote?.running) {
1474
+ return syncRunMessage({
1475
+ ...state,
1476
+ remote,
1477
+ messages: finalizeAssistant(state.messages, state.finalText, { error: true })
1478
+ });
1479
+ }
1480
+ return { ...state, remote };
1481
+ }
1482
+ case "event": {
1483
+ const event = withoutOwnWords(action.event);
1484
+ const next = syncRunMessage(
1485
+ applyEvent(state, event, {
1486
+ at: action.at,
1487
+ attachments: action.attachments,
1488
+ ...action.remote ? { remote: true } : {},
1489
+ ...action.goal ? { goal: action.goal } : {}
1490
+ })
1491
+ );
1492
+ const cap = action.maxEvents ?? 200;
1493
+ const events = cap > 0 ? [...state.events, event].slice(-cap) : [...state.events, event];
1494
+ return { ...next, events };
1495
+ }
1496
+ case "undelivered":
1497
+ return {
1498
+ ...state,
1499
+ queued: action.keepQueued ? state.queued : sentToOtherTab(state.queued),
1500
+ undelivered: action.texts
1501
+ };
1502
+ case "remote-send":
1503
+ return state.queued.some((q) => q.id === action.id) ? state : {
1504
+ ...state,
1505
+ queued: [
1506
+ ...state.queued,
1507
+ { id: action.id, text: action.text, sentTo: "another-tab" }
1508
+ ]
1509
+ };
1510
+ case "remote-answer": {
1511
+ const queued = state.queued.filter((q) => q.id !== action.id);
1512
+ return action.answer === "refused" ? { ...state, queued, undelivered: [...state.undelivered, action.text] } : { ...state, queued };
1513
+ }
1514
+ case "load": {
1515
+ const maxSeq = action.messages.reduce((n, m) => {
1516
+ const k = Number(/^msg-(\d+)$/.exec(m.id)?.[1] ?? -1);
1517
+ return Math.max(n, k + 1);
1518
+ }, state.seq);
1519
+ return {
1520
+ ...createInitialAgentState(),
1521
+ status: state.status,
1522
+ messages: action.messages.map((m) => m.pending ? { ...m, pending: false } : m),
1523
+ totalUsage: action.totalUsage ?? emptyUsage(),
1524
+ seq: maxSeq,
1525
+ learned: state.learned
1526
+ };
1527
+ }
1528
+ default:
1529
+ return state;
1530
+ }
1531
+ };
1532
+
1533
+ // src/composer.ts
1534
+ var parseSlash = (text2) => {
1535
+ const m = /^\/([\w-]*)(?:\s+([\s\S]*))?$/.exec(text2.trimStart());
1536
+ return m ? { name: m[1].toLowerCase(), args: (m[2] ?? "").trim() } : void 0;
1537
+ };
1538
+ var steerIntent = (input) => {
1539
+ if (!input.busy) return "idle";
1540
+ if (!input.steering) return "ignore";
1541
+ if (!input.raw && !input.hasAttachments) return "ignore";
1542
+ if (parseSlash(input.raw)) return "ignore";
1543
+ return input.hasAttachments ? "attachments" : "steer";
1544
+ };
1545
+ var notReadyIntent = (input) => {
1546
+ if (!input.hasContent) return "ignore";
1547
+ if (input.disabled) return "refuse";
1548
+ if (input.ready) return "send";
1549
+ if (input.status === "initializing") return "wait";
1550
+ return "refuse";
1551
+ };
1552
+ var notReadyReason = (input) => input.disabled ? "disabled" : input.status === "error" ? "failed" : "unavailable";
1553
+ var waitingSendStep = (input) => {
1554
+ if (input.disabled) return "stop";
1555
+ if (input.ready) return "send";
1556
+ if (input.status === "initializing" || input.status === "running") return "wait";
1557
+ if (input.status === "error") return "failed";
1558
+ return "stop";
1559
+ };
1560
+ var filterCommands = (commands, query) => {
1561
+ const q = query.toLowerCase();
1562
+ if (!q) return commands;
1563
+ const starts = commands.filter((c) => c.name.toLowerCase().startsWith(q));
1564
+ const contains = commands.filter(
1565
+ (c) => !starts.includes(c) && (c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q))
1566
+ );
1567
+ return [...starts, ...contains];
1568
+ };
1569
+ var attachmentKindOf = (mediaType, name) => {
1570
+ if (mediaType.startsWith("image/")) return "image";
1571
+ if (mediaType === "application/pdf" || /\.pdf$/i.test(name)) return "pdf";
1572
+ if (mediaType.startsWith("text/") || /json|xml|yaml|javascript|typescript|csv|markdown|x-sh|sql|toml/.test(mediaType) || /\.(txt|md|markdown|json|csv|tsv|ya?ml|xml|html?|css|m?[jt]sx?|py|sh|log|sql|toml|ini|env)$/i.test(
1573
+ name
1574
+ )) {
1575
+ return "text";
1576
+ }
1577
+ return "file";
1578
+ };
1579
+ var lineCountOf = (text2) => {
1580
+ const lines = text2.split("\n");
1581
+ return lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
1582
+ };
1583
+ var textExcerpt = (text2, maxChars) => {
1584
+ const totalLines = lineCountOf(text2);
1585
+ if (text2.length <= maxChars) return { text: text2, lastLine: totalLines, lineWhole: true, totalLines };
1586
+ let end = Math.max(0, Math.floor(maxChars));
1587
+ const code = text2.charCodeAt(end - 1);
1588
+ if (code >= 55296 && code <= 56319) end -= 1;
1589
+ const head = text2.slice(0, end);
1590
+ const lineEnd = head.lastIndexOf("\n");
1591
+ const atLine = lineEnd >= end / 2;
1592
+ const cut = atLine ? head.slice(0, lineEnd) : head;
1593
+ const lastLine = cut.split("\n").length;
1594
+ return { text: cut, lastLine, lineWhole: atLine, totalLines };
1595
+ };
1596
+ var excerptNote = (excerpt, totalChars, readTool = "fs_read") => {
1597
+ const from = excerpt.lineWhole ? excerpt.lastLine + 1 : excerpt.lastLine;
1598
+ return `[This is only the beginning of a long text: the first ${excerpt.text.length} of ${totalChars} characters (lines 1-${excerpt.lastLine} of ${excerpt.totalLines}${excerpt.lineWhole ? "" : `, line ${excerpt.lastLine} cut`}). The whole text is in the file named above - read on with ${readTool} from line ${from} (startLine / endLine), or search it, only when the answer needs it.]`;
1599
+ };
1600
+ var withAttachments = (text2, files, options = {}) => {
1601
+ const texts = files.filter((f) => f.kind === "text" && f.text !== void 0);
1602
+ const saved = files.filter((f) => f.kind !== "text" && f.path);
1603
+ if (texts.length === 0 && saved.length === 0) return text2;
1604
+ const limit = options.excerptChars;
1605
+ const blocks = texts.map((f) => {
1606
+ const whole = f.text;
1607
+ const cuts = limit !== void 0 && f.path !== void 0 && !f.converted && whole.length > limit;
1608
+ const excerpt = cuts ? textExcerpt(whole, limit) : void 0;
1609
+ const body = excerpt ? excerpt.text : whole;
1610
+ const fence = body.includes("```") ? "~~~" : "```";
1611
+ if (excerpt)
1612
+ return `### ${f.name} (its beginning; the whole text: ${f.path})
1613
+ ${excerptNote(excerpt, whole.length, options.readTool)}
1614
+ ${fence}
1615
+ ${body}
1616
+ ${fence}`;
1617
+ const where = f.path ? ` (also saved as ${f.path})` : "";
1618
+ return `### ${f.name}${where}
1619
+ ${fence}
1620
+ ${body}
1621
+ ${fence}`;
1622
+ });
1623
+ const kind = (f) => f.kind === "image" ? "picture" : f.kind === "pdf" ? "PDF" : "file";
1624
+ const lines = saved.map(
1625
+ (f) => `- ${kind(f)} "${f.name.replace(/["\s]+/g, " ").trim()}" (also saved as ${f.path})`
1626
+ );
1627
+ return [
1628
+ text2,
1629
+ ...blocks.length ? [`Attached file(s):
1630
+ ${blocks.join("\n\n")}`] : [],
1631
+ ...lines.length ? [`Also attached:
1632
+ ${lines.join("\n")}`] : []
1633
+ ].join("\n\n");
1634
+ };
1635
+ var ATTACHMENT_BOUNDS = {
1636
+ maxBytes: 20 * 1024 * 1024,
1637
+ // The largest JPEGs a phone writes (a 200 MP shot: ~20-40 MB) pass, and a long PDF with its
1638
+ // pictures; past this it is read into memory for nothing the model would get.
1639
+ maxSourceBytes: 50 * 1024 * 1024,
1640
+ // The largest phone sensor (200 MP: 16320 × 12240) passes, ~800 MB decoded; past this is a
1641
+ // scan, a render or a decompression bomb (a PNG of a few KB can declare 30000 × 30000 px).
1642
+ imageMaxSourcePixels: 2e8,
1643
+ // Under what the providers take in one request (Anthropic: 100 pictures, 32 MB; OpenAI: 50 MB).
1644
+ maxImages: 20,
1645
+ maxTotalBytes: 20 * 1024 * 1024
1646
+ };
1647
+ var attachmentTransformOf = (input) => input.converts ? "convert" : input.kind === "image" && input.imageMaxDimension !== false && input.mediaType !== "image/gif" && input.mediaType !== "image/svg+xml" ? "downscale" : "none";
1648
+ var attachmentOverLimit = (file, stage, transform, bounds) => {
1649
+ if (stage === "original" && transform !== "none") {
1650
+ const sourceBytes = Math.max(bounds.maxSourceBytes, bounds.maxBytes);
1651
+ if (file.bytes > sourceBytes) return { bound: "bytes", limit: sourceBytes };
1652
+ if (transform === "downscale" && file.pixels !== void 0 && file.pixels > bounds.imageMaxSourcePixels)
1653
+ return { bound: "pixels", limit: bounds.imageMaxSourcePixels };
1654
+ return void 0;
1655
+ }
1656
+ return file.bytes > bounds.maxBytes ? { bound: "bytes", limit: bounds.maxBytes } : void 0;
1657
+ };
1658
+ var messageOverLimit = (inMessage, next, bounds) => {
1659
+ if (next.kind === "image" && inMessage.filter((a) => a.kind === "image").length >= bounds.maxImages)
1660
+ return "images";
1661
+ const total = inMessage.reduce((n, a) => n + a.bytes, 0);
1662
+ return total + next.bytes > bounds.maxTotalBytes ? "bytes" : void 0;
1663
+ };
1664
+ var attachmentLabel = (text2, files) => files.length ? `${text2}
1665
+ 📎 ${files.map((f) => f.name).join(", ")}` : text2;
1666
+ var attachmentRefusal = (kind, caps, canConvertPdf = false) => {
1667
+ if (kind === "text" || !caps) return void 0;
1668
+ if (kind === "image" && caps.images === false) {
1669
+ return "This model can't see images — switch to a vision-capable model (Gemini, Claude, GPT-4o/5) to attach one.";
1670
+ }
1671
+ if (kind === "pdf" && caps.pdf === false && !canConvertPdf) {
1672
+ return "This model can't read PDF files — convert it to text first, or switch to Gemini, Claude or GPT-4o/5.";
1673
+ }
1674
+ if (kind === "file" && caps.files === false) {
1675
+ return "This model can't take file attachments — paste the text instead.";
1676
+ }
1677
+ return void 0;
1678
+ };
1679
+ var menuSections = (options) => {
1680
+ const out = [];
1681
+ for (const option of options) {
1682
+ const section = option.section || void 0;
1683
+ const last = out[out.length - 1];
1684
+ if (last && last.section === section) last.options.push(option);
1685
+ else out.push({ ...section ? { section } : {}, options: [option] });
1686
+ }
1687
+ return out;
1688
+ };
1689
+ var menuKeyTarget = (key, index, count) => {
1690
+ if (count <= 0) return void 0;
1691
+ switch (key) {
1692
+ case "ArrowDown":
1693
+ return index < 0 ? 0 : (index + 1) % count;
1694
+ case "ArrowUp":
1695
+ return index < 0 ? count - 1 : (index - 1 + count) % count;
1696
+ case "Home":
1697
+ return 0;
1698
+ case "End":
1699
+ return count - 1;
1700
+ default:
1701
+ return void 0;
1702
+ }
1703
+ };
1704
+ var formatElapsed = (ms) => {
1705
+ const s = Math.max(0, Math.floor(ms / 1e3));
1706
+ if (s < 60) return `${s}s`;
1707
+ const m = Math.floor(s / 60);
1708
+ if (m < 60) return `${m}m ${s % 60}s`;
1709
+ return `${Math.floor(m / 60)}h ${m % 60}m`;
1710
+ };
1711
+ var kTokens = (n) => n >= 1e3 ? `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k` : `${n}`;
1712
+ var defaultNoticeTexts = {
1713
+ limit: (kind, used, cap) => {
1714
+ const calls = kind === "tool-calls";
1715
+ const what = calls ? "Tool-call" : `${kind[0].toUpperCase()}${kind.slice(1)}-token`;
1716
+ const amount = calls ? `${used}/${cap} calls` : `${kTokens(used)}/${kTokens(cap)} tokens`;
1717
+ return `${what} limit reached · ${amount} — the agent stopped early and answered with what it had`;
1718
+ },
1719
+ compacted: (scope, before, after) => `Context compacted (${scope}) · ${kTokens(before)} → ${kTokens(after)} tokens`
1720
+ };
1721
+ var noticesOf = (state, texts = {}) => {
1722
+ const t = { ...defaultNoticeTexts, ...texts };
1723
+ const out = [];
1724
+ if (state.status === "error" && state.error) {
1725
+ out.push({ id: `error:${state.error}`, tone: "error", text: state.error });
1726
+ }
1727
+ if (state.budget) {
1728
+ const b = state.budget;
1729
+ out.push({
1730
+ id: `budget:${state.goal ?? ""}:${b.kind}:${b.cap}`,
1731
+ tone: "warn",
1732
+ text: t.limit(b.kind, b.tokens, b.cap)
1733
+ });
1734
+ }
1735
+ const last = state.compactions.at(-1);
1736
+ if (last) {
1737
+ out.push({
1738
+ id: `compact:${state.compactions.length}:${last.beforeTokens}:${last.afterTokens}`,
1739
+ tone: "info",
1740
+ text: t.compacted(last.scope, last.beforeTokens, last.afterTokens)
1741
+ });
1742
+ }
1743
+ return out;
1744
+ };
1745
+ var formatClock = (ms) => {
1746
+ const s = Math.max(0, Math.floor(ms / 1e3));
1747
+ const two = (n) => String(n).padStart(2, "0");
1748
+ const h = Math.floor(s / 3600);
1749
+ const m = Math.floor(s % 3600 / 60);
1750
+ return h > 0 ? `${h}:${two(m)}:${two(s % 60)}` : `${m}:${two(s % 60)}`;
1751
+ };
1752
+ var micProblemText = (code, message, labels) => {
1753
+ if (code === "not-allowed" || code === "service-not-allowed") return labels.micDenied;
1754
+ if (code === "audio-capture") return labels.micMissing;
1755
+ if (code === "busy") return labels.micBusy;
1756
+ if (code === "unsupported") return labels.micUnsupported;
1757
+ if (message) return message;
1758
+ return code && code !== "transcription" && code !== "failed" ? `${labels.dictationFailed} (${code})` : labels.dictationFailed;
1759
+ };
1760
+ var voiceMessageName = (at, extension) => {
1761
+ const two = (n) => String(n).padStart(2, "0");
1762
+ return `voice-${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())}-${two(
1763
+ at.getHours()
1764
+ )}${two(at.getMinutes())}${two(at.getSeconds())}.${extension}`;
1765
+ };
1766
+ var INPUT_COUNTER_FROM = 0.9;
1767
+ var inputCounterShown = (count, max) => count >= Math.ceil(max * INPUT_COUNTER_FROM);
1768
+ var boxLength = (text2) => text2.replace(/\r\n?/g, "\n").length;
1769
+ var insertionFits = (current, start, end, inserted, max) => current.length - Math.max(0, end - start) + boxLength(inserted) <= max;
1770
+ var isOneCharacter = (text2) => {
1771
+ if (text2.length === 0) return false;
1772
+ if (text2.length === 1) return true;
1773
+ const Segmenter = Intl.Segmenter;
1774
+ if (Segmenter) {
1775
+ const it = new Segmenter(void 0, { granularity: "grapheme" }).segment(text2)[Symbol.iterator]();
1776
+ it.next();
1777
+ return it.next().done === true;
1778
+ }
1779
+ return [...text2].length === 1;
1780
+ };
1781
+ var longTextRoute = (input) => {
1782
+ if (input.max === void 0) return "insert";
1783
+ if (insertionFits(input.current, input.start, input.end, input.inserted, input.max))
1784
+ return "insert";
1785
+ if (input.fromBox && isOneCharacter(input.inserted)) return "stop";
1786
+ return input.attachments ? "attach" : "refuse";
1787
+ };
1788
+ var isHigh = (code) => code >= 55296 && code <= 56319;
1789
+ var isLow = (code) => code >= 56320 && code <= 57343;
1790
+ var overflowOf = (prev, next, max) => {
1791
+ if (next.length <= max || next.length <= prev.length) return void 0;
1792
+ let head = 0;
1793
+ const most = Math.min(prev.length, next.length);
1794
+ while (head < most && prev.charCodeAt(head) === next.charCodeAt(head)) head += 1;
1795
+ if (head > 0 && isHigh(next.charCodeAt(head - 1)) && isLow(next.charCodeAt(head))) head -= 1;
1796
+ let tail = 0;
1797
+ while (tail < most - head && prev.charCodeAt(prev.length - 1 - tail) === next.charCodeAt(next.length - 1 - tail))
1798
+ tail += 1;
1799
+ const to = next.length - tail;
1800
+ if (tail > 0 && isLow(next.charCodeAt(to)) && isHigh(next.charCodeAt(to - 1))) tail -= 1;
1801
+ return { inserted: next.slice(head, next.length - tail) };
1802
+ };
1803
+ var longTextName = (at, kind = "pasted", taken = []) => {
1804
+ const two = (n) => String(n).padStart(2, "0");
1805
+ const stem = `${kind}-${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())}-${two(
1806
+ at.getHours()
1807
+ )}${two(at.getMinutes())}${two(at.getSeconds())}`;
1808
+ let name = `${stem}.txt`;
1809
+ for (let n = 2; taken.includes(name); n += 1) name = `${stem}-${n}.txt`;
1810
+ return name;
1811
+ };
1812
+ var dataUrlParts = (dataUrl) => {
1813
+ const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(dataUrl);
1814
+ if (!m) throw new Error("not a data URL");
1815
+ const mimeType = m[1] ?? "application/octet-stream";
1816
+ return m[2] ? { content: m[3], encoding: "base64", mimeType } : { content: decodeURIComponent(m[3]), encoding: "utf8", mimeType };
1817
+ };
1818
+ var attachmentFileName = (name) => name.replace(/[^\w.-]+/g, "_").slice(0, 80) || "file";
1819
+ var freeAttachmentPath = async (name, taken) => {
1820
+ const file = attachmentFileName(name);
1821
+ const dot = file.lastIndexOf(".");
1822
+ const stem = dot > 0 ? file.slice(0, dot) : file;
1823
+ const ext = dot > 0 ? file.slice(dot) : "";
1824
+ let path = `/attachments/${file}`;
1825
+ for (let n = 2; await taken(path); n += 1) path = `/attachments/${stem}-${n}${ext}`;
1826
+ return path;
1827
+ };
1828
+ var saveAttachments = async (files, items) => {
1829
+ const created = [];
1830
+ const paths = /* @__PURE__ */ new Map();
1831
+ const mine = /* @__PURE__ */ new Set();
1832
+ const taken = async (path) => mine.has(path) || await files.read(path) !== void 0;
1833
+ for (const a of items) {
1834
+ if (!a.dataUrl && a.text === void 0) continue;
1835
+ try {
1836
+ if (files.saveAttachment) {
1837
+ const { content, encoding, mimeType } = a.dataUrl ? dataUrlParts(a.dataUrl) : { content: a.text, encoding: "utf8", mimeType: a.mediaType };
1838
+ const placed = await files.saveAttachment(
1839
+ `/attachments/${attachmentFileName(a.name)}`,
1840
+ content,
1841
+ { mimeType, encoding }
1842
+ );
1843
+ if (placed.created) created.push(placed.path);
1844
+ paths.set(a, placed.path);
1845
+ continue;
1846
+ }
1847
+ const path = await freeAttachmentPath(a.name, taken);
1848
+ mine.add(path);
1849
+ if (a.dataUrl) await files.writeDataUrl(path, a.dataUrl);
1850
+ else await files.write(path, a.text, { mimeType: a.mediaType });
1851
+ created.push(path);
1852
+ paths.set(a, path);
1853
+ } catch {
1854
+ for (const path of created) {
1855
+ try {
1856
+ await files.delete(path);
1857
+ } catch {
1858
+ }
1859
+ }
1860
+ return { saved: false, failed: [a.name] };
1861
+ }
1862
+ }
1863
+ for (const [a, path] of paths) a.path = path;
1864
+ return { saved: true };
1865
+ };
1866
+
1867
+ // src/labels.ts
1868
+ var plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
1869
+ var characters = (n) => `${n.toLocaleString("en-US")} ${n === 1 ? "character" : "characters"}`;
1870
+ var kb = (n) => n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 / 1024).toFixed(1)} MB`;
1871
+ var defaultLabels = {
1872
+ emptyState: "Ask the agent to do something.",
1873
+ status: {
1874
+ idle: "Idle",
1875
+ initializing: "Loading model…",
1876
+ ready: "Ready",
1877
+ running: "Working…",
1878
+ error: "Failed to start"
1879
+ },
1880
+ history: "Chats",
1881
+ newChat: "New chat",
1882
+ files: "Files",
1883
+ totalUsage: "Tokens this conversation used, by kind",
1884
+ showHistory: "Show chats",
1885
+ showFiles: "Show files",
1886
+ close: "Close",
1887
+ steps: (n) => plural(n, "step", "steps"),
1888
+ toolCalls: (n) => plural(n, "tool call", "tool calls"),
1889
+ subagents: (n) => plural(n, "subagent", "subagents"),
1890
+ skillsUsed: (names) => `skills: ${names}`,
1891
+ learnedNow: (names) => `learned: ${names}`,
1892
+ fetches: (n) => plural(n, "web request", "web requests"),
1893
+ fetchRefused: (reason) => `refused: ${reason}`,
1894
+ answerThoughts: "Thinking about the answer",
1895
+ answerStopped: "Stopped.",
1896
+ stepThoughts: "Thoughts",
1897
+ usageTitle: "Tokens this answer spent, by kind",
1898
+ attachments: "Attachments",
1899
+ planned: "Plan",
1900
+ replanned: (mode, reason) => `Replanned (${mode}): ${reason}`,
1901
+ notebookTitle: "Notebook",
1902
+ notebookEmpty: "The agent has not written any lessons down yet.",
1903
+ notebookForget: "Forget",
1904
+ notebookRevision: (n) => `revision ${n}`,
1905
+ notebookFrom: "from",
1906
+ memorySaved: "Remembered",
1907
+ memoryUpdated: "Memory updated",
1908
+ memoryForgotten: "Forgotten",
1909
+ memoryUndo: "Undo",
1910
+ memoryUndone: "Undone",
1911
+ placeholder: "Ask the agent to do something… ( / for commands, Ctrl+V to paste an image )",
1912
+ listening: "Listening…",
1913
+ message: "Message",
1914
+ dropHint: "Drop files or images to attach them",
1915
+ attach: "Attach files",
1916
+ attachTitle: "Attach files or images (or paste with Ctrl+V, or drop them here)",
1917
+ commands: "Commands",
1918
+ commandsTitle: "Commands and skills ( / )",
1919
+ send: "Send",
1920
+ stop: "Stop",
1921
+ dismiss: "Dismiss",
1922
+ remove: (name) => `Remove ${name}`,
1923
+ dictate: "Dictate (speech to text)",
1924
+ dictateTitle: "Dictate — speech to text in the browser",
1925
+ stopDictation: "Stop dictation",
1926
+ micListening: "Listening — tap to finish",
1927
+ microphone: "Microphone",
1928
+ transcribing: "Transcribing…",
1929
+ micDenied: "The microphone is blocked for this site. Allow it in the browser's site settings (the icon beside the address), then try again.",
1930
+ micMissing: "No microphone was found on this device.",
1931
+ micBusy: "The microphone is in use by another app.",
1932
+ micUnsupported: "This browser cannot record audio on this page.",
1933
+ dictationFailed: "Dictation did not work.",
1934
+ recordVoiceMessage: "Record a voice message",
1935
+ voiceMessage: "Voice message",
1936
+ audioDuration: (clock) => clock,
1937
+ recording: (elapsed) => `Recording ${elapsed}`,
1938
+ recordingDone: "Attach the recording",
1939
+ recordingCancel: "Discard the recording",
1940
+ recordingLimit: "The recording reached its longest and was stopped; it is attached.",
1941
+ model: "Model",
1942
+ thinking: "Thinking",
1943
+ toolConsent: "Tool consent",
1944
+ modes: {
1945
+ autopilot: {
1946
+ label: "Auto",
1947
+ hint: "Never ask: every tool runs - the assistant’s and an app’s. Per-tool rules still apply"
1948
+ },
1949
+ "ask-writes": {
1950
+ label: "Ask",
1951
+ hint: "Run read-only tools freely; ask before anything that may change state"
1952
+ },
1953
+ "ask-all": { label: "Ask all", hint: "Ask before every tool call" },
1954
+ "read-only": {
1955
+ label: "Read-only",
1956
+ hint: "Only read-only tools; refuse changes without asking"
1957
+ }
1958
+ },
1959
+ timerRunning: "This run so far",
1960
+ timerLast: "The last run took",
1961
+ agents: (n) => plural(n, "agent", "agents"),
1962
+ agentsTitle: "Subagents running in this run",
1963
+ notices: defaultNoticeTexts,
1964
+ attachmentsOnly: "(attachments)",
1965
+ seeAttachments: "See the attachments.",
1966
+ tooLarge: (name, mb) => `${name} is larger than ${mb} MB.`,
1967
+ tooManyPixels: (name, megapixels) => `${name} has more than ${megapixels} megapixels — too large a picture to attach.`,
1968
+ binaryText: (name) => `${name} looks binary — it can't be attached as text.`,
1969
+ downscaledFrom: (size) => `downscaled from ${size}`,
1970
+ convertedFrom: (name) => `converted from ${name}`,
1971
+ tooManyImages: (names, max) => `${names}: not added — at most ${max} pictures go in one message.`,
1972
+ messageTooLarge: (names, mb) => `${names}: not added — the message would be over ${mb} MB.`,
1973
+ pastedText: (chars) => `Pasted text · ${characters(chars)}`,
1974
+ dictatedText: (chars) => `Dictated text · ${characters(chars)}`,
1975
+ inputCount: (count, max) => `${count.toLocaleString("en-US")} / ${max.toLocaleString("en-US")}`,
1976
+ inputLimit: (max) => `The message holds up to ${max.toLocaleString("en-US")} characters`,
1977
+ inputLimitReached: (max) => `The message is full: ${max.toLocaleString("en-US")} characters. A longer paste is attached as a file.`,
1978
+ inputLimitFull: (max) => `The message is full: ${max.toLocaleString("en-US")} characters.`,
1979
+ pastedAsFile: (chars) => `Pasted text attached as a file: ${characters(chars)}`,
1980
+ dictatedAsFile: (chars) => `Dictated text attached as a file: ${characters(chars)}`,
1981
+ longTextRefused: (max) => `The text is longer than a message holds (${max.toLocaleString("en-US")} characters) — it was not inserted.`,
1982
+ attachmentSaveFailed: (names) => `${names}: could not be saved in the files, so the message was not sent. Free some space or remove it, then send again.`,
1983
+ commandGroups: { commands: "Commands", consent: "Consent", skills: "Skills" },
1984
+ commandDescriptions: {
1985
+ compact: "Summarise the conversation to free context",
1986
+ new: "Start a new conversation",
1987
+ stop: "Stop the current run",
1988
+ autopilot: "Run every tool without asking",
1989
+ ask: "Ask before tools that may change state",
1990
+ askAll: "Ask before every tool call",
1991
+ readOnly: "Only read; refuse changes",
1992
+ think: (levels) => `Set thinking: ${levels}`
1993
+ },
1994
+ thinkingLevels: {
1995
+ off: "Default",
1996
+ none: "No thinking",
1997
+ low: "Low",
1998
+ medium: "Medium",
1999
+ high: "High"
2000
+ },
2001
+ filesEmpty: "No files yet. Attachments and files the agent writes appear here.",
2002
+ upload: "Upload",
2003
+ download: "Download",
2004
+ delete: "Delete",
2005
+ preview: "Preview",
2006
+ bytes: kb,
2007
+ historyEmpty: "No saved chats yet.",
2008
+ deleteChat: "Delete chat",
2009
+ messagesCount: (n) => plural(n, "message", "messages"),
2010
+ approvalLead: "The agent wants to run",
2011
+ approve: "Allow once",
2012
+ alwaysAllow: "Always allow",
2013
+ deny: "Deny",
2014
+ declinedReason: "the user declined",
2015
+ readOnlyTool: "read-only",
2016
+ consentWaiting: "waiting for your consent",
2017
+ consentAllowed: "allowed",
2018
+ consentDenied: (reason) => `denied${reason ? ` — ${reason}` : ""}`,
2019
+ placeholderBusy: "Tell the agent something while it works…",
2020
+ steer: "Send to the agent",
2021
+ noAttachmentsWhileBusy: "Files can’t be added while the agent is working — send them with your next message.",
2022
+ sendWhenReady: "Sends when the agent is ready",
2023
+ sendWhenReadyButton: "Send when the agent is ready",
2024
+ cancelSendWhenReady: "Don’t send",
2025
+ notSentFailed: "Not sent: the agent could not start. Your message is still here.",
2026
+ notSentUnavailable: "Not sent: the agent isn’t ready. Your message is still here.",
2027
+ notSentDisabled: "Not sent: sending is turned off. Your message is still here.",
2028
+ queuedWaiting: "waiting for the agent’s next step",
2029
+ queuedForSession: (heldBy) => heldBy === "this-tab" ? "waiting for the other run to finish" : "waiting for the other tab to finish",
2030
+ queuedForOtherTab: "waiting for the other tab to pick it up",
2031
+ noteAt: {
2032
+ round: "you said, between tool calls",
2033
+ step: "you said, after this step",
2034
+ final: "you said, before the answer"
2035
+ },
2036
+ undelivered: (n) => `Not delivered (${plural(n, "message", "messages")})`,
2037
+ sendUndelivered: "Send now",
2038
+ discardUndelivered: "Discard",
2039
+ stopSubagent: "Stop this subagent",
2040
+ subagentStopped: "stopped",
2041
+ remoteRunning: "Running in another tab: follow it here, write to it or stop it.",
2042
+ remoteWaitingConsent: "It waits for an answer in the other tab.",
2043
+ remoteGone: "The tab running this conversation closed before it finished.",
2044
+ sessionBusy: (heldBy) => heldBy === "this-tab" ? "Waiting for the other run of this conversation to finish…" : "Waiting for the other tab to finish this conversation…",
2045
+ fromAnotherTab: "from another tab",
2046
+ failed: "failed",
2047
+ toolCostTitle: "Estimated tokens of the arguments and of the result fed back to the model (chars / 4), and the call's duration",
2048
+ tierNames: { light: "light", standard: "standard", strong: "strong" },
2049
+ tierReasons: {
2050
+ planned: "The planner rated this step for this model tier",
2051
+ default: "The planner did not rate this step: it runs on the standard model",
2052
+ fallback: "The tier the planner asked for is not configured: the nearest one runs the step"
2053
+ },
2054
+ escalationReasons: {
2055
+ blocked: "reported a blocker",
2056
+ "empty-result": "produced no result",
2057
+ "tool-arguments": "kept sending tool arguments that did not parse",
2058
+ "output-cut": "output was cut off",
2059
+ error: "the model call failed"
2060
+ },
2061
+ escalated: (from, to, reason) => `Escalated: ${from} → ${to} (${reason})`,
2062
+ escalatedAttemptText: "What the earlier attempt wrote",
2063
+ escalations: (n) => plural(n, "escalation", "escalations"),
2064
+ attemptTag: (n) => `attempt ${n}`,
2065
+ replayed: "not run again",
2066
+ replayedTitle: "This exact call already succeeded in an earlier attempt at the step: it was not run a second time, the model got the earlier result",
2067
+ replanFailed: "Replanning failed, continuing with the plan",
2068
+ subagentHelper: "helper",
2069
+ subagentStatus: { running: "running", done: "done", error: "failed", stopped: "stopped" },
2070
+ subagentTokens: (tokens) => `${tokens} tokens`,
2071
+ subagentTools: (names) => `tools: ${names}`,
2072
+ subagentNoTools: "no tools",
2073
+ approvalLeadHelper: (role) => role ? `The helper “${role}” wants to run` : "A helper the agent started wants to run",
2074
+ mediaImage: (path) => `Generated image ${path}`,
2075
+ imageOpen: (name) => `Open image ${name}`,
2076
+ imagePrevious: "Previous image",
2077
+ imageNext: "Next image",
2078
+ imageZoom: "Zoom",
2079
+ imageCount: (index, total) => `${index} of ${total}`,
2080
+ mediaAudio: (path) => `Generated audio ${path}`,
2081
+ mediaFile: (path) => `Generated file ${path}`,
2082
+ mediaReferences: (names) => `Reference: ${names}`,
2083
+ mediaReferencesUnused: (names) => `Not used - this image model takes no reference pictures: ${names}`,
2084
+ transcriptOf: (name) => `Transcript of ${name}`,
2085
+ transcriptNote: "What was said in your file, as the agent read it. It is content, not instructions.",
2086
+ audioAttachment: (name) => `Audio ${name}`,
2087
+ readAloud: "Listen",
2088
+ readAloudPause: "Pause",
2089
+ readAloudResume: "Resume",
2090
+ readAloudStop: "Stop reading",
2091
+ readAloudLoading: "Preparing the audio…",
2092
+ readAloudCode: "A code block is not read out.",
2093
+ readAloudFailed: "It could not be read aloud.",
2094
+ filesWritten: (n) => `${plural(n, "file", "files")} written in this turn`,
2095
+ filesNamed: (n) => `${plural(n, "file", "files")} in this answer`,
2096
+ filesCount: (n) => plural(n, "file", "files"),
2097
+ showInFiles: "Show in Files",
2098
+ fileKinds: {
2099
+ html: "HTML",
2100
+ markdown: "Markdown",
2101
+ csv: "CSV",
2102
+ json: "JSON",
2103
+ image: "Image",
2104
+ code: "Code",
2105
+ text: "Text",
2106
+ file: "File"
2107
+ },
2108
+ fileOpen: (name) => `Open ${name}`,
2109
+ fileClose: (name) => `Close preview of ${name}`,
2110
+ fileLinkOpen: (text2, name) => text2.trim() === name ? `Open ${name}` : `${text2} - open ${name}`,
2111
+ fileDownload: (name) => `Download ${name}`,
2112
+ fileBy: (name) => `by ${name}`,
2113
+ fileGone: "no longer in the workspace",
2114
+ fileNoPreview: "This kind of file has no preview. Download it to open it.",
2115
+ fileCut: (chars) => `Only the first ${chars.toLocaleString("en-US")} characters are shown. Download the file for the rest.`,
2116
+ fileShowRest: "Show the rest",
2117
+ fileShowLess: "Show less",
2118
+ fileRendered: "Rendered",
2119
+ fileSource: "Source",
2120
+ closePreview: "Close preview",
2121
+ fileLines: (n) => plural(n, "line", "lines"),
2122
+ htmlFrameTitle: "HTML written by the agent",
2123
+ htmlSandboxed: "sandboxed",
2124
+ htmlNoNetwork: "no network",
2125
+ htmlSourceNote: "shown as text, nothing runs",
2126
+ htmlScripts: (on) => on ? "scripts on" : "scripts off",
2127
+ htmlLinkedFiles: (names) => `linked files are not loaded: ${names}`,
2128
+ htmlTooLarge: "This page is too large to preview. It is shown as source.",
2129
+ htmlTaller: "Make the preview taller",
2130
+ htmlShorter: "Make the preview shorter",
2131
+ htmlFrameName: (path) => `Preview of ${path}`,
2132
+ usageMedia: (n) => plural(n, "media call", "media calls"),
2133
+ usageDecisions: (n) => plural(n, "decision call", "decision calls"),
2134
+ decisionAccepted: (choice, confidence) => `decision model: ${choice} (${confidence})`,
2135
+ decisionFellBack: (reason, detail) => `decision model fell back: ${reason}${detail ? ` (${detail})` : ""}`,
2136
+ decisionReasons: {
2137
+ "low-confidence": "low confidence",
2138
+ "invalid-choice": "an answer that is not an option",
2139
+ "invalid-confidence": "a confidence that is not a probability",
2140
+ error: "the call failed",
2141
+ timeout: "timed out",
2142
+ "needs-model": "the choice needs the model"
2143
+ },
2144
+ searchQuery: "Searched the web for",
2145
+ searchNoResults: "no results",
2146
+ searchFiltered: (n) => `${n} left out by the web access policy`,
2147
+ searchTruncated: "list cut short",
2148
+ elicitationTitle: "A question from an MCP server",
2149
+ elicitationLead: (server) => `The MCP server “${server}” asks for your input`,
2150
+ elicitationLeadHelper: (server, role) => role ? `The MCP server “${server}” asks for your input (a call by the helper “${role}”)` : `The MCP server “${server}” asks for your input (a call by a helper)`,
2151
+ elicitationDuring: "during",
2152
+ elicitationCount: (index, total) => `${index} of ${total}`,
2153
+ elicitationFrom: (server) => `From the server “${server}”`,
2154
+ elicitationRequired: "required",
2155
+ elicitationChoose: "Choose…",
2156
+ elicitationSubmit: "Submit",
2157
+ elicitationDecline: "Decline",
2158
+ elicitationCancel: "Cancel",
2159
+ elicitationErrors: {
2160
+ required: (field) => `${field} is required.`,
2161
+ tooShort: (field, limit) => `${field} must be at least ${limit} characters.`,
2162
+ tooLong: (field, limit) => `${field} must be at most ${limit} characters.`,
2163
+ email: (field) => `${field} must be an email address.`,
2164
+ uri: (field) => `${field} must be a full address, such as https://example.com.`,
2165
+ date: (field) => `${field} must be a date.`,
2166
+ dateTime: (field) => `${field} must be a date and a time.`,
2167
+ notNumber: (field) => `${field} must be a number.`,
2168
+ notInteger: (field) => `${field} must be a whole number.`,
2169
+ belowMinimum: (field, limit) => `${field} must be ${limit} or more.`,
2170
+ aboveMaximum: (field, limit) => `${field} must be ${limit} or less.`,
2171
+ notAnOption: (field) => `${field} must be one of the options.`,
2172
+ tooFew: (field, limit) => `${field}: choose at least ${limit}.`,
2173
+ tooMany: (field, limit) => `${field}: choose at most ${limit}.`
2174
+ },
2175
+ elicitationFix: (n) => `${plural(n, "field needs", "fields need")} a correction.`,
2176
+ elicitationUrlLead: (server) => `The MCP server “${server}” asks you to open a page on`,
2177
+ elicitationUrlFull: "Full address",
2178
+ elicitationOpen: "Open in a new tab",
2179
+ elicitationOpened: "Opened in a new tab. Finish there, then confirm here.",
2180
+ elicitationUrlDone: "I have finished there",
2181
+ elicitationUrlRefused: "This link is not a secure (https) address, so it is not opened from here.",
2182
+ elicitationExpiresIn: (time) => `Cancelled automatically in ${time}`,
2183
+ elicitationExpires: "Cancelled automatically if it is left unanswered",
2184
+ elicitationAutomatic: (server, reason) => `A question from the MCP server “${server}” was answered automatically, and its tool call did not finish: ${reason}.`,
2185
+ elicitationReasons: {
2186
+ timeout: "nobody answered in time",
2187
+ "step-timeout": "the step ran out of time while the question was waiting",
2188
+ aborted: "the run was stopped",
2189
+ stopped: "the run was stopped",
2190
+ "cap-per-call": "the tool call had already asked too many questions",
2191
+ "cap-per-run": "too many questions had already been asked in this run",
2192
+ "unsupported-schema": "the form it sent cannot be shown",
2193
+ "unsupported-mode": "it asked in a way this app does not offer",
2194
+ "insecure-url": "the link it sent was refused",
2195
+ "invalid-request": "its request was malformed",
2196
+ subagent: "a helper is not allowed to ask you",
2197
+ "handler-error": "the question could not be shown",
2198
+ "invalid-answer": "the answer did not fit the form and was not sent",
2199
+ "after-failure": "an earlier question of the same call had already failed",
2200
+ "no-tool-call": "no tool call was in progress"
2201
+ },
2202
+ elicitationDismiss: "Dismiss",
2203
+ questionLead: "The agent asks you",
2204
+ questionLeadHelper: (role) => role ? `The helper “${role}” asks you` : "A helper the agent started asks you",
2205
+ questionCount: (index, total) => `${index} of ${total}`,
2206
+ questionSeveral: "Pick one or more, then Send.",
2207
+ questionSend: "Send",
2208
+ questionOther: "Other…",
2209
+ questionOtherLabel: "Your answer",
2210
+ questionSkip: "Skip",
2211
+ questionExpiresIn: (time) => `If you do not answer, the agent decides by itself in ${time}`,
2212
+ questionRemote: "Answered in the other tab, where the agent is running.",
2213
+ questionAutomatic: (reason) => `The agent went on without your answer: ${reason}.`,
2214
+ questionReasons: {
2215
+ timeout: "nobody answered in time",
2216
+ stopped: "the run was stopped",
2217
+ "handler-error": "the question could not be shown",
2218
+ "invalid-answer": "the answer did not fit the question",
2219
+ "cannot-park": "the question could not wait here"
2220
+ },
2221
+ questionDismiss: "Dismiss",
2222
+ appFrom: (server) => `App from server “${server}”`,
2223
+ appSandboxed: "sandboxed",
2224
+ appSandboxedOrigin: "sandboxed on its own origin",
2225
+ appSandboxOrigin: (origin) => `Runs on its own origin, ${origin}: its storage is its own, never this page's.`,
2226
+ appSandboxFallback: (reason) => `Not on an origin of its own (${reason}): it runs in an opaque sandbox, with no storage of its own.`,
2227
+ appSandboxReasons: {
2228
+ invalid: "the sandbox URL is not valid",
2229
+ insecure: "the sandbox URL is not https",
2230
+ "same-origin": "the sandbox URL is on this page's origin",
2231
+ "no-page-origin": "this page has no origin of its own",
2232
+ "server-name": "the server's name is not a DNS label",
2233
+ "too-many-origins": "it declares too many origins",
2234
+ "no-answer": "the sandbox page did not answer"
2235
+ },
2236
+ appSandboxBroken: "The app reloaded its frame, so it was stopped. Reload it to start again.",
2237
+ appWaiting: "waiting for you",
2238
+ appWaitingFocus: "Go to what the app is waiting for",
2239
+ appPromptsLabel: (server) => `What the app from “${server}” is waiting for`,
2240
+ appTag: "app",
2241
+ appsCount: (n) => plural(n, "app", "apps"),
2242
+ appLoading: "Loading the app…",
2243
+ appFailed: (reason) => `The app could not be shown: ${reason}`,
2244
+ appUnavailable: (server) => `The server “${server}” is not connected, so its app cannot be shown.`,
2245
+ appHidden: "hidden",
2246
+ appShow: "Show",
2247
+ appMenu: "App menu",
2248
+ appReload: "Reload app",
2249
+ appOpenPanel: "Open in panel",
2250
+ appTaller: "Taller than the chat - this app scrolls inside its frame.",
2251
+ appHide: "Hide app",
2252
+ appServedBy: (server, uri) => `Served by ${server} as ${uri}. It cannot read this chat, your keys or your files.`,
2253
+ appInPanel: "open in the panel",
2254
+ appBringBack: "Bring back",
2255
+ appClosePanel: "Close the panel",
2256
+ appPanelNote: (server) => `Content from the server “${server}”. It cannot read this chat, your keys or your files.`,
2257
+ appFrameName: (server) => `App from server ${server}`,
2258
+ appRan: (names) => `The app ran ${names}`,
2259
+ appRefused: "refused",
2260
+ approvalLeadApp: (server) => `The app “${server}” wants to run`,
2261
+ approvalFromApp: (server, readOnly) => `Asked by the app, not by the agent. This tool ${readOnly ? "only reads" : "changes"} data on the server “${server}”.`,
2262
+ appLinkLead: (server) => `The app “${server}” wants to open a link. Open it?`,
2263
+ appLinkNote: "Opens in a new tab, outside this chat. Check the site name before you continue.",
2264
+ appLinkOpen: "Open",
2265
+ appCancel: "Cancel",
2266
+ appMessageLead: (server) => `The app “${server}” wants to put a message in your message box`,
2267
+ appMessageNote: "Nothing is sent until you send it yourself, and you can change it first. It is the app’s text, not yours.",
2268
+ appMessageAccept: "Put in the message box",
2269
+ appMessageDiscard: "Discard",
2270
+ appFullscreenBadge: "full screen",
2271
+ appFullscreenExit: "Exit full screen",
2272
+ appFullscreenEnter: "Full screen",
2273
+ appFullscreenKey: "Esc",
2274
+ appDownloadLead: (server) => `The app “${server}” wants to save a file to your device`,
2275
+ appDownloadType: (mimeType) => mimeType ?? "type not given",
2276
+ appDownloadSize: kb,
2277
+ appDownloadSource: (source, server) => source === "link" ? `Read from the server “${server}” for the app.` : "Made by the app inside its frame.",
2278
+ appDownloadNote: "This page saves it, not the app. Programs, scripts and web pages are never saved; check the name before you save.",
2279
+ appDownloadSave: "Save file",
2280
+ appSamplingLead: (server) => `The app “${server}” asks the agent’s model for an answer`,
2281
+ appSamplingSystem: "Its instructions",
2282
+ appSamplingRole: (role) => role === "user" ? "Asks" : "Earlier answer",
2283
+ appSamplingImages: (count) => plural(count, "image", "images"),
2284
+ appSamplingTokens: (tokens, asked) => tokens < asked ? `Up to ${tokens} tokens (the app asked for ${asked}).` : `Up to ${tokens} tokens.`,
2285
+ appSamplingNote: "Only this text is sent - not your chat. The answer goes to the app only, and its tokens count in your total.",
2286
+ appSamplingAllow: "Allow once",
2287
+ appSamplingAlways: "Always for this app",
2288
+ appSamplingDeny: "Deny",
2289
+ skillConsentLead: (server, skill) => `The server “${server}” offers the skill “${skill}”`,
2290
+ skillConsentSize: (bytes, files) => `SKILL.md ${kb(bytes)}${files ? ` · ${plural(files, "more file", "more files")}` : ""}`,
2291
+ skillConsentByUri: "Not in the server’s list: the agent asked for it by its address.",
2292
+ skillConsentNested: (enclosing) => `It sits inside the skill “${enclosing}”: allowing that one did not allow this one.`,
2293
+ skillConsentDynamic: "This server publishes no checksums for this skill: you approve the copy the agent just read, and only that copy is used.",
2294
+ skillConsentNoFileListing: "The server cannot list this skill’s files: that copy is its SKILL.md alone.",
2295
+ skillConsentPreview: "Show what the agent would read",
2296
+ skillConsentFiles: (paths, more) => `Its files, read as text and never run: ${paths}${more ? ` and ${more} more` : ""}`,
2297
+ skillConsentNote: (server, consent) => `Instructions written by the server “${server}”, not by you. They reach the agent only if you allow it${consent === "ask" ? ", and you are asked again in every task that loads them." : " - you are asked again if the server changes them."} They cannot change the agent’s rules or approvals.`,
2298
+ skillConsentAllow: "Allow once",
2299
+ skillConsentAlways: "Always for this server",
2300
+ skillConsentDeny: "Deny",
2301
+ skillConsentDeclined: "the user declined the skill"
2302
+ };
2303
+ var NESTED = [
2304
+ "status",
2305
+ "modes",
2306
+ "commandGroups",
2307
+ "commandDescriptions",
2308
+ "thinkingLevels",
2309
+ "noteAt",
2310
+ "tierNames",
2311
+ "tierReasons",
2312
+ "escalationReasons",
2313
+ "subagentStatus",
2314
+ "decisionReasons",
2315
+ "elicitationErrors",
2316
+ "elicitationReasons",
2317
+ "questionReasons",
2318
+ "fileKinds",
2319
+ "appSandboxReasons"
2320
+ ];
2321
+ var mergeLabels = (base, over) => {
2322
+ if (!over) return base;
2323
+ const out = { ...base, ...over };
2324
+ for (const key of NESTED) {
2325
+ if (over[key]) out[key] = { ...base[key], ...over[key] };
2326
+ }
2327
+ return out;
2328
+ };
2329
+
2330
+ // src/named-files.ts
2331
+ var NAMED_FILES_MAX = 12;
2332
+ var NAMED_FILES_SCAN_MAX = 200;
2333
+ var NAMED_FILES_TEXT_MAX = 1e5;
2334
+ var PATH_MAX = 512;
2335
+ var workspacePathOf = (raw) => {
2336
+ if (raw.length < 2 || raw.length > PATH_MAX) return void 0;
2337
+ if (raw[0] !== "/" || raw[1] === "/") return void 0;
2338
+ if (/[\u0000-\u001f\u007f\\]/.test(raw)) return void 0;
2339
+ const segments = raw.slice(1).split("/");
2340
+ for (const s of segments) {
2341
+ if (!s || s === "." || s === ".." || s.trim() !== s) return void 0;
2342
+ }
2343
+ return raw;
2344
+ };
2345
+ var withoutFences = (text2) => {
2346
+ const lines = text2.split("\n");
2347
+ let fence;
2348
+ for (let i = 0; i < lines.length; i++) {
2349
+ const open = /^ {0,3}(`{3,}|~{3,})/.exec(lines[i]);
2350
+ if (!fence) {
2351
+ if (open && !(open[1][0] === "`" && lines[i].slice(open[0].length).includes("`"))) {
2352
+ fence = { char: open[1][0], size: open[1].length };
2353
+ lines[i] = " ".repeat(lines[i].length);
2354
+ }
2355
+ continue;
2356
+ }
2357
+ const close = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(lines[i]);
2358
+ if (close && close[1][0] === fence.char && close[1].length >= fence.size) fence = void 0;
2359
+ lines[i] = " ".repeat(lines[i].length);
2360
+ }
2361
+ return lines.join("\n");
2362
+ };
2363
+ var decoded = (s) => {
2364
+ if (!s.includes("%")) return s;
2365
+ try {
2366
+ return decodeURIComponent(s);
2367
+ } catch {
2368
+ return s;
2369
+ }
2370
+ };
2371
+ var codeSpansOf = (text2) => {
2372
+ const runs = [];
2373
+ for (let i = text2.indexOf("`"); i >= 0; i = text2.indexOf("`", i)) {
2374
+ let j = i + 1;
2375
+ while (j < text2.length && text2.charCodeAt(j) === 96) j++;
2376
+ runs.push({ at: i, size: j - i });
2377
+ i = j;
2378
+ }
2379
+ const next = new Array(runs.length);
2380
+ const later = /* @__PURE__ */ new Map();
2381
+ for (let k = runs.length - 1; k >= 0; k--) {
2382
+ next[k] = later.get(runs[k].size) ?? -1;
2383
+ later.set(runs[k].size, k);
2384
+ }
2385
+ const spans = [];
2386
+ for (let k = 0; k < runs.length; ) {
2387
+ const close = next[k];
2388
+ if (close < 0) {
2389
+ k++;
2390
+ continue;
2391
+ }
2392
+ const open = runs[k];
2393
+ const end = runs[close].at + runs[close].size;
2394
+ spans.push({ at: open.at, end, inner: text2.slice(open.at + open.size, runs[close].at) });
2395
+ k = close + 1;
2396
+ }
2397
+ return spans;
2398
+ };
2399
+ var LINK = /!?\[[^[\]\n]*\]\(\s*(<[^<>\n]+>|[^\s()<>]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^()\n]*\)))?\s*\)/g;
2400
+ var pathsNamedIn = (text2) => {
2401
+ if (!text2) return [];
2402
+ const head = text2.length > NAMED_FILES_TEXT_MAX ? text2.slice(0, NAMED_FILES_TEXT_MAX) : text2;
2403
+ if (!head.includes("/")) return [];
2404
+ const found = [];
2405
+ let masked = withoutFences(head);
2406
+ const spans = codeSpansOf(masked);
2407
+ const parts = [];
2408
+ let from = 0;
2409
+ for (const span of spans) {
2410
+ let inner = span.inner;
2411
+ if (inner.length > 2 && inner.startsWith(" ") && inner.endsWith(" ")) inner = inner.slice(1, -1);
2412
+ const path = workspacePathOf(inner);
2413
+ if (path) found.push({ at: span.at, path });
2414
+ parts.push(masked.slice(from, span.at), " ".repeat(span.end - span.at));
2415
+ from = span.end;
2416
+ }
2417
+ masked = parts.join("") + masked.slice(from);
2418
+ for (const m of masked.matchAll(LINK)) {
2419
+ const dest = m[1].startsWith("<") ? m[1].slice(1, -1) : m[1];
2420
+ const path = workspacePathOf(decoded(dest));
2421
+ if (path) found.push({ at: m.index, path });
2422
+ }
2423
+ found.sort((a, b) => a.at - b.at);
2424
+ const out = [];
2425
+ const seen = /* @__PURE__ */ new Set();
2426
+ for (const { path } of found) {
2427
+ if (seen.has(path)) continue;
2428
+ seen.add(path);
2429
+ out.push(path);
2430
+ if (out.length >= NAMED_FILES_SCAN_MAX) break;
2431
+ }
2432
+ return out;
2433
+ };
2434
+ var namedFilesOf = (named, exists, { exclude, max = NAMED_FILES_MAX } = {}) => {
2435
+ const skip = new Set(exclude ?? []);
2436
+ const out = [];
2437
+ for (const path of named) {
2438
+ if (out.length >= max) break;
2439
+ if (skip.has(path) || !exists(path)) continue;
2440
+ skip.add(path);
2441
+ out.push(path);
2442
+ }
2443
+ return out;
2444
+ };
2445
+
2446
+ // src/follow-scroll.ts
2447
+ var FOLLOW_REJOIN_PX = 80;
2448
+ var FOLLOW_LEAVE_PX = 2;
2449
+ var endGap = (m) => m.scrollHeight - m.scrollTop - m.clientHeight;
2450
+ var reach = (m) => Math.min(m.scrollTop, Math.max(0, m.scrollHeight - m.clientHeight));
2451
+ var followsAfterScroll = (following, before, now) => {
2452
+ if (before.scrollHeight !== now.scrollHeight || before.clientHeight !== now.clientHeight)
2453
+ return following;
2454
+ if (now.scrollTop < reach(before) - FOLLOW_LEAVE_PX) return false;
2455
+ if (now.scrollTop > before.scrollTop) return endGap(now) < FOLLOW_REJOIN_PX ? true : following;
2456
+ return following;
2457
+ };
2458
+ var followsAfterResize = (following, before, now) => following && !(now.clientHeight === before.clientHeight && now.scrollHeight >= before.scrollHeight && now.scrollTop < reach(before) - FOLLOW_LEAVE_PX);
2459
+
2460
+ // src/dom-root.ts
2461
+ var DOCUMENT_NODE = 9;
2462
+ var DOCUMENT_FRAGMENT_NODE = 11;
2463
+ var MAX_DEPTH = 64;
2464
+ var isShadowRoot = (node) => typeof node === "object" && node !== null && node.nodeType === DOCUMENT_FRAGMENT_NODE && "host" in node && Boolean(node.host);
2465
+ var isDocument = (node) => typeof node === "object" && node !== null && node.nodeType === DOCUMENT_NODE;
2466
+ var rootOf = (node) => {
2467
+ if (isDocument(node)) return node;
2468
+ const root = typeof node.getRootNode === "function" ? node.getRootNode() : void 0;
2469
+ if (isDocument(root) || isShadowRoot(root)) return root;
2470
+ return node.ownerDocument;
2471
+ };
2472
+ var activeElementOf = (at) => {
2473
+ const root = isDocument(at) || isShadowRoot(at) ? at : rootOf(at);
2474
+ return root.activeElement ?? null;
2475
+ };
2476
+ var deepActiveElement = (root) => {
2477
+ let active = root.activeElement ?? null;
2478
+ for (let i = 0; active && i < MAX_DEPTH; i++) {
2479
+ const inner = active.shadowRoot?.activeElement;
2480
+ if (!inner || inner === active) break;
2481
+ active = inner;
2482
+ }
2483
+ return active;
2484
+ };
2485
+ var nothingFocused = (doc) => {
2486
+ const active = doc.activeElement;
2487
+ return !active || active === doc.body;
2488
+ };
2489
+ var composedContains = (ancestor, node) => {
2490
+ let at = node;
2491
+ for (let i = 0; at && i < 1e5; i++) {
2492
+ if (at === ancestor) return true;
2493
+ at = at.parentNode ?? (isShadowRoot(at) ? at.host : null);
2494
+ }
2495
+ return false;
2496
+ };
2497
+ var pathOf = (event) => typeof event.composedPath === "function" ? event.composedPath() : [];
2498
+ var eventTargetOf = (event) => pathOf(event)[0] ?? event.target;
2499
+ var isEventInside = (event, node) => {
2500
+ if (!node) return false;
2501
+ const target = event.target;
2502
+ const path = pathOf(event);
2503
+ if (path.length > 0 && path[0] !== target) return path.includes(node);
2504
+ return typeof target?.nodeType === "number" && node.contains(target);
2505
+ };
2506
+ var deepElementFromPoint = (doc, x, y) => {
2507
+ if (typeof doc.elementFromPoint !== "function") return null;
2508
+ let hit = doc.elementFromPoint(x, y);
2509
+ for (let i = 0; hit && i < MAX_DEPTH; i++) {
2510
+ const shadow = hit.shadowRoot;
2511
+ if (!shadow || typeof shadow.elementFromPoint !== "function") break;
2512
+ const inner = shadow.elementFromPoint(x, y);
2513
+ if (!inner || inner === hit || !composedContains(shadow, inner)) break;
2514
+ hit = inner;
2515
+ }
2516
+ return hit;
2517
+ };
2518
+ var shadowRootsAround = (node) => {
2519
+ const roots = [];
2520
+ let root = rootOf(node);
2521
+ for (let i = 0; isShadowRoot(root) && i < MAX_DEPTH; i++) {
2522
+ roots.push(root);
2523
+ root = rootOf(root.host);
2524
+ }
2525
+ return roots;
2526
+ };
2527
+ var listenScrollAround = (node, listener) => {
2528
+ const view = node.ownerDocument?.defaultView ?? globalThis;
2529
+ const targets = [view, ...shadowRootsAround(node)];
2530
+ for (const t of targets) t.addEventListener("scroll", listener, true);
2531
+ return () => {
2532
+ for (const t of targets) t.removeEventListener("scroll", listener, true);
2533
+ };
2534
+ };
2535
+ var portalHostOf = (from, selector) => {
2536
+ const near = from.closest(selector);
2537
+ if (near) return near;
2538
+ const root = rootOf(from);
2539
+ return isShadowRoot(root) ? root : from.ownerDocument.body;
2540
+ };
2541
+
2542
+ // src/file-kinds.ts
2543
+ var import_agent_web2 = require("@dudko.dev/agent-web");
2544
+ 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;
2545
+ var mimeOf = (mediaType) => mediaType.toLowerCase().split(";")[0].trim();
2546
+ var fileKindOf = (path, mediaType) => {
2547
+ const mime = mimeOf(mediaType);
2548
+ if (Object.hasOwn(import_agent_web2.MEDIA_IMAGE_TYPES, mime)) return "image";
2549
+ if (mime === "text/html" || mime === "application/xhtml+xml" || /\.x?html?$/i.test(path))
2550
+ return "html";
2551
+ if (mime === "text/markdown" || /\.(?:md|markdown)$/i.test(path)) return "markdown";
2552
+ if (mime === "text/csv" || /\.(?:csv|tsv)$/i.test(path)) return "csv";
2553
+ if (mime === "application/json" || /\.json$/i.test(path)) return "json";
2554
+ if (CODE.test(path)) return "code";
2555
+ if (mime === "text/plain" || /\.(?:txt|log)$/i.test(path) || (0, import_agent_web2.isTextMime)(mime)) return "text";
2556
+ return "file";
2557
+ };
2558
+ var fileNameOf = (path) => path.split("/").filter(Boolean).pop() || "file";
2559
+
2560
+ // src/image-resize.ts
2561
+ var canvasOf = (w, h) => {
2562
+ if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(w, h);
2563
+ if (typeof document !== "undefined") {
2564
+ const c = document.createElement("canvas");
2565
+ c.width = w;
2566
+ c.height = h;
2567
+ return c;
2568
+ }
2569
+ return void 0;
2570
+ };
2571
+ var toBlob = (canvas, type, quality) => "convertToBlob" in canvas ? canvas.convertToBlob({ type, quality }) : new Promise((resolve) => canvas.toBlob(resolve, type, quality));
2572
+ var WINDOW = 64 * 1024;
2573
+ var SOF = /* @__PURE__ */ new Set([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207]);
2574
+ var imageSizeOf = async (file) => {
2575
+ let at = 0;
2576
+ let buf = new Uint8Array(0);
2577
+ const read = async (start, length) => {
2578
+ if (start < 0 || start + length > file.size) return void 0;
2579
+ if (start < at || start + length > at + buf.length) {
2580
+ at = start;
2581
+ buf = new Uint8Array(
2582
+ await file.slice(start, Math.min(file.size, start + Math.max(WINDOW, length))).arrayBuffer()
2583
+ );
2584
+ }
2585
+ return buf.subarray(start - at, start - at + length);
2586
+ };
2587
+ const sized = (width, height) => width > 0 && height > 0 ? { width, height } : void 0;
2588
+ try {
2589
+ const head = await read(0, 30);
2590
+ if (!head) return void 0;
2591
+ const u16be = (b, i) => b[i] << 8 | b[i + 1];
2592
+ const u32be = (b, i) => u16be(b, i) * 65536 + u16be(b, i + 2);
2593
+ const ascii = (b, i, n) => String.fromCharCode(...Array.from(b.subarray(i, i + n)));
2594
+ if (ascii(head, 1, 3) === "PNG" && head[0] === 137 && ascii(head, 12, 4) === "IHDR")
2595
+ return sized(u32be(head, 16), u32be(head, 20));
2596
+ if (ascii(head, 0, 4) === "RIFF" && ascii(head, 8, 4) === "WEBP") {
2597
+ const chunk = ascii(head, 12, 4);
2598
+ const u16le = (i) => head[i] | head[i + 1] << 8;
2599
+ const u24le = (i) => u16le(i) | head[i + 2] << 16;
2600
+ if (chunk === "VP8X") return sized(u24le(24) + 1, u24le(27) + 1);
2601
+ if (chunk === "VP8L" && head[20] === 47) {
2602
+ const bits = (u16le(21) | u16le(23) << 16) >>> 0;
2603
+ return sized((bits & 16383) + 1, (bits >>> 14 & 16383) + 1);
2604
+ }
2605
+ if (chunk === "VP8 " && head[23] === 157 && head[24] === 1 && head[25] === 42)
2606
+ return sized(u16le(26) & 16383, u16le(28) & 16383);
2607
+ return void 0;
2608
+ }
2609
+ if (head[0] === 255 && head[1] === 216) {
2610
+ let p = 2;
2611
+ for (let segments = 0; segments < 4096; segments++) {
2612
+ const m = await read(p, 4);
2613
+ if (!m || m[0] !== 255) return void 0;
2614
+ const marker = m[1];
2615
+ if (marker === 255) {
2616
+ p += 1;
2617
+ continue;
2618
+ }
2619
+ if (marker === 1 || marker >= 208 && marker <= 216) {
2620
+ p += 2;
2621
+ continue;
2622
+ }
2623
+ if (marker === 217 || marker === 218) return void 0;
2624
+ const length = u16be(m, 2);
2625
+ if (length < 2) return void 0;
2626
+ if (SOF.has(marker)) {
2627
+ const frame = await read(p + 4, 5);
2628
+ return frame ? sized(u16be(frame, 3), u16be(frame, 1)) : void 0;
2629
+ }
2630
+ p += 2 + length;
2631
+ }
2632
+ }
2633
+ return void 0;
2634
+ } catch {
2635
+ return void 0;
2636
+ }
2637
+ };
2638
+ var downscaleImage = async (file, opts = {}) => {
2639
+ const maxDimension = opts.maxDimension ?? 1568;
2640
+ const maxPixels = opts.maxPixels ?? 115e4;
2641
+ if (typeof createImageBitmap !== "function" || !file.type.startsWith("image/") || file.type === "image/gif" || file.type === "image/svg+xml") {
2642
+ return file;
2643
+ }
2644
+ let bitmap;
2645
+ try {
2646
+ bitmap = await createImageBitmap(file);
2647
+ } catch {
2648
+ return file;
2649
+ }
2650
+ const { width, height } = bitmap;
2651
+ const scale = Math.min(
2652
+ 1,
2653
+ maxDimension / Math.max(width, height),
2654
+ Math.sqrt(maxPixels / Math.max(1, width * height))
2655
+ );
2656
+ if (scale >= 1) {
2657
+ bitmap.close();
2658
+ return file;
2659
+ }
2660
+ const w = Math.max(1, Math.round(width * scale));
2661
+ const h = Math.max(1, Math.round(height * scale));
2662
+ const canvas = canvasOf(w, h);
2663
+ const ctx = canvas?.getContext("2d");
2664
+ if (!canvas || !ctx) {
2665
+ bitmap.close();
2666
+ return file;
2667
+ }
2668
+ ctx.drawImage(bitmap, 0, 0, w, h);
2669
+ bitmap.close();
2670
+ const type = file.type === "image/png" || file.type === "image/webp" ? file.type : "image/jpeg";
2671
+ const out = await toBlob(canvas, type, opts.quality ?? 0.9);
2672
+ return out && out.size < file.size ? out : file;
2673
+ };
2674
+
2675
+ // src/format.ts
2676
+ var previewValue = (value, max = 140) => {
2677
+ if (value === void 0) return "";
2678
+ let text2;
2679
+ if (typeof value === "string") text2 = value;
2680
+ else {
2681
+ try {
2682
+ text2 = JSON.stringify(value);
2683
+ } catch {
2684
+ text2 = String(value);
2685
+ }
2686
+ }
2687
+ text2 = text2.replace(/\s+/g, " ").trim();
2688
+ return text2.length > max ? `${text2.slice(0, max - 1)}…` : text2;
2689
+ };
2690
+ var formatTokens = (n) => n >= 1e3 ? `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
2691
+ var formatDuration = (ms) => {
2692
+ if (ms < 1e3) return `${Math.round(ms)} ms`;
2693
+ if (ms < 6e4) return `${(ms / 1e3).toFixed(ms < 1e4 ? 1 : 0)} s`;
2694
+ const s = Math.round(ms / 1e3);
2695
+ return `${Math.floor(s / 60)}m ${s % 60}s`;
2696
+ };
2697
+ var isDataImage = (v) => typeof v === "string" && /^data:image\/[\w.+-]+;base64,/.test(v);
2698
+ var imagesInOutput = (output, depth = 0) => {
2699
+ if (depth > 2 || output == null) return [];
2700
+ if (isDataImage(output)) return [output];
2701
+ if (Array.isArray(output)) return output.flatMap((v) => imagesInOutput(v, depth + 1));
2702
+ if (typeof output === "object") {
2703
+ const o = output;
2704
+ if (o.type === "image" && typeof o.data === "string") {
2705
+ const mime = typeof o.mimeType === "string" ? o.mimeType : "image/png";
2706
+ return [o.data.startsWith("data:") ? o.data : `data:${mime};base64,${o.data}`];
2707
+ }
2708
+ for (const key of ["dataUrl", "url", "image"])
2709
+ if (isDataImage(o[key])) return [o[key]];
2710
+ if (depth < 2) return Object.values(o).flatMap((v) => imagesInOutput(v, depth + 1));
2711
+ }
2712
+ return [];
2713
+ };
2714
+ var text = (v, max) => typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, max) : "";
2715
+ var webSearchOf = (output) => {
2716
+ let value = output;
2717
+ if (typeof value === "string") {
2718
+ try {
2719
+ value = JSON.parse(value);
2720
+ } catch {
2721
+ return void 0;
2722
+ }
2723
+ }
2724
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2725
+ const o = value;
2726
+ if (typeof o.query !== "string" || !Array.isArray(o.results)) return void 0;
2727
+ const results = [];
2728
+ for (const r of o.results.slice(0, 10)) {
2729
+ if (!r || typeof r !== "object") continue;
2730
+ const item = r;
2731
+ if (typeof item.url !== "string") continue;
2732
+ let url;
2733
+ try {
2734
+ url = new URL(item.url);
2735
+ } catch {
2736
+ continue;
2737
+ }
2738
+ if (url.protocol !== "https:" && url.protocol !== "http:") continue;
2739
+ const date = text(item.date, 40);
2740
+ results.push({
2741
+ title: text(item.title, 200) || url.host,
2742
+ url: url.href,
2743
+ host: url.host,
2744
+ snippet: text(item.snippet, 400),
2745
+ ...date ? { date } : {}
2746
+ });
2747
+ }
2748
+ return {
2749
+ query: text(o.query, 300),
2750
+ results,
2751
+ filtered: typeof o.filtered === "number" && o.filtered > 0 ? o.filtered : 0,
2752
+ truncated: o.truncated === true
2753
+ };
2754
+ };
2755
+ var formatProbability = (p) => String(Math.round(p * 100) / 100);
2756
+
2757
+ // src/approval-queue.ts
2758
+ var createApprovalQueue = () => {
2759
+ const waiting = /* @__PURE__ */ new Map();
2760
+ const handler = (req2, ctx) => new Promise((resolve) => {
2761
+ const signal = ctx?.signal;
2762
+ if (signal?.aborted) {
2763
+ resolve({ approved: false, reason: "no longer asked" });
2764
+ return;
2765
+ }
2766
+ const onAbort = () => {
2767
+ if (waiting.get(req2.id) !== settle) return;
2768
+ settle({ approved: false, reason: "no longer asked" });
2769
+ };
2770
+ const settle = (decision) => {
2771
+ waiting.delete(req2.id);
2772
+ signal?.removeEventListener("abort", onAbort);
2773
+ resolve(decision);
2774
+ };
2775
+ signal?.addEventListener("abort", onAbort, { once: true });
2776
+ waiting.set(req2.id, settle);
2777
+ });
2778
+ const answer = (id, decision) => {
2779
+ const settle = waiting.get(id);
2780
+ if (!settle) return false;
2781
+ settle(decision);
2782
+ return true;
2783
+ };
2784
+ return {
2785
+ handler,
2786
+ approve: (id, options) => answer(id, { approved: true, remember: options?.remember }),
2787
+ deny: (id, reason) => answer(id, { approved: false, reason }),
2788
+ settleAll: (decision) => {
2789
+ for (const settle of [...waiting.values()]) settle(decision);
2790
+ },
2791
+ pending: () => [...waiting.keys()]
2792
+ };
2793
+ };
2794
+
2795
+ // src/elicitation.ts
2796
+ var ELICITATION_TIMEOUT_MS = 3e5;
2797
+ var elicitationSettings = (option) => {
2798
+ if (option === true) return {};
2799
+ if (typeof option === "object" && option !== null) return { ...option };
2800
+ return void 0;
2801
+ };
2802
+ var elicitationConnectOptions = (option, handler) => {
2803
+ const settings = elicitationSettings(option);
2804
+ return settings ? { onElicitation: handler, elicitation: settings } : {};
2805
+ };
2806
+ var TIMER_MAX_MS2 = 2147483647;
2807
+ var elicitationTimeoutOf = (settings) => {
2808
+ const raw = settings.timeoutMs;
2809
+ if (raw === void 0 || raw === null) return ELICITATION_TIMEOUT_MS;
2810
+ if (typeof raw !== "number" || !(raw > 0) || raw > TIMER_MAX_MS2) return void 0;
2811
+ return Math.max(1, Math.floor(raw));
2812
+ };
2813
+ var createElicitationQueue = (options = {}) => {
2814
+ const now = options.now ?? Date.now;
2815
+ const waiting = /* @__PURE__ */ new Map();
2816
+ let disposed = false;
2817
+ const list = () => [...waiting.values()].map((w) => w.request);
2818
+ const changed = () => {
2819
+ if (!disposed) options.onChange?.(list());
2820
+ };
2821
+ const handler = (request, ctx) => new Promise((resolve) => {
2822
+ const signal = ctx?.signal;
2823
+ if (disposed || signal?.aborted || waiting.has(request.id)) {
2824
+ resolve({ action: "cancel" });
2825
+ return;
2826
+ }
2827
+ const onAbort = () => {
2828
+ if (waiting.get(request.id)?.settle !== settle) return;
2829
+ settle({ action: "cancel" });
2830
+ changed();
2831
+ };
2832
+ const settle = (result) => {
2833
+ if (waiting.get(request.id)?.settle !== settle) return;
2834
+ waiting.delete(request.id);
2835
+ signal?.removeEventListener("abort", onAbort);
2836
+ resolve(result);
2837
+ };
2838
+ signal?.addEventListener("abort", onAbort, { once: true });
2839
+ const timeoutMs = typeof options.timeoutMs === "function" ? options.timeoutMs() : options.timeoutMs;
2840
+ waiting.set(request.id, {
2841
+ request: {
2842
+ ...request,
2843
+ ...timeoutMs !== void 0 ? { expiresAt: now() + timeoutMs } : {}
2844
+ },
2845
+ settle
2846
+ });
2847
+ changed();
2848
+ });
2849
+ return {
2850
+ handler,
2851
+ pending: list,
2852
+ answer: (id, result) => {
2853
+ const entry = waiting.get(id);
2854
+ if (!entry) return false;
2855
+ entry.settle(result);
2856
+ changed();
2857
+ return true;
2858
+ },
2859
+ cancel: (match) => {
2860
+ let any = false;
2861
+ for (const entry of [...waiting.values()]) {
2862
+ if (match && !match(entry.request)) continue;
2863
+ entry.settle({ action: "cancel" });
2864
+ any = true;
2865
+ }
2866
+ if (any) changed();
2867
+ },
2868
+ dispose: () => {
2869
+ disposed = true;
2870
+ for (const entry of [...waiting.values()]) entry.settle({ action: "cancel" });
2871
+ }
2872
+ };
2873
+ };
2874
+ var titled = (options) => options.map((o) => ({ value: o.const, label: o.title || o.const }));
2875
+ var optionsOf = (schema) => {
2876
+ if (schema.type === "array") {
2877
+ const items = schema.items;
2878
+ if (items?.anyOf) return titled(items.anyOf);
2879
+ return (items?.enum ?? []).map((value) => ({ value, label: value }));
2880
+ }
2881
+ if (schema.type !== "string") return void 0;
2882
+ if (schema.oneOf) return titled(schema.oneOf);
2883
+ if (schema.enum) {
2884
+ const names = schema.enumNames;
2885
+ return schema.enum.map((value, i) => ({ value, label: names?.[i] || value }));
2886
+ }
2887
+ return void 0;
2888
+ };
2889
+ var controlOf = (schema) => {
2890
+ switch (schema.type) {
2891
+ case "boolean":
2892
+ return "checkbox";
2893
+ case "number":
2894
+ case "integer":
2895
+ return "number";
2896
+ case "array":
2897
+ return "multiselect";
2898
+ default:
2899
+ if (schema.enum || schema.oneOf) return "select";
2900
+ switch (schema.format) {
2901
+ case "email":
2902
+ return "email";
2903
+ case "uri":
2904
+ return "url";
2905
+ case "date":
2906
+ return "date";
2907
+ case "date-time":
2908
+ return "datetime";
2909
+ default:
2910
+ return "text";
2911
+ }
2912
+ }
2913
+ };
2914
+ var elicitationFields = (schema) => {
2915
+ const required = new Set(schema?.required ?? []);
2916
+ return Object.entries(schema?.properties ?? {}).map(([name, field]) => {
2917
+ const options = optionsOf(field);
2918
+ return {
2919
+ name,
2920
+ label: field.title || name,
2921
+ ...field.description ? { description: field.description } : {},
2922
+ required: required.has(name),
2923
+ control: controlOf(field),
2924
+ ...options ? { options } : {},
2925
+ schema: field
2926
+ };
2927
+ });
2928
+ };
2929
+ var pad = (n) => String(n).padStart(2, "0");
2930
+ var toLocalInput = (value) => {
2931
+ const date = new Date(value);
2932
+ if (Number.isNaN(date.getTime())) return "";
2933
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
2934
+ };
2935
+ var elicitationInitialDraft = (schema) => {
2936
+ const draft = {};
2937
+ for (const field of elicitationFields(schema)) {
2938
+ const preset = field.schema.default;
2939
+ switch (field.control) {
2940
+ case "checkbox":
2941
+ draft[field.name] = preset === true;
2942
+ break;
2943
+ case "multiselect":
2944
+ draft[field.name] = Array.isArray(preset) ? [...preset] : [];
2945
+ break;
2946
+ case "number":
2947
+ draft[field.name] = typeof preset === "number" ? String(preset) : "";
2948
+ break;
2949
+ case "datetime":
2950
+ draft[field.name] = typeof preset === "string" ? toLocalInput(preset) : "";
2951
+ break;
2952
+ default:
2953
+ draft[field.name] = typeof preset === "string" ? preset : "";
2954
+ }
2955
+ }
2956
+ return draft;
2957
+ };
2958
+ var ELICITATION_VALUE_MAX_CHARS = 1e4;
2959
+ var ELICITATION_MAX_OPTIONS = 100;
2960
+ var NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
2961
+ var numberOf = (text2) => {
2962
+ const trimmed = text2.trim();
2963
+ if (!NUMBER.test(trimmed)) return void 0;
2964
+ const n = Number(trimmed);
2965
+ return Number.isFinite(n) ? n : void 0;
2966
+ };
2967
+ var formatIssue = (format, value) => {
2968
+ switch (format) {
2969
+ case "email":
2970
+ return /^[^@\s]+@[^@\s]+$/.test(value) ? void 0 : "email";
2971
+ case "uri":
2972
+ try {
2973
+ return new URL(value) ? void 0 : "uri";
2974
+ } catch {
2975
+ return "uri";
2976
+ }
2977
+ case "date":
2978
+ return /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(value)) ? void 0 : "date";
2979
+ case "date-time":
2980
+ return /^\d{4}-\d{2}-\d{2}T/.test(value) && !Number.isNaN(Date.parse(value)) ? void 0 : "dateTime";
2981
+ default:
2982
+ return void 0;
2983
+ }
2984
+ };
2985
+ var dateTimeOf = (value) => {
2986
+ const date = new Date(value);
2987
+ return Number.isNaN(date.getTime()) ? value : date.toISOString();
2988
+ };
2989
+ var answerOf = (field, raw) => {
2990
+ const { schema } = field;
2991
+ switch (field.control) {
2992
+ case "checkbox":
2993
+ return { value: raw === true };
2994
+ case "multiselect": {
2995
+ const picked = Array.isArray(raw) ? raw : [];
2996
+ if (picked.length === 0 && !field.required) return { empty: true };
2997
+ const allowed = new Set((field.options ?? []).map((o) => o.value));
2998
+ if (!picked.every((item) => allowed.has(item))) return { issue: { kind: "notAnOption" } };
2999
+ if (schema.minItems !== void 0 && picked.length < schema.minItems) {
3000
+ return { issue: { kind: "tooFew", limit: schema.minItems } };
3001
+ }
3002
+ const max = Math.min(schema.maxItems ?? ELICITATION_MAX_OPTIONS, ELICITATION_MAX_OPTIONS);
3003
+ if (picked.length > max) return { issue: { kind: "tooMany", limit: max } };
3004
+ return { value: [...picked] };
3005
+ }
3006
+ case "number": {
3007
+ const text2 = typeof raw === "string" ? raw.trim() : "";
3008
+ if (!text2) return { empty: true };
3009
+ const n = numberOf(text2);
3010
+ if (n === void 0) return { issue: { kind: "notNumber" } };
3011
+ if (schema.type === "integer" && !Number.isInteger(n)) {
3012
+ return { issue: { kind: "notInteger" } };
3013
+ }
3014
+ if (schema.minimum !== void 0 && n < schema.minimum) {
3015
+ return { issue: { kind: "belowMinimum", limit: schema.minimum } };
3016
+ }
3017
+ if (schema.maximum !== void 0 && n > schema.maximum) {
3018
+ return { issue: { kind: "aboveMaximum", limit: schema.maximum } };
3019
+ }
3020
+ return { value: n };
3021
+ }
3022
+ case "select": {
3023
+ const text2 = typeof raw === "string" ? raw : "";
3024
+ if (!text2) return { empty: true };
3025
+ return (field.options ?? []).some((o) => o.value === text2) ? { value: text2 } : { issue: { kind: "notAnOption" } };
3026
+ }
3027
+ default: {
3028
+ const typed = typeof raw === "string" ? raw : "";
3029
+ if (!typed) return { empty: true };
3030
+ const text2 = field.control === "datetime" ? dateTimeOf(typed) : typed;
3031
+ const max = schema.maxLength ?? ELICITATION_VALUE_MAX_CHARS;
3032
+ if (text2.length > max) return { issue: { kind: "tooLong", limit: max } };
3033
+ if (schema.minLength !== void 0 && text2.length < schema.minLength) {
3034
+ return { issue: { kind: "tooShort", limit: schema.minLength } };
3035
+ }
3036
+ const format = formatIssue(schema.format, text2);
3037
+ return format ? { issue: { kind: format } } : { value: text2 };
3038
+ }
3039
+ }
3040
+ };
3041
+ var elicitationFormAnswer = (schema, draft) => {
3042
+ const content = {};
3043
+ const issues = {};
3044
+ for (const field of elicitationFields(schema)) {
3045
+ const answer = answerOf(field, Object.hasOwn(draft, field.name) ? draft[field.name] : void 0);
3046
+ if ("issue" in answer) {
3047
+ issues[field.name] = answer.issue;
3048
+ } else if ("empty" in answer) {
3049
+ if (field.required) issues[field.name] = { kind: "required" };
3050
+ } else {
3051
+ content[field.name] = answer.value;
3052
+ }
3053
+ }
3054
+ return Object.keys(issues).length > 0 ? { ok: false, issues } : { ok: true, content };
3055
+ };
3056
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
3057
+ var elicitationLink = (raw) => {
3058
+ const text2 = typeof raw === "string" ? raw : "";
3059
+ let url;
3060
+ try {
3061
+ url = new URL(text2);
3062
+ } catch {
3063
+ return { host: "", href: text2, openable: false };
3064
+ }
3065
+ const secure = url.protocol === "https:" || url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname);
3066
+ return {
3067
+ host: url.host,
3068
+ href: url.href,
3069
+ openable: secure && !url.username && !url.password && !/\s/.test(text2)
3070
+ };
3071
+ };
3072
+ var formatCountdown = (ms) => {
3073
+ const total = Math.max(0, Math.ceil(ms / 1e3));
3074
+ return `${Math.floor(total / 60)}:${pad(total % 60)}`;
3075
+ };
3076
+
3077
+ // src/prompt-arming.ts
3078
+ var PROMPT_ARM_MS = 500;
3079
+ var ACTIVATING_KEYS = /* @__PURE__ */ new Set(["Enter", " ", "Spacebar"]);
3080
+ var createPromptArming = (delayMs = PROMPT_ARM_MS) => {
3081
+ const delay = Number.isFinite(delayMs) && delayMs >= 0 ? delayMs : PROMPT_ARM_MS;
3082
+ let where;
3083
+ let since = 0;
3084
+ let armedAt = Number.POSITIVE_INFINITY;
3085
+ let downAt = Number.NEGATIVE_INFINITY;
3086
+ let key = "none";
3087
+ let keyAt = Number.NEGATIVE_INFINITY;
3088
+ return {
3089
+ get armed() {
3090
+ return armedAt !== Number.POSITIVE_INFINITY;
3091
+ },
3092
+ sample(next, now) {
3093
+ if (next === void 0 || next !== where) {
3094
+ where = next;
3095
+ since = now;
3096
+ armedAt = Number.POSITIVE_INFINITY;
3097
+ return false;
3098
+ }
3099
+ if (armedAt === Number.POSITIVE_INFINITY && now - since >= delay) armedAt = now;
3100
+ return armedAt !== Number.POSITIVE_INFINITY;
3101
+ },
3102
+ pointerDown(at) {
3103
+ downAt = at;
3104
+ },
3105
+ keyDown(k, at) {
3106
+ if (!ACTIVATING_KEYS.has(k.key)) return true;
3107
+ if (k.repeat || at < armedAt) {
3108
+ key = "blocked";
3109
+ keyAt = at;
3110
+ return false;
3111
+ }
3112
+ key = "counts";
3113
+ keyAt = at;
3114
+ return true;
3115
+ },
3116
+ click(detail, now) {
3117
+ const armedNow = armedAt <= now;
3118
+ const ok = detail > 0 ? armedNow && downAt >= armedAt : armedNow && (key === "none" || key === "counts" && keyAt >= armedAt);
3119
+ downAt = Number.NEGATIVE_INFINITY;
3120
+ key = "none";
3121
+ return ok;
3122
+ }
3123
+ };
3124
+ };
3125
+
3126
+ // src/chat-history.ts
3127
+ var core = __toESM(require("@dudko.dev/agent-web"), 1);
3128
+ var DB_VERSION = 1;
3129
+ var req = (r) => new Promise((resolve, reject) => {
3130
+ r.onsuccess = () => resolve(r.result);
3131
+ r.onerror = () => reject(r.error);
3132
+ });
3133
+ var committed = (tx, r) => new Promise((resolve, reject) => {
3134
+ tx.oncomplete = () => resolve();
3135
+ tx.onabort = () => reject(tx.error ?? r.error ?? new Error("the transaction was aborted"));
3136
+ tx.onerror = () => reject(tx.error ?? r.error);
3137
+ });
3138
+ var ChatHistoryStore = class {
3139
+ /** The IndexedDB database (undefined in memory): the name its `chats` notices go out under. */
3140
+ dbName;
3141
+ name;
3142
+ storeName;
3143
+ memory;
3144
+ db;
3145
+ constructor(opts = {}) {
3146
+ this.name = opts.dbName ?? "agent-web-react";
3147
+ this.storeName = opts.storeName ?? "chats";
3148
+ if (opts.memory || typeof indexedDB === "undefined") this.memory = /* @__PURE__ */ new Map();
3149
+ this.dbName = this.memory ? void 0 : this.name;
3150
+ }
3151
+ /**
3152
+ * The store's connection, opened on first use. Never in another tab's way: when another
3153
+ * connection asks to delete or upgrade the database (`versionchange` - another tab's
3154
+ * `indexedDB.deleteDatabase`, a newer copy of this package), it is closed at once, so that
3155
+ * request goes ahead instead of waiting for this tab to close; one the browser closed by itself
3156
+ * (site data cleared) is let go too. The next use opens the database again - after a deletion a
3157
+ * new, empty one (no chats: `list()` is empty, a save starts it again); after an upgrade by a
3158
+ * newer copy, the open fails until the page is reloaded with that copy.
3159
+ */
3160
+ open() {
3161
+ if (this.db) return this.db;
3162
+ const opening = new Promise((resolve, reject) => {
3163
+ const r = indexedDB.open(this.name, DB_VERSION);
3164
+ r.onupgradeneeded = () => {
3165
+ if (!r.result.objectStoreNames.contains(this.storeName)) {
3166
+ r.result.createObjectStore(this.storeName, { keyPath: "id" });
3167
+ }
3168
+ };
3169
+ r.onsuccess = () => {
3170
+ const db = r.result;
3171
+ const forget = () => {
3172
+ if (this.db === opening) this.db = void 0;
3173
+ };
3174
+ db.addEventListener("versionchange", () => {
3175
+ forget();
3176
+ db.close();
3177
+ });
3178
+ db.addEventListener("close", forget);
3179
+ resolve(db);
3180
+ };
3181
+ r.onerror = () => reject(r.error);
3182
+ }).catch((err) => {
3183
+ if (this.db === opening) this.db = void 0;
3184
+ throw err;
3185
+ });
3186
+ this.db = opening;
3187
+ return opening;
3188
+ }
3189
+ async tx(mode) {
3190
+ const db = await this.open();
3191
+ return db.transaction(this.storeName, mode).objectStore(this.storeName);
3192
+ }
3193
+ /** One write in its own transaction, resolved once it committed - then the notice. */
3194
+ async write(op, notice) {
3195
+ const db = await this.open();
3196
+ const tx = db.transaction(this.storeName, "readwrite");
3197
+ await committed(tx, op(tx.objectStore(this.storeName)));
3198
+ this.announce(notice);
3199
+ }
3200
+ announce(notice) {
3201
+ if (typeof core.postStorageChange === "function") {
3202
+ core.postStorageChange(this.dbName, { kind: "chats", ...notice });
3203
+ }
3204
+ }
3205
+ /**
3206
+ * Read the stored record and write what `merge` makes of it in ONE readwrite transaction: no
3207
+ * other tab's save can land between the read and the write. `merge` is synchronous (a
3208
+ * transaction does not survive an await). Resolves with what was written, once committed.
3209
+ */
3210
+ async putMerged(id, merge) {
3211
+ if (this.memory) {
3212
+ const record = merge(this.memory.get(id));
3213
+ this.memory.set(record.id, structuredClone(record));
3214
+ return record;
3215
+ }
3216
+ const db = await this.open();
3217
+ const tx = db.transaction(this.storeName, "readwrite");
3218
+ const store = tx.objectStore(this.storeName);
3219
+ let written;
3220
+ let failed;
3221
+ const read = store.get(id);
3222
+ const done = committed(tx, read);
3223
+ read.onsuccess = () => {
3224
+ try {
3225
+ written = merge(read.result);
3226
+ store.put(written);
3227
+ } catch (err) {
3228
+ failed = err;
3229
+ tx.abort();
3230
+ }
3231
+ };
3232
+ try {
3233
+ await done;
3234
+ } catch (err) {
3235
+ throw failed ?? err;
3236
+ }
3237
+ if (!written) throw new Error("the chat could not be saved");
3238
+ this.announce({ op: "put", key: id });
3239
+ return written;
3240
+ }
3241
+ async list() {
3242
+ const all = this.memory ? [...this.memory.values()] : await req((await this.tx("readonly")).getAll());
3243
+ return all.map(({ messages, ...rest }) => ({ ...rest, messageCount: messages.length })).sort((a, b) => b.updatedAt - a.updatedAt);
3244
+ }
3245
+ async get(id) {
3246
+ if (this.memory) return this.memory.get(id);
3247
+ return req((await this.tx("readonly")).get(id));
3248
+ }
3249
+ async put(record) {
3250
+ if (this.memory) {
3251
+ this.memory.set(record.id, structuredClone(record));
3252
+ return;
3253
+ }
3254
+ await this.write((store) => store.put(record), { op: "put", key: record.id });
3255
+ }
3256
+ async delete(id) {
3257
+ if (this.memory) {
3258
+ this.memory.delete(id);
3259
+ return;
3260
+ }
3261
+ await this.write((store) => store.delete(id), { op: "delete", key: id });
3262
+ }
3263
+ async clear() {
3264
+ if (this.memory) {
3265
+ this.memory.clear();
3266
+ return;
3267
+ }
3268
+ await this.write((store) => store.clear(), { op: "clear" });
3269
+ }
3270
+ };
3271
+ var attachmentsText = (attachments, texts = {}) => attachments.length > 0 && attachments.every((a) => a.mediaType.toLowerCase().startsWith("audio/")) ? texts.voiceMessage ?? "Voice message" : attachments.map((a) => a.name).join(", ");
3272
+ var oneLine = (text2) => (text2 ?? "").replace(/\s+/g, " ").trim();
3273
+ var chatTitle = (messages, texts = {}) => {
3274
+ const at = messages.findIndex((m) => m.role === "user");
3275
+ const user = at >= 0 ? messages[at] : void 0;
3276
+ let first = oneLine(user?.content);
3277
+ if (!first && user?.attachments?.length) {
3278
+ const answer = messages.slice(at + 1).find((m) => m.role === "assistant");
3279
+ const heard = answer?.transcripts?.find((t) => t.source === "attachment")?.text;
3280
+ first = oneLine(heard) || oneLine(attachmentsText(user.attachments, texts));
3281
+ }
3282
+ if (!first) return "New chat";
3283
+ return first.length > 60 ? `${first.slice(0, 59)}…` : first;
3284
+ };
3285
+ var newChatId = () => `chat-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
3286
+ var USAGE_KEYS = [
3287
+ "inputTokens",
3288
+ "outputTokens",
3289
+ "totalTokens",
3290
+ "reasoningTokens",
3291
+ "cachedInputTokens",
3292
+ "cacheWriteTokens"
3293
+ ];
3294
+ var sumUsage = (base, more) => {
3295
+ const out = { ...base ?? {} };
3296
+ for (const u of more) {
3297
+ if (!u) continue;
3298
+ for (const k of USAGE_KEYS) out[k] = (out[k] ?? 0) + (u[k] ?? 0);
3299
+ }
3300
+ for (const k of USAGE_KEYS) out[k] ??= 0;
3301
+ return out;
3302
+ };
3303
+ var renumber = (own, after) => {
3304
+ let next = after.reduce(
3305
+ (max, m) => Math.max(max, Number(/^msg-(\d+)$/.exec(m.id)?.[1] ?? -1)),
3306
+ -1
3307
+ );
3308
+ return own.map((m) => ({ ...m, id: `msg-${next += 1}` }));
3309
+ };
3310
+ var turnAt = (m) => typeof m.startedAt === "number" && Number.isFinite(m.startedAt) ? m.startedAt : void 0;
3311
+ var placeByTurn = (stored, own) => {
3312
+ let i = stored.length;
3313
+ while (i > 0 && turnAt(stored[i - 1]) !== void 0) i -= 1;
3314
+ const out = stored.slice(0, i);
3315
+ for (const m of own) {
3316
+ const at = turnAt(m);
3317
+ while (i < stored.length && (at === void 0 || turnAt(stored[i]) <= at)) {
3318
+ out.push(stored[i]);
3319
+ i += 1;
3320
+ }
3321
+ out.push(m);
3322
+ }
3323
+ return [...out, ...stored.slice(i)];
3324
+ };
3325
+ var ownUnsaved = (messages, base) => messages.some((m) => !m.remote && !base?.known.has(m));
3326
+ var unchangedSince = (messages, base) => base !== void 0 && messages.length === base.known.size && messages.every((m) => base.known.has(m));
3327
+ var mergeChatRecord = (view, stored, base, texts) => {
3328
+ const local = view.messages.filter((m) => !m.remote);
3329
+ if (!stored || base && stored.updatedAt <= base.updatedAt) {
3330
+ return { record: { ...view, messages: local }, merged: false };
3331
+ }
3332
+ const own = local.filter((m) => !base?.known.has(m));
3333
+ const messages = placeByTurn(stored.messages, renumber(own, stored.messages));
3334
+ return {
3335
+ record: {
3336
+ ...view,
3337
+ createdAt: stored.createdAt,
3338
+ title: chatTitle(messages, texts),
3339
+ messages,
3340
+ totalUsage: sumUsage(
3341
+ stored.totalUsage,
3342
+ own.map((m) => m.role === "assistant" ? m.usage : void 0)
3343
+ )
3344
+ },
3345
+ merged: true
3346
+ };
3347
+ };
3348
+ var saveChat = async (store, view, base, texts) => {
3349
+ let merged = false;
3350
+ const record = await store.putMerged(view.id, (stored) => {
3351
+ const out = mergeChatRecord(view, stored, base, texts);
3352
+ merged = out.merged;
3353
+ return out.record;
3354
+ });
3355
+ return { record, merged };
3356
+ };
3357
+
3358
+ // src/util.ts
3359
+ var errMessage = (err) => err instanceof Error ? err.message : String(err);
3360
+ var coalesce = (fn, ms = 100) => {
3361
+ let timer;
3362
+ return {
3363
+ call: () => {
3364
+ if (timer !== void 0) clearTimeout(timer);
3365
+ timer = setTimeout(() => {
3366
+ timer = void 0;
3367
+ fn();
3368
+ }, ms);
3369
+ },
3370
+ cancel: () => {
3371
+ if (timer !== void 0) clearTimeout(timer);
3372
+ timer = void 0;
3373
+ }
3374
+ };
3375
+ };
3376
+ var listenToOtherTabs = (core2, dbName, listener) => typeof core2.onStorageChange === "function" && dbName ? core2.onStorageChange(dbName, listener) : () => void 0;
3377
+ var followOtherTabs = (core2, dbName, accept, settle, ms = 100) => {
3378
+ const later = coalesce(settle, ms);
3379
+ const off = listenToOtherTabs(core2, dbName, (change) => {
3380
+ if (accept(change)) later.call();
3381
+ });
3382
+ return () => {
3383
+ off();
3384
+ later.cancel();
3385
+ };
3386
+ };
3387
+ var remoteAnswerOf = (ok, stillWatching) => ok ? "taken" : stillWatching ? "refused" : "unknown";
3388
+
3389
+ // src/html-preview.ts
3390
+ var sandboxedCsp = (scripts = false) => [
3391
+ "default-src 'none'",
3392
+ scripts ? "script-src 'unsafe-inline'" : "script-src 'none'",
3393
+ "style-src 'unsafe-inline'",
3394
+ "img-src data: blob:",
3395
+ "font-src data:",
3396
+ "media-src data: blob:",
3397
+ "connect-src 'none'",
3398
+ "frame-src 'none'",
3399
+ "child-src 'none'",
3400
+ "object-src 'none'",
3401
+ "form-action 'none'",
3402
+ "base-uri 'none'",
3403
+ "webrtc 'block'"
3404
+ ].join("; ");
3405
+ var sandboxTokens = (scripts = false) => scripts ? "allow-scripts" : "";
3406
+ var escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3407
+ var cspMetaTag = (policy) => `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(policy)}">`;
3408
+ var cspMeta = (scripts) => cspMetaTag(sandboxedCsp(scripts));
3409
+ var DOCTYPE = /^[\t\n\f\r ]*<!doctype[^>]*>/i;
3410
+ var withCspFirst = (html, scripts = false) => withPolicyFirst(html, sandboxedCsp(scripts));
3411
+ var withPolicyFirst = (html, policy) => {
3412
+ const doctype = DOCTYPE.exec(html)?.[0] ?? "";
3413
+ return `${doctype}${cspMetaTag(policy)}${html.slice(doctype.length)}`;
3414
+ };
3415
+ var buildSandboxedDocument = (html, { scripts = false } = {}) => "<!doctype html><html><head>" + cspMeta(scripts) + `<style>html,body{margin:0;height:100%;overflow:hidden;background:transparent}iframe{display:block;border:0;width:100%;height:100%}</style></head><body><iframe sandbox="${sandboxTokens(scripts)}" referrerpolicy="no-referrer" srcdoc="${escapeAttribute(withCspFirst(html, scripts))}"></iframe></body></html>`;
3416
+ var HTML_PREVIEW_MAX_CHARS = 1e6;
3417
+ var ASSET_ATTR = /\b(?:src|href)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
3418
+ var linkedFilesOf = (html, max = 4) => {
3419
+ const found = [];
3420
+ for (const m of html.matchAll(ASSET_ATTR)) {
3421
+ const ref = (m[1] ?? m[2] ?? m[3] ?? "").trim();
3422
+ if (!ref || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(ref)) continue;
3423
+ if (!found.includes(ref)) found.push(ref);
3424
+ if (found.length >= max) break;
3425
+ }
3426
+ return found;
3427
+ };
3428
+ var RAW_TEXT = /^<(script|style|textarea|title)\b/i;
3429
+ var tokenizeHtml = (source) => {
3430
+ const out = [];
3431
+ const push = (kind, text2) => {
3432
+ if (!text2) return;
3433
+ const last = out[out.length - 1];
3434
+ if (last && last.kind === kind) last.text += text2;
3435
+ else out.push({ kind, text: text2 });
3436
+ };
3437
+ let i = 0;
3438
+ const n = source.length;
3439
+ while (i < n) {
3440
+ const lt = source.indexOf("<", i);
3441
+ if (lt < 0) {
3442
+ push("text", source.slice(i));
3443
+ break;
3444
+ }
3445
+ push("text", source.slice(i, lt));
3446
+ i = lt;
3447
+ if (source.startsWith("<!--", i)) {
3448
+ const end = source.indexOf("-->", i + 4);
3449
+ const stop = end < 0 ? n : end + 3;
3450
+ push("comment", source.slice(i, stop));
3451
+ i = stop;
3452
+ continue;
3453
+ }
3454
+ const open = /^<[!/?]?[a-zA-Z][^\s/>]*/.exec(source.slice(i, i + 80));
3455
+ if (!open) {
3456
+ push("text", "<");
3457
+ i += 1;
3458
+ continue;
3459
+ }
3460
+ push("tag", open[0]);
3461
+ const raw = RAW_TEXT.exec(open[0])?.[1].toLowerCase();
3462
+ i += open[0].length;
3463
+ while (i < n && source[i] !== ">") {
3464
+ const c = source[i];
3465
+ if (c === '"' || c === "'") {
3466
+ const end = source.indexOf(c, i + 1);
3467
+ const stop = end < 0 ? n : end + 1;
3468
+ push("string", source.slice(i, stop));
3469
+ i = stop;
3470
+ } else if (/[^\s=/>"']/.test(c)) {
3471
+ const name = /^[^\s=/>"']+/.exec(source.slice(i, i + 200))?.[0] ?? c;
3472
+ const before = out[out.length - 1];
3473
+ push(before?.kind === "text" && before.text.endsWith("=") ? "string" : "attr", name);
3474
+ i += name.length;
3475
+ } else {
3476
+ push(c === "/" ? "tag" : "text", c);
3477
+ i += 1;
3478
+ }
3479
+ }
3480
+ if (i < n) {
3481
+ push("tag", ">");
3482
+ i += 1;
3483
+ }
3484
+ if (raw) {
3485
+ const close = source.toLowerCase().indexOf(`</${raw}`, i);
3486
+ const stop = close < 0 ? n : close;
3487
+ push("text", source.slice(i, stop));
3488
+ i = stop;
3489
+ }
3490
+ }
3491
+ return out;
3492
+ };
3493
+ var FRAME_MIN_HEIGHT = 120;
3494
+ var FRAME_MAX_HEIGHT = 800;
3495
+ var clampFrameHeight = (height) => Math.min(
3496
+ FRAME_MAX_HEIGHT,
3497
+ Math.max(FRAME_MIN_HEIGHT, Math.round(Number.isFinite(height) ? height : 300))
3498
+ );
3499
+
3500
+ // src/voice/record.ts
3501
+ var MicError = class extends Error {
3502
+ code;
3503
+ constructor(code, message = code) {
3504
+ super(message);
3505
+ this.name = "MicError";
3506
+ this.code = code;
3507
+ }
3508
+ };
3509
+ var RECORDING_DEFAULT_MAX_MS = 5 * 60 * 1e3;
3510
+ var RECORDING_TYPES = [
3511
+ "audio/webm;codecs=opus",
3512
+ "audio/webm",
3513
+ "audio/mp4",
3514
+ "audio/ogg;codecs=opus",
3515
+ "audio/ogg"
3516
+ ];
3517
+ var pickRecordingType = (isTypeSupported) => {
3518
+ if (!isTypeSupported) return void 0;
3519
+ for (const type of RECORDING_TYPES) {
3520
+ try {
3521
+ if (isTypeSupported(type)) return type;
3522
+ } catch {
3523
+ }
3524
+ }
3525
+ return void 0;
3526
+ };
3527
+ var audioTypeOf = (type) => {
3528
+ const base = (type ?? "").toLowerCase().split(";")[0].trim();
3529
+ if (/^(audio|video)\/(mp4|x-m4a|m4a|aac-mp4)$/.test(base)) return "audio/mp4";
3530
+ if (/^(audio|video)\/webm$/.test(base)) return "audio/webm";
3531
+ if (base === "audio/ogg" || base === "application/ogg") return "audio/ogg";
3532
+ if (base === "audio/wav" || base === "audio/x-wav" || base === "audio/wave") return "audio/wav";
3533
+ if (base === "audio/mpeg" || base === "audio/mp3") return "audio/mpeg";
3534
+ if (base === "audio/aac") return "audio/aac";
3535
+ return "audio/webm";
3536
+ };
3537
+ var audioExtensionOf = (type) => ({
3538
+ "audio/mp4": "m4a",
3539
+ "audio/ogg": "ogg",
3540
+ "audio/wav": "wav",
3541
+ "audio/mpeg": "mp3",
3542
+ "audio/aac": "aac"
3543
+ })[audioTypeOf(type)] ?? "webm";
3544
+ var micProblemOf = (err) => {
3545
+ if (err instanceof MicError) return err.code;
3546
+ const name = err && typeof err === "object" ? String(err.name) : "";
3547
+ if (name === "NotAllowedError" || name === "SecurityError" || name === "PermissionDeniedError")
3548
+ return "not-allowed";
3549
+ if (name === "NotFoundError" || name === "OverconstrainedError" || name === "DevicesNotFoundError")
3550
+ return "audio-capture";
3551
+ if (name === "NotReadableError" || name === "TrackStartError" || name === "AbortError")
3552
+ return "busy";
3553
+ if (name === "NotSupportedError" || name === "TypeError") return "unsupported";
3554
+ return "failed";
3555
+ };
3556
+ var defaults = (deps) => {
3557
+ const g = globalThis;
3558
+ const devices = g.navigator?.mediaDevices;
3559
+ return {
3560
+ getUserMedia: deps.getUserMedia ?? (devices?.getUserMedia ? devices.getUserMedia.bind(devices) : void 0),
3561
+ MediaRecorder: deps.MediaRecorder ?? g.MediaRecorder,
3562
+ now: deps.now ?? Date.now
3563
+ };
3564
+ };
3565
+ var recordingSupported = (deps = {}) => {
3566
+ const d = defaults(deps);
3567
+ return Boolean(d.getUserMedia && d.MediaRecorder);
3568
+ };
3569
+ var stopTracks = (stream) => {
3570
+ for (const track of stream?.getTracks() ?? []) {
3571
+ try {
3572
+ track.stop();
3573
+ } catch {
3574
+ }
3575
+ }
3576
+ };
3577
+ var startRecording = async (options = {}) => {
3578
+ const d = defaults(options);
3579
+ if (!d.getUserMedia || !d.MediaRecorder) throw new MicError("unsupported");
3580
+ let stream;
3581
+ try {
3582
+ stream = await d.getUserMedia({ audio: true });
3583
+ } catch (err) {
3584
+ throw new MicError(micProblemOf(err));
3585
+ }
3586
+ let recorder;
3587
+ try {
3588
+ const type = pickRecordingType(d.MediaRecorder.isTypeSupported?.bind(d.MediaRecorder));
3589
+ recorder = new d.MediaRecorder(stream, type ? { mimeType: type } : void 0);
3590
+ } catch (err) {
3591
+ stopTracks(stream);
3592
+ throw new MicError(micProblemOf(err) === "failed" ? "unsupported" : micProblemOf(err));
3593
+ }
3594
+ const startedAt = d.now();
3595
+ const chunks = [];
3596
+ let cancelled = false;
3597
+ let failure;
3598
+ let settle = () => {
3599
+ };
3600
+ const ended = new Promise((resolve) => settle = resolve);
3601
+ let finish;
3602
+ let fail;
3603
+ const result = new Promise((resolve, reject) => {
3604
+ finish = resolve;
3605
+ fail = reject;
3606
+ });
3607
+ result.catch(() => {
3608
+ });
3609
+ let limit;
3610
+ const end = () => {
3611
+ stopTracks(stream);
3612
+ clearTimeout(limit);
3613
+ settle();
3614
+ };
3615
+ recorder.ondataavailable = (event) => {
3616
+ if (event.data && event.data.size > 0) chunks.push(event.data);
3617
+ };
3618
+ recorder.onerror = () => {
3619
+ failure = new MicError("failed");
3620
+ end();
3621
+ fail?.(failure);
3622
+ };
3623
+ recorder.onstop = () => {
3624
+ end();
3625
+ if (cancelled) return fail?.(new MicError("failed", "cancelled"));
3626
+ if (failure) return fail?.(failure);
3627
+ const mediaType = audioTypeOf(recorder.mimeType || chunks[0]?.type);
3628
+ finish?.({
3629
+ blob: new Blob(chunks, { type: mediaType }),
3630
+ mediaType,
3631
+ durationMs: Math.max(0, d.now() - startedAt)
3632
+ });
3633
+ };
3634
+ const stopRecorder = () => {
3635
+ try {
3636
+ if (recorder.state !== "inactive") recorder.stop();
3637
+ else recorder.onstop?.();
3638
+ } catch {
3639
+ recorder.onstop?.();
3640
+ }
3641
+ };
3642
+ const maxMs = options.maxMs ?? RECORDING_DEFAULT_MAX_MS;
3643
+ limit = setTimeout(() => {
3644
+ stopRecorder();
3645
+ options.onLimit?.();
3646
+ }, maxMs);
3647
+ try {
3648
+ recorder.start(1e3);
3649
+ } catch (err) {
3650
+ end();
3651
+ throw new MicError(micProblemOf(err) === "failed" ? "unsupported" : micProblemOf(err));
3652
+ }
3653
+ return {
3654
+ startedAt,
3655
+ ended,
3656
+ stop: () => {
3657
+ stopRecorder();
3658
+ return result;
3659
+ },
3660
+ cancel: () => {
3661
+ cancelled = true;
3662
+ chunks.length = 0;
3663
+ stopRecorder();
3664
+ end();
3665
+ }
3666
+ };
3667
+ };
3668
+
3669
+ // src/voice/recognizer.ts
3670
+ var createRecordingRecognizer = (options) => () => {
3671
+ let recording;
3672
+ let starting;
3673
+ let stopAsked = false;
3674
+ let aborted = false;
3675
+ let ended = false;
3676
+ const controller = new AbortController();
3677
+ const rec = {
3678
+ lang: "",
3679
+ continuous: true,
3680
+ interimResults: false,
3681
+ onresult: null,
3682
+ onerror: null,
3683
+ onend: null,
3684
+ start() {
3685
+ if (starting) return;
3686
+ starting = (async () => {
3687
+ try {
3688
+ recording = await startRecording({
3689
+ ...options,
3690
+ maxMs: options.maxMs,
3691
+ onLimit: () => rec.stop()
3692
+ });
3693
+ } catch (err) {
3694
+ if (!aborted) rec.onerror?.({ error: micProblemOf(err) });
3695
+ return finish();
3696
+ }
3697
+ if (aborted) {
3698
+ recording.cancel();
3699
+ return finish();
3700
+ }
3701
+ if (stopAsked) void transcribeNow();
3702
+ })();
3703
+ },
3704
+ stop() {
3705
+ if (stopAsked || ended) return;
3706
+ stopAsked = true;
3707
+ if (recording) void transcribeNow();
3708
+ },
3709
+ abort() {
3710
+ if (ended) return;
3711
+ aborted = true;
3712
+ controller.abort();
3713
+ recording?.cancel();
3714
+ if (!starting || recording) finish();
3715
+ }
3716
+ };
3717
+ const finish = () => {
3718
+ if (ended) return;
3719
+ ended = true;
3720
+ rec.onend?.();
3721
+ };
3722
+ let transcribing = false;
3723
+ const transcribeNow = async () => {
3724
+ if (transcribing || !recording) return;
3725
+ transcribing = true;
3726
+ let audio;
3727
+ try {
3728
+ audio = await recording.stop();
3729
+ } catch (err) {
3730
+ if (!aborted) rec.onerror?.({ error: micProblemOf(err) });
3731
+ return finish();
3732
+ }
3733
+ if (aborted) return finish();
3734
+ if (audio.blob.size === 0) return finish();
3735
+ try {
3736
+ const text2 = (await options.transcribe(audio, { lang: rec.lang, signal: controller.signal })).replace(/\s+/g, " ").trim();
3737
+ if (!aborted && text2)
3738
+ rec.onresult?.({
3739
+ resultIndex: 0,
3740
+ results: [{ isFinal: true, 0: { transcript: text2 } }]
3741
+ });
3742
+ } catch (err) {
3743
+ if (!aborted)
3744
+ rec.onerror?.({
3745
+ error: "transcription",
3746
+ message: err instanceof Error ? err.message : String(err)
3747
+ });
3748
+ }
3749
+ finish();
3750
+ };
3751
+ return rec;
3752
+ };
3753
+
3754
+ // src/voice/speak.ts
3755
+ var SpeechOutputError = class extends Error {
3756
+ code;
3757
+ constructor(code) {
3758
+ super(code);
3759
+ this.name = "SpeechOutputError";
3760
+ this.code = code;
3761
+ }
3762
+ };
3763
+ var asOutputError = (err) => err instanceof SpeechOutputError ? err : new SpeechOutputError(
3764
+ err && typeof err === "object" && "name" in err ? String(err.name) : "playback-failed"
3765
+ );
3766
+ var speakableText = (markdown, options = {}) => {
3767
+ const out = [];
3768
+ const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
3769
+ let fence;
3770
+ let fenceSaid = false;
3771
+ for (const raw of lines) {
3772
+ const line = raw.trimEnd();
3773
+ const opener = /^\s*(`{3,}|~{3,})/.exec(line);
3774
+ if (fence !== void 0) {
3775
+ if (opener && opener[1][0] === fence[0] && opener[1].length >= fence.length) fence = void 0;
3776
+ continue;
3777
+ }
3778
+ if (opener) {
3779
+ fence = opener[1];
3780
+ if (options.code && !fenceSaid) out.push(options.code);
3781
+ fenceSaid = true;
3782
+ continue;
3783
+ }
3784
+ fenceSaid = false;
3785
+ if (/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(line)) continue;
3786
+ if (/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)) continue;
3787
+ let text2 = line.replace(/^\s{0,3}#{1,6}\s+/, "").replace(/^\s*>\s?/, "").replace(/^\s*(?:[-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?/, "");
3788
+ if (/^\s*\|.*\|\s*$/.test(text2))
3789
+ text2 = text2.replace(/^\s*\||\|\s*$/g, "").split("|").map((c) => c.trim()).filter(Boolean).join(", ");
3790
+ text2 = text2.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/<(https?:\/\/[^>\s]+)>/g, (_m, url) => hostOf(url)).replace(/\bhttps?:\/\/[^\s)]+/g, (url) => hostOf(url)).replace(/`+([^`]*)`+/g, "$1").replace(/(\*\*|__)(.+?)\1/g, "$2").replace(/(^|[^\w*])[*_]([^*_\s][^*_]*?)[*_](?=[^\w*]|$)/g, "$1$2").replace(/~~(.+?)~~/g, "$1").replace(/<\/?[a-z][^>]*>/gi, "").replace(/[*_#`~>|]/g, " ").replace(/\s+/g, " ").trim();
3791
+ if (!text2) continue;
3792
+ out.push(/[.!?…:;。!?]$/.test(text2) ? text2 : `${text2}.`);
3793
+ }
3794
+ return out.join(" ").trim();
3795
+ };
3796
+ var hostOf = (url) => {
3797
+ try {
3798
+ return new URL(url).hostname.replace(/^www\./, "");
3799
+ } catch {
3800
+ return "";
3801
+ }
3802
+ };
3803
+ var splitForSpeech = (text2, max = 220) => {
3804
+ const pieces = [];
3805
+ let rest = text2.trim();
3806
+ while (rest.length > max) {
3807
+ const window = rest.slice(0, max + 1);
3808
+ let cut = -1;
3809
+ for (const m of window.matchAll(/[.!?…。!?;:](\s|$)/g))
3810
+ if (m.index !== void 0 && m.index + 1 <= max) cut = m.index + 1;
3811
+ if (cut < max / 3) cut = window.lastIndexOf(" ");
3812
+ if (cut <= 0) cut = max;
3813
+ pieces.push(rest.slice(0, cut).trim());
3814
+ rest = rest.slice(cut).trim();
3815
+ }
3816
+ if (rest) pieces.push(rest);
3817
+ return pieces;
3818
+ };
3819
+ var SCRIPT_RANGES = [
3820
+ ["latin", /\p{Script=Latin}/u],
3821
+ ["cyrillic", /\p{Script=Cyrillic}/u],
3822
+ ["greek", /\p{Script=Greek}/u],
3823
+ ["arabic", /\p{Script=Arabic}/u],
3824
+ ["hebrew", /\p{Script=Hebrew}/u],
3825
+ ["kana", /[\p{Script=Hiragana}\p{Script=Katakana}]/u],
3826
+ ["han", /\p{Script=Han}/u],
3827
+ ["hangul", /\p{Script=Hangul}/u],
3828
+ ["devanagari", /\p{Script=Devanagari}/u],
3829
+ ["thai", /\p{Script=Thai}/u],
3830
+ ["georgian", /\p{Script=Georgian}/u],
3831
+ ["armenian", /\p{Script=Armenian}/u]
3832
+ ];
3833
+ var LANGUAGE_SCRIPT = {
3834
+ ru: "cyrillic",
3835
+ uk: "cyrillic",
3836
+ be: "cyrillic",
3837
+ bg: "cyrillic",
3838
+ sr: "cyrillic",
3839
+ mk: "cyrillic",
3840
+ kk: "cyrillic",
3841
+ ky: "cyrillic",
3842
+ tg: "cyrillic",
3843
+ mn: "cyrillic",
3844
+ el: "greek",
3845
+ ar: "arabic",
3846
+ fa: "arabic",
3847
+ ur: "arabic",
3848
+ he: "hebrew",
3849
+ yi: "hebrew",
3850
+ zh: "han",
3851
+ ja: "kana",
3852
+ ko: "hangul",
3853
+ hi: "devanagari",
3854
+ mr: "devanagari",
3855
+ ne: "devanagari",
3856
+ th: "thai",
3857
+ ka: "georgian",
3858
+ hy: "armenian"
3859
+ };
3860
+ var SCRIPT_DEFAULT = {
3861
+ latin: "en",
3862
+ cyrillic: "ru",
3863
+ greek: "el",
3864
+ arabic: "ar",
3865
+ hebrew: "he",
3866
+ han: "zh",
3867
+ kana: "ja",
3868
+ hangul: "ko",
3869
+ devanagari: "hi",
3870
+ thai: "th",
3871
+ georgian: "ka",
3872
+ armenian: "hy"
3873
+ };
3874
+ var scriptOfLanguage = (lang) => {
3875
+ const parts = lang.toLowerCase().replace(/_/g, "-").split("-");
3876
+ if (parts.includes("latn")) return "latin";
3877
+ if (parts.includes("cyrl")) return "cyrillic";
3878
+ return LANGUAGE_SCRIPT[parts[0]] ?? "latin";
3879
+ };
3880
+ var scriptOfText = (text2) => {
3881
+ const counts = /* @__PURE__ */ new Map();
3882
+ for (const ch of text2) {
3883
+ if (!/\p{L}/u.test(ch)) continue;
3884
+ const found = SCRIPT_RANGES.find(([, re]) => re.test(ch));
3885
+ if (!found) continue;
3886
+ counts.set(found[0], (counts.get(found[0]) ?? 0) + 1);
3887
+ }
3888
+ if (counts.has("kana")) {
3889
+ counts.set("kana", (counts.get("kana") ?? 0) + (counts.get("han") ?? 0));
3890
+ counts.delete("han");
3891
+ }
3892
+ let best;
3893
+ let most = 0;
3894
+ for (const [script, n] of counts)
3895
+ if (n > most) {
3896
+ best = script;
3897
+ most = n;
3898
+ }
3899
+ return best;
3900
+ };
3901
+ var languageOfText = (text2, preferred = []) => {
3902
+ const mine = preferred.filter((l) => Boolean(l));
3903
+ const script = scriptOfText(text2);
3904
+ if (!script) return mine[0];
3905
+ return mine.find((l) => scriptOfLanguage(l) === script) ?? SCRIPT_DEFAULT[script];
3906
+ };
3907
+ var voiceFor = (voices, lang, preferred) => {
3908
+ if (preferred) {
3909
+ const chosen = voices.find((v) => v.voiceURI === preferred);
3910
+ if (chosen && (!lang || scriptOfLanguage(chosen.lang) === scriptOfLanguage(lang))) return chosen;
3911
+ }
3912
+ if (!lang) return void 0;
3913
+ const norm = (l) => l.toLowerCase().replace(/_/g, "-");
3914
+ const want = norm(lang);
3915
+ const base = want.split("-")[0];
3916
+ const rank = (v) => [v.localService ? 1 : 0, v.default ? 1 : 0];
3917
+ const best = (list) => [...list].sort((a, b) => {
3918
+ const ra = rank(a);
3919
+ const rb = rank(b);
3920
+ return rb[0] - ra[0] || rb[1] - ra[1] || a.name.localeCompare(b.name);
3921
+ })[0];
3922
+ const exact = voices.filter((v) => norm(v.lang) === want);
3923
+ if (exact.length) return best(exact);
3924
+ const same = voices.filter((v) => norm(v.lang).split("-")[0] === base);
3925
+ return same.length ? best(same) : void 0;
3926
+ };
3927
+ var voicesOf = (voices, lang) => {
3928
+ if (!lang) return [...voices];
3929
+ const base = lang.toLowerCase().split(/[-_]/)[0];
3930
+ return voices.filter((v) => v.lang.toLowerCase().split(/[-_]/)[0] === base);
3931
+ };
3932
+ var speechSynthesisSupported = () => typeof globalThis !== "undefined" && "speechSynthesis" in globalThis && typeof globalThis.SpeechSynthesisUtterance === "function";
3933
+ var createBrowserSpeaker = (options = {}) => (text2, { lang, onState }) => {
3934
+ const synth = options.synth ?? globalThis.speechSynthesis;
3935
+ const make = options.createUtterance ?? ((t) => new globalThis.SpeechSynthesisUtterance(t));
3936
+ const voice = voiceFor(synth.getVoices(), lang, options.voice);
3937
+ let settle;
3938
+ let fail;
3939
+ const done = new Promise((resolve, reject) => {
3940
+ settle = resolve;
3941
+ fail = reject;
3942
+ });
3943
+ done.catch(() => {
3944
+ });
3945
+ let over = false;
3946
+ const end = (err) => {
3947
+ if (over) return;
3948
+ over = true;
3949
+ if (err) fail(err);
3950
+ else settle();
3951
+ };
3952
+ const pieces = splitForSpeech(text2);
3953
+ synth.cancel();
3954
+ if (pieces.length === 0) {
3955
+ end();
3956
+ return { pause() {
3957
+ }, resume() {
3958
+ }, stop() {
3959
+ }, done };
3960
+ }
3961
+ let started = false;
3962
+ pieces.forEach((piece, i) => {
3963
+ const u = make(piece);
3964
+ u.lang = voice?.lang ?? lang ?? "";
3965
+ try {
3966
+ u.voice = voice ?? null;
3967
+ } catch {
3968
+ }
3969
+ u.rate = options.rate ?? 1;
3970
+ u.onstart = () => {
3971
+ if (!started && !over) onState("playing");
3972
+ started = true;
3973
+ };
3974
+ u.onend = () => {
3975
+ if (i === pieces.length - 1) end();
3976
+ };
3977
+ u.onerror = (event) => {
3978
+ if (event.error === "interrupted" || event.error === "canceled") end();
3979
+ else end(new SpeechOutputError(event.error || "synthesis-failed"));
3980
+ };
3981
+ synth.speak(u);
3982
+ });
3983
+ onState("loading");
3984
+ return {
3985
+ pause: () => {
3986
+ if (over) return;
3987
+ synth.pause();
3988
+ onState("paused");
3989
+ },
3990
+ resume: () => {
3991
+ if (over) return;
3992
+ synth.resume();
3993
+ onState("playing");
3994
+ },
3995
+ stop: () => {
3996
+ if (over) return;
3997
+ synth.cancel();
3998
+ end();
3999
+ },
4000
+ done
4001
+ };
4002
+ };
4003
+ var silence = () => {
4004
+ const samples = 16;
4005
+ const view = new DataView(new ArrayBuffer(44 + samples * 2));
4006
+ const text2 = (at, s) => {
4007
+ for (let i = 0; i < s.length; i++) view.setUint8(at + i, s.charCodeAt(i));
4008
+ };
4009
+ text2(0, "RIFF");
4010
+ view.setUint32(4, 36 + samples * 2, true);
4011
+ text2(8, "WAVEfmt ");
4012
+ view.setUint32(16, 16, true);
4013
+ view.setUint16(20, 1, true);
4014
+ view.setUint16(22, 1, true);
4015
+ view.setUint32(24, 8e3, true);
4016
+ view.setUint32(28, 16e3, true);
4017
+ view.setUint16(32, 2, true);
4018
+ view.setUint16(34, 16, true);
4019
+ text2(36, "data");
4020
+ view.setUint32(40, samples * 2, true);
4021
+ return new Blob([view.buffer], { type: "audio/wav" });
4022
+ };
4023
+ var createAudioSpeaker = (options) => (text2, { lang, onState }) => {
4024
+ const urls = options.objectUrl ?? {
4025
+ create: (b) => URL.createObjectURL(b),
4026
+ revoke: (u) => URL.revokeObjectURL(u)
4027
+ };
4028
+ const audio = options.createAudio?.() ?? new Audio();
4029
+ const controller = new AbortController();
4030
+ const pieces = splitForSpeech(text2, options.maxChars ?? 2e3);
4031
+ let settle;
4032
+ let fail;
4033
+ const done = new Promise((resolve, reject) => {
4034
+ settle = resolve;
4035
+ fail = reject;
4036
+ });
4037
+ done.catch(() => {
4038
+ });
4039
+ let over = false;
4040
+ let paused = false;
4041
+ let current;
4042
+ const made = /* @__PURE__ */ new Map();
4043
+ const make = (i) => {
4044
+ if (!made.has(i)) {
4045
+ const p = options.synthesize(pieces[i], { lang, signal: controller.signal });
4046
+ p.catch(() => {
4047
+ });
4048
+ made.set(i, p);
4049
+ }
4050
+ return made.get(i);
4051
+ };
4052
+ const release = () => {
4053
+ if (current) urls.revoke(current);
4054
+ current = void 0;
4055
+ };
4056
+ const end = (err) => {
4057
+ if (over) return;
4058
+ over = true;
4059
+ controller.abort();
4060
+ audio.pause();
4061
+ audio.onended = null;
4062
+ audio.onerror = null;
4063
+ release();
4064
+ if (err) fail(err);
4065
+ else settle();
4066
+ };
4067
+ const playFrom = async (i) => {
4068
+ if (over) return;
4069
+ if (i >= pieces.length) return end();
4070
+ onState(i === 0 || !current ? "loading" : "playing");
4071
+ let blob;
4072
+ try {
4073
+ blob = await make(i);
4074
+ } catch (err) {
4075
+ return end(err instanceof Error ? err : new Error(String(err)));
4076
+ }
4077
+ if (over) return;
4078
+ if (i + 1 < pieces.length) make(i + 1);
4079
+ release();
4080
+ current = urls.create(blob);
4081
+ audio.src = current;
4082
+ audio.onended = () => void playFrom(i + 1);
4083
+ audio.onerror = () => end(new SpeechOutputError("playback-failed"));
4084
+ if (paused) return onState("paused");
4085
+ try {
4086
+ await audio.play();
4087
+ if (!over) onState("playing");
4088
+ } catch (err) {
4089
+ end(asOutputError(err));
4090
+ }
4091
+ };
4092
+ if (pieces.length === 0) end();
4093
+ else {
4094
+ if (options.unlock !== false) {
4095
+ current = urls.create(silence());
4096
+ audio.src = current;
4097
+ audio.play().catch(() => {
4098
+ });
4099
+ }
4100
+ void playFrom(0);
4101
+ }
4102
+ return {
4103
+ pause: () => {
4104
+ if (over) return;
4105
+ paused = true;
4106
+ audio.pause();
4107
+ onState("paused");
4108
+ },
4109
+ resume: () => {
4110
+ if (over || !paused) return;
4111
+ paused = false;
4112
+ if (current)
4113
+ audio.play().then(
4114
+ () => !over && onState("playing"),
4115
+ (err) => end(asOutputError(err))
4116
+ );
4117
+ else onState("loading");
4118
+ },
4119
+ stop: () => end(),
4120
+ done
4121
+ };
4122
+ };
4123
+ // Annotate the CommonJS export names for ESM import in node:
4124
+ 0 && (module.exports = {
4125
+ ASK_USER_TOOL_NAME,
4126
+ ATTACHMENT_BOUNDS,
4127
+ ChatHistoryStore,
4128
+ ELICITATION_MAX_OPTIONS,
4129
+ ELICITATION_TIMEOUT_MS,
4130
+ ELICITATION_VALUE_MAX_CHARS,
4131
+ FOLLOW_LEAVE_PX,
4132
+ FOLLOW_REJOIN_PX,
4133
+ FRAME_MAX_HEIGHT,
4134
+ FRAME_MIN_HEIGHT,
4135
+ HTML_PREVIEW_MAX_CHARS,
4136
+ INPUT_COUNTER_FROM,
4137
+ MicError,
4138
+ NAMED_FILES_MAX,
4139
+ NAMED_FILES_SCAN_MAX,
4140
+ NAMED_FILES_TEXT_MAX,
4141
+ PROMPT_ARM_MS,
4142
+ QUESTION_TIMEOUT_MS,
4143
+ RECORDING_DEFAULT_MAX_MS,
4144
+ RECORDING_TYPES,
4145
+ SpeechOutputError,
4146
+ activeElementOf,
4147
+ agentStateReducer,
4148
+ agentStatusOf,
4149
+ askUserOutputKept,
4150
+ askUserWith,
4151
+ attachmentFileName,
4152
+ attachmentKindOf,
4153
+ attachmentLabel,
4154
+ attachmentOverLimit,
4155
+ attachmentRefusal,
4156
+ attachmentTransformOf,
4157
+ attachmentsText,
4158
+ audioExtensionOf,
4159
+ audioTypeOf,
4160
+ boxLength,
4161
+ buildSandboxedDocument,
4162
+ chatTitle,
4163
+ clampFrameHeight,
4164
+ coalesce,
4165
+ composedContains,
4166
+ createApprovalQueue,
4167
+ createAudioSpeaker,
4168
+ createBrowserSpeaker,
4169
+ createElicitationQueue,
4170
+ createInitialAgentState,
4171
+ createPromptArming,
4172
+ createQuestionQueue,
4173
+ createRecordingRecognizer,
4174
+ cspMetaTag,
4175
+ dataUrlParts,
4176
+ deepActiveElement,
4177
+ deepElementFromPoint,
4178
+ defaultLabels,
4179
+ defaultNoticeTexts,
4180
+ downscaleImage,
4181
+ elicitationConnectOptions,
4182
+ elicitationFields,
4183
+ elicitationFormAnswer,
4184
+ elicitationInitialDraft,
4185
+ elicitationLink,
4186
+ elicitationSettings,
4187
+ elicitationTimeoutOf,
4188
+ endGap,
4189
+ errMessage,
4190
+ escapeAttribute,
4191
+ eventTargetOf,
4192
+ excerptNote,
4193
+ fileKindOf,
4194
+ fileNameOf,
4195
+ filterCommands,
4196
+ followOtherTabs,
4197
+ followsAfterResize,
4198
+ followsAfterScroll,
4199
+ formatClock,
4200
+ formatCountdown,
4201
+ formatDuration,
4202
+ formatElapsed,
4203
+ formatProbability,
4204
+ formatTokens,
4205
+ freeAttachmentPath,
4206
+ imageSizeOf,
4207
+ imagesInOutput,
4208
+ inputCounterShown,
4209
+ insertionFits,
4210
+ isEventInside,
4211
+ isOneCharacter,
4212
+ isShadowRoot,
4213
+ languageOfText,
4214
+ lessonsOf,
4215
+ lineCountOf,
4216
+ linkedFilesOf,
4217
+ listenScrollAround,
4218
+ listenToOtherTabs,
4219
+ longTextName,
4220
+ longTextRoute,
4221
+ menuKeyTarget,
4222
+ menuSections,
4223
+ mergeChatRecord,
4224
+ mergeLabels,
4225
+ messageOverLimit,
4226
+ micProblemOf,
4227
+ micProblemText,
4228
+ namedFilesOf,
4229
+ newChatId,
4230
+ notReadyIntent,
4231
+ notReadyReason,
4232
+ nothingFocused,
4233
+ noticesOf,
4234
+ overflowOf,
4235
+ ownUnsaved,
4236
+ parseSlash,
4237
+ pathsNamedIn,
4238
+ pendingApprovalsOf,
4239
+ pickRecordingType,
4240
+ portalHostOf,
4241
+ previewValue,
4242
+ questionChoiceOf,
4243
+ questionOtherOf,
4244
+ questionTimeoutOf,
4245
+ recordingSupported,
4246
+ remoteAnswerOf,
4247
+ rootOf,
4248
+ sandboxTokens,
4249
+ sandboxedCsp,
4250
+ saveAttachments,
4251
+ saveChat,
4252
+ scriptOfLanguage,
4253
+ scriptOfText,
4254
+ shadowRootsAround,
4255
+ speakableText,
4256
+ speechSynthesisSupported,
4257
+ splitForSpeech,
4258
+ startRecording,
4259
+ steerIntent,
4260
+ stopTracks,
4261
+ subagentTree,
4262
+ textExcerpt,
4263
+ tokenizeHtml,
4264
+ unchangedSince,
4265
+ voiceFor,
4266
+ voiceMessageName,
4267
+ voicesOf,
4268
+ waitingSendStep,
4269
+ webSearchOf,
4270
+ withAttachments,
4271
+ withCspFirst,
4272
+ withPolicyFirst,
4273
+ withoutOwnWords,
4274
+ workspacePathOf
4275
+ });
4276
+ //# sourceMappingURL=index.cjs.map