@circuitwall/jarela 2.5.0 → 2.5.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 (188) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/app-path-routes-manifest.json +5 -5
  3. package/.next/standalone/.next/build-manifest.json +2 -2
  4. package/.next/standalone/.next/prerender-manifest.json +3 -3
  5. package/.next/standalone/.next/react-loadable-manifest.json +2 -2
  6. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  13. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  14. package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
  15. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  16. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  17. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  19. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/chats/route.js +8 -1
  20. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/chats/route.js.nft.json +1 -1
  21. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/lookup/route.js +8 -1
  22. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/lookup/route.js.nft.json +1 -1
  23. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/pair/route.js +8 -1
  24. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/pair/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js +8 -1
  26. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/status/route.js +8 -1
  28. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/status/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +7 -0
  30. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/api/v1/credentials/[id]/route.js +7 -0
  32. package/.next/standalone/.next/server/app/api/v1/credentials/[id]/route.js.nft.json +1 -1
  33. package/.next/standalone/.next/server/app/api/v1/credentials/route.js +7 -0
  34. package/.next/standalone/.next/server/app/api/v1/credentials/route.js.nft.json +1 -1
  35. package/.next/standalone/.next/server/app/api/v1/dashboard/pricing-task/route.js +8 -1
  36. package/.next/standalone/.next/server/app/api/v1/dashboard/pricing-task/route.js.nft.json +1 -1
  37. package/.next/standalone/.next/server/app/api/v1/delegations/codex/[job_id]/route.js +7 -0
  38. package/.next/standalone/.next/server/app/api/v1/delegations/codex/[job_id]/route.js.nft.json +1 -1
  39. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/reindex/route.js +7 -0
  40. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/reindex/route.js.nft.json +1 -1
  41. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/route.js +8 -1
  42. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/route.js.nft.json +1 -1
  43. package/.next/standalone/.next/server/app/api/v1/documents/sources/route.js +8 -1
  44. package/.next/standalone/.next/server/app/api/v1/documents/sources/route.js.nft.json +1 -1
  45. package/.next/standalone/.next/server/app/api/v1/events/route.js +8 -1
  46. package/.next/standalone/.next/server/app/api/v1/events/route.js.nft.json +1 -1
  47. package/.next/standalone/.next/server/app/api/v1/extension/agents/route.js +8 -1
  48. package/.next/standalone/.next/server/app/api/v1/extension/agents/route.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/api/v1/extension/fill/route.js +8 -1
  50. package/.next/standalone/.next/server/app/api/v1/extension/fill/route.js.nft.json +1 -1
  51. package/.next/standalone/.next/server/app/api/v1/extension/refine/route.js +8 -1
  52. package/.next/standalone/.next/server/app/api/v1/extension/refine/route.js.nft.json +1 -1
  53. package/.next/standalone/.next/server/app/api/v1/extension/turn/route.js +8 -1
  54. package/.next/standalone/.next/server/app/api/v1/extension/turn/route.js.nft.json +1 -1
  55. package/.next/standalone/.next/server/app/api/v1/extensions/route.js +8 -1
  56. package/.next/standalone/.next/server/app/api/v1/extensions/route.js.nft.json +1 -1
  57. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/config/route.js +8 -1
  58. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/config/route.js.nft.json +1 -1
  59. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/route.js +8 -1
  60. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/route.js.nft.json +1 -1
  61. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +8 -1
  62. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js.nft.json +1 -1
  63. package/.next/standalone/.next/server/app/api/v1/health/probes/route.js +7 -0
  64. package/.next/standalone/.next/server/app/api/v1/health/probes/route.js.nft.json +1 -1
  65. package/.next/standalone/.next/server/app/api/v1/integrations/[name]/test/route.js +7 -0
  66. package/.next/standalone/.next/server/app/api/v1/integrations/[name]/test/route.js.nft.json +1 -1
  67. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/callback/route.js +22 -1
  68. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/start/route.js +22 -1
  69. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/status/route.js +22 -1
  70. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/callback/route.js +19 -2
  71. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/start/route.js +19 -2
  72. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/status/route.js +19 -2
  73. package/.next/standalone/.next/server/app/api/v1/packages/defaults/[id]/route.js +12 -2
  74. package/.next/standalone/.next/server/app/api/v1/packages/defaults/[id]/route.js.nft.json +1 -1
  75. package/.next/standalone/.next/server/app/api/v1/packages/install/[id]/route.js +7 -0
  76. package/.next/standalone/.next/server/app/api/v1/packages/install/[id]/route.js.nft.json +1 -1
  77. package/.next/standalone/.next/server/app/api/v1/packages/install/route.js +7 -0
  78. package/.next/standalone/.next/server/app/api/v1/packages/install/route.js.nft.json +1 -1
  79. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/enabled/route.js +7 -0
  80. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/enabled/route.js.nft.json +1 -1
  81. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/route.js +7 -0
  82. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/route.js.nft.json +1 -1
  83. package/.next/standalone/.next/server/app/api/v1/packages/manifests/route.js +7 -0
  84. package/.next/standalone/.next/server/app/api/v1/packages/manifests/route.js.nft.json +1 -1
  85. package/.next/standalone/.next/server/app/api/v1/packages/reload/route.js +12 -2
  86. package/.next/standalone/.next/server/app/api/v1/packages/reload/route.js.nft.json +1 -1
  87. package/.next/standalone/.next/server/app/api/v1/packages/route.js +12 -2
  88. package/.next/standalone/.next/server/app/api/v1/packages/route.js.nft.json +1 -1
  89. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +8 -1
  90. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.nft.json +1 -1
  91. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js +7 -0
  92. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js.nft.json +1 -1
  93. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/deny/route.js +7 -0
  94. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/deny/route.js.nft.json +1 -1
  95. package/.next/standalone/.next/server/app/api/v1/pending-actions/route.js +7 -0
  96. package/.next/standalone/.next/server/app/api/v1/pending-actions/route.js.nft.json +1 -1
  97. package/.next/standalone/.next/server/app/api/v1/scheduled-tasks/[id]/run/route.js +8 -1
  98. package/.next/standalone/.next/server/app/api/v1/scheduled-tasks/[id]/run/route.js.nft.json +1 -1
  99. package/.next/standalone/.next/server/app/api/v1/system/restart/route.js +7 -0
  100. package/.next/standalone/.next/server/app/api/v1/system/restart/route.js.nft.json +1 -1
  101. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +52 -45
  102. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.nft.json +1 -1
  103. package/.next/standalone/.next/server/app/api/v1/tools/route.js +8 -1
  104. package/.next/standalone/.next/server/app/api/v1/tools/route.js.nft.json +1 -1
  105. package/.next/standalone/.next/server/app/api/v1/update/apply/route.js.nft.json +1 -1
  106. package/.next/standalone/.next/server/app/api/v1/watchers/[id]/run/route.js +8 -1
  107. package/.next/standalone/.next/server/app/api/v1/watchers/[id]/run/route.js.nft.json +1 -1
  108. package/.next/standalone/.next/server/app/api/v1/watchers/route.js +8 -1
  109. package/.next/standalone/.next/server/app/api/v1/watchers/route.js.nft.json +1 -1
  110. package/.next/standalone/.next/server/app/page.js +73385 -73375
  111. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  112. package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
  113. package/.next/standalone/.next/server/app-paths-manifest.json +5 -5
  114. package/.next/standalone/.next/server/chunks/1433.js +1 -1
  115. package/.next/standalone/.next/server/chunks/210.js +6 -6
  116. package/.next/standalone/.next/server/chunks/3524.js +31 -15
  117. package/.next/standalone/.next/server/chunks/3566.js +1 -1
  118. package/.next/standalone/.next/server/chunks/4189.js +1 -1
  119. package/.next/standalone/.next/server/chunks/{9590.js → 423.js} +10 -3
  120. package/.next/standalone/.next/server/chunks/4596.js +5 -2
  121. package/.next/standalone/.next/server/chunks/46.js +7 -0
  122. package/.next/standalone/.next/server/chunks/540.js +29 -5
  123. package/.next/standalone/.next/server/chunks/5585.js +41 -3
  124. package/.next/standalone/.next/server/chunks/5908.js +10 -10
  125. package/.next/standalone/.next/server/chunks/{3399.js → 6058.js} +485 -3
  126. package/.next/standalone/.next/server/chunks/{9164.js → 6190.js} +13828 -13581
  127. package/.next/standalone/.next/server/chunks/{1388.js → 8842.js} +5961 -5793
  128. package/.next/standalone/.next/server/chunks/9032.js +5 -5
  129. package/.next/standalone/.next/server/chunks/{7547.js → 9217.js} +485 -3
  130. package/.next/standalone/.next/server/instrumentation.js +7 -0
  131. package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
  132. package/.next/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
  133. package/.next/standalone/.next/server/middleware.js +7 -0
  134. package/.next/standalone/.next/server/pages/404.html +2 -2
  135. package/.next/standalone/.next/server/pages/500.html +1 -1
  136. package/.next/standalone/.next/server/preview-props.json +3 -3
  137. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  138. package/.next/standalone/.next/static/chunks/app/{page-2ef8d75d40eb4311.js → page-4112e14360a9909e.js} +1291 -1281
  139. package/.next/standalone/.next/static/css/{c160ea862133acd2.css → 5b30046ba49144c5.css} +2 -2
  140. package/.next/standalone/docs/adoption/changesets.json +151 -0
  141. package/.next/standalone/package.json +2 -1
  142. package/CHANGELOG.md +46 -0
  143. package/browser-extension/background.js +5 -539
  144. package/browser-extension/lib/form-editing.mjs +541 -0
  145. package/components/chat/MessageBubble.tsx +4 -736
  146. package/components/chat/MessageContent.tsx +749 -0
  147. package/components/dashboard/DashboardPanel.test.tsx +34 -0
  148. package/components/dashboard/DashboardPanel.tsx +1 -1
  149. package/components/layout/MenuPanel.tsx +1 -1
  150. package/components/ui/BootScreen.test.tsx +1 -0
  151. package/components/ui/BootScreen.tsx +1 -0
  152. package/components/ui/ServerStatus.test.tsx +50 -0
  153. package/components/ui/ServerStatus.tsx +10 -8
  154. package/hooks/useSSE.test.ts +46 -0
  155. package/lib/agents/llm.ts +1 -1
  156. package/lib/agents/output-validator/validator.test.ts +4 -0
  157. package/lib/agents/output-validator/validator.ts +1 -1
  158. package/lib/agents/prompt-registry.test.ts +11 -0
  159. package/lib/agents/prompt-registry.ts +13 -0
  160. package/lib/agents/retry-prompts.ts +17 -0
  161. package/lib/agents/run-retry.ts +671 -0
  162. package/lib/agents/run-thread.retry.test.ts +176 -2
  163. package/lib/agents/run-thread.test.ts +6 -6
  164. package/lib/agents/run-thread.ts +9 -717
  165. package/lib/agents/stream-collector.test.ts +28 -4
  166. package/lib/agents/stream-collector.ts +5 -28
  167. package/lib/agents/tool-outcomes.ts +61 -0
  168. package/lib/documents/remote/confluence.test.ts +65 -0
  169. package/lib/documents/remote/confluence.ts +35 -9
  170. package/lib/documents/remote/jira.ts +1 -1
  171. package/lib/health/probes.test.ts +32 -0
  172. package/lib/health/probes.ts +29 -14
  173. package/lib/integrations/atlassian/manifest.ts +5 -3
  174. package/lib/integrations/github/manifest.ts +7 -4
  175. package/lib/integrations/gmail-oauth.ts +16 -1
  176. package/lib/integrations/microsoft-oauth.ts +17 -2
  177. package/lib/integrations/outlook/manifest.ts +10 -8
  178. package/lib/stores/integrations.ts +1 -0
  179. package/lib/tools/communications/calendar-aliases.test.ts +77 -1
  180. package/lib/tools/communications/gmail.test.ts +13 -0
  181. package/lib/tools/communications/ms-graph.test.ts +26 -3
  182. package/lib/tools/communications/ms-graph.ts +9 -11
  183. package/lib/tools/communications/outlook-calendar.ts +94 -17
  184. package/lib/tools/packages/default-packages/atlassian.ts +8 -2
  185. package/package.json +2 -1
  186. package/scripts/standalone-footprint.mjs +1 -1
  187. /package/.next/standalone/.next/static/{544OFJV-q0RC6Gjgje4LT → VZXMorlOmSmi3dUr7K5UX}/_buildManifest.js +0 -0
  188. /package/.next/standalone/.next/static/{544OFJV-q0RC6Gjgje4LT → VZXMorlOmSmi3dUr7K5UX}/_ssgManifest.js +0 -0
@@ -0,0 +1,541 @@
1
+ function runFieldOperation(operation, value) {
2
+ function roots() {
3
+ const found = [document];
4
+ for (let index = 0; index < found.length; index++) {
5
+ for (const element of found[index].querySelectorAll("*")) {
6
+ if (element.shadowRoot) found.push(element.shadowRoot);
7
+ }
8
+ }
9
+ return found;
10
+ }
11
+
12
+ function queryAll(selector) {
13
+ return roots().flatMap((root) => [...root.querySelectorAll(selector)]);
14
+ }
15
+
16
+ function isEditable(element) {
17
+ if (element instanceof HTMLTextAreaElement) return true;
18
+ if (element instanceof HTMLInputElement) return /^(text|search|email|url|tel)$/i.test(element.type || "text");
19
+ return Boolean(element?.isContentEditable);
20
+ }
21
+
22
+ function findTarget() {
23
+ const pinned = queryAll("[data-jarela-fill-target]").find(isEditable);
24
+ if (pinned) return pinned;
25
+ let active = document.activeElement;
26
+ while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
27
+ if (isEditable(active)) return active;
28
+ const editableParent = active?.closest?.("[contenteditable=''], [contenteditable='true']");
29
+ if (isEditable(editableParent)) return editableParent;
30
+ const dialog = queryAll("[role='dialog'], dialog[open]")[0];
31
+ const field = dialog?.querySelector("textarea, input[type='text'], input[type='search'], input[type='email'], input[type='url'], input[type='tel'], [contenteditable=''], [contenteditable='true']");
32
+ return isEditable(field) ? field : null;
33
+ }
34
+
35
+ function capture() {
36
+
37
+
38
+
39
+ const sel = window.getSelection?.();
40
+ const trimmedSelection = (sel?.toString() || "").trim();
41
+
42
+ // Reuse an existing mark if a prior call already pinned the
43
+ // editable in this frame (e.g. the menu has stolen focus).
44
+ const el = findTarget();
45
+
46
+ if (!isEditable(el)) {
47
+ // Selection-only state (no field focused in this frame).
48
+ return trimmedSelection ? { hasField: false, original: trimmedSelection } : null;
49
+ }
50
+
51
+ // Clear stale marks on siblings, then pin this one.
52
+ queryAll("[data-jarela-fill-target]").forEach((n) => {
53
+ if (n !== el) {
54
+ n.removeAttribute("data-jarela-fill-target");
55
+ delete n.dataset?.jarelaFillStart;
56
+ delete n.dataset?.jarelaFillEnd;
57
+ delete n.dataset?.jarelaFillCaretOffset;
58
+ delete n.dataset?.jarelaFillCaretEndOffset;
59
+ }
60
+ });
61
+ queryAll("[data-jarela-fill-caret]").forEach((n) => n.remove());
62
+ el.setAttribute("data-jarela-fill-target", "1");
63
+
64
+ // Capture range NOW (start..end). For input/textarea: selection
65
+ // indices. For contenteditable: text-offsets from the editable's
66
+ // start, measured via synthetic range so element-node containers
67
+ // (multi-paragraph selections in Gmail/Outlook) work the same as
68
+ // text-node containers. Dataset on the editable root survives
69
+ // framework reconciliation where a marker <span> would be
70
+ // stripped. `original` is empty when the selection is collapsed.
71
+ let original = "";
72
+ if (el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement) {
73
+ const s = Number(el.selectionStart ?? el.value.length);
74
+ const e = Number(el.selectionEnd ?? el.value.length);
75
+ el.dataset.jarelaFillStart = String(s);
76
+ el.dataset.jarelaFillEnd = String(e);
77
+ if (s !== e) original = String(el.value || "").slice(Math.min(s, e), Math.max(s, e));
78
+ } else if (el.isContentEditable) {
79
+ try {
80
+ const doc = el.ownerDocument || document;
81
+ if (sel && sel.rangeCount > 0) {
82
+ const range = sel.getRangeAt(0);
83
+ if (el.contains(range.startContainer) && el.contains(range.endContainer)) {
84
+ function offsetFromStart(container, offsetInContainer) {
85
+ const r = doc.createRange();
86
+ r.selectNodeContents(el);
87
+ r.setEnd(container, offsetInContainer);
88
+ return r.toString().length;
89
+ }
90
+ const startOffset = offsetFromStart(range.startContainer, range.startOffset);
91
+ const endOffset = offsetFromStart(range.endContainer, range.endOffset);
92
+ el.dataset.jarelaFillCaretOffset = String(startOffset);
93
+ el.dataset.jarelaFillCaretEndOffset = String(endOffset);
94
+ if (startOffset !== endOffset) original = range.toString();
95
+ }
96
+ }
97
+ } catch {
98
+ // Best-effort — fall back to end-of-field insertion.
99
+ }
100
+ }
101
+
102
+ return { hasField: true, original };
103
+
104
+ }
105
+
106
+ function clear() {
107
+ queryAll("[data-jarela-fill-target]").forEach((n) => {
108
+ n.removeAttribute("data-jarela-fill-target");
109
+ delete n.dataset?.jarelaFillStart;
110
+ delete n.dataset?.jarelaFillEnd;
111
+ delete n.dataset?.jarelaFillCaretOffset;
112
+ delete n.dataset?.jarelaFillCaretEndOffset;
113
+ });
114
+ queryAll("[data-jarela-fill-caret]").forEach((n) => n.remove());
115
+
116
+ }
117
+
118
+ function context(selectedTextOverride) {
119
+ function normalizeText(v, max = 5000) {
120
+ return (v || "").replace(/\s+/g, " ").trim().slice(0, max);
121
+ }
122
+
123
+ const active = findTarget();
124
+ const isTextarea = active instanceof HTMLTextAreaElement;
125
+ const isTextInput = active instanceof HTMLInputElement && /^(text|search|email|url|tel)$/i.test(active.type || "text");
126
+ const target = active;
127
+
128
+ let selectedText = normalizeText(selectedTextOverride || "", 3000);
129
+ if (!selectedText) {
130
+ if (isTextarea || isTextInput) {
131
+ const start = Number(active.selectionStart ?? 0);
132
+ const end = Number(active.selectionEnd ?? 0);
133
+ selectedText = normalizeText(String(active.value || "").slice(Math.min(start, end), Math.max(start, end)), 3000);
134
+ } else {
135
+ selectedText = normalizeText(window.getSelection?.()?.toString() || "", 3000);
136
+ }
137
+ }
138
+
139
+ const title = document.title;
140
+ const url = location.href;
141
+ const h1 = normalizeText(document.querySelector("h1")?.textContent || "", 300);
142
+ const h2 = normalizeText(document.querySelector("h2")?.textContent || "", 300);
143
+ const meta = normalizeText(document.querySelector('meta[name="description"]')?.getAttribute("content") || "", 400);
144
+
145
+ // Find the nearest meaningful container around the focused field.
146
+ // Walk up the DOM and keep the largest ancestor whose text content is
147
+ // "reasonable" (>= 200 chars, <= 20000). This picks the email thread
148
+ // around a Gmail reply, the issue around a GitHub comment box, the
149
+ // dialog around a compose form — but stops short of containers that
150
+ // have already absorbed the whole page chrome (nav, sidebars, inbox
151
+ // listing). Empty when there's no focused field.
152
+ function findScope(field) {
153
+ let node = field?.parentElement || null;
154
+ let best = null;
155
+ while (node && node !== document.body) {
156
+ const len = (node.innerText || "").trim().length;
157
+ if (len > 20000) break;
158
+ if (len >= 200) best = node;
159
+ node = node.parentElement;
160
+ }
161
+ return best;
162
+ }
163
+
164
+ // Pull the scope's text minus the field's own current draft (so the
165
+ // model doesn't see its own future output reflected back). Keep the
166
+ // tail when truncating because email threads / comment threads put
167
+ // the message being replied to closest to the reply box.
168
+ function scopeText(scope, field, max = 6000) {
169
+ if (!scope) return "";
170
+ let raw = scope.innerText || "";
171
+ let draft = "";
172
+ if (field instanceof HTMLTextAreaElement || field instanceof HTMLInputElement) {
173
+ draft = String(field.value || "");
174
+ } else if (field?.isContentEditable) {
175
+ draft = field.innerText || "";
176
+ }
177
+ if (draft && draft.trim().length > 0 && raw.includes(draft)) {
178
+ raw = raw.split(draft).join(" ");
179
+ }
180
+ const cleaned = raw.replace(/\s+/g, " ").trim();
181
+ if (cleaned.length <= max) return cleaned;
182
+ return "... " + cleaned.slice(-max);
183
+ }
184
+
185
+ // Coarse classification of WHAT the field is for. The model already
186
+ // gets the raw signals (tag, type, label, placeholder, host) and is
187
+ // free to override this hint, but stating an explicit kind makes the
188
+ // output style much more consistent: "search query" stays a bare
189
+ // keyword list, "email reply" gets a greeting + sign-off, "chat
190
+ // message" stays terse, etc.
191
+ function detectFieldKind(field, hostName) {
192
+ if (!field) return "";
193
+ const tag = (field.tagName || "").toLowerCase();
194
+ const type = (field.type || "").toLowerCase();
195
+ const role = (field.getAttribute?.("role") || "").toLowerCase();
196
+ const label = String(
197
+ (field.id ? document.querySelector(`label[for="${CSS.escape(field.id)}"]`)?.textContent : "")
198
+ || field.closest?.("label")?.textContent
199
+ || field.getAttribute?.("aria-label")
200
+ || field.placeholder
201
+ || field.name
202
+ || "",
203
+ ).toLowerCase();
204
+ const host = (hostName || "").toLowerCase();
205
+
206
+ if (type === "search" || role === "searchbox" || /\bsearch\b|\bquery\b/.test(label)) return "search query";
207
+ if (type === "email") return "email address";
208
+ if (type === "url") return "url";
209
+ if (type === "tel") return "phone number";
210
+ if (type === "number") return "numeric value";
211
+ if (type === "password") return "password";
212
+
213
+ const emailHost = /(^|\.)mail\.google\.com$|(^|\.)outlook\.(live|office)\.com$|(^|\.)mail\.yahoo\.com$|(^|\.)proton\.me$/.test(host);
214
+ const isLongForm = tag === "textarea" || field.isContentEditable;
215
+
216
+ if (emailHost && isLongForm) return "email reply";
217
+ if (emailHost && /subject/.test(label)) return "email subject";
218
+ if (/(^|\.)github\.com$/.test(host) && isLongForm) return "github comment";
219
+ if (/(^|\.)(x|twitter)\.com$/.test(host) && isLongForm) return "social post";
220
+ if (/(^|\.)linkedin\.com$/.test(host) && isLongForm) return "social post";
221
+ if (/(^|\.)slack\.com$|(^|\.)discord\.com$/.test(host) && isLongForm) return "chat message";
222
+ if (/(^|\.)reddit\.com$|(^|\.)stackoverflow\.com$/.test(host) && isLongForm) return "forum post";
223
+
224
+ if (/reply|response/.test(label)) return "reply";
225
+ if (/comment/.test(label)) return "comment";
226
+ if (/message|chat|send/.test(label) && isLongForm) return "chat message";
227
+ if (/subject|title|headline/.test(label)) return "short title";
228
+ if (/description|bio|about/.test(label) && isLongForm) return "description";
229
+
230
+ if (isLongForm) return "long-form text";
231
+ if (tag === "input") return "short form field";
232
+ return "";
233
+ }
234
+
235
+ let targetInfo = "";
236
+ const scope = target ? findScope(target) : null;
237
+ if (target) {
238
+ const label = target.id
239
+ ? document.querySelector(`label[for="${CSS.escape(target.id)}"]`)?.textContent
240
+ : target.closest("label")?.textContent;
241
+ const placeholder = "placeholder" in target ? String(target.placeholder || "") : "";
242
+ const name = "name" in target ? String(target.name || "") : "";
243
+ const aria = target.getAttribute?.("aria-label") || "";
244
+ const tag = (target.tagName || "").toLowerCase();
245
+ const type = "type" in target ? String(target.type || "") : "";
246
+ const role = target.getAttribute?.("role") || "";
247
+ const maxlen = "maxLength" in target && Number(target.maxLength) > 0 ? Number(target.maxLength) : 0;
248
+ const kind = detectFieldKind(target, location.host);
249
+ targetInfo = [
250
+ kind ? `Field kind: ${kind}` : "",
251
+ `Field tag: ${tag}${target.isContentEditable ? " (contenteditable)" : ""}`,
252
+ type ? `Field type: ${type}` : "",
253
+ role ? `Field role: ${role}` : "",
254
+ maxlen ? `Field maxlength: ${maxlen}` : "",
255
+ `Field label: ${normalizeText(label || "", 200)}`,
256
+ `Field name: ${normalizeText(name, 120)}`,
257
+ `Field placeholder: ${normalizeText(placeholder, 200)}`,
258
+ `Field aria-label: ${normalizeText(aria, 200)}`,
259
+ ].filter((line) => line && !line.endsWith(": ")).join("\n");
260
+ }
261
+
262
+ const pageContext = [
263
+ `Host: ${location.host}`,
264
+ h1 ? `Main heading: ${h1}` : "",
265
+ h2 ? `Secondary heading: ${h2}` : "",
266
+ meta ? `Meta description: ${meta}` : "",
267
+ targetInfo,
268
+ ].filter(Boolean).join("\n");
269
+
270
+ // Priority order for the primary text payload:
271
+ // 1. user's explicit selection (always wins)
272
+ // 2. scope text around the focused field (the thread / form / dialog
273
+ // the field actually belongs to)
274
+ // 3. document.body.innerText cap 5000 (only when there's no focused
275
+ // field at all — context-menu fill on a passive page region)
276
+ let text;
277
+ if (selectedText) text = selectedText;
278
+ else if (target) text = scopeText(scope, target) || "";
279
+ else text = normalizeText(document.body?.innerText || "", 5000);
280
+ return { url, title, text, page_context: pageContext, has_target: Boolean(target) };
281
+
282
+ }
283
+
284
+ function fill(nextText) {
285
+ const active = findTarget();
286
+ if (!active) return { ok: false, reason: "No focused field" };
287
+
288
+ if (active instanceof HTMLTextAreaElement || (active instanceof HTMLInputElement && /^(text|search|email|url|tel)$/i.test(active.type || "text"))) {
289
+ active.focus();
290
+ // Prefer the caret captured at mark time \u2014 the context menu +
291
+ // spinner + LLM round-trip blur the field, after which
292
+ // selectionStart/End reset to value.length and we'd append.
293
+ const savedStart = active.dataset?.jarelaFillStart;
294
+ const savedEnd = active.dataset?.jarelaFillEnd;
295
+ const start = savedStart !== undefined
296
+ ? Number(savedStart)
297
+ : Number(active.selectionStart ?? active.value.length);
298
+ const end = savedEnd !== undefined
299
+ ? Number(savedEnd)
300
+ : Number(active.selectionEnd ?? active.value.length);
301
+ const left = active.value.slice(0, Math.min(start, end));
302
+ const right = active.value.slice(Math.max(start, end));
303
+ active.value = `${left}${nextText}${right}`;
304
+ const cursor = left.length + nextText.length;
305
+ active.selectionStart = cursor;
306
+ active.selectionEnd = cursor;
307
+ active.dispatchEvent(new Event("input", { bubbles: true }));
308
+ active.dispatchEvent(new Event("change", { bubbles: true }));
309
+ return { ok: true };
310
+ }
311
+
312
+ if (active.isContentEditable) {
313
+ active.focus();
314
+ // Restore the saved range (start..end) so insertText REPLACES any
315
+ // selected text. Falls back to caret-only or end-of-field if the
316
+ // field's text shrank between mark and fill.
317
+ const savedStart = active.dataset?.jarelaFillCaretOffset;
318
+ const savedEnd = active.dataset?.jarelaFillCaretEndOffset ?? savedStart;
319
+ try {
320
+ const sel = window.getSelection();
321
+ const range = document.createRange();
322
+ if (savedStart !== undefined) {
323
+ const startTarget = Number(savedStart);
324
+ const endTarget = Number(savedEnd);
325
+ const walker = document.createTreeWalker(active, NodeFilter.SHOW_TEXT);
326
+ let n;
327
+ let acc = 0;
328
+ let placedStart = false;
329
+ let placedEnd = false;
330
+ while ((n = walker.nextNode())) {
331
+ const len = (n.nodeValue || "").length;
332
+ if (!placedStart && startTarget <= acc + len) {
333
+ range.setStart(n, startTarget - acc);
334
+ placedStart = true;
335
+ }
336
+ if (!placedEnd && endTarget <= acc + len) {
337
+ range.setEnd(n, endTarget - acc);
338
+ placedEnd = true;
339
+ }
340
+ if (placedStart && placedEnd) break;
341
+ acc += len;
342
+ }
343
+ if (!placedStart || !placedEnd) {
344
+ // Field shrank or text changed; clamp to end.
345
+ range.selectNodeContents(active);
346
+ range.collapse(false);
347
+ }
348
+ } else {
349
+ // No offset captured (shadow-root host or detached frame).
350
+ range.selectNodeContents(active);
351
+ range.collapse(false);
352
+ }
353
+ sel?.removeAllRanges();
354
+ sel?.addRange(range);
355
+ } catch {
356
+ // Selection APIs throw inside detached frames; fall through to insertText.
357
+ }
358
+ delete active.dataset?.jarelaFillCaretOffset;
359
+ delete active.dataset?.jarelaFillCaretEndOffset;
360
+ const inserted = document.execCommand("insertText", false, nextText);
361
+ if (!inserted) {
362
+ // execCommand can be a no-op in some shadow roots / custom editors —
363
+ // fall back to a plain textContent assignment + input event so the
364
+ // host framework still sees the change.
365
+ active.textContent = `${active.textContent || ""}${nextText}`;
366
+ }
367
+ active.dispatchEvent(new Event("input", { bubbles: true }));
368
+ return { ok: true };
369
+ }
370
+
371
+ return { ok: false, reason: "Focused element is not editable" };
372
+
373
+ }
374
+
375
+ function show() {
376
+ const active = findTarget();
377
+ if (!active || typeof active.getBoundingClientRect !== "function") return;
378
+ const rect = active.getBoundingClientRect();
379
+ document.getElementById("jarela-fill-spinner")?.remove();
380
+ const el = document.createElement("div");
381
+ el.id = "jarela-fill-spinner";
382
+ el.innerHTML = '<svg viewBox="0 0 14 14"><circle cx="7" cy="7" r="5.5"/></svg>';
383
+ el.style.top = `${Math.max(2, rect.top + 4)}px`;
384
+ el.style.left = `${Math.max(2, rect.right - 22)}px`;
385
+ document.body.appendChild(el);
386
+
387
+ }
388
+
389
+ function hide() { document.getElementById("jarela-fill-spinner")?.remove();
390
+ }
391
+
392
+ const handlers = { capture, clear, context, fill, show, hide };
393
+ return handlers[operation](value);
394
+ }
395
+
396
+ function frameTarget(tabId, frameId) {
397
+ return typeof frameId === "number" ? { tabId, frameIds: [frameId] } : { tabId };
398
+ }
399
+
400
+ export async function copyTextToClipboard(tabId, text) {
401
+ const [{ result }] = await chrome.scripting.executeScript({
402
+ target: { tabId },
403
+ args: [text],
404
+ func: async (value) => {
405
+ try {
406
+ await navigator.clipboard.writeText(value);
407
+ return { ok: true };
408
+ } catch {
409
+ try {
410
+ const ta = document.createElement("textarea");
411
+ ta.value = value;
412
+ ta.style.position = "fixed";
413
+ ta.style.left = "-9999px";
414
+ ta.style.top = "0";
415
+ document.body.appendChild(ta);
416
+ ta.focus();
417
+ ta.select();
418
+ const copied = document.execCommand("copy");
419
+ ta.remove();
420
+ return { ok: copied };
421
+ } catch {
422
+ return { ok: false };
423
+ }
424
+ }
425
+ },
426
+ });
427
+ return Boolean(result?.ok);
428
+ }
429
+
430
+
431
+ // Unified capture: in one pass per same-origin frame, find the focused
432
+ // editable (and pin it with `data-jarela-fill-target` + dataset offsets
433
+ // so we can restore the caret/selection after the LLM round-trip blurs
434
+ // the field) AND/OR snapshot the current selection text. Returns:
435
+ // { ok, frameId, hasField, original }
436
+ // where `original` is the selected text inside the editable (rewrite
437
+ // mode) or the loose page selection (clipboard mode), and is empty for
438
+ // pure-fill mode (caret-only). Picks the frame with an editable; falls
439
+ // back to the longest selection-only frame.
440
+ export async function captureField(tabId) {
441
+ let results;
442
+ try {
443
+ results = await chrome.scripting.executeScript({
444
+ target: { tabId, allFrames: true },
445
+ args: ["capture"],
446
+ func: runFieldOperation,
447
+ });
448
+ } catch {
449
+ return { ok: false };
450
+ }
451
+
452
+ let fieldHit = null;
453
+ let selHit = null;
454
+ for (const r of results || []) {
455
+ const v = r?.result;
456
+ if (!v) continue;
457
+ if (v.hasField) {
458
+ if (!fieldHit) fieldHit = { ...v, frameId: r.frameId ?? 0 };
459
+ } else if (!selHit || (v.original?.length ?? 0) > (selHit.original?.length ?? 0)) {
460
+ selHit = { ...v, frameId: r.frameId ?? 0 };
461
+ }
462
+ }
463
+ const winner = fieldHit || selHit;
464
+ return winner ? { ok: true, ...winner } : { ok: false };
465
+ }
466
+
467
+
468
+ export async function clearFillTarget(tabId, frameId) {
469
+ try {
470
+ await chrome.scripting.executeScript({
471
+ target: frameTarget(tabId, frameId),
472
+ args: ["clear"],
473
+ func: runFieldOperation,
474
+ });
475
+ } catch {
476
+ // Tab/frame may be gone — nothing to clean up.
477
+ }
478
+ }
479
+
480
+
481
+ export async function getFillContext(tabId, frameId, selectionOverride) {
482
+ const [{ result }] = await chrome.scripting.executeScript({
483
+ target: frameTarget(tabId, frameId),
484
+ args: ["context", selectionOverride ?? ""],
485
+ func: runFieldOperation,
486
+ });
487
+ return result;
488
+ }
489
+
490
+
491
+ export async function fillFocusedField(tabId, frameId, value) {
492
+ const [{ result }] = await chrome.scripting.executeScript({
493
+ target: frameTarget(tabId, frameId),
494
+ args: ["fill", value],
495
+ func: runFieldOperation,
496
+ });
497
+ return result;
498
+ }
499
+
500
+
501
+ // Anchors a small rotating SVG spinner to the focused field so the user
502
+ // gets visual confirmation that a fill turn is running. Mirrors the chat
503
+ // CountdownRing geometry (r=5.5, viewBox 14×14) at field-sized scale.
504
+ export async function showFillSpinner(tabId, frameId) {
505
+ try {
506
+ await chrome.scripting.insertCSS({
507
+ target: frameTarget(tabId, frameId),
508
+ css: `
509
+ #jarela-fill-spinner { position: fixed; z-index: 2147483647; pointer-events: none;
510
+ width: 18px; height: 18px; border-radius: 50%;
511
+ background: rgba(15, 23, 42, 0.92); box-shadow: 0 1px 4px rgba(0,0,0,0.4);
512
+ display: flex; align-items: center; justify-content: center; }
513
+ #jarela-fill-spinner svg { width: 14px; height: 14px; animation: jarela-fill-spin 1s linear infinite; }
514
+ #jarela-fill-spinner circle { fill: none; stroke: #818cf8; stroke-width: 1.5;
515
+ stroke-linecap: round; stroke-dasharray: 8.6 26; }
516
+ @keyframes jarela-fill-spin { to { transform: rotate(360deg); } }
517
+ @media (prefers-reduced-motion: reduce) { #jarela-fill-spinner svg { animation: none; } }
518
+ `,
519
+ });
520
+ await chrome.scripting.executeScript({
521
+ target: frameTarget(tabId, frameId),
522
+ args: ["show"],
523
+ func: runFieldOperation,
524
+ });
525
+ } catch (err) {
526
+ console.warn("[jarela] showFillSpinner failed:", err);
527
+ }
528
+ }
529
+
530
+
531
+ export async function hideFillSpinner(tabId, frameId) {
532
+ try {
533
+ await chrome.scripting.executeScript({
534
+ target: frameTarget(tabId, frameId),
535
+ args: ["hide"],
536
+ func: runFieldOperation,
537
+ });
538
+ } catch {
539
+ // Tab may have navigated away — nothing to clean up.
540
+ }
541
+ }