@agent-native/core 0.12.2 → 0.12.4

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 (38) hide show
  1. package/dist/a2a/artifact-response.d.ts.map +1 -1
  2. package/dist/a2a/artifact-response.js +103 -9
  3. package/dist/a2a/artifact-response.js.map +1 -1
  4. package/dist/client/composer/TiptapComposer.d.ts +1 -0
  5. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  6. package/dist/client/composer/TiptapComposer.js +32 -23
  7. package/dist/client/composer/TiptapComposer.js.map +1 -1
  8. package/dist/client/extensions/ExtensionViewer.d.ts.map +1 -1
  9. package/dist/client/extensions/ExtensionViewer.js +7 -2
  10. package/dist/client/extensions/ExtensionViewer.js.map +1 -1
  11. package/dist/client/extensions/ExtensionViewerPage.d.ts.map +1 -1
  12. package/dist/client/extensions/ExtensionViewerPage.js +4 -1
  13. package/dist/client/extensions/ExtensionViewerPage.js.map +1 -1
  14. package/dist/client/extensions/ExtensionsListPage.js +1 -1
  15. package/dist/client/extensions/ExtensionsListPage.js.map +1 -1
  16. package/dist/client/theme.d.ts.map +1 -1
  17. package/dist/client/theme.js +5 -1
  18. package/dist/client/theme.js.map +1 -1
  19. package/dist/client/vite-dev-recovery-script.d.ts +10 -0
  20. package/dist/client/vite-dev-recovery-script.d.ts.map +1 -0
  21. package/dist/client/vite-dev-recovery-script.js +199 -0
  22. package/dist/client/vite-dev-recovery-script.js.map +1 -0
  23. package/dist/extensions/actions.d.ts.map +1 -1
  24. package/dist/extensions/actions.js +5 -1
  25. package/dist/extensions/actions.js.map +1 -1
  26. package/dist/scripts/call-agent.js +1 -1
  27. package/dist/scripts/call-agent.js.map +1 -1
  28. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  29. package/dist/server/agent-chat-plugin.js +8 -4
  30. package/dist/server/agent-chat-plugin.js.map +1 -1
  31. package/dist/server/auth.d.ts.map +1 -1
  32. package/dist/server/auth.js +245 -36
  33. package/dist/server/auth.js.map +1 -1
  34. package/dist/vite/client.d.ts +1 -4
  35. package/dist/vite/client.d.ts.map +1 -1
  36. package/dist/vite/client.js +39 -128
  37. package/dist/vite/client.js.map +1 -1
  38. package/package.json +1 -1
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Synchronous dev-only browser recovery for Vite optimized-dependency races.
3
+ *
4
+ * Keep this script dependency-free and non-module-safe: React Router SSR roots
5
+ * inline it before `<Scripts />`, and the Vite plugin injects it at
6
+ * `head-prepend` for HTML that does pass through transformIndexHtml.
7
+ */
8
+ export function getViteDevRecoveryScript() {
9
+ return `
10
+ (function() {
11
+ var RELOAD_KEY = "__an_optimize_reload";
12
+ var MAX_RELOADS = 3;
13
+ var RESET_AFTER_MS = 8000;
14
+
15
+ var reloadTimer = null;
16
+ var overlayShown = false;
17
+
18
+ // Track recent reloads in sessionStorage. If we reload too many times
19
+ // in a short window, stop and show a manual-refresh message instead of
20
+ // looping forever.
21
+ function readReloadHistory() {
22
+ try {
23
+ var raw = sessionStorage.getItem(RELOAD_KEY);
24
+ if (!raw) return [];
25
+ var arr = JSON.parse(raw);
26
+ var cutoff = Date.now() - 30000;
27
+ return Array.isArray(arr) ? arr.filter(function(t) { return t > cutoff; }) : [];
28
+ } catch (e) { return []; }
29
+ }
30
+ function recordReload() {
31
+ try {
32
+ var history = readReloadHistory();
33
+ history.push(Date.now());
34
+ sessionStorage.setItem(RELOAD_KEY, JSON.stringify(history));
35
+ } catch (e) {}
36
+ }
37
+ // Reset the counter after a stable period (page didn't fail again).
38
+ setTimeout(function() {
39
+ try { sessionStorage.removeItem(RELOAD_KEY); } catch (e) {}
40
+ }, RESET_AFTER_MS);
41
+
42
+ function showOverlay(title, subtitle) {
43
+ if (overlayShown) return;
44
+ overlayShown = true;
45
+ var mount = function() {
46
+ if (!document.body) { setTimeout(mount, 16); return; }
47
+ var el = document.createElement("div");
48
+ el.id = "__an-reload-overlay";
49
+ el.style.cssText = [
50
+ "position:fixed","inset:0","z-index:2147483647",
51
+ "display:flex","align-items:center","justify-content:center",
52
+ "background:rgba(0,0,0,0.6)","backdrop-filter:blur(8px)",
53
+ "-webkit-backdrop-filter:blur(8px)",
54
+ "font-family:-apple-system,BlinkMacSystemFont,system-ui,sans-serif",
55
+ "color:#fff","font-size:14px"
56
+ ].join(";");
57
+ el.innerHTML =
58
+ '<div style="background:#171717;padding:20px 24px;border-radius:12px;' +
59
+ 'border:1px solid rgba(255,255,255,0.1);max-width:340px;text-align:center;' +
60
+ 'box-shadow:0 20px 60px rgba(0,0,0,0.5)">' +
61
+ '<div style="font-weight:600;margin-bottom:6px">' + title + '</div>' +
62
+ '<div style="font-size:12px;opacity:0.7">' + subtitle + '</div>' +
63
+ '</div>';
64
+ document.body.appendChild(el);
65
+ };
66
+ mount();
67
+ }
68
+
69
+ function scheduleReload(reason) {
70
+ if (reloadTimer) return;
71
+ var history = readReloadHistory();
72
+ if (history.length >= MAX_RELOADS) {
73
+ console.warn("[agent-native] Dev server keeps re-bundling. Manual refresh needed.", reason);
74
+ showOverlay(
75
+ "Dev server out of sync",
76
+ "Auto-reload gave up after " + MAX_RELOADS + " tries. Refresh the page (\\u2318R / Ctrl+R)."
77
+ );
78
+ return;
79
+ }
80
+ console.log("[agent-native] Vite re-bundled deps (" + reason + "), reloading\\u2026");
81
+ recordReload();
82
+ // First reload is silent. One refresh almost always fixes it and the
83
+ // overlay flash is more disruptive than the reload itself. Only show
84
+ // the overlay starting on the second attempt, when something is clearly
85
+ // taking longer than expected.
86
+ if (history.length >= 1) {
87
+ showOverlay("Updating dev server\\u2026", "Reloading the page");
88
+ }
89
+ reloadTimer = setTimeout(function() { window.location.reload(); }, 300);
90
+ }
91
+
92
+ function looksLikeViteFailureMessage(message) {
93
+ if (!message) return false;
94
+ return message.indexOf("Failed to fetch dynamically imported module") !== -1
95
+ || message.indexOf("error loading dynamically imported module") !== -1
96
+ || message.indexOf("Importing a module script failed") !== -1
97
+ || message.indexOf("Outdated Optimize Dep") !== -1
98
+ || message.indexOf("Optimize Deps Processing Error") !== -1
99
+ || (message.indexOf("504") !== -1 && (
100
+ message.indexOf(".vite/deps") !== -1 ||
101
+ message.indexOf("/node_modules/.vite/deps/") !== -1
102
+ ));
103
+ }
104
+
105
+ function looksLikeViteDep(url) {
106
+ if (!url) return false;
107
+ // Only treat same-origin URLs as Vite deps. Do not reload the page
108
+ // because some third-party CDN script 404'd.
109
+ try {
110
+ var u = new URL(url, window.location.href);
111
+ if (u.origin !== window.location.origin) return false;
112
+ } catch (e) { return false; }
113
+ return url.indexOf("/node_modules/.vite/deps/") !== -1
114
+ || url.indexOf("/@fs/") !== -1
115
+ || url.indexOf("/@id/") !== -1
116
+ || url.indexOf("?v=") !== -1
117
+ || url.indexOf("?import") !== -1
118
+ || /\\.(m?js|ts|tsx|jsx)(\\?|$)/.test(url);
119
+ }
120
+
121
+ // 1) <script type="module"> / <link> 504. These fire on the element, not
122
+ // window, so use capture phase to catch resource load errors.
123
+ window.addEventListener("error", function(e) {
124
+ var t = e.target;
125
+ if (!t || t === window) {
126
+ var message = String(e.message || "");
127
+ if (looksLikeViteFailureMessage(message)) {
128
+ scheduleReload("window error");
129
+ }
130
+ return;
131
+ }
132
+ var tag = t.tagName;
133
+ if (tag !== "SCRIPT" && tag !== "LINK") return;
134
+ var url = t.src || t.href || "";
135
+ if (looksLikeViteDep(url)) {
136
+ var name = url.split("/").pop();
137
+ scheduleReload("script 504: " + name);
138
+ }
139
+ }, true);
140
+
141
+ // Vite's documented hook for failed dynamic-import preloads. This mostly
142
+ // targets production chunk skew, but it also fires for some dev optimizer
143
+ // races, so wire it into the same guarded reload path.
144
+ window.addEventListener("vite:preloadError", function(e) {
145
+ var payload = e && e.payload;
146
+ var msg = String((payload && (payload.message || payload)) || "");
147
+ if (!msg || looksLikeViteFailureMessage(msg)) {
148
+ if (e.preventDefault) e.preventDefault();
149
+ scheduleReload("preload error");
150
+ }
151
+ });
152
+
153
+ // 2) Dynamic import failures (React Router code splitting, lazy components).
154
+ window.addEventListener("unhandledrejection", function(e) {
155
+ var msg = String((e.reason && (e.reason.message || e.reason)) || "");
156
+ if (looksLikeViteFailureMessage(msg)) {
157
+ scheduleReload("dynamic import");
158
+ }
159
+ });
160
+
161
+ // Static module-graph fetch failures for child imports don't always surface
162
+ // as element errors or rejections. Chrome exposes the HTTP status via
163
+ // Resource Timing; when available, use it as a final safety net.
164
+ var seenResources = {};
165
+ function checkResourceEntry(entry) {
166
+ var url = entry && entry.name;
167
+ if (!url || seenResources[url]) return;
168
+ seenResources[url] = true;
169
+ if (!looksLikeViteDep(url)) return;
170
+ if (entry.responseStatus === 504) {
171
+ var name = url.split("/").pop();
172
+ scheduleReload("resource 504: " + name);
173
+ }
174
+ }
175
+ function checkExistingResources() {
176
+ try {
177
+ var entries = performance.getEntriesByType("resource") || [];
178
+ for (var i = 0; i < entries.length; i++) checkResourceEntry(entries[i]);
179
+ } catch (e) {}
180
+ }
181
+ if (window.PerformanceObserver) {
182
+ try {
183
+ var observer = new PerformanceObserver(function(list) {
184
+ var entries = list.getEntries();
185
+ for (var i = 0; i < entries.length; i++) checkResourceEntry(entries[i]);
186
+ });
187
+ observer.observe({ type: "resource", buffered: true });
188
+ } catch (e) {
189
+ setTimeout(checkExistingResources, 0);
190
+ }
191
+ } else {
192
+ setTimeout(checkExistingResources, 0);
193
+ }
194
+ })();`;
195
+ }
196
+ export function shouldInlineViteDevRecoveryScript() {
197
+ return (typeof process !== "undefined" && process.env?.NODE_ENV !== "production");
198
+ }
199
+ //# sourceMappingURL=vite-dev-recovery-script.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-dev-recovery-script.js","sourceRoot":"","sources":["../../src/client/vite-dev-recovery-script.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAyLH,CAAC;AACP,CAAC;AAED,MAAM,UAAU,iCAAiC;IAC/C,OAAO,CACL,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,GAAG,EAAE,QAAQ,KAAK,YAAY,CACzE,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Synchronous dev-only browser recovery for Vite optimized-dependency races.\n *\n * Keep this script dependency-free and non-module-safe: React Router SSR roots\n * inline it before `<Scripts />`, and the Vite plugin injects it at\n * `head-prepend` for HTML that does pass through transformIndexHtml.\n */\nexport function getViteDevRecoveryScript(): string {\n return `\n(function() {\n var RELOAD_KEY = \"__an_optimize_reload\";\n var MAX_RELOADS = 3;\n var RESET_AFTER_MS = 8000;\n\n var reloadTimer = null;\n var overlayShown = false;\n\n // Track recent reloads in sessionStorage. If we reload too many times\n // in a short window, stop and show a manual-refresh message instead of\n // looping forever.\n function readReloadHistory() {\n try {\n var raw = sessionStorage.getItem(RELOAD_KEY);\n if (!raw) return [];\n var arr = JSON.parse(raw);\n var cutoff = Date.now() - 30000;\n return Array.isArray(arr) ? arr.filter(function(t) { return t > cutoff; }) : [];\n } catch (e) { return []; }\n }\n function recordReload() {\n try {\n var history = readReloadHistory();\n history.push(Date.now());\n sessionStorage.setItem(RELOAD_KEY, JSON.stringify(history));\n } catch (e) {}\n }\n // Reset the counter after a stable period (page didn't fail again).\n setTimeout(function() {\n try { sessionStorage.removeItem(RELOAD_KEY); } catch (e) {}\n }, RESET_AFTER_MS);\n\n function showOverlay(title, subtitle) {\n if (overlayShown) return;\n overlayShown = true;\n var mount = function() {\n if (!document.body) { setTimeout(mount, 16); return; }\n var el = document.createElement(\"div\");\n el.id = \"__an-reload-overlay\";\n el.style.cssText = [\n \"position:fixed\",\"inset:0\",\"z-index:2147483647\",\n \"display:flex\",\"align-items:center\",\"justify-content:center\",\n \"background:rgba(0,0,0,0.6)\",\"backdrop-filter:blur(8px)\",\n \"-webkit-backdrop-filter:blur(8px)\",\n \"font-family:-apple-system,BlinkMacSystemFont,system-ui,sans-serif\",\n \"color:#fff\",\"font-size:14px\"\n ].join(\";\");\n el.innerHTML =\n '<div style=\"background:#171717;padding:20px 24px;border-radius:12px;' +\n 'border:1px solid rgba(255,255,255,0.1);max-width:340px;text-align:center;' +\n 'box-shadow:0 20px 60px rgba(0,0,0,0.5)\">' +\n '<div style=\"font-weight:600;margin-bottom:6px\">' + title + '</div>' +\n '<div style=\"font-size:12px;opacity:0.7\">' + subtitle + '</div>' +\n '</div>';\n document.body.appendChild(el);\n };\n mount();\n }\n\n function scheduleReload(reason) {\n if (reloadTimer) return;\n var history = readReloadHistory();\n if (history.length >= MAX_RELOADS) {\n console.warn(\"[agent-native] Dev server keeps re-bundling. Manual refresh needed.\", reason);\n showOverlay(\n \"Dev server out of sync\",\n \"Auto-reload gave up after \" + MAX_RELOADS + \" tries. Refresh the page (\\\\u2318R / Ctrl+R).\"\n );\n return;\n }\n console.log(\"[agent-native] Vite re-bundled deps (\" + reason + \"), reloading\\\\u2026\");\n recordReload();\n // First reload is silent. One refresh almost always fixes it and the\n // overlay flash is more disruptive than the reload itself. Only show\n // the overlay starting on the second attempt, when something is clearly\n // taking longer than expected.\n if (history.length >= 1) {\n showOverlay(\"Updating dev server\\\\u2026\", \"Reloading the page\");\n }\n reloadTimer = setTimeout(function() { window.location.reload(); }, 300);\n }\n\n function looksLikeViteFailureMessage(message) {\n if (!message) return false;\n return message.indexOf(\"Failed to fetch dynamically imported module\") !== -1\n || message.indexOf(\"error loading dynamically imported module\") !== -1\n || message.indexOf(\"Importing a module script failed\") !== -1\n || message.indexOf(\"Outdated Optimize Dep\") !== -1\n || message.indexOf(\"Optimize Deps Processing Error\") !== -1\n || (message.indexOf(\"504\") !== -1 && (\n message.indexOf(\".vite/deps\") !== -1 ||\n message.indexOf(\"/node_modules/.vite/deps/\") !== -1\n ));\n }\n\n function looksLikeViteDep(url) {\n if (!url) return false;\n // Only treat same-origin URLs as Vite deps. Do not reload the page\n // because some third-party CDN script 404'd.\n try {\n var u = new URL(url, window.location.href);\n if (u.origin !== window.location.origin) return false;\n } catch (e) { return false; }\n return url.indexOf(\"/node_modules/.vite/deps/\") !== -1\n || url.indexOf(\"/@fs/\") !== -1\n || url.indexOf(\"/@id/\") !== -1\n || url.indexOf(\"?v=\") !== -1\n || url.indexOf(\"?import\") !== -1\n || /\\\\.(m?js|ts|tsx|jsx)(\\\\?|$)/.test(url);\n }\n\n // 1) <script type=\"module\"> / <link> 504. These fire on the element, not\n // window, so use capture phase to catch resource load errors.\n window.addEventListener(\"error\", function(e) {\n var t = e.target;\n if (!t || t === window) {\n var message = String(e.message || \"\");\n if (looksLikeViteFailureMessage(message)) {\n scheduleReload(\"window error\");\n }\n return;\n }\n var tag = t.tagName;\n if (tag !== \"SCRIPT\" && tag !== \"LINK\") return;\n var url = t.src || t.href || \"\";\n if (looksLikeViteDep(url)) {\n var name = url.split(\"/\").pop();\n scheduleReload(\"script 504: \" + name);\n }\n }, true);\n\n // Vite's documented hook for failed dynamic-import preloads. This mostly\n // targets production chunk skew, but it also fires for some dev optimizer\n // races, so wire it into the same guarded reload path.\n window.addEventListener(\"vite:preloadError\", function(e) {\n var payload = e && e.payload;\n var msg = String((payload && (payload.message || payload)) || \"\");\n if (!msg || looksLikeViteFailureMessage(msg)) {\n if (e.preventDefault) e.preventDefault();\n scheduleReload(\"preload error\");\n }\n });\n\n // 2) Dynamic import failures (React Router code splitting, lazy components).\n window.addEventListener(\"unhandledrejection\", function(e) {\n var msg = String((e.reason && (e.reason.message || e.reason)) || \"\");\n if (looksLikeViteFailureMessage(msg)) {\n scheduleReload(\"dynamic import\");\n }\n });\n\n // Static module-graph fetch failures for child imports don't always surface\n // as element errors or rejections. Chrome exposes the HTTP status via\n // Resource Timing; when available, use it as a final safety net.\n var seenResources = {};\n function checkResourceEntry(entry) {\n var url = entry && entry.name;\n if (!url || seenResources[url]) return;\n seenResources[url] = true;\n if (!looksLikeViteDep(url)) return;\n if (entry.responseStatus === 504) {\n var name = url.split(\"/\").pop();\n scheduleReload(\"resource 504: \" + name);\n }\n }\n function checkExistingResources() {\n try {\n var entries = performance.getEntriesByType(\"resource\") || [];\n for (var i = 0; i < entries.length; i++) checkResourceEntry(entries[i]);\n } catch (e) {}\n }\n if (window.PerformanceObserver) {\n try {\n var observer = new PerformanceObserver(function(list) {\n var entries = list.getEntries();\n for (var i = 0; i < entries.length; i++) checkResourceEntry(entries[i]);\n });\n observer.observe({ type: \"resource\", buffered: true });\n } catch (e) {\n setTimeout(checkExistingResources, 0);\n }\n } else {\n setTimeout(checkExistingResources, 0);\n }\n})();`;\n}\n\nexport function shouldInlineViteDevRecoveryScript(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../src/extensions/actions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAyBhE,wBAAgB,4BAA4B,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAob1E"}
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../src/extensions/actions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAyBhE,wBAAgB,4BAA4B,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAwb1E"}
@@ -185,7 +185,11 @@ export function createExtensionActionEntries() {
185
185
  result = await getExtension(id);
186
186
  if (!result)
187
187
  return `Error: extension not found: ${id}`;
188
- return { ok: true, extension: result };
188
+ const hiddenIds = await getHiddenExtensionIdsForCurrentUser();
189
+ return {
190
+ ok: true,
191
+ extension: await summarizeExtension(result, hiddenIds, false),
192
+ };
189
193
  },
190
194
  },
191
195
  "delete-extension": {
@@ -1 +1 @@
1
- {"version":3,"file":"actions.js","sourceRoot":"","sources":["../../src/extensions/actions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAC;AACvE,OAAO,EACL,eAAe,EACf,eAAe,EACf,mCAAmC,EACnC,YAAY,EACZ,aAAa,EACb,cAAc,EACd,eAAe,EACf,eAAe,EACf,sBAAsB,GAEvB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAI1B,MAAM,UAAU,4BAA4B;IAC1C,OAAO;QACL,iBAAiB,EAAE;YACjB,IAAI,EAAE;gBACJ,WAAW,EACT,kNAAkN;gBACpN,UAAU,EAAE;oBACV,IAAI,EAAE,QAAQ;oBACd,UAAU,EAAE;wBACV,MAAM,EAAE;4BACN,IAAI,EAAE,QAAQ;4BACd,WAAW,EACT,iHAAiH;yBACpH;wBACD,aAAa,EAAE;4BACb,IAAI,EAAE,SAAS;4BACf,WAAW,EACT,oFAAoF;yBACvF;wBACD,cAAc,EAAE;4BACd,IAAI,EAAE,SAAS;4BACf,WAAW,EACT,4EAA4E;yBAC/E;wBACD,KAAK,EAAE;4BACL,IAAI,EAAE,QAAQ;4BACd,WAAW,EAAE,6CAA6C;yBAC3D;qBACF;iBACF;aACF;YACD,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;gBAClB,MAAM,aAAa,GAAG,aAAa,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;gBACzD,MAAM,cAAc,GAAG,aAAa,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC3D,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,EAAE,MAAM,IAAI,EAAE,CAAC;qBACtC,IAAI,EAAE;qBACN,WAAW,EAAE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AAE,OAAO,SAAS,CAAC;IAC1C,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACrE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IAC7C,IACE,MAAM,CAAC,IAAI,CACT,CAAC,KAAK,EAAE,EAAE,CACR,CAAC,KAAK;QACN,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CACpC,EACD,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { ActionEntry } from \"../agent/production-agent.js\";\nimport { writeAppState } from \"../application-state/script-helpers.js\";\nimport {\n createExtension,\n deleteExtension,\n getHiddenExtensionIdsForCurrentUser,\n getExtension,\n hideExtension,\n listExtensions,\n unhideExtension,\n updateExtension,\n updateExtensionContent,\n type ExtensionRow,\n} from \"./store.js\";\nimport { resolveAccess } from \"../sharing/access.js\";\nimport {\n addExtensionSlotTarget,\n installExtensionSlot,\n uninstallExtensionSlot,\n listExtensionsForSlot,\n listSlotsForExtension,\n} from \"./slots/store.js\";\n\ntype ExtensionPatch = { find: string; replace: string };\n\nexport function createExtensionActionEntries(): Record<string, ActionEntry> {\n return {\n \"list-extensions\": {\n tool: {\n description:\n \"List extensions visible in the current user's Extensions list/sidebar. Use this before updating, hiding, or deleting existing extensions; do not query the legacy tools table directly for extension management.\",\n parameters: {\n type: \"object\",\n properties: {\n search: {\n type: \"string\",\n description:\n \"Optional case-insensitive filter matched against id, name, description, and owner email. Example: Connect Zoom.\",\n },\n includeHidden: {\n type: \"boolean\",\n description:\n \"Include extensions the current user has hidden from their list. Defaults to false.\",\n },\n includeContent: {\n type: \"boolean\",\n description:\n \"Include full Alpine.js content. Defaults to false to keep results concise.\",\n },\n limit: {\n type: \"number\",\n description: \"Maximum results to return. Defaults to 100.\",\n },\n },\n },\n },\n run: async (args) => {\n const includeHidden = coerceBoolean(args?.includeHidden);\n const includeContent = coerceBoolean(args?.includeContent);\n const search = String(args?.search ?? \"\")\n .trim()\n .toLowerCase();\n const limit = coerceLimit(args?.limit);\n const hiddenIds = await getHiddenExtensionIdsForCurrentUser();\n\n let rows = await listExtensions({ includeHidden });\n if (search) {\n rows = rows.filter((row) =>\n [row.id, row.name, row.description, row.ownerEmail]\n .join(\"\\n\")\n .toLowerCase()\n .includes(search),\n );\n }\n\n rows = rows.slice(0, limit);\n const extensions = await Promise.all(\n rows.map((row) => summarizeExtension(row, hiddenIds, includeContent)),\n );\n return {\n ok: true,\n count: extensions.length,\n extensions,\n };\n },\n readOnly: true,\n },\n\n \"create-extension\": {\n tool: {\n description:\n \"Create a sandboxed Alpine.js mini-app extension. Use this when the user asks to create, build, or make an extension/widget/dashboard/calculator. Call this action exactly once per requested extension. The content must be a self-contained Alpine.js HTML body snippet that can use appAction(), appFetch(), dbQuery(), dbExec(), extensionFetch(), and extensionData. Prefer appAction(name, params) for app data and actions, including read actions mounted as GET; do not call template /api/* routes from appFetch because the extension bridge only allows framework /_agent-native/* paths. Parse JSON string action results before aggregating; use dbQuery()/dbExec() only for known existing SQL tables.\",\n parameters: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description:\n 'Short display name for the extension. Do not include \"app\" — e.g. name a todo app \"Todos\", a weather app \"Weather\".',\n },\n description: {\n type: \"string\",\n description: \"One-sentence summary of what the extension does.\",\n },\n content: {\n type: \"string\",\n description:\n \"Self-contained Alpine.js HTML body snippet. The iframe canvas already has modest default padding, so avoid duplicate outer padding unless the design needs it. Use semantic Tailwind colors (bg-background, text-foreground, bg-primary, etc.) for native theming. Do not include a full app build, React code, or source files.\",\n },\n icon: {\n type: \"string\",\n description: \"Optional icon name or short label.\",\n },\n },\n required: [\"name\", \"content\"],\n },\n },\n run: async (args) => {\n const name = String(args?.name ?? \"\").trim();\n const content = String(args?.content ?? \"\").trim();\n if (!name) return \"Error: name is required.\";\n if (!content) return \"Error: content is required.\";\n\n const extension = await createExtension({\n name,\n description: String(args?.description ?? \"\").trim(),\n content,\n icon: args?.icon ? String(args.icon) : undefined,\n });\n\n // Auto-navigate so the user lands on the new extension instead of\n // having to read the JSON response and click a link. Writes a\n // one-shot `navigate` app-state command the UI consumes and clears.\n try {\n await writeAppState(\"navigate\", {\n view: \"extensions\",\n extensionId: extension.id,\n path: `/extensions/${extension.id}`,\n });\n } catch {\n // Non-fatal — agent can still mention the path in its reply.\n }\n\n return {\n ok: true,\n extension,\n next: `Created. The user is being navigated to the new extension automatically — no further navigation tool calls needed.`,\n };\n },\n },\n\n \"update-extension\": {\n tool: {\n description:\n \"Update an existing sandboxed Alpine.js mini-app extension. Prefer patches for surgical edits; use full content replacement only when necessary.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Extension id to update.\",\n },\n name: {\n type: \"string\",\n description: \"Optional new display name.\",\n },\n description: {\n type: \"string\",\n description: \"Optional new description.\",\n },\n content: {\n type: \"string\",\n description:\n \"Optional full replacement Alpine.js HTML body snippet.\",\n },\n patches: {\n type: \"string\",\n description:\n 'Optional JSON array of { \"find\": \"...\", \"replace\": \"...\" } patches to apply to the current content.',\n },\n icon: {\n type: \"string\",\n description: \"Optional icon name or short label.\",\n },\n visibility: {\n type: \"string\",\n description: \"Optional sharing visibility.\",\n enum: [\"private\", \"org\", \"public\"],\n },\n },\n required: [\"id\"],\n },\n },\n run: async (args) => {\n const id = String(args?.id ?? \"\").trim();\n if (!id) return \"Error: id is required.\";\n\n let result = null;\n if (args?.content !== undefined || args?.patches !== undefined) {\n const patches = parsePatches((args as any).patches);\n if (args?.patches !== undefined && !patches) {\n return \"Error: patches must be a JSON array of { find, replace } objects.\";\n }\n result = await updateExtensionContent(id, {\n content:\n args?.content !== undefined ? String(args.content) : undefined,\n patches,\n });\n }\n\n const meta: Record<string, string> = {};\n if (args?.name !== undefined) meta.name = String(args.name).trim();\n if (args?.description !== undefined) {\n meta.description = String(args.description).trim();\n }\n if (args?.icon !== undefined) meta.icon = String(args.icon);\n if (args?.visibility !== undefined) {\n meta.visibility = String(args.visibility);\n }\n if (Object.keys(meta).length > 0) {\n result = await updateExtension(id, meta as any);\n }\n\n if (!result) result = await getExtension(id);\n if (!result) return `Error: extension not found: ${id}`;\n return { ok: true, extension: result };\n },\n },\n\n \"delete-extension\": {\n tool: {\n description:\n \"Permanently delete an extension everywhere it is shared. Requires owner/admin access. If the user only wants a shared extension removed from their own sidebar/list, use hide-extension instead.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description:\n \"Extension id to permanently delete. Use list-extensions first if you only know the display name.\",\n },\n },\n required: [\"id\"],\n },\n },\n run: async (args) => {\n const id = String(args?.id ?? \"\").trim();\n if (!id) return \"Error: id is required.\";\n const extension = await getExtension(id);\n if (!extension) return `Error: extension not found: ${id}`;\n\n try {\n const ok = await deleteExtension(id);\n if (!ok) return `Error: extension not found: ${id}`;\n return { ok: true, deleted: summarizeDeletedExtension(extension) };\n } catch (err: any) {\n return {\n ok: false,\n error: err?.message ?? String(err),\n next: \"If the user wants this gone only from their own view, call hide-extension with the same id.\",\n };\n }\n },\n },\n\n \"hide-extension\": {\n tool: {\n description:\n \"Hide an accessible extension from the current user's Extensions list/sidebar without deleting it for anyone else. Use this when the user says to remove a shared extension from their view, or when delete-extension reports that the current user is not owner/admin.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description:\n \"Extension id to hide for the current user. Use list-extensions first if you only know the display name.\",\n },\n },\n required: [\"id\"],\n },\n },\n run: async (args) => {\n const id = String(args?.id ?? \"\").trim();\n if (!id) return \"Error: id is required.\";\n const extension = await getExtension(id);\n if (!extension) return `Error: extension not found: ${id}`;\n\n await hideExtension(id);\n return { ok: true, hidden: summarizeDeletedExtension(extension) };\n },\n },\n\n \"unhide-extension\": {\n tool: {\n description:\n \"Restore an extension the current user previously hid so it appears in their Extensions list/sidebar again. Use list-extensions with includeHidden=true to find hidden ids.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Extension id to restore for the current user.\",\n },\n },\n required: [\"id\"],\n },\n },\n run: async (args) => {\n const id = String(args?.id ?? \"\").trim();\n if (!id) return \"Error: id is required.\";\n await unhideExtension(id);\n return { ok: true, id };\n },\n },\n\n \"add-extension-slot-target\": {\n tool: {\n description:\n 'Declare that an extension can render in a UI extension-point slot of an app (e.g. \"mail.contact-sidebar.bottom\"). Apps drop ExtensionSlot components in their UI; this action registers an extension as installable into one of those slots. Slot IDs follow the convention <app>.<area>.<position>. Caller must have editor access to the extension.',\n parameters: {\n type: \"object\",\n properties: {\n extensionId: { type: \"string\", description: \"Extension id.\" },\n slotId: {\n type: \"string\",\n description:\n 'Slot identifier — e.g. \"mail.contact-sidebar.bottom\".',\n },\n config: {\n type: \"string\",\n description:\n \"Optional JSON string with slot-specific config (defaults, hints, etc.).\",\n },\n },\n required: [\"extensionId\", \"slotId\"],\n },\n },\n run: async (args) => {\n const extensionId = String(args?.extensionId ?? \"\").trim();\n const slotId = String(args?.slotId ?? \"\").trim();\n if (!extensionId) return \"Error: extensionId is required.\";\n if (!slotId) return \"Error: slotId is required.\";\n const row = await addExtensionSlotTarget(\n extensionId,\n slotId,\n args?.config ? String(args.config) : undefined,\n );\n return { ok: true, slot: row };\n },\n },\n\n \"install-extension\": {\n tool: {\n description:\n \"Install an extension as a widget in an extension-point slot for the current user. The extension must already declare the slot via add-extension-slot-target. Per-user installation — only affects the calling user's view. Use after creating an extension that targets a slot, or when the user asks to add an existing widget to a slot.\",\n parameters: {\n type: \"object\",\n properties: {\n extensionId: {\n type: \"string\",\n description: \"Extension id to install.\",\n },\n slotId: {\n type: \"string\",\n description:\n 'Slot identifier — e.g. \"mail.contact-sidebar.bottom\".',\n },\n position: {\n type: \"number\",\n description:\n \"Optional integer position within the slot (lower = earlier). Defaults to end.\",\n },\n config: {\n type: \"string\",\n description:\n \"Optional JSON string with per-install config (overrides, settings).\",\n },\n },\n required: [\"extensionId\", \"slotId\"],\n },\n },\n run: async (args) => {\n const extensionId = String(args?.extensionId ?? \"\").trim();\n const slotId = String(args?.slotId ?? \"\").trim();\n if (!extensionId) return \"Error: extensionId is required.\";\n if (!slotId) return \"Error: slotId is required.\";\n const position =\n args?.position !== undefined && args.position !== null\n ? Number(args.position)\n : undefined;\n const row = await installExtensionSlot(extensionId, slotId, {\n position: Number.isFinite(position as number) ? position : undefined,\n config: args?.config ? String(args.config) : undefined,\n });\n return { ok: true, install: row };\n },\n },\n\n \"uninstall-extension\": {\n tool: {\n description:\n \"Remove an extension from an extension-point slot for the current user. Does not delete the extension itself.\",\n parameters: {\n type: \"object\",\n properties: {\n extensionId: { type: \"string\", description: \"Extension id.\" },\n slotId: { type: \"string\", description: \"Slot identifier.\" },\n },\n required: [\"extensionId\", \"slotId\"],\n },\n },\n run: async (args) => {\n const extensionId = String(args?.extensionId ?? \"\").trim();\n const slotId = String(args?.slotId ?? \"\").trim();\n if (!extensionId) return \"Error: extensionId is required.\";\n if (!slotId) return \"Error: slotId is required.\";\n await uninstallExtensionSlot(extensionId, slotId);\n return { ok: true };\n },\n },\n\n \"list-extensions-for-slot\": {\n tool: {\n description:\n \"List extensions the current user has access to that declare a given extension-point slot. Use to discover what's available to install into a slot the user mentioned.\",\n parameters: {\n type: \"object\",\n properties: {\n slotId: { type: \"string\", description: \"Slot identifier.\" },\n },\n required: [\"slotId\"],\n },\n },\n run: async (args) => {\n const slotId = String(args?.slotId ?? \"\").trim();\n if (!slotId) return \"Error: slotId is required.\";\n return { extensions: await listExtensionsForSlot(slotId) };\n },\n readOnly: true,\n },\n\n \"list-extension-slots\": {\n tool: {\n description:\n \"List the extension-point slots a specific extension declares it can render in. Caller must have viewer access to the extension.\",\n parameters: {\n type: \"object\",\n properties: {\n extensionId: { type: \"string\", description: \"Extension id.\" },\n },\n required: [\"extensionId\"],\n },\n },\n run: async (args) => {\n const extensionId = String(args?.extensionId ?? \"\").trim();\n if (!extensionId) return \"Error: extensionId is required.\";\n return { slots: await listSlotsForExtension(extensionId) };\n },\n readOnly: true,\n },\n };\n}\n\nasync function summarizeExtension(\n row: ExtensionRow,\n hiddenIds: Set<string>,\n includeContent: boolean,\n) {\n const access = await resolveAccess(\"extension\", row.id).catch(() => null);\n return {\n id: row.id,\n name: row.name,\n description: row.description,\n icon: row.icon,\n ownerEmail: row.ownerEmail,\n visibility: row.visibility,\n role: access?.role ?? null,\n canEdit: access\n ? [\"owner\", \"admin\", \"editor\"].includes(access.role)\n : false,\n canDelete: access ? [\"owner\", \"admin\"].includes(access.role) : false,\n hidden: hiddenIds.has(row.id),\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n ...(includeContent ? { content: row.content } : {}),\n };\n}\n\nfunction summarizeDeletedExtension(row: ExtensionRow) {\n return {\n id: row.id,\n name: row.name,\n ownerEmail: row.ownerEmail,\n visibility: row.visibility,\n };\n}\n\nfunction coerceBoolean(value: unknown): boolean {\n return value === true || value === \"true\";\n}\n\nfunction coerceLimit(value: unknown): number {\n const limit = Number(value ?? 100);\n if (!Number.isFinite(limit)) return 100;\n return Math.min(Math.max(1, Math.floor(limit)), 500);\n}\n\nfunction parsePatches(value: unknown): ExtensionPatch[] | undefined {\n if (value === undefined) return undefined;\n const parsed = typeof value === \"string\" ? JSON.parse(value) : value;\n if (!Array.isArray(parsed)) return undefined;\n if (\n parsed.some(\n (patch) =>\n !patch ||\n typeof patch.find !== \"string\" ||\n typeof patch.replace !== \"string\",\n )\n ) {\n return undefined;\n }\n return parsed;\n}\n"]}
1
+ {"version":3,"file":"actions.js","sourceRoot":"","sources":["../../src/extensions/actions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAC;AACvE,OAAO,EACL,eAAe,EACf,eAAe,EACf,mCAAmC,EACnC,YAAY,EACZ,aA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AAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACrE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IAC7C,IACE,MAAM,CAAC,IAAI,CACT,CAAC,KAAK,EAAE,EAAE,CACR,CAAC,KAAK;QACN,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CACpC,EACD,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { ActionEntry } from \"../agent/production-agent.js\";\nimport { writeAppState } from \"../application-state/script-helpers.js\";\nimport {\n createExtension,\n deleteExtension,\n getHiddenExtensionIdsForCurrentUser,\n getExtension,\n hideExtension,\n listExtensions,\n unhideExtension,\n updateExtension,\n updateExtensionContent,\n type ExtensionRow,\n} from \"./store.js\";\nimport { resolveAccess } from \"../sharing/access.js\";\nimport {\n addExtensionSlotTarget,\n installExtensionSlot,\n uninstallExtensionSlot,\n listExtensionsForSlot,\n listSlotsForExtension,\n} from \"./slots/store.js\";\n\ntype ExtensionPatch = { find: string; replace: string };\n\nexport function createExtensionActionEntries(): Record<string, ActionEntry> {\n return {\n \"list-extensions\": {\n tool: {\n description:\n \"List extensions visible in the current user's Extensions list/sidebar. Use this before updating, hiding, or deleting existing extensions; do not query the legacy tools table directly for extension management.\",\n parameters: {\n type: \"object\",\n properties: {\n search: {\n type: \"string\",\n description:\n \"Optional case-insensitive filter matched against id, name, description, and owner email. Example: Connect Zoom.\",\n },\n includeHidden: {\n type: \"boolean\",\n description:\n \"Include extensions the current user has hidden from their list. Defaults to false.\",\n },\n includeContent: {\n type: \"boolean\",\n description:\n \"Include full Alpine.js content. Defaults to false to keep results concise.\",\n },\n limit: {\n type: \"number\",\n description: \"Maximum results to return. Defaults to 100.\",\n },\n },\n },\n },\n run: async (args) => {\n const includeHidden = coerceBoolean(args?.includeHidden);\n const includeContent = coerceBoolean(args?.includeContent);\n const search = String(args?.search ?? \"\")\n .trim()\n .toLowerCase();\n const limit = coerceLimit(args?.limit);\n const hiddenIds = await getHiddenExtensionIdsForCurrentUser();\n\n let rows = await listExtensions({ includeHidden });\n if (search) {\n rows = rows.filter((row) =>\n [row.id, row.name, row.description, row.ownerEmail]\n .join(\"\\n\")\n .toLowerCase()\n .includes(search),\n );\n }\n\n rows = rows.slice(0, limit);\n const extensions = await Promise.all(\n rows.map((row) => summarizeExtension(row, hiddenIds, includeContent)),\n );\n return {\n ok: true,\n count: extensions.length,\n extensions,\n };\n },\n readOnly: true,\n },\n\n \"create-extension\": {\n tool: {\n description:\n \"Create a sandboxed Alpine.js mini-app extension. Use this when the user asks to create, build, or make an extension/widget/dashboard/calculator. Call this action exactly once per requested extension. The content must be a self-contained Alpine.js HTML body snippet that can use appAction(), appFetch(), dbQuery(), dbExec(), extensionFetch(), and extensionData. Prefer appAction(name, params) for app data and actions, including read actions mounted as GET; do not call template /api/* routes from appFetch because the extension bridge only allows framework /_agent-native/* paths. Parse JSON string action results before aggregating; use dbQuery()/dbExec() only for known existing SQL tables.\",\n parameters: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description:\n 'Short display name for the extension. Do not include \"app\" — e.g. name a todo app \"Todos\", a weather app \"Weather\".',\n },\n description: {\n type: \"string\",\n description: \"One-sentence summary of what the extension does.\",\n },\n content: {\n type: \"string\",\n description:\n \"Self-contained Alpine.js HTML body snippet. The iframe canvas already has modest default padding, so avoid duplicate outer padding unless the design needs it. Use semantic Tailwind colors (bg-background, text-foreground, bg-primary, etc.) for native theming. Do not include a full app build, React code, or source files.\",\n },\n icon: {\n type: \"string\",\n description: \"Optional icon name or short label.\",\n },\n },\n required: [\"name\", \"content\"],\n },\n },\n run: async (args) => {\n const name = String(args?.name ?? \"\").trim();\n const content = String(args?.content ?? \"\").trim();\n if (!name) return \"Error: name is required.\";\n if (!content) return \"Error: content is required.\";\n\n const extension = await createExtension({\n name,\n description: String(args?.description ?? \"\").trim(),\n content,\n icon: args?.icon ? String(args.icon) : undefined,\n });\n\n // Auto-navigate so the user lands on the new extension instead of\n // having to read the JSON response and click a link. Writes a\n // one-shot `navigate` app-state command the UI consumes and clears.\n try {\n await writeAppState(\"navigate\", {\n view: \"extensions\",\n extensionId: extension.id,\n path: `/extensions/${extension.id}`,\n });\n } catch {\n // Non-fatal — agent can still mention the path in its reply.\n }\n\n return {\n ok: true,\n extension,\n next: `Created. The user is being navigated to the new extension automatically — no further navigation tool calls needed.`,\n };\n },\n },\n\n \"update-extension\": {\n tool: {\n description:\n \"Update an existing sandboxed Alpine.js mini-app extension. Prefer patches for surgical edits; use full content replacement only when necessary.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Extension id to update.\",\n },\n name: {\n type: \"string\",\n description: \"Optional new display name.\",\n },\n description: {\n type: \"string\",\n description: \"Optional new description.\",\n },\n content: {\n type: \"string\",\n description:\n \"Optional full replacement Alpine.js HTML body snippet.\",\n },\n patches: {\n type: \"string\",\n description:\n 'Optional JSON array of { \"find\": \"...\", \"replace\": \"...\" } patches to apply to the current content.',\n },\n icon: {\n type: \"string\",\n description: \"Optional icon name or short label.\",\n },\n visibility: {\n type: \"string\",\n description: \"Optional sharing visibility.\",\n enum: [\"private\", \"org\", \"public\"],\n },\n },\n required: [\"id\"],\n },\n },\n run: async (args) => {\n const id = String(args?.id ?? \"\").trim();\n if (!id) return \"Error: id is required.\";\n\n let result = null;\n if (args?.content !== undefined || args?.patches !== undefined) {\n const patches = parsePatches((args as any).patches);\n if (args?.patches !== undefined && !patches) {\n return \"Error: patches must be a JSON array of { find, replace } objects.\";\n }\n result = await updateExtensionContent(id, {\n content:\n args?.content !== undefined ? String(args.content) : undefined,\n patches,\n });\n }\n\n const meta: Record<string, string> = {};\n if (args?.name !== undefined) meta.name = String(args.name).trim();\n if (args?.description !== undefined) {\n meta.description = String(args.description).trim();\n }\n if (args?.icon !== undefined) meta.icon = String(args.icon);\n if (args?.visibility !== undefined) {\n meta.visibility = String(args.visibility);\n }\n if (Object.keys(meta).length > 0) {\n result = await updateExtension(id, meta as any);\n }\n\n if (!result) result = await getExtension(id);\n if (!result) return `Error: extension not found: ${id}`;\n const hiddenIds = await getHiddenExtensionIdsForCurrentUser();\n return {\n ok: true,\n extension: await summarizeExtension(result, hiddenIds, false),\n };\n },\n },\n\n \"delete-extension\": {\n tool: {\n description:\n \"Permanently delete an extension everywhere it is shared. Requires owner/admin access. If the user only wants a shared extension removed from their own sidebar/list, use hide-extension instead.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description:\n \"Extension id to permanently delete. Use list-extensions first if you only know the display name.\",\n },\n },\n required: [\"id\"],\n },\n },\n run: async (args) => {\n const id = String(args?.id ?? \"\").trim();\n if (!id) return \"Error: id is required.\";\n const extension = await getExtension(id);\n if (!extension) return `Error: extension not found: ${id}`;\n\n try {\n const ok = await deleteExtension(id);\n if (!ok) return `Error: extension not found: ${id}`;\n return { ok: true, deleted: summarizeDeletedExtension(extension) };\n } catch (err: any) {\n return {\n ok: false,\n error: err?.message ?? String(err),\n next: \"If the user wants this gone only from their own view, call hide-extension with the same id.\",\n };\n }\n },\n },\n\n \"hide-extension\": {\n tool: {\n description:\n \"Hide an accessible extension from the current user's Extensions list/sidebar without deleting it for anyone else. Use this when the user says to remove a shared extension from their view, or when delete-extension reports that the current user is not owner/admin.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description:\n \"Extension id to hide for the current user. Use list-extensions first if you only know the display name.\",\n },\n },\n required: [\"id\"],\n },\n },\n run: async (args) => {\n const id = String(args?.id ?? \"\").trim();\n if (!id) return \"Error: id is required.\";\n const extension = await getExtension(id);\n if (!extension) return `Error: extension not found: ${id}`;\n\n await hideExtension(id);\n return { ok: true, hidden: summarizeDeletedExtension(extension) };\n },\n },\n\n \"unhide-extension\": {\n tool: {\n description:\n \"Restore an extension the current user previously hid so it appears in their Extensions list/sidebar again. Use list-extensions with includeHidden=true to find hidden ids.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Extension id to restore for the current user.\",\n },\n },\n required: [\"id\"],\n },\n },\n run: async (args) => {\n const id = String(args?.id ?? \"\").trim();\n if (!id) return \"Error: id is required.\";\n await unhideExtension(id);\n return { ok: true, id };\n },\n },\n\n \"add-extension-slot-target\": {\n tool: {\n description:\n 'Declare that an extension can render in a UI extension-point slot of an app (e.g. \"mail.contact-sidebar.bottom\"). Apps drop ExtensionSlot components in their UI; this action registers an extension as installable into one of those slots. Slot IDs follow the convention <app>.<area>.<position>. Caller must have editor access to the extension.',\n parameters: {\n type: \"object\",\n properties: {\n extensionId: { type: \"string\", description: \"Extension id.\" },\n slotId: {\n type: \"string\",\n description:\n 'Slot identifier — e.g. \"mail.contact-sidebar.bottom\".',\n },\n config: {\n type: \"string\",\n description:\n \"Optional JSON string with slot-specific config (defaults, hints, etc.).\",\n },\n },\n required: [\"extensionId\", \"slotId\"],\n },\n },\n run: async (args) => {\n const extensionId = String(args?.extensionId ?? \"\").trim();\n const slotId = String(args?.slotId ?? \"\").trim();\n if (!extensionId) return \"Error: extensionId is required.\";\n if (!slotId) return \"Error: slotId is required.\";\n const row = await addExtensionSlotTarget(\n extensionId,\n slotId,\n args?.config ? String(args.config) : undefined,\n );\n return { ok: true, slot: row };\n },\n },\n\n \"install-extension\": {\n tool: {\n description:\n \"Install an extension as a widget in an extension-point slot for the current user. The extension must already declare the slot via add-extension-slot-target. Per-user installation — only affects the calling user's view. Use after creating an extension that targets a slot, or when the user asks to add an existing widget to a slot.\",\n parameters: {\n type: \"object\",\n properties: {\n extensionId: {\n type: \"string\",\n description: \"Extension id to install.\",\n },\n slotId: {\n type: \"string\",\n description:\n 'Slot identifier — e.g. \"mail.contact-sidebar.bottom\".',\n },\n position: {\n type: \"number\",\n description:\n \"Optional integer position within the slot (lower = earlier). Defaults to end.\",\n },\n config: {\n type: \"string\",\n description:\n \"Optional JSON string with per-install config (overrides, settings).\",\n },\n },\n required: [\"extensionId\", \"slotId\"],\n },\n },\n run: async (args) => {\n const extensionId = String(args?.extensionId ?? \"\").trim();\n const slotId = String(args?.slotId ?? \"\").trim();\n if (!extensionId) return \"Error: extensionId is required.\";\n if (!slotId) return \"Error: slotId is required.\";\n const position =\n args?.position !== undefined && args.position !== null\n ? Number(args.position)\n : undefined;\n const row = await installExtensionSlot(extensionId, slotId, {\n position: Number.isFinite(position as number) ? position : undefined,\n config: args?.config ? String(args.config) : undefined,\n });\n return { ok: true, install: row };\n },\n },\n\n \"uninstall-extension\": {\n tool: {\n description:\n \"Remove an extension from an extension-point slot for the current user. Does not delete the extension itself.\",\n parameters: {\n type: \"object\",\n properties: {\n extensionId: { type: \"string\", description: \"Extension id.\" },\n slotId: { type: \"string\", description: \"Slot identifier.\" },\n },\n required: [\"extensionId\", \"slotId\"],\n },\n },\n run: async (args) => {\n const extensionId = String(args?.extensionId ?? \"\").trim();\n const slotId = String(args?.slotId ?? \"\").trim();\n if (!extensionId) return \"Error: extensionId is required.\";\n if (!slotId) return \"Error: slotId is required.\";\n await uninstallExtensionSlot(extensionId, slotId);\n return { ok: true };\n },\n },\n\n \"list-extensions-for-slot\": {\n tool: {\n description:\n \"List extensions the current user has access to that declare a given extension-point slot. Use to discover what's available to install into a slot the user mentioned.\",\n parameters: {\n type: \"object\",\n properties: {\n slotId: { type: \"string\", description: \"Slot identifier.\" },\n },\n required: [\"slotId\"],\n },\n },\n run: async (args) => {\n const slotId = String(args?.slotId ?? \"\").trim();\n if (!slotId) return \"Error: slotId is required.\";\n return { extensions: await listExtensionsForSlot(slotId) };\n },\n readOnly: true,\n },\n\n \"list-extension-slots\": {\n tool: {\n description:\n \"List the extension-point slots a specific extension declares it can render in. Caller must have viewer access to the extension.\",\n parameters: {\n type: \"object\",\n properties: {\n extensionId: { type: \"string\", description: \"Extension id.\" },\n },\n required: [\"extensionId\"],\n },\n },\n run: async (args) => {\n const extensionId = String(args?.extensionId ?? \"\").trim();\n if (!extensionId) return \"Error: extensionId is required.\";\n return { slots: await listSlotsForExtension(extensionId) };\n },\n readOnly: true,\n },\n };\n}\n\nasync function summarizeExtension(\n row: ExtensionRow,\n hiddenIds: Set<string>,\n includeContent: boolean,\n) {\n const access = await resolveAccess(\"extension\", row.id).catch(() => null);\n return {\n id: row.id,\n name: row.name,\n description: row.description,\n icon: row.icon,\n ownerEmail: row.ownerEmail,\n visibility: row.visibility,\n role: access?.role ?? null,\n canEdit: access\n ? [\"owner\", \"admin\", \"editor\"].includes(access.role)\n : false,\n canDelete: access ? [\"owner\", \"admin\"].includes(access.role) : false,\n hidden: hiddenIds.has(row.id),\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n ...(includeContent ? { content: row.content } : {}),\n };\n}\n\nfunction summarizeDeletedExtension(row: ExtensionRow) {\n return {\n id: row.id,\n name: row.name,\n ownerEmail: row.ownerEmail,\n visibility: row.visibility,\n };\n}\n\nfunction coerceBoolean(value: unknown): boolean {\n return value === true || value === \"true\";\n}\n\nfunction coerceLimit(value: unknown): number {\n const limit = Number(value ?? 100);\n if (!Number.isFinite(limit)) return 100;\n return Math.min(Math.max(1, Math.floor(limit)), 500);\n}\n\nfunction parsePatches(value: unknown): ExtensionPatch[] | undefined {\n if (value === undefined) return undefined;\n const parsed = typeof value === \"string\" ? JSON.parse(value) : value;\n if (!Array.isArray(parsed)) return undefined;\n if (\n parsed.some(\n (patch) =>\n !patch ||\n typeof patch.find !== \"string\" ||\n typeof patch.replace !== \"string\",\n )\n ) {\n return undefined;\n }\n return parsed;\n}\n"]}
@@ -48,7 +48,7 @@ export const tool = {
48
48
  description: "Call a DIFFERENT, separately-deployed agent app to ask a question or delegate a task. This is strictly for cross-app A2A communication — for example, asking the mail agent to send an email while you are the calendar agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. " +
49
49
  "IMPORTANT — handling the response: " +
50
50
  "(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. " +
51
- '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. "the agent created the deck but didn\'t return a link — open the app directly to view it"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +
51
+ '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. "the agent created the deck/image but didn\'t return a link — open the app directly to view it"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +
52
52
  "(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured.",
53
53
  parameters: {
54
54
  type: "object",
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL,SAAS,EACT,mBAAmB,EACnB,SAAS,EACT,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAC5F,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAElE,MAAM,6CAA6C,GAAG,MAAM,CAAC;AAC7D,MAAM,kCAAkC,GAAG,KAAK,CAAC;AACjD,MAAM,yBAAyB,GAAG,KAAK,CAAC;AAExC,SAAS,cAAc,CAAC,KAAyB;IAC/C,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,MAAM,MAAM,GAA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G,CAAC,CAAC;IACvD,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,4CAA4C;AAC5C,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,qDAAqD,EACrD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionTool } from \"../agent/types.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport { createHash } from \"node:crypto\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n A2AClient,\n A2ATaskTimeoutError,\n callAgent,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s. Keep delegated\n // calls very short so multi-agent integration requests queue downstream\n // continuations quickly instead of spending the parent Slack/email processor\n // budget waiting on separately deployed apps one-by-one.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Call a DIFFERENT, separately-deployed agent app to ask a question or delegate a task. This is strictly for cross-app A2A communication — for example, asking the mail agent to send an email while you are the calendar agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +\n \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured.\",\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description: \"The message/question to send to the other agent\",\n },\n },\n required: [\"agent\", \"message\"],\n },\n};\n\nexport async function run(\n args: Record<string, string>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const { agent: agentIdOrName, message } = args;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message) return \"Error: --message is required\";\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const messageWithHint =\n `${message}\\n\\n` +\n `[Note: this request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts.]`;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: !callerOrgSecret,\n },\n );\n } catch {}\n }\n\n const client = new A2AClient(agent.url, apiKey);\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n const existingContinuationText =\n await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) return existingContinuationText;\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is we lose progressive in-UI text streaming for cross-app\n // A2A calls, but the receiving agent's full response still surfaces via\n // the tool_result event below.\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n ...(callTimeoutMs ? { timeoutMs: callTimeoutMs } : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n const timeoutTaskId = getA2ATaskTimeoutTaskId(pollErr);\n if (timeoutTaskId) {\n const queued = await enqueueIntegrationContinuationIfPossible(\n timeoutTaskId,\n agent,\n message,\n callerEmail,\n );\n if (queued) {\n responseText =\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent accepted this delegated subtask and will post its own final result to the originating integration thread automatically. ` +\n `Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting its result separately.`;\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n });\n\n return responseText || \"(empty response)\";\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n return expandRelativeUrls(sanitized, agent.url) || \"(empty response)\";\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\n }\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n taskId: string,\n agent: { name: string; url: string },\n message: string,\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n dedupeKey: getIntegrationContinuationDedupeKey(message),\n a2aTaskId: taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\nfunction getA2ATaskTimeoutTaskId(err: unknown): string | null {\n if (err instanceof A2ATaskTimeoutError) return err.taskId;\n\n const candidate = err as\n | { name?: unknown; taskId?: unknown; message?: unknown }\n | null\n | undefined;\n const message = String(candidate?.message ?? \"\");\n if (\n candidate?.name === \"A2ATaskTimeoutError\" &&\n typeof candidate.taskId === \"string\"\n ) {\n return candidate.taskId;\n }\n\n const match = message.match(/^A2A task ([^\\s]+) did not complete\\b/);\n return match?.[1] ?? null;\n}\n\nasync function formatExistingIntegrationContinuationIfRetry(\n agent: {\n name: string;\n url: string;\n },\n message: string,\n): Promise<string | null> {\n const integration = getIntegrationRequestContext();\n if (!integration || (integration.attempts ?? 1) <= 1) return null;\n\n try {\n const { getA2AContinuationsForIntegrationTaskAgent } =\n await import(\"../integrations/a2a-continuations-store.js\");\n const continuations = await getA2AContinuationsForIntegrationTaskAgent(\n integration.taskId,\n agent.url,\n getIntegrationContinuationDedupeKey(message),\n );\n const active = continuations.find((continuation) =>\n [\"pending\", \"processing\", \"delivering\", \"completed\"].includes(\n continuation.status,\n ),\n );\n if (!active) return null;\n\n const state =\n active.status === \"completed\"\n ? \"already completed this delegated subtask and posted its result to the originating integration thread\"\n : \"already accepted this delegated subtask and is still working on it for the originating integration thread\";\n return (\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent ${state}. Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting or has posted its result separately.`\n );\n } catch (err) {\n console.error(\"[call-agent] Failed to inspect existing continuation:\", err);\n return null;\n }\n}\n\nfunction getIntegrationContinuationDedupeKey(message: string): string {\n const normalized = message.trim().replace(/\\s+/g, \" \");\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s(\\[<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
1
+ {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL,SAAS,EACT,mBAAmB,EACnB,SAAS,EACT,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAC5F,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,0BAA0B,EAC1B,4B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AAI,6IAA6I,KAAK,CAAC,IAAI,kDAAkD,CACrQ,CAAC;IACJ,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,uDAAuD,EAAE,GAAG,CAAC,CAAC;QAC5E,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,mCAAmC,CAAC,OAAe;IAC1D,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACvD,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,4CAA4C;AAC5C,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,qDAAqD,EACrD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionTool } from \"../agent/types.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport { createHash } from \"node:crypto\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n A2AClient,\n A2ATaskTimeoutError,\n callAgent,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s. Keep delegated\n // calls very short so multi-agent integration requests queue downstream\n // continuations quickly instead of spending the parent Slack/email processor\n // budget waiting on separately deployed apps one-by-one.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Call a DIFFERENT, separately-deployed agent app to ask a question or delegate a task. This is strictly for cross-app A2A communication — for example, asking the mail agent to send an email while you are the calendar agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck/image but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +\n \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured.\",\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description: \"The message/question to send to the other agent\",\n },\n },\n required: [\"agent\", \"message\"],\n },\n};\n\nexport async function run(\n args: Record<string, string>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const { agent: agentIdOrName, message } = args;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message) return \"Error: --message is required\";\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const messageWithHint =\n `${message}\\n\\n` +\n `[Note: this request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts.]`;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: !callerOrgSecret,\n },\n );\n } catch {}\n }\n\n const client = new A2AClient(agent.url, apiKey);\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n const existingContinuationText =\n await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) return existingContinuationText;\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is we lose progressive in-UI text streaming for cross-app\n // A2A calls, but the receiving agent's full response still surfaces via\n // the tool_result event below.\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n ...(callTimeoutMs ? { timeoutMs: callTimeoutMs } : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n const timeoutTaskId = getA2ATaskTimeoutTaskId(pollErr);\n if (timeoutTaskId) {\n const queued = await enqueueIntegrationContinuationIfPossible(\n timeoutTaskId,\n agent,\n message,\n callerEmail,\n );\n if (queued) {\n responseText =\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent accepted this delegated subtask and will post its own final result to the originating integration thread automatically. ` +\n `Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting its result separately.`;\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n });\n\n return responseText || \"(empty response)\";\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n return expandRelativeUrls(sanitized, agent.url) || \"(empty response)\";\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\n }\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n taskId: string,\n agent: { name: string; url: string },\n message: string,\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n dedupeKey: getIntegrationContinuationDedupeKey(message),\n a2aTaskId: taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\nfunction getA2ATaskTimeoutTaskId(err: unknown): string | null {\n if (err instanceof A2ATaskTimeoutError) return err.taskId;\n\n const candidate = err as\n | { name?: unknown; taskId?: unknown; message?: unknown }\n | null\n | undefined;\n const message = String(candidate?.message ?? \"\");\n if (\n candidate?.name === \"A2ATaskTimeoutError\" &&\n typeof candidate.taskId === \"string\"\n ) {\n return candidate.taskId;\n }\n\n const match = message.match(/^A2A task ([^\\s]+) did not complete\\b/);\n return match?.[1] ?? null;\n}\n\nasync function formatExistingIntegrationContinuationIfRetry(\n agent: {\n name: string;\n url: string;\n },\n message: string,\n): Promise<string | null> {\n const integration = getIntegrationRequestContext();\n if (!integration || (integration.attempts ?? 1) <= 1) return null;\n\n try {\n const { getA2AContinuationsForIntegrationTaskAgent } =\n await import(\"../integrations/a2a-continuations-store.js\");\n const continuations = await getA2AContinuationsForIntegrationTaskAgent(\n integration.taskId,\n agent.url,\n getIntegrationContinuationDedupeKey(message),\n );\n const active = continuations.find((continuation) =>\n [\"pending\", \"processing\", \"delivering\", \"completed\"].includes(\n continuation.status,\n ),\n );\n if (!active) return null;\n\n const state =\n active.status === \"completed\"\n ? \"already completed this delegated subtask and posted its result to the originating integration thread\"\n : \"already accepted this delegated subtask and is still working on it for the originating integration thread\";\n return (\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent ${state}. Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting or has posted its result separately.`\n );\n } catch (err) {\n console.error(\"[call-agent] Failed to inspect existing continuation:\", err);\n return null;\n }\n}\n\nfunction getIntegrationContinuationDedupeKey(message: string): string {\n const normalized = message.trim().replace(/\\s+/g, \" \");\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s(\\[<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-chat-plugin.d.ts","sourceRoot":"","sources":["../../src/server/agent-chat-plugin.ts"],"names":[],"mappings":"AAaA,OAAO,EAUL,KAAK,WAAW,EAC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