@agent-native/core 0.84.57 → 0.84.58
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.
- package/corpus/README.md +1 -1
- package/corpus/core/CHANGELOG.md +8 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/action.ts +11 -0
- package/corpus/core/src/agent/production-agent.ts +24 -46
- package/corpus/core/src/client/AssistantChat.tsx +69 -12
- package/corpus/core/src/client/MultiTabAssistantChat.tsx +1 -1
- package/corpus/core/src/client/conversation/use-near-bottom-autoscroll.ts +45 -2
- package/corpus/core/src/coding-tools/run-code.ts +1 -0
- package/corpus/core/src/integrations/webhook-handler.ts +10 -9
- package/corpus/core/src/server/action-discovery.ts +3 -0
- package/corpus/core/src/server/credential-provider.ts +11 -6
- package/corpus/templates/analytics/server/lib/agent-chat-plan-mode.ts +29 -0
- package/corpus/templates/analytics/server/plugins/agent-chat.ts +9 -1
- package/corpus/templates/design/actions/list-design-extensions.ts +2 -2
- package/corpus/templates/design/app/components/design/CodeWorkbenchHost.tsx +11 -89
- package/corpus/templates/design/app/components/design/DesignExtensionsPanel.tsx +314 -181
- package/corpus/templates/design/app/components/design/DesignImportPanel.tsx +92 -134
- package/corpus/templates/design/app/components/design/EditPanel.tsx +93 -19
- package/corpus/templates/design/app/components/design/MultiScreenCanvas.tsx +18 -26
- package/corpus/templates/design/app/components/design/TokensPanel.tsx +220 -192
- package/corpus/templates/design/app/components/design/code-workbench-theme.ts +150 -0
- package/corpus/templates/design/app/i18n/zh-TW.ts +5 -7
- package/corpus/templates/design/app/i18n-data.ts +61 -77
- package/corpus/templates/design/app/lib/design-import.ts +4 -1
- package/corpus/templates/design/app/pages/DesignEditor.tsx +97 -48
- package/corpus/templates/design/changelog/2026-07-02-design-inspector-and-canvas-controls-stay-consistent-when-se.md +6 -0
- package/corpus/templates/design/changelog/2026-07-02-fixed-a-crash-when-opening-the-code-editor.md +6 -0
- package/corpus/templates/design/changelog/2026-07-02-fixed-motion-drawer-open-transition.md +6 -0
- package/corpus/templates/design/changelog/2026-07-02-improved-design-assets-panel.md +6 -0
- package/dist/action.d.ts +8 -0
- package/dist/action.d.ts.map +1 -1
- package/dist/action.js +3 -0
- package/dist/action.js.map +1 -1
- package/dist/agent/production-agent.d.ts +10 -11
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +21 -44
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/client/AssistantChat.d.ts +1 -0
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +61 -11
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/MultiTabAssistantChat.js +1 -1
- package/dist/client/MultiTabAssistantChat.js.map +1 -1
- package/dist/client/conversation/use-near-bottom-autoscroll.d.ts.map +1 -1
- package/dist/client/conversation/use-near-bottom-autoscroll.js +43 -2
- package/dist/client/conversation/use-near-bottom-autoscroll.js.map +1 -1
- package/dist/coding-tools/run-code.d.ts.map +1 -1
- package/dist/coding-tools/run-code.js +1 -0
- package/dist/coding-tools/run-code.js.map +1 -1
- package/dist/collab/awareness.d.ts +2 -2
- package/dist/collab/awareness.d.ts.map +1 -1
- package/dist/collab/routes.d.ts +1 -1
- package/dist/file-upload/actions/upload-image.d.ts +2 -2
- package/dist/integrations/webhook-handler.d.ts +1 -0
- package/dist/integrations/webhook-handler.d.ts.map +1 -1
- package/dist/integrations/webhook-handler.js +9 -9
- package/dist/integrations/webhook-handler.js.map +1 -1
- package/dist/notifications/routes.d.ts +3 -3
- package/dist/observability/routes.d.ts +5 -5
- package/dist/server/action-discovery.d.ts.map +1 -1
- package/dist/server/action-discovery.js +3 -0
- package/dist/server/action-discovery.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/credential-provider.d.ts +4 -0
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +13 -7
- package/dist/server/credential-provider.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-near-bottom-autoscroll.d.ts","sourceRoot":"","sources":["../../../src/client/conversation/use-near-bottom-autoscroll.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,8BAA8B;IAC7C,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;
|
|
1
|
+
{"version":3,"file":"use-near-bottom-autoscroll.d.ts","sourceRoot":"","sources":["../../../src/client/conversation/use-near-bottom-autoscroll.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,8BAA8B;IAC7C,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAqCD,wBAAgB,uBAAuB,CAAC,QAAQ,SAAS,WAAW,EAAE,EACpE,SAAS,EACT,SAAiB,EACjB,SAAa,EACb,OAAc,GACf,EAAE,8BAA8B;;;;;;;EA6NhC"}
|
|
@@ -1,4 +1,35 @@
|
|
|
1
1
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
function eventElementTarget(event) {
|
|
3
|
+
const target = event.target;
|
|
4
|
+
if (!(target instanceof Node))
|
|
5
|
+
return null;
|
|
6
|
+
if (target instanceof HTMLElement)
|
|
7
|
+
return target;
|
|
8
|
+
return target.parentElement;
|
|
9
|
+
}
|
|
10
|
+
function canScrollElementVertically(element, deltaY) {
|
|
11
|
+
if (element.scrollHeight <= element.clientHeight)
|
|
12
|
+
return false;
|
|
13
|
+
const style = window.getComputedStyle(element);
|
|
14
|
+
const overflowY = style.overflowY || style.overflow;
|
|
15
|
+
if (!/(auto|scroll|overlay)/.test(overflowY))
|
|
16
|
+
return false;
|
|
17
|
+
if (deltaY < 0)
|
|
18
|
+
return element.scrollTop > 0;
|
|
19
|
+
if (deltaY > 0) {
|
|
20
|
+
return element.scrollTop + element.clientHeight < element.scrollHeight - 1;
|
|
21
|
+
}
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
function nestedScrollableConsumesVerticalIntent(event, root, deltaY) {
|
|
25
|
+
let element = eventElementTarget(event);
|
|
26
|
+
while (element && element !== root) {
|
|
27
|
+
if (canScrollElementVertically(element, deltaY))
|
|
28
|
+
return true;
|
|
29
|
+
element = element.parentElement;
|
|
30
|
+
}
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
2
33
|
export function useNearBottomAutoscroll({ followKey, streaming = false, threshold = 4, enabled = true, }) {
|
|
3
34
|
const scrollRef = useRef(null);
|
|
4
35
|
const isNearBottomRef = useRef(true);
|
|
@@ -55,6 +86,9 @@ export function useNearBottomAutoscroll({ followKey, streaming = false, threshol
|
|
|
55
86
|
lastScrollTopRef.current = el.scrollTop;
|
|
56
87
|
let lastScrollHeight = el.scrollHeight;
|
|
57
88
|
const onWheel = (event) => {
|
|
89
|
+
if (nestedScrollableConsumesVerticalIntent(event, el, event.deltaY)) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
58
92
|
if (event.deltaY < 0)
|
|
59
93
|
detachFromBottom();
|
|
60
94
|
};
|
|
@@ -67,14 +101,19 @@ export function useNearBottomAutoscroll({ followKey, streaming = false, threshol
|
|
|
67
101
|
return;
|
|
68
102
|
const lastTouchY = lastTouchYRef.current;
|
|
69
103
|
if (lastTouchY != null && nextTouchY > lastTouchY) {
|
|
70
|
-
|
|
104
|
+
const deltaY = lastTouchY - nextTouchY;
|
|
105
|
+
if (!nestedScrollableConsumesVerticalIntent(event, el, deltaY)) {
|
|
106
|
+
detachFromBottom();
|
|
107
|
+
}
|
|
71
108
|
}
|
|
72
109
|
lastTouchYRef.current = nextTouchY;
|
|
73
110
|
};
|
|
74
111
|
const onTouchEnd = () => {
|
|
75
112
|
lastTouchYRef.current = null;
|
|
76
113
|
};
|
|
77
|
-
const onScroll = () => {
|
|
114
|
+
const onScroll = (event) => {
|
|
115
|
+
if (event.target !== el)
|
|
116
|
+
return;
|
|
78
117
|
const previousScrollTop = lastScrollTopRef.current;
|
|
79
118
|
const nextScrollTop = el.scrollTop;
|
|
80
119
|
const nextScrollHeight = el.scrollHeight;
|
|
@@ -101,6 +140,8 @@ export function useNearBottomAutoscroll({ followKey, streaming = false, threshol
|
|
|
101
140
|
event.key === "PageUp" ||
|
|
102
141
|
event.key === "Home" ||
|
|
103
142
|
(event.key === " " && event.shiftKey)) {
|
|
143
|
+
if (nestedScrollableConsumesVerticalIntent(event, el, -1))
|
|
144
|
+
return;
|
|
104
145
|
detachFromBottom();
|
|
105
146
|
}
|
|
106
147
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-near-bottom-autoscroll.js","sourceRoot":"","sources":["../../../src/client/conversation/use-near-bottom-autoscroll.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AASjE,MAAM,UAAU,uBAAuB,CAA+B,EACpE,SAAS,EACT,SAAS,GAAG,KAAK,EACjB,SAAS,GAAG,CAAC,EACb,OAAO,GAAG,IAAI,GACiB;IAC/B,MAAM,SAAS,GAAG,MAAM,CAAkB,IAAI,CAAC,CAAC;IAChD,MAAM,eAAe,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IACrC,MAAM,mBAAmB,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;IACtC,MAAM,gBAAgB,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;IACnC,MAAM,aAAa,GAAG,MAAM,CAAgB,IAAI,CAAC,CAAC;IAClD,MAAM,CAAC,kBAAkB,EAAE,qBAAqB,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAEpE,MAAM,UAAU,GAAG,WAAW,CAC5B,CAAC,EAAe,EAAE,EAAE,CAClB,EAAE,CAAC,YA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AAE,SAAS,EAAE,wBAAwB,CAAC,CAAC,CAAC;IAEnD,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,CAAC,OAAO,IAAI,CAAC,SAAS;YAAE,OAAO;QACnC,MAAM,EAAE,GAAG,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE;YACjC,yBAAyB,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;QACzD,CAAC,EAAE,GAAG,CAAC,CAAC;QACR,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;IACxC,CAAC,EAAE,CAAC,OAAO,EAAE,yBAAyB,EAAE,SAAS,CAAC,CAAC,CAAC;IAEpD,OAAO;QACL,SAAS;QACT,eAAe;QACf,kBAAkB;QAClB,cAAc;QACd,cAAc;QACd,wBAAwB;KACzB,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseNearBottomAutoscrollOptions {\n followKey: unknown;\n streaming?: boolean;\n threshold?: number;\n enabled?: boolean;\n}\n\nexport function useNearBottomAutoscroll<TElement extends HTMLElement>({\n followKey,\n streaming = false,\n threshold = 4,\n enabled = true,\n}: UseNearBottomAutoscrollOptions) {\n const scrollRef = useRef<TElement | null>(null);\n const isNearBottomRef = useRef(true);\n const followGenerationRef = useRef(0);\n const lastScrollTopRef = useRef(0);\n const lastTouchYRef = useRef<number | null>(null);\n const [showScrollToBottom, setShowScrollToBottom] = useState(false);\n\n const isAtBottom = useCallback(\n (el: HTMLElement) =>\n el.scrollHeight - el.scrollTop - el.clientHeight <= threshold,\n [threshold],\n );\n\n const setFollowingBottom = useCallback(\n (following: boolean, forceGeneration = false, el?: HTMLElement) => {\n if (forceGeneration || isNearBottomRef.current !== following) {\n followGenerationRef.current += 1;\n }\n isNearBottomRef.current = following;\n const canScroll = !el || el.scrollHeight > el.clientHeight + threshold;\n setShowScrollToBottom(!following && canScroll);\n },\n [threshold],\n );\n\n const detachFromBottom = useCallback(() => {\n setFollowingBottom(false, true, scrollRef.current ?? undefined);\n }, [setFollowingBottom]);\n\n const updateBottomState = useCallback(() => {\n const el = scrollRef.current;\n if (!el) return;\n if (isAtBottom(el)) setFollowingBottom(true, false, el);\n else if (!isNearBottomRef.current) {\n setShowScrollToBottom(el.scrollHeight > el.clientHeight + threshold);\n }\n }, [isAtBottom, setFollowingBottom, threshold]);\n\n const scrollToBottomIfFollowing = useCallback(\n (generation: number) => {\n if (\n followGenerationRef.current !== generation ||\n !isNearBottomRef.current\n ) {\n return;\n }\n const el = scrollRef.current;\n if (!el) return;\n el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight);\n lastScrollTopRef.current = el.scrollTop;\n setFollowingBottom(true, false, el);\n },\n [setFollowingBottom],\n );\n\n const scrollToBottom = useCallback(() => {\n const el = scrollRef.current;\n if (!el) return;\n setFollowingBottom(true, true, el);\n el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight);\n lastScrollTopRef.current = el.scrollTop;\n }, [setFollowingBottom]);\n\n useEffect(() => {\n const el = scrollRef.current;\n if (!el || !enabled) return;\n lastScrollTopRef.current = el.scrollTop;\n let lastScrollHeight = el.scrollHeight;\n\n const onWheel = (event: WheelEvent) => {\n if (event.deltaY < 0) detachFromBottom();\n };\n\n const onTouchStart = (event: TouchEvent) => {\n lastTouchYRef.current = event.touches[0]?.clientY ?? null;\n };\n\n const onTouchMove = (event: TouchEvent) => {\n const nextTouchY = event.touches[0]?.clientY;\n if (nextTouchY == null) return;\n const lastTouchY = lastTouchYRef.current;\n if (lastTouchY != null && nextTouchY > lastTouchY) {\n detachFromBottom();\n }\n lastTouchYRef.current = nextTouchY;\n };\n\n const onTouchEnd = () => {\n lastTouchYRef.current = null;\n };\n\n const onScroll = () => {\n const previousScrollTop = lastScrollTopRef.current;\n const nextScrollTop = el.scrollTop;\n const nextScrollHeight = el.scrollHeight;\n // When the message list briefly shrinks (a re-render swaps content, a\n // streaming/reconnect placeholder collapses, images unload, the message\n // list remounts as a new run starts, etc.) the browser is forced to clamp\n // scrollTop downward and fires a scroll event. That clamp is not the user\n // scrolling up — treating it as such detaches auto-follow and strands the\n // conversation scrolled up, sometimes all the way at the top. Only treat a\n // downward jump as user intent when the content did not shrink underneath\n // it. Genuine user scroll-ups (wheel/touch/keys, scrollbar drag at a\n // stable height) are unaffected.\n const contentShrank = nextScrollHeight < lastScrollHeight;\n lastScrollTopRef.current = nextScrollTop;\n lastScrollHeight = nextScrollHeight;\n if (nextScrollTop < previousScrollTop && !contentShrank) {\n detachFromBottom();\n return;\n }\n updateBottomState();\n };\n const onKeyDown = (event: KeyboardEvent) => {\n if (\n event.key === \"ArrowUp\" ||\n event.key === \"PageUp\" ||\n event.key === \"Home\" ||\n (event.key === \" \" && event.shiftKey)\n ) {\n detachFromBottom();\n }\n };\n el.addEventListener(\"wheel\", onWheel, { passive: true });\n el.addEventListener(\"touchstart\", onTouchStart, { passive: true });\n el.addEventListener(\"touchmove\", onTouchMove, { passive: true });\n el.addEventListener(\"touchend\", onTouchEnd, { passive: true });\n el.addEventListener(\"touchcancel\", onTouchEnd, { passive: true });\n el.addEventListener(\"scroll\", onScroll, { passive: true });\n el.addEventListener(\"keydown\", onKeyDown);\n updateBottomState();\n\n // Re-check near-bottom whenever the scroll container's content grows\n // (e.g. new messages appended, images loaded, tool-call details expanded).\n // Without this the \"near bottom\" flag can get stuck as `false` even though\n // the user never scrolled away — the container just grew taller.\n let ro: ResizeObserver | null = null;\n let mo: MutationObserver | null = null;\n if (typeof ResizeObserver !== \"undefined\") {\n const observeResizeTargets = () => {\n ro?.disconnect();\n ro = new ResizeObserver(() => {\n if (isNearBottomRef.current) {\n scrollToBottomIfFollowing(followGenerationRef.current);\n } else {\n updateBottomState();\n }\n });\n ro.observe(el);\n // Also watch direct children so inline content changes are caught.\n for (const child of Array.from(el.children)) ro.observe(child);\n };\n observeResizeTargets();\n if (typeof MutationObserver !== \"undefined\") {\n mo = new MutationObserver(() => {\n observeResizeTargets();\n if (isNearBottomRef.current) {\n scrollToBottomIfFollowing(followGenerationRef.current);\n }\n });\n mo.observe(el, { childList: true });\n }\n }\n\n return () => {\n el.removeEventListener(\"wheel\", onWheel);\n el.removeEventListener(\"touchstart\", onTouchStart);\n el.removeEventListener(\"touchmove\", onTouchMove);\n el.removeEventListener(\"touchend\", onTouchEnd);\n el.removeEventListener(\"touchcancel\", onTouchEnd);\n el.removeEventListener(\"scroll\", onScroll);\n el.removeEventListener(\"keydown\", onKeyDown);\n ro?.disconnect();\n mo?.disconnect();\n };\n }, [detachFromBottom, enabled, scrollToBottomIfFollowing, updateBottomState]);\n\n const scrollToBottomAfterPaint = useCallback(() => {\n const generation = followGenerationRef.current;\n scrollToBottomIfFollowing(generation);\n requestAnimationFrame(() => {\n scrollToBottomIfFollowing(generation);\n requestAnimationFrame(() => scrollToBottomIfFollowing(generation));\n });\n window.setTimeout(() => scrollToBottomIfFollowing(generation), 80);\n }, [scrollToBottomIfFollowing]);\n\n const markNearBottom = useCallback(() => {\n setFollowingBottom(true, true, scrollRef.current ?? undefined);\n }, [setFollowingBottom]);\n\n useEffect(() => {\n if (!enabled || !isNearBottomRef.current) return;\n scrollToBottomAfterPaint();\n }, [enabled, followKey, scrollToBottomAfterPaint]);\n\n useEffect(() => {\n if (!enabled || !streaming) return;\n const id = window.setInterval(() => {\n scrollToBottomIfFollowing(followGenerationRef.current);\n }, 100);\n return () => window.clearInterval(id);\n }, [enabled, scrollToBottomIfFollowing, streaming]);\n\n return {\n scrollRef,\n isNearBottomRef,\n showScrollToBottom,\n markNearBottom,\n scrollToBottom,\n scrollToBottomAfterPaint,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-near-bottom-autoscroll.js","sourceRoot":"","sources":["../../../src/client/conversation/use-near-bottom-autoscroll.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AASjE,SAAS,kBAAkB,CAAC,KAAY;I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CAAC,EAAE,CAAC,CAAC;IACxC,CAAC,EAAE,CAAC,OAAO,EAAE,yBAAyB,EAAE,SAAS,CAAC,CAAC,CAAC;IAEpD,OAAO;QACL,SAAS;QACT,eAAe;QACf,kBAAkB;QAClB,cAAc;QACd,cAAc;QACd,wBAAwB;KACzB,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseNearBottomAutoscrollOptions {\n followKey: unknown;\n streaming?: boolean;\n threshold?: number;\n enabled?: boolean;\n}\n\nfunction eventElementTarget(event: Event): HTMLElement | null {\n const target = event.target;\n if (!(target instanceof Node)) return null;\n if (target instanceof HTMLElement) return target;\n return target.parentElement;\n}\n\nfunction canScrollElementVertically(\n element: HTMLElement,\n deltaY: number,\n): boolean {\n if (element.scrollHeight <= element.clientHeight) return false;\n const style = window.getComputedStyle(element);\n const overflowY = style.overflowY || style.overflow;\n if (!/(auto|scroll|overlay)/.test(overflowY)) return false;\n if (deltaY < 0) return element.scrollTop > 0;\n if (deltaY > 0) {\n return element.scrollTop + element.clientHeight < element.scrollHeight - 1;\n }\n return false;\n}\n\nfunction nestedScrollableConsumesVerticalIntent(\n event: Event,\n root: HTMLElement,\n deltaY: number,\n): boolean {\n let element = eventElementTarget(event);\n while (element && element !== root) {\n if (canScrollElementVertically(element, deltaY)) return true;\n element = element.parentElement;\n }\n return false;\n}\n\nexport function useNearBottomAutoscroll<TElement extends HTMLElement>({\n followKey,\n streaming = false,\n threshold = 4,\n enabled = true,\n}: UseNearBottomAutoscrollOptions) {\n const scrollRef = useRef<TElement | null>(null);\n const isNearBottomRef = useRef(true);\n const followGenerationRef = useRef(0);\n const lastScrollTopRef = useRef(0);\n const lastTouchYRef = useRef<number | null>(null);\n const [showScrollToBottom, setShowScrollToBottom] = useState(false);\n\n const isAtBottom = useCallback(\n (el: HTMLElement) =>\n el.scrollHeight - el.scrollTop - el.clientHeight <= threshold,\n [threshold],\n );\n\n const setFollowingBottom = useCallback(\n (following: boolean, forceGeneration = false, el?: HTMLElement) => {\n if (forceGeneration || isNearBottomRef.current !== following) {\n followGenerationRef.current += 1;\n }\n isNearBottomRef.current = following;\n const canScroll = !el || el.scrollHeight > el.clientHeight + threshold;\n setShowScrollToBottom(!following && canScroll);\n },\n [threshold],\n );\n\n const detachFromBottom = useCallback(() => {\n setFollowingBottom(false, true, scrollRef.current ?? undefined);\n }, [setFollowingBottom]);\n\n const updateBottomState = useCallback(() => {\n const el = scrollRef.current;\n if (!el) return;\n if (isAtBottom(el)) setFollowingBottom(true, false, el);\n else if (!isNearBottomRef.current) {\n setShowScrollToBottom(el.scrollHeight > el.clientHeight + threshold);\n }\n }, [isAtBottom, setFollowingBottom, threshold]);\n\n const scrollToBottomIfFollowing = useCallback(\n (generation: number) => {\n if (\n followGenerationRef.current !== generation ||\n !isNearBottomRef.current\n ) {\n return;\n }\n const el = scrollRef.current;\n if (!el) return;\n el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight);\n lastScrollTopRef.current = el.scrollTop;\n setFollowingBottom(true, false, el);\n },\n [setFollowingBottom],\n );\n\n const scrollToBottom = useCallback(() => {\n const el = scrollRef.current;\n if (!el) return;\n setFollowingBottom(true, true, el);\n el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight);\n lastScrollTopRef.current = el.scrollTop;\n }, [setFollowingBottom]);\n\n useEffect(() => {\n const el = scrollRef.current;\n if (!el || !enabled) return;\n lastScrollTopRef.current = el.scrollTop;\n let lastScrollHeight = el.scrollHeight;\n\n const onWheel = (event: WheelEvent) => {\n if (nestedScrollableConsumesVerticalIntent(event, el, event.deltaY)) {\n return;\n }\n if (event.deltaY < 0) detachFromBottom();\n };\n\n const onTouchStart = (event: TouchEvent) => {\n lastTouchYRef.current = event.touches[0]?.clientY ?? null;\n };\n\n const onTouchMove = (event: TouchEvent) => {\n const nextTouchY = event.touches[0]?.clientY;\n if (nextTouchY == null) return;\n const lastTouchY = lastTouchYRef.current;\n if (lastTouchY != null && nextTouchY > lastTouchY) {\n const deltaY = lastTouchY - nextTouchY;\n if (!nestedScrollableConsumesVerticalIntent(event, el, deltaY)) {\n detachFromBottom();\n }\n }\n lastTouchYRef.current = nextTouchY;\n };\n\n const onTouchEnd = () => {\n lastTouchYRef.current = null;\n };\n\n const onScroll = (event: Event) => {\n if (event.target !== el) return;\n const previousScrollTop = lastScrollTopRef.current;\n const nextScrollTop = el.scrollTop;\n const nextScrollHeight = el.scrollHeight;\n // When the message list briefly shrinks (a re-render swaps content, a\n // streaming/reconnect placeholder collapses, images unload, the message\n // list remounts as a new run starts, etc.) the browser is forced to clamp\n // scrollTop downward and fires a scroll event. That clamp is not the user\n // scrolling up — treating it as such detaches auto-follow and strands the\n // conversation scrolled up, sometimes all the way at the top. Only treat a\n // downward jump as user intent when the content did not shrink underneath\n // it. Genuine user scroll-ups (wheel/touch/keys, scrollbar drag at a\n // stable height) are unaffected.\n const contentShrank = nextScrollHeight < lastScrollHeight;\n lastScrollTopRef.current = nextScrollTop;\n lastScrollHeight = nextScrollHeight;\n if (nextScrollTop < previousScrollTop && !contentShrank) {\n detachFromBottom();\n return;\n }\n updateBottomState();\n };\n const onKeyDown = (event: KeyboardEvent) => {\n if (\n event.key === \"ArrowUp\" ||\n event.key === \"PageUp\" ||\n event.key === \"Home\" ||\n (event.key === \" \" && event.shiftKey)\n ) {\n if (nestedScrollableConsumesVerticalIntent(event, el, -1)) return;\n detachFromBottom();\n }\n };\n el.addEventListener(\"wheel\", onWheel, { passive: true });\n el.addEventListener(\"touchstart\", onTouchStart, { passive: true });\n el.addEventListener(\"touchmove\", onTouchMove, { passive: true });\n el.addEventListener(\"touchend\", onTouchEnd, { passive: true });\n el.addEventListener(\"touchcancel\", onTouchEnd, { passive: true });\n el.addEventListener(\"scroll\", onScroll, { passive: true });\n el.addEventListener(\"keydown\", onKeyDown);\n updateBottomState();\n\n // Re-check near-bottom whenever the scroll container's content grows\n // (e.g. new messages appended, images loaded, tool-call details expanded).\n // Without this the \"near bottom\" flag can get stuck as `false` even though\n // the user never scrolled away — the container just grew taller.\n let ro: ResizeObserver | null = null;\n let mo: MutationObserver | null = null;\n if (typeof ResizeObserver !== \"undefined\") {\n const observeResizeTargets = () => {\n ro?.disconnect();\n ro = new ResizeObserver(() => {\n if (isNearBottomRef.current) {\n scrollToBottomIfFollowing(followGenerationRef.current);\n } else {\n updateBottomState();\n }\n });\n ro.observe(el);\n // Also watch direct children so inline content changes are caught.\n for (const child of Array.from(el.children)) ro.observe(child);\n };\n observeResizeTargets();\n if (typeof MutationObserver !== \"undefined\") {\n mo = new MutationObserver(() => {\n observeResizeTargets();\n if (isNearBottomRef.current) {\n scrollToBottomIfFollowing(followGenerationRef.current);\n }\n });\n mo.observe(el, { childList: true });\n }\n }\n\n return () => {\n el.removeEventListener(\"wheel\", onWheel);\n el.removeEventListener(\"touchstart\", onTouchStart);\n el.removeEventListener(\"touchmove\", onTouchMove);\n el.removeEventListener(\"touchend\", onTouchEnd);\n el.removeEventListener(\"touchcancel\", onTouchEnd);\n el.removeEventListener(\"scroll\", onScroll);\n el.removeEventListener(\"keydown\", onKeyDown);\n ro?.disconnect();\n mo?.disconnect();\n };\n }, [detachFromBottom, enabled, scrollToBottomIfFollowing, updateBottomState]);\n\n const scrollToBottomAfterPaint = useCallback(() => {\n const generation = followGenerationRef.current;\n scrollToBottomIfFollowing(generation);\n requestAnimationFrame(() => {\n scrollToBottomIfFollowing(generation);\n requestAnimationFrame(() => scrollToBottomIfFollowing(generation));\n });\n window.setTimeout(() => scrollToBottomIfFollowing(generation), 80);\n }, [scrollToBottomIfFollowing]);\n\n const markNearBottom = useCallback(() => {\n setFollowingBottom(true, true, scrollRef.current ?? undefined);\n }, [setFollowingBottom]);\n\n useEffect(() => {\n if (!enabled || !isNearBottomRef.current) return;\n scrollToBottomAfterPaint();\n }, [enabled, followKey, scrollToBottomAfterPaint]);\n\n useEffect(() => {\n if (!enabled || !streaming) return;\n const id = window.setInterval(() => {\n scrollToBottomIfFollowing(followGenerationRef.current);\n }, 100);\n return () => window.clearInterval(id);\n }, [enabled, scrollToBottomIfFollowing, streaming]);\n\n return {\n scrollRef,\n isNearBottomRef,\n showScrollToBottom,\n markNearBottom,\n scrollToBottom,\n scrollToBottomAfterPaint,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-code.d.ts","sourceRoot":"","sources":["../../src/coding-tools/run-code.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAMH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAmBhE,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAC7C,IAAI,GAAE,cAAmB,GACxB,WAAW,
|
|
1
|
+
{"version":3,"file":"run-code.d.ts","sourceRoot":"","sources":["../../src/coding-tools/run-code.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAMH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAmBhE,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAC7C,IAAI,GAAE,cAAmB,GACxB,WAAW,CAoJb"}
|
|
@@ -56,6 +56,7 @@ export function createRunCodeEntry(getActions, opts = {}) {
|
|
|
56
56
|
const extraBridgeTools = new Set(opts.bridgeTools ?? []);
|
|
57
57
|
return {
|
|
58
58
|
readOnly: true,
|
|
59
|
+
allowInPlanMode: false,
|
|
59
60
|
// Allow a generous per-call timeout so large data-processing jobs don't hit
|
|
60
61
|
// the agent-loop's default 60 s cap.
|
|
61
62
|
timeoutMs: MAX_TIMEOUT_MS,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-code.js","sourceRoot":"","sources":["../../src/coding-tools/run-code.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,IAAI,MAAM,WAAW,CAAC;AAI7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,kBAAkB,GAAG,OAAO,CAAC;AACnC,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,MAAM,wBAAwB,GAAG,MAAM,CAAC;AACxC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AACjC,uFAAuF;AACvF,MAAM,qBAAqB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAE/C,wDAAwD;AACxD,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACnC,sBAAsB;IACtB,mBAAmB;IACnB,sBAAsB;IACtB,aAAa;IACb,iBAAiB;CAClB,CAAC,CAAC;AAUH;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,UAA6C,EAC7C,IAAI,GAAmB,EAAE;IAEzB,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IAEzD,OAAO;QACL,QAAQ,EAAE,IAAI;QACd,4EAA4E;QAC5E,qCAAqC;QACrC,SAAS,EAAE,cAAc;QACzB,cAAc,EAAE,gBAAgB;QAChC,IAAI,EAAE;YACJ,WAAW,EAAE;gBACX,sFAAsF;gBACtF,mHAAmH;gBACnH,8bAA8b;gBAC9b,oBAAoB;gBACpB,uHAAuH;gBACvH,mIAAmI;gBACnI,+HAA+H;gBAC/H,0DAA0D;gBAC1D,6FAA6F;gBAC7F,0GAA0G;gBAC1G,0LAA0L;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the agent.\n *\n * Executes user-supplied JavaScript in an isolated child process with:\n * - A scrubbed environment (no app secrets or env vars; only PATH/HOME/TMPDIR).\n * - A fresh temporary working directory.\n * - An ephemeral bridge HTTP server on 127.0.0.1 so the child can call\n * allowlisted registered tools (provider-api-request, web-request, etc.)\n * with the same request context as the parent — without leaking secrets.\n *\n * Security notes:\n * - The bridge token is a 32-byte random hex string generated per invocation.\n * - The bridge binds to 127.0.0.1 only; no external exposure.\n * - The allowlist of callable bridge tools is enforced server-side.\n * - Secret values are NEVER included in the env passed to the child.\n * - When the Node permission model is available (`--permission`, or\n * `--experimental-permission` on Node 20), the child is denied filesystem\n * access outside its own temp dir, child processes, workers, and native\n * addons. Outbound network from the child is NOT blocked by the permission\n * model; the env scrub means such requests carry no credentials, and all\n * authenticated calls must go through the bridge (which applies the\n * registered tools' host allowlists and SSRF guards).\n *\n * The actual execution is delegated to a pluggable `SandboxAdapter` (see\n * `./sandbox`). The default `LocalChildProcessAdapter` preserves the spawned\n * child-process behavior described above; a remote/durable adapter can be\n * plugged in via `registerSandboxAdapter()` / `AGENT_NATIVE_SANDBOX` without\n * changing this file. The bridge, env scrub, module building, and output\n * formatting stay here in the parent regardless of adapter.\n */\n\nimport crypto from \"node:crypto\";\nimport http from \"node:http\";\n\nimport type { ActionRunContext } from \"../action.js\";\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { getSandboxAdapter } from \"./sandbox/index.js\";\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst MAX_TIMEOUT_MS = 600_000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 50_000;\nconst MAX_OUTPUT_CHARS = 200_000;\n/** Hard cap on bridge request bodies so sandboxed code can't exhaust parent memory. */\nconst BRIDGE_MAX_BODY_BYTES = 10 * 1024 * 1024;\n\n/** Tools callable via the sandbox bridge by default. */\nconst DEFAULT_BRIDGE_TOOLS = new Set([\n \"provider-api-request\",\n \"provider-api-docs\",\n \"provider-api-catalog\",\n \"web-request\",\n \"workspace-files\",\n]);\n\nexport interface RunCodeOptions {\n /**\n * Extra tool names (beyond the default set) that the sandbox bridge will\n * forward to the registered action registry.\n */\n bridgeTools?: string[];\n}\n\n/**\n * Create a `run-code` ActionEntry.\n *\n * @param getActions Supplier that returns the current action registry (called\n * at invocation time so updates are reflected).\n * @param opts Optional configuration.\n */\nexport function createRunCodeEntry(\n getActions: () => Record<string, ActionEntry>,\n opts: RunCodeOptions = {},\n): ActionEntry {\n const extraBridgeTools = new Set(opts.bridgeTools ?? []);\n\n return {\n readOnly: true,\n // Allow a generous per-call timeout so large data-processing jobs don't hit\n // the agent-loop's default 60 s cap.\n timeoutMs: MAX_TIMEOUT_MS,\n maxResultChars: MAX_OUTPUT_CHARS,\n tool: {\n description: [\n \"Execute JavaScript (Node.js, ESM, top-level await supported) in an isolated sandbox.\",\n \"Use this to fetch, join, aggregate, and reduce large datasets, returning only printed output to the conversation.\",\n \"The sandbox runs with a scrubbed environment (no secrets) and, where the Node permission model is available, no filesystem access outside its own temp dir, no child processes, and no workers. Authenticated calls must go through the provided globals; direct network requests carry no credentials. Note: isolation is process-level (env scrub + Node permission model), not an OS-level container — outbound network from sandbox code is not blocked.\",\n \"Available globals:\",\n \" - `appAction(name, args?)` — call any registered agent-exposed read-only app action/tool and get its parsed result.\",\n \" Use this to loop over app data readers and compose multi-source analyses without forcing every intermediate result into chat.\",\n \" - `providerFetch(provider, path, init?)` — authenticated call to a registered provider via the provider-api-request action.\",\n \" Returns the parsed JSON result (or throws on error).\",\n \" Supports stageAs/saveToFile/fetchAllPages; use cursorBodyPath for POST-body pagination.\",\n \" Example: `const data = await providerFetch('<provider-id>', '/records', { query: { limit: 100 } });`\",\n \" - `providerRequest(provider, path, init?)` — same authenticated call, but returns the full provider-api envelope with request, response status/headers, truncation, and body metadata.\",\n \" - `providerFetchAll(provider, path, init?)` — generic pagination helper for cursor, page, and offset APIs. Pass `pagination: { itemsPath, cursorPath or nextCursorPath, cursorParam or cursorBodyPath, pageParam, offsetParam, pageSize, maxPages }`. Returns `{ items, pages, pageCount, itemCount, hasMore, lastCursor, stoppedReason }`.\",\n \" - `providerSearchAll(provider, path, init?, options?)` — streaming search helper for broad provider corpora such as transcripts, messages, tickets, issues, notes, events, or documents. Use this before hand-written loops when searching many provider records for terms/phrases/regexes or proving absence. Pass the same `pagination` config as `providerFetchAll`, plus options like `{ query, queries, terms, regex, textPaths, idPaths, metadataPaths, maxHits }`. Returns structured hits with item ids, paths, snippets, page/item indexes, and coverage fields (`pageCount`, `itemCount`, `hasMore`, `stoppedReason`).\",\n \" - `webFetch(url, init?)` — outbound HTTP request via the web-request action.\",\n \" Returns `{ status, body }` where body is the response text. Supports responseMode, extract, includeLinks, search, maxChars, and saveToFile.\",\n \" Example: `const { body } = await webFetch('https://api.example.com/data', { responseMode: 'raw' });`\",\n \" - `webRead(url, init?)` — convenience wrapper for webFetch with `responseMode: 'auto'` and extracted HTML/markdown or bounded matches.\",\n \" Example: `const docs = await webRead('https://docs.example.com/api', { search: { query: 'pagination' } });`\",\n \" - `workspaceRead(path, opts?)` — read a Resources-backed workspace file by path. Returns content string or null. opts: { offset?, maxChars? }.\",\n \" - `workspaceReadMeta(path, opts?)` — read a workspace file with metadata such as sizeBytes, truncated, and nextOffset.\",\n \" - `workspaceWrite(path, content, contentType?)` — create or overwrite a workspace file. Use `scratch/...` for temporary staging; use durable folders only for files the user should keep.\",\n \" - `workspaceAppend(path, content)` — append text to a workspace file.\",\n \" - `workspaceList(prefix?)` — list workspace files, returns [{ path, sizeBytes, contentType, updatedAt }].\",\n \"Print results with `console.log()`; only stdout+stderr are returned.\",\n \"Timeout defaults to 120 s (max 600 s). Output is truncated to 50 000 chars by default (max 200 000).\",\n ].join(\" \"),\n parameters: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description:\n \"JavaScript source to execute. ESM syntax, top-level await allowed.\",\n },\n timeoutMs: {\n type: \"number\",\n description: `Execution timeout in milliseconds. Default: ${DEFAULT_TIMEOUT_MS}. Max: ${MAX_TIMEOUT_MS}.`,\n },\n maxOutputChars: {\n type: \"number\",\n description: `Maximum combined stdout+stderr characters to return. Default: ${DEFAULT_MAX_OUTPUT_CHARS}. Max: ${MAX_OUTPUT_CHARS}.`,\n },\n },\n required: [\"code\"],\n },\n },\n run: async (args: Record<string, string>, context?: ActionRunContext) => {\n const code = typeof args.code === \"string\" ? args.code : \"\";\n if (!code.trim()) return \"Error: code is required.\";\n\n const requestedTimeout = Number(args.timeoutMs);\n const timeoutMs =\n Number.isFinite(requestedTimeout) && requestedTimeout > 0\n ? Math.min(requestedTimeout, MAX_TIMEOUT_MS)\n : DEFAULT_TIMEOUT_MS;\n\n const requestedMaxOutput = Number(args.maxOutputChars);\n const maxOutputChars =\n Number.isFinite(requestedMaxOutput) && requestedMaxOutput > 0\n ? Math.min(requestedMaxOutput, MAX_OUTPUT_CHARS)\n : DEFAULT_MAX_OUTPUT_CHARS;\n\n const actions = getActions();\n const bridgeToken = crypto.randomBytes(32).toString(\"hex\");\n\n // Start bridge server — resolves once the server is listening.\n const {\n bridgePort,\n getUsedTools,\n cleanup: cleanupBridge,\n } = await startBridgeServer(\n bridgeToken,\n actions,\n context,\n DEFAULT_BRIDGE_TOOLS,\n extraBridgeTools,\n );\n\n try {\n // Build scrubbed env — only safe POSIX vars, no secrets. The adapter\n // points TMPDIR/TEMP/TMP at the sandbox's own temp dir.\n const safeEnv: Record<string, string> = {};\n for (const key of [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"TEMP\",\n \"TMP\",\n \"LANG\",\n \"LC_ALL\",\n ]) {\n if (process.env[key]) safeEnv[key] = process.env[key]!;\n }\n\n // Delegate execution to the active sandbox adapter (local child process\n // by default; remote/durable adapters can be registered via\n // ./sandbox). The bridge, env scrub, module, and output formatting stay\n // in the parent regardless of adapter.\n const { stdout, stderr, exitCode, timedOut } =\n await getSandboxAdapter().run({\n moduleSource: buildSandboxModule(code, bridgePort, bridgeToken),\n env: safeEnv,\n timeoutMs,\n bridgePort,\n });\n\n const combined =\n [\n stdout ? `stdout:\\n${stdout}` : \"\",\n stderr ? `stderr:\\n${stderr}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\\n\") || \"(no output)\";\n\n const lines: string[] = [];\n if (timedOut) lines.push(`timedOut: true (${timeoutMs}ms)`);\n if (exitCode !== 0 && exitCode !== null)\n lines.push(`exitCode: ${exitCode}`);\n const usedTools = getUsedTools();\n if (usedTools.length)\n lines.push(`bridgeToolsUsed: ${usedTools.join(\", \")}`);\n lines.push(combined);\n\n const full = lines.join(\"\\n\\n\");\n if (full.length > maxOutputChars) {\n const truncated = full.slice(0, maxOutputChars);\n return `${truncated}\\n\\n...[truncated ${(full.length - maxOutputChars).toLocaleString()} chars]`;\n }\n return full;\n } finally {\n // The active sandbox adapter owns its own temp-file cleanup; the parent\n // only tears down the bridge server here.\n cleanupBridge();\n }\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bridge server\n// ---------------------------------------------------------------------------\n\ninterface BridgeResult {\n server: http.Server;\n bridgePort: number;\n getUsedTools: () => string[];\n cleanup: () => void;\n}\n\nasync function startBridgeServer(\n token: string,\n actions: Record<string, ActionEntry>,\n context: ActionRunContext | undefined,\n defaultTools: Set<string>,\n extraTools: Set<string>,\n): Promise<BridgeResult> {\n const usedTools = new Set<string>();\n const server = http.createServer((req, res) => {\n if (req.method !== \"POST\" || req.url !== \"/tool\") {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n\n // Validate bearer token — must match exactly.\n const authHeader = req.headers.authorization ?? \"\";\n if (authHeader !== `Bearer ${token}`) {\n res.writeHead(401);\n res.end(\"Unauthorized\");\n return;\n }\n\n let body = \"\";\n let receivedBytes = 0;\n let rejected = false;\n req.on(\"data\", (chunk: Buffer) => {\n receivedBytes += chunk.length;\n if (receivedBytes > BRIDGE_MAX_BODY_BYTES) {\n rejected = true;\n res.writeHead(413);\n res.end(\"Payload too large\");\n req.destroy();\n return;\n }\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n if (rejected) return;\n handleBridgeRequest(\n body,\n actions,\n context,\n defaultTools,\n extraTools,\n usedTools,\n res,\n );\n });\n req.on(\"error\", () => {\n res.writeHead(500);\n res.end(\"Request error\");\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve());\n });\n\n const addr = server.address() as { port: number };\n const bridgePort = addr.port;\n\n const cleanup = () => {\n try {\n server.close();\n } catch {}\n };\n\n return {\n server,\n bridgePort,\n getUsedTools: () => Array.from(usedTools).sort(),\n cleanup,\n };\n}\n\nfunction handleBridgeRequest(\n rawBody: string,\n actions: Record<string, ActionEntry>,\n context: ActionRunContext | undefined,\n defaultTools: Set<string>,\n extraTools: Set<string>,\n usedTools: Set<string>,\n res: http.ServerResponse,\n): void {\n let parsed: { tool?: string; args?: Record<string, string> };\n try {\n parsed = JSON.parse(rawBody);\n } catch {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid JSON body\" }));\n return;\n }\n\n const toolName = typeof parsed.tool === \"string\" ? parsed.tool.trim() : \"\";\n if (!toolName) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Missing tool name\" }));\n return;\n }\n\n // Enforce allowlist.\n const entry = actions[toolName];\n const isReadOnlyAction =\n entry?.readOnly === true &&\n entry.agentTool !== false &&\n entry.toolCallable !== false;\n if (\n !defaultTools.has(toolName) &&\n !extraTools.has(toolName) &&\n !isReadOnlyAction\n ) {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Tool \"${toolName}\" is not an agent-exposed read-only action or sandbox bridge allowlisted tool.`,\n }),\n );\n return;\n }\n\n if (!entry) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: `Tool \"${toolName}\" is not registered.` }));\n return;\n }\n\n const toolArgs = parsed.args ?? {};\n usedTools.add(toolName);\n // Run the tool with the parent request context so auth/org/owner resolution\n // works exactly as it does in the normal agent loop.\n entry\n .run(toolArgs, context)\n .then((result: unknown) => {\n const body =\n typeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ result: body }));\n })\n .catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: message }));\n });\n}\n\n// ---------------------------------------------------------------------------\n// Sandbox module template\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap the user's code in an ESM module that:\n * 1. Defines `providerFetch`, `providerRequest`, `providerFetchAll`,\n * `providerSearchAll`, and `webFetch` helpers via the bridge.\n * 2. Runs the user's code as top-level await in an async IIFE.\n */\nfunction buildSandboxModule(\n userCode: string,\n bridgePort: number,\n bridgeToken: string,\n): string {\n return `\nimport { createRequire } from \"node:module\";\nconst require = createRequire(import.meta.url);\n\nconst _bridgeBase = \"http://127.0.0.1:${bridgePort}/tool\";\nconst _bridgeToken = \"${bridgeToken}\";\n\nasync function _bridgeCall(tool, args) {\n const http = await import(\"node:http\");\n return new Promise((resolve, reject) => {\n const body = JSON.stringify({ tool, args });\n const options = {\n hostname: \"127.0.0.1\",\n port: ${bridgePort},\n path: \"/tool\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": Buffer.byteLength(body),\n \"Authorization\": \"Bearer \" + _bridgeToken,\n },\n };\n const req = http.request(options, (res) => {\n let data = \"\";\n res.on(\"data\", (chunk) => { data += chunk; });\n res.on(\"end\", () => {\n try {\n const parsed = JSON.parse(data);\n if (parsed.error) {\n reject(new Error(parsed.error));\n } else {\n resolve(parsed.result);\n }\n } catch (e) {\n reject(new Error(\"Bridge response parse error: \" + e.message));\n }\n });\n });\n req.on(\"error\", reject);\n req.end(body);\n });\n}\n\nfunction _parseBridgeResult(rawResult) {\n if (typeof rawResult !== \"string\") return rawResult;\n try { return JSON.parse(rawResult); } catch { return rawResult; }\n}\n\n/**\n * Call any registered agent-exposed read-only app action/tool via the sandbox bridge.\n * Mutating and explicitly hidden actions are blocked by the parent bridge.\n */\nasync function appAction(name, args = {}) {\n return _parseBridgeResult(await _bridgeCall(name, args));\n}\n\nasync function providerRequest(provider, apiPath, init = {}) {\n const method = (init.method || \"GET\").toUpperCase();\n const rawResult = await _bridgeCall(\"provider-api-request\", {\n provider,\n path: apiPath,\n method,\n ...(init.query ? { query: init.query } : {}),\n ...(init.body ? { body: init.body } : {}),\n ...(init.headers ? { headers: init.headers } : {}),\n ...(init.auth ? { auth: init.auth } : {}),\n ...(init.connectionId ? { connectionId: init.connectionId } : {}),\n ...(init.accountId ? { accountId: init.accountId } : {}),\n ...(init.timeoutMs ? { timeoutMs: init.timeoutMs } : {}),\n ...(init.maxBytes ? { maxBytes: init.maxBytes } : {}),\n ...(init.stageAs ? { stageAs: init.stageAs } : {}),\n ...(init.itemsPath ? { itemsPath: init.itemsPath } : {}),\n ...(init.pagination ? { pagination: init.pagination } : {}),\n ...(init.saveToFile ? { saveToFile: init.saveToFile } : {}),\n ...(init.fetchAllPages ? { fetchAllPages: init.fetchAllPages } : {}),\n });\n return _parseBridgeResult(rawResult);\n}\n\n/**\n * Call a provider API via the authenticated provider-api-request action.\n * Returns the parsed JSON response body (or throws on error).\n */\nasync function providerFetch(provider, apiPath, init = {}) {\n const parsed = await providerRequest(provider, apiPath, init);\n // Unwrap the provider-api-request envelope ({ provider, request, response, guidance })\n // so callers get the actual response body. fetchAllPages / saveToFile results\n // (which have no \\`response\\` field) are returned as-is.\n if (parsed && typeof parsed === \"object\" && parsed.response && typeof parsed.response === \"object\") {\n const r = parsed.response;\n if (typeof r.status === \"number\" && r.status >= 400) {\n const detail = typeof r.text === \"string\" ? r.text : JSON.stringify(r.json ?? \"\");\n throw new Error(\\`Provider request failed (\\${r.status}): \\${String(detail).slice(0, 500)}\\`);\n }\n return r.json !== undefined ? r.json : r.text;\n }\n return parsed;\n}\n\nfunction _cloneJson(value) {\n if (value === undefined || value === null) return value;\n return JSON.parse(JSON.stringify(value));\n}\n\nfunction _pathParts(path) {\n if (!path || typeof path !== \"string\") return [];\n return path\n .replace(/\\\\[(\\\\d+)\\\\]/g, \".$1\")\n .split(\".\")\n .map((part) => part.trim())\n .filter(Boolean);\n}\n\nfunction _getByPath(value, path) {\n let current = value;\n for (const part of _pathParts(path)) {\n if (current === undefined || current === null) return undefined;\n current = current[part];\n }\n return current;\n}\n\nfunction _setByPath(value, path, nextValue) {\n const parts = _pathParts(path);\n if (!parts.length) return value;\n const root = value && typeof value === \"object\" ? _cloneJson(value) : {};\n let current = root;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!current[part] || typeof current[part] !== \"object\") current[part] = {};\n current = current[part];\n }\n current[parts[parts.length - 1]] = nextValue;\n return root;\n}\n\nfunction _extractItems(page, itemsPath) {\n if (itemsPath) {\n const value = _getByPath(page, itemsPath);\n return Array.isArray(value) ? value : [];\n }\n if (Array.isArray(page)) return page;\n if (!page || typeof page !== \"object\") return [];\n for (const key of [\"data\", \"results\", \"items\", \"records\", \"rows\", \"calls\", \"callTranscripts\", \"transcripts\", \"messages\", \"tickets\", \"issues\", \"deals\", \"events\", \"notes\", \"documents\", \"entries\", \"objects\"]) {\n if (Array.isArray(page[key])) return page[key];\n }\n return [];\n}\n\nfunction _withoutProviderFetchAllOptions(init) {\n const {\n pagination: _pagination,\n fetchAllPages: _fetchAllPages,\n stageAs: _stageAs,\n itemsPath: _itemsPath,\n saveToFile: _saveToFile,\n ...rest\n } = init || {};\n return rest;\n}\n\nfunction _asArray(value) {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction _stringifySearchValue(value) {\n if (typeof value === \"string\") return value;\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction _collectStrings(value, basePath = \"\", out = [], limit = 5000) {\n if (out.length >= limit || value === undefined || value === null) return out;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n out.push({ path: basePath || \"$\", text: String(value) });\n return out;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length && out.length < limit; i++) {\n _collectStrings(value[i], basePath ? basePath + \"[\" + i + \"]\" : \"[\" + i + \"]\", out, limit);\n }\n return out;\n }\n if (typeof value === \"object\") {\n for (const key of Object.keys(value)) {\n if (out.length >= limit) break;\n _collectStrings(value[key], basePath ? basePath + \".\" + key : key, out, limit);\n }\n }\n return out;\n}\n\nfunction _collectSearchStrings(item, textPaths, maxFieldsPerItem) {\n const paths = _asArray(textPaths).filter((path) => typeof path === \"string\" && path.trim());\n if (!paths.length) return _collectStrings(item, \"\", [], maxFieldsPerItem);\n const out = [];\n for (const path of paths) {\n const value = _getByPath(item, path);\n if (value !== undefined) _collectStrings(value, path, out, maxFieldsPerItem);\n if (out.length >= maxFieldsPerItem) break;\n }\n return out;\n}\n\nfunction _firstValueByPath(value, paths) {\n for (const path of paths) {\n const found = _getByPath(value, path);\n if (found !== undefined && found !== null && String(found) !== \"\") {\n return { path, value: found };\n }\n }\n return null;\n}\n\nconst _DEFAULT_ID_PATHS = [\n \"id\",\n \"callId\",\n \"callID\",\n \"call_id\",\n \"call.id\",\n \"call.metaData.id\",\n \"metaData.id\",\n \"metadata.id\",\n \"recordId\",\n \"record_id\",\n \"objectId\",\n \"object_id\",\n \"ticketId\",\n \"ticket_id\",\n \"issueId\",\n \"issue_id\",\n \"messageId\",\n \"message_id\",\n \"conversationId\",\n \"conversation_id\",\n \"eventId\",\n \"event_id\",\n \"documentId\",\n \"document_id\",\n \"url\",\n \"webUrl\",\n \"permalink\",\n];\n\nfunction _extractItemIdentity(item, idPaths) {\n const paths = [\n ..._asArray(idPaths).filter((path) => typeof path === \"string\" && path.trim()),\n ..._DEFAULT_ID_PATHS,\n ];\n const found = _firstValueByPath(item, paths);\n if (!found) return { id: null, idPath: null };\n return { id: _stringifySearchValue(found.value), idPath: found.path };\n}\n\nfunction _extractMetadata(item, metadataPaths) {\n const metadata = {};\n for (const path of _asArray(metadataPaths)) {\n if (typeof path !== \"string\" || !path.trim()) continue;\n const value = _getByPath(item, path);\n if (value !== undefined) metadata[path] = value;\n }\n return metadata;\n}\n\nfunction _makeSnippet(text, index, contextChars) {\n const source = String(text);\n const context = Math.max(20, Math.min(Number(contextChars) || 180, 1000));\n const start = Math.max(0, index - context);\n const end = Math.min(source.length, Math.max(index, 0) + context);\n const prefix = start > 0 ? \"...\" : \"\";\n const suffix = end < source.length ? \"...\" : \"\";\n return (prefix + source.slice(start, end) + suffix).replace(/\\\\s+/g, \" \").trim();\n}\n\nfunction _normalizeFlags(flags, caseSensitive) {\n const raw = typeof flags === \"string\" ? flags : \"\";\n const allowed = raw.replace(/[^dgimsuvy]/g, \"\");\n const withoutGlobalOrSticky = allowed.replace(/[gy]/g, \"\");\n const withCase =\n caseSensitive || /i/.test(withoutGlobalOrSticky)\n ? withoutGlobalOrSticky\n : withoutGlobalOrSticky + \"i\";\n return withCase + \"g\";\n}\n\nfunction _normalizedSearchTerms(options) {\n const explicitTerms = _asArray(options.terms)\n .map((term) => String(term).trim())\n .filter(Boolean);\n if (explicitTerms.length) return explicitTerms;\n if (options.matchMode === \"allTerms\" && typeof options.query === \"string\") {\n return options.query\n .split(/\\\\s+/)\n .map((term) => term.trim())\n .filter(Boolean);\n }\n return [];\n}\n\nfunction _findItemWideTermMatch(fields, options) {\n const terms = _normalizedSearchTerms(options);\n if (!terms.length || options.matchMode === \"anyTerm\") return null;\n const caseSensitive = Boolean(options.caseSensitive);\n const normalizedFields = fields.map((field) => ({\n field,\n haystack: caseSensitive ? String(field.text) : String(field.text).toLowerCase(),\n }));\n const termHits = terms.map((term) => {\n const searchTerm = caseSensitive ? term : term.toLowerCase();\n for (const entry of normalizedFields) {\n const index = entry.haystack.indexOf(searchTerm);\n if (index >= 0) return { term, field: entry.field, index };\n }\n return { term, field: null, index: -1 };\n });\n if (termHits.some((hit) => hit.index < 0 || !hit.field)) return null;\n const first = termHits\n .filter((hit) => hit.field)\n .sort((a, b) => {\n const fieldOrder = fields.indexOf(a.field) - fields.indexOf(b.field);\n return fieldOrder || a.index - b.index;\n })[0];\n return {\n field: first.field,\n match: {\n kind: \"allTerms\",\n query: terms.join(\" \"),\n index: first.index,\n match: first.term,\n },\n };\n}\n\nfunction _findSearchMatches(text, options, includeTerms = true) {\n const source = String(text);\n const caseSensitive = Boolean(options.caseSensitive);\n const haystack = caseSensitive ? source : source.toLowerCase();\n const maxMatchesPerField = _boundedNumber(options.maxMatchesPerField, 1000, 1, 100000);\n const matches = [];\n\n const addSubstring = (needle, label, kind) => {\n if (needle === undefined || needle === null) return;\n const rawNeedle = String(needle);\n if (!rawNeedle) return;\n const searchNeedle = caseSensitive ? rawNeedle : rawNeedle.toLowerCase();\n let from = 0;\n while (from <= haystack.length) {\n const index = haystack.indexOf(searchNeedle, from);\n if (index < 0) break;\n matches.push({ kind, query: label ?? rawNeedle, index, match: source.slice(index, index + rawNeedle.length) });\n from = index + Math.max(1, searchNeedle.length);\n if (matches.length >= maxMatchesPerField) break;\n }\n };\n\n if (options.regex) {\n try {\n const regex = new RegExp(String(options.regex), _normalizeFlags(options.regexFlags, caseSensitive));\n let match;\n while ((match = regex.exec(source)) && typeof match.index === \"number\") {\n matches.push({ kind: \"regex\", query: String(options.regex), index: match.index, match: match[0] });\n if (matches.length >= maxMatchesPerField) break;\n if (match[0] === \"\") regex.lastIndex += 1;\n }\n } catch (err) {\n throw new Error(\"providerSearchAll invalid regex: \" + (err?.message || err));\n }\n }\n\n for (const query of _asArray(options.query).concat(_asArray(options.queries))) {\n addSubstring(query, String(query), \"query\");\n }\n\n const terms = includeTerms ? _normalizedSearchTerms(options) : [];\n if (terms.length) {\n const termHits = terms\n .map((term) => {\n const searchTerm = caseSensitive ? term : term.toLowerCase();\n const index = haystack.indexOf(searchTerm);\n return { term, index };\n })\n .filter((hit) => hit.index >= 0);\n const mode = options.matchMode === \"anyTerm\" ? \"anyTerm\" : \"allTerms\";\n if ((mode === \"allTerms\" && termHits.length === terms.length) || (mode === \"anyTerm\" && termHits.length > 0)) {\n const first = termHits.sort((a, b) => a.index - b.index)[0];\n matches.push({ kind: mode, query: terms.join(\" \"), index: first.index, match: first.term });\n }\n }\n\n return matches.sort((a, b) => a.index - b.index);\n}\n\nfunction _boundedNumber(value, defaultValue, min, max) {\n const parsed = Number(value);\n const finite = Number.isFinite(parsed) ? parsed : defaultValue;\n return Math.max(min, Math.min(finite, max));\n}\n\nfunction _hitKey(identity, path, query, index, pageIndex, pageItemIndex) {\n const itemKey =\n identity.id !== null && identity.id !== undefined\n ? \"id:\" + identity.id\n : \"page:\" + String(pageIndex) + \":\" + String(pageItemIndex);\n return [itemKey, path ?? \"\", query ?? \"\", String(index ?? \"\")].join(\"\\\\n\");\n}\n\n/**\n * Stream pages from a provider API and search item text structurally. This is\n * for broad mention searches and absence checks where keeping every raw page\n * in memory or hand-parsing JSON strings is brittle.\n */\nasync function providerSearchAll(provider, apiPath, init = {}, options = {}) {\n const pagination = init.pagination || init.fetchAllPages || {};\n const itemsPath = pagination.itemsPath || init.itemsPath || options.itemsPath;\n const cursorPath = pagination.nextCursorPath || pagination.cursorPath;\n const maxPagesRaw = Number(pagination.maxPages || init.maxPages || options.maxPages || 100);\n const maxPages = Math.max(1, Math.min(Number.isFinite(maxPagesRaw) ? maxPagesRaw : 100, 500));\n const maxHits = _boundedNumber(options.maxHits, 100, 1, 5000);\n const maxHitsPerItem = _boundedNumber(options.maxHitsPerItem, 3, 1, 100);\n const maxFieldsPerItem = _boundedNumber(options.maxFieldsPerItem, 5000, 1, 50000);\n const contextChars = options.contextChars ?? options.snippetChars ?? 180;\n const baseInit = _withoutProviderFetchAllOptions(init);\n let query = _cloneJson(init.query || {});\n let body = _cloneJson(init.body);\n let pageNumber = Number(pagination.startPage || 1);\n let offset = Number(pagination.startOffset || 0);\n let lastCursor = null;\n let stoppedReason = \"completed\";\n let itemCount = 0;\n let matchedItemCount = 0;\n let totalHitCount = 0;\n const hits = [];\n const seenHitKeys = new Set();\n let pageIndex = 0;\n\n for (; pageIndex < maxPages; pageIndex++) {\n if (pagination.pageParam) query = { ...(query || {}), [pagination.pageParam]: pageNumber };\n if (pagination.offsetParam) query = { ...(query || {}), [pagination.offsetParam]: offset };\n\n const page = await providerFetch(provider, apiPath, {\n ...baseInit,\n query,\n ...(body !== undefined ? { body } : {}),\n });\n const nextCursor = cursorPath ? _getByPath(page, cursorPath) : undefined;\n const hasNextCursor =\n nextCursor !== undefined && nextCursor !== null && String(nextCursor) !== \"\";\n if (hasNextCursor && lastCursor !== null && String(nextCursor) === String(lastCursor)) {\n stoppedReason = \"repeated-cursor\";\n break;\n }\n\n const pageItems = _extractItems(page, itemsPath);\n itemCount += pageItems.length;\n\n for (let pageItemIndex = 0; pageItemIndex < pageItems.length; pageItemIndex++) {\n const item = pageItems[pageItemIndex];\n const identity = _extractItemIdentity(item, options.idPaths);\n const metadata = _extractMetadata(item, options.metadataPaths);\n const fields = _collectSearchStrings(item, options.textPaths, maxFieldsPerItem);\n let storedItemHitCount = 0;\n let itemMatched = false;\n\n const addHit = (field, match) => {\n const key = _hitKey(identity, field.path, match.query, match.index, pageIndex, pageItemIndex);\n if (seenHitKeys.has(key)) return false;\n seenHitKeys.add(key);\n totalHitCount += 1;\n if (!itemMatched) {\n matchedItemCount += 1;\n itemMatched = true;\n }\n if (hits.length < maxHits && storedItemHitCount < maxHitsPerItem) {\n storedItemHitCount += 1;\n hits.push({\n id: identity.id,\n idPath: identity.idPath,\n pageIndex,\n pageItemIndex,\n itemIndex: itemCount - pageItems.length + pageItemIndex,\n path: field.path,\n kind: match.kind,\n query: match.query,\n match: match.match,\n snippet: _makeSnippet(field.text, match.index, contextChars),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n });\n }\n return true;\n };\n\n const itemWideTermMatch = _findItemWideTermMatch(fields, options);\n if (itemWideTermMatch) {\n addHit(itemWideTermMatch.field, itemWideTermMatch.match);\n }\n\n for (const field of fields) {\n const fieldMatches = _findSearchMatches(field.text, options, !itemWideTermMatch);\n for (const match of fieldMatches) {\n addHit(field, match);\n }\n }\n }\n\n if (hasNextCursor) {\n lastCursor = nextCursor;\n if (pagination.cursorBodyPath) {\n body = _setByPath(body || {}, pagination.cursorBodyPath, nextCursor);\n } else if (pagination.cursorParam) {\n query = { ...(query || {}), [pagination.cursorParam]: nextCursor };\n } else {\n stoppedReason = \"cursor-found-without-destination\";\n break;\n }\n continue;\n }\n\n lastCursor = null;\n if (pagination.pageParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n pageNumber += 1;\n continue;\n }\n if (pagination.offsetParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n const step = Number(pagination.pageSize || pageItems.length);\n if (!Number.isFinite(step) || step <= 0) {\n stoppedReason = \"invalid-page-size\";\n break;\n }\n offset += step;\n if (pagination.pageSize && pageItems.length < Number(pagination.pageSize)) {\n stoppedReason = \"short-page\";\n break;\n }\n continue;\n }\n\n break;\n }\n\n const pageCount = pageIndex + (pageIndex < maxPages ? 1 : 0);\n const hitPageOrOffsetLimit =\n Boolean(pagination.pageParam || pagination.offsetParam) &&\n stoppedReason === \"completed\" &&\n pageCount >= maxPages;\n const hasMore =\n stoppedReason === \"cursor-found-without-destination\" ||\n (lastCursor !== null && pageCount >= maxPages) || hitPageOrOffsetLimit;\n if (hasMore && stoppedReason === \"completed\") stoppedReason = \"max-pages\";\n\n return {\n hits,\n hitCount: hits.length,\n totalHitCount,\n truncatedHits: totalHitCount > hits.length,\n matchedItemCount,\n itemCount,\n pageCount,\n hasMore,\n lastCursor,\n stoppedReason,\n searched: {\n provider,\n path: apiPath,\n itemsPath: itemsPath || null,\n textPaths: _asArray(options.textPaths),\n idPaths: _asArray(options.idPaths),\n query: options.query ?? null,\n queries: _asArray(options.queries),\n terms: _asArray(options.terms),\n regex: options.regex ?? null,\n matchMode: options.matchMode || (options.terms ? \"allTerms\" : \"query\"),\n caseSensitive: Boolean(options.caseSensitive),\n },\n };\n}\n\n/**\n * Fetch every page from a provider API using generic cursor, page-number, or\n * offset pagination. Prefer this inside run-code when the answer depends on a\n * broad provider corpus rather than a single bounded request.\n */\nasync function providerFetchAll(provider, apiPath, init = {}) {\n const pagination = init.pagination || init.fetchAllPages || {};\n const itemsPath = pagination.itemsPath || init.itemsPath;\n const cursorPath = pagination.nextCursorPath || pagination.cursorPath;\n const maxPagesRaw = Number(pagination.maxPages || init.maxPages || 50);\n const maxPages = Math.max(1, Math.min(Number.isFinite(maxPagesRaw) ? maxPagesRaw : 50, 200));\n const baseInit = _withoutProviderFetchAllOptions(init);\n let query = _cloneJson(init.query || {});\n let body = _cloneJson(init.body);\n let pageNumber = Number(pagination.startPage || 1);\n let offset = Number(pagination.startOffset || 0);\n const pages = [];\n const items = [];\n let lastCursor = null;\n let stoppedReason = \"completed\";\n\n for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {\n if (pagination.pageParam) {\n query = { ...(query || {}), [pagination.pageParam]: pageNumber };\n }\n if (pagination.offsetParam) {\n query = { ...(query || {}), [pagination.offsetParam]: offset };\n }\n\n const page = await providerFetch(provider, apiPath, {\n ...baseInit,\n query,\n ...(body !== undefined ? { body } : {}),\n });\n pages.push(page);\n const pageItems = _extractItems(page, itemsPath);\n items.push(...pageItems);\n\n const nextCursor = cursorPath ? _getByPath(page, cursorPath) : undefined;\n if (nextCursor !== undefined && nextCursor !== null && String(nextCursor) !== \"\") {\n if (lastCursor !== null && String(nextCursor) === String(lastCursor)) {\n stoppedReason = \"repeated-cursor\";\n break;\n }\n lastCursor = nextCursor;\n if (pagination.cursorBodyPath) {\n body = _setByPath(body || {}, pagination.cursorBodyPath, nextCursor);\n } else if (pagination.cursorParam) {\n query = { ...(query || {}), [pagination.cursorParam]: nextCursor };\n } else {\n stoppedReason = \"cursor-found-without-destination\";\n break;\n }\n continue;\n }\n\n lastCursor = null;\n if (pagination.pageParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n pageNumber += 1;\n continue;\n }\n if (pagination.offsetParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n const step = Number(pagination.pageSize || pageItems.length);\n if (!Number.isFinite(step) || step <= 0) {\n stoppedReason = \"invalid-page-size\";\n break;\n }\n offset += step;\n if (pagination.pageSize && pageItems.length < Number(pagination.pageSize)) {\n stoppedReason = \"short-page\";\n break;\n }\n continue;\n }\n\n break;\n }\n\n const hitPageOrOffsetLimit =\n Boolean(pagination.pageParam || pagination.offsetParam) &&\n stoppedReason === \"completed\" &&\n pages.length >= maxPages;\n const hasMore =\n (lastCursor !== null && pages.length >= maxPages) || hitPageOrOffsetLimit;\n if (hasMore) stoppedReason = \"max-pages\";\n return {\n items,\n pages,\n pageCount: pages.length,\n itemCount: items.length,\n hasMore,\n lastCursor,\n stoppedReason,\n };\n}\n\n/**\n * Make an outbound HTTP request via the web-request action.\n * Returns an object \\`{ status, body }\\` where \\`body\\` is the response text.\n */\nasync function webFetch(url, init = {}) {\n const method = (init.method || \"GET\").toUpperCase();\n const rawResult = await _bridgeCall(\"web-request\", {\n url,\n method,\n ...(init.headers ? { headers: typeof init.headers === \"string\" ? init.headers : JSON.stringify(init.headers) } : {}),\n ...(init.body ? { body: typeof init.body === \"string\" ? init.body : JSON.stringify(init.body) } : {}),\n ...(init.responseMode ? { responseMode: init.responseMode } : {}),\n ...(init.extract ? { extract: init.extract } : {}),\n ...(init.includeLinks !== undefined ? { includeLinks: init.includeLinks } : {}),\n ...(init.search ? { search: init.search } : {}),\n ...(init.maxChars ? { maxChars: init.maxChars } : {}),\n ...(init.saveToFile ? { saveToFile: init.saveToFile } : {}),\n });\n // rawResult is \"HTTP <status> <statusText>\\\\n\\\\n<body>\"\n const statusMatch = typeof rawResult === \"string\" ? rawResult.match(/^HTTP (\\\\d+) [^\\\\n]*\\\\n\\\\n/) : null;\n if (statusMatch) {\n return {\n status: Number(statusMatch[1]),\n body: rawResult.slice(statusMatch[0].length),\n };\n }\n return { status: 0, body: rawResult };\n}\n\nasync function webRead(url, init = {}) {\n return webFetch(url, {\n responseMode: \"auto\",\n includeLinks: true,\n ...init,\n });\n}\n\n/**\n * Read a Resources-backed workspace file by path. Returns the file content as\n * a string, or null if not found.\n * Supports optional offset and maxChars for paging large files.\n */\nasync function workspaceRead(path, opts = {}) {\n const parsed = await workspaceReadMeta(path, opts);\n if (parsed && parsed.ok === false) return null;\n return parsed && typeof parsed.content === \"string\" ? parsed.content : null;\n}\n\n/**\n * Read a workspace file by path and return the full metadata envelope.\n * Use this when offset/maxChars paging or truncation status matters.\n */\nasync function workspaceReadMeta(path, opts = {}) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"read\",\n path,\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.maxChars !== undefined ? { maxChars: opts.maxChars } : {}),\n });\n return _parseBridgeResult(rawResult);\n}\n\n/**\n * Write (create or overwrite) a workspace file. Use \\`scratch/...\\` for\n * temporary staging files.\n * \\`content\\` must be a string. Returns metadata { path, sizeBytes, updatedAt }.\n */\nasync function workspaceWrite(path, content, contentType = \"text/plain\") {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"write\",\n path,\n content: typeof content === \"string\" ? content : JSON.stringify(content),\n contentType,\n });\n try { return typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult; } catch { return rawResult; }\n}\n\n/**\n * Append text to a workspace file (creates if absent).\n */\nasync function workspaceAppend(path, content) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"append\",\n path,\n content: typeof content === \"string\" ? content : JSON.stringify(content),\n });\n try { return typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult; } catch { return rawResult; }\n}\n\n/**\n * List workspace files, optionally filtered by path prefix.\n * Returns an array of { path, sizeBytes, contentType, updatedAt }.\n */\nasync function workspaceList(prefix) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"list\",\n ...(prefix ? { path: prefix } : {}),\n });\n const parsed = typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult;\n if (parsed && Array.isArray(parsed.files)) return parsed.files;\n if (Array.isArray(parsed)) return parsed;\n throw new Error(\"workspaceList: unexpected result shape: \" + JSON.stringify(parsed).slice(0, 200));\n}\n\n// Run user code\n(async () => {\n${userCode}\n})().catch((err) => {\n console.error(\"Unhandled error:\", err?.message ?? String(err));\n process.exit(1);\n});\n`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"run-code.js","sourceRoot":"","sources":["../../src/coding-tools/run-code.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,IAAI,MAAM,WAAW,CAAC;AAI7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,kBAAkB,GAAG,OAAO,CAAC;AACnC,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,MAAM,wBAAwB,GAAG,MAAM,CAAC;AACxC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AACjC,uFAAuF;AACvF,MAAM,qBAAqB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAE/C,wDAAwD;AACxD,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACnC,sBAAsB;IACtB,mBAAmB;IACnB,sBAAsB;IACtB,aAAa;IACb,iBAAiB;CAClB,CAAC,CAAC;AAUH;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,UAA6C,EAC7C,IAAI,GAAmB,EAAE;IAEzB,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IAEzD,OAAO;QACL,QAAQ,E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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqxBtB,QAAQ;;;;;CAKT,CAAC;AACF,CAAC","sourcesContent":["/**\n * Sandboxed JavaScript execution tool for the agent.\n *\n * Executes user-supplied JavaScript in an isolated child process with:\n * - A scrubbed environment (no app secrets or env vars; only PATH/HOME/TMPDIR).\n * - A fresh temporary working directory.\n * - An ephemeral bridge HTTP server on 127.0.0.1 so the child can call\n * allowlisted registered tools (provider-api-request, web-request, etc.)\n * with the same request context as the parent — without leaking secrets.\n *\n * Security notes:\n * - The bridge token is a 32-byte random hex string generated per invocation.\n * - The bridge binds to 127.0.0.1 only; no external exposure.\n * - The allowlist of callable bridge tools is enforced server-side.\n * - Secret values are NEVER included in the env passed to the child.\n * - When the Node permission model is available (`--permission`, or\n * `--experimental-permission` on Node 20), the child is denied filesystem\n * access outside its own temp dir, child processes, workers, and native\n * addons. Outbound network from the child is NOT blocked by the permission\n * model; the env scrub means such requests carry no credentials, and all\n * authenticated calls must go through the bridge (which applies the\n * registered tools' host allowlists and SSRF guards).\n *\n * The actual execution is delegated to a pluggable `SandboxAdapter` (see\n * `./sandbox`). The default `LocalChildProcessAdapter` preserves the spawned\n * child-process behavior described above; a remote/durable adapter can be\n * plugged in via `registerSandboxAdapter()` / `AGENT_NATIVE_SANDBOX` without\n * changing this file. The bridge, env scrub, module building, and output\n * formatting stay here in the parent regardless of adapter.\n */\n\nimport crypto from \"node:crypto\";\nimport http from \"node:http\";\n\nimport type { ActionRunContext } from \"../action.js\";\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { getSandboxAdapter } from \"./sandbox/index.js\";\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst MAX_TIMEOUT_MS = 600_000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 50_000;\nconst MAX_OUTPUT_CHARS = 200_000;\n/** Hard cap on bridge request bodies so sandboxed code can't exhaust parent memory. */\nconst BRIDGE_MAX_BODY_BYTES = 10 * 1024 * 1024;\n\n/** Tools callable via the sandbox bridge by default. */\nconst DEFAULT_BRIDGE_TOOLS = new Set([\n \"provider-api-request\",\n \"provider-api-docs\",\n \"provider-api-catalog\",\n \"web-request\",\n \"workspace-files\",\n]);\n\nexport interface RunCodeOptions {\n /**\n * Extra tool names (beyond the default set) that the sandbox bridge will\n * forward to the registered action registry.\n */\n bridgeTools?: string[];\n}\n\n/**\n * Create a `run-code` ActionEntry.\n *\n * @param getActions Supplier that returns the current action registry (called\n * at invocation time so updates are reflected).\n * @param opts Optional configuration.\n */\nexport function createRunCodeEntry(\n getActions: () => Record<string, ActionEntry>,\n opts: RunCodeOptions = {},\n): ActionEntry {\n const extraBridgeTools = new Set(opts.bridgeTools ?? []);\n\n return {\n readOnly: true,\n allowInPlanMode: false,\n // Allow a generous per-call timeout so large data-processing jobs don't hit\n // the agent-loop's default 60 s cap.\n timeoutMs: MAX_TIMEOUT_MS,\n maxResultChars: MAX_OUTPUT_CHARS,\n tool: {\n description: [\n \"Execute JavaScript (Node.js, ESM, top-level await supported) in an isolated sandbox.\",\n \"Use this to fetch, join, aggregate, and reduce large datasets, returning only printed output to the conversation.\",\n \"The sandbox runs with a scrubbed environment (no secrets) and, where the Node permission model is available, no filesystem access outside its own temp dir, no child processes, and no workers. Authenticated calls must go through the provided globals; direct network requests carry no credentials. Note: isolation is process-level (env scrub + Node permission model), not an OS-level container — outbound network from sandbox code is not blocked.\",\n \"Available globals:\",\n \" - `appAction(name, args?)` — call any registered agent-exposed read-only app action/tool and get its parsed result.\",\n \" Use this to loop over app data readers and compose multi-source analyses without forcing every intermediate result into chat.\",\n \" - `providerFetch(provider, path, init?)` — authenticated call to a registered provider via the provider-api-request action.\",\n \" Returns the parsed JSON result (or throws on error).\",\n \" Supports stageAs/saveToFile/fetchAllPages; use cursorBodyPath for POST-body pagination.\",\n \" Example: `const data = await providerFetch('<provider-id>', '/records', { query: { limit: 100 } });`\",\n \" - `providerRequest(provider, path, init?)` — same authenticated call, but returns the full provider-api envelope with request, response status/headers, truncation, and body metadata.\",\n \" - `providerFetchAll(provider, path, init?)` — generic pagination helper for cursor, page, and offset APIs. Pass `pagination: { itemsPath, cursorPath or nextCursorPath, cursorParam or cursorBodyPath, pageParam, offsetParam, pageSize, maxPages }`. Returns `{ items, pages, pageCount, itemCount, hasMore, lastCursor, stoppedReason }`.\",\n \" - `providerSearchAll(provider, path, init?, options?)` — streaming search helper for broad provider corpora such as transcripts, messages, tickets, issues, notes, events, or documents. Use this before hand-written loops when searching many provider records for terms/phrases/regexes or proving absence. Pass the same `pagination` config as `providerFetchAll`, plus options like `{ query, queries, terms, regex, textPaths, idPaths, metadataPaths, maxHits }`. Returns structured hits with item ids, paths, snippets, page/item indexes, and coverage fields (`pageCount`, `itemCount`, `hasMore`, `stoppedReason`).\",\n \" - `webFetch(url, init?)` — outbound HTTP request via the web-request action.\",\n \" Returns `{ status, body }` where body is the response text. Supports responseMode, extract, includeLinks, search, maxChars, and saveToFile.\",\n \" Example: `const { body } = await webFetch('https://api.example.com/data', { responseMode: 'raw' });`\",\n \" - `webRead(url, init?)` — convenience wrapper for webFetch with `responseMode: 'auto'` and extracted HTML/markdown or bounded matches.\",\n \" Example: `const docs = await webRead('https://docs.example.com/api', { search: { query: 'pagination' } });`\",\n \" - `workspaceRead(path, opts?)` — read a Resources-backed workspace file by path. Returns content string or null. opts: { offset?, maxChars? }.\",\n \" - `workspaceReadMeta(path, opts?)` — read a workspace file with metadata such as sizeBytes, truncated, and nextOffset.\",\n \" - `workspaceWrite(path, content, contentType?)` — create or overwrite a workspace file. Use `scratch/...` for temporary staging; use durable folders only for files the user should keep.\",\n \" - `workspaceAppend(path, content)` — append text to a workspace file.\",\n \" - `workspaceList(prefix?)` — list workspace files, returns [{ path, sizeBytes, contentType, updatedAt }].\",\n \"Print results with `console.log()`; only stdout+stderr are returned.\",\n \"Timeout defaults to 120 s (max 600 s). Output is truncated to 50 000 chars by default (max 200 000).\",\n ].join(\" \"),\n parameters: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description:\n \"JavaScript source to execute. ESM syntax, top-level await allowed.\",\n },\n timeoutMs: {\n type: \"number\",\n description: `Execution timeout in milliseconds. Default: ${DEFAULT_TIMEOUT_MS}. Max: ${MAX_TIMEOUT_MS}.`,\n },\n maxOutputChars: {\n type: \"number\",\n description: `Maximum combined stdout+stderr characters to return. Default: ${DEFAULT_MAX_OUTPUT_CHARS}. Max: ${MAX_OUTPUT_CHARS}.`,\n },\n },\n required: [\"code\"],\n },\n },\n run: async (args: Record<string, string>, context?: ActionRunContext) => {\n const code = typeof args.code === \"string\" ? args.code : \"\";\n if (!code.trim()) return \"Error: code is required.\";\n\n const requestedTimeout = Number(args.timeoutMs);\n const timeoutMs =\n Number.isFinite(requestedTimeout) && requestedTimeout > 0\n ? Math.min(requestedTimeout, MAX_TIMEOUT_MS)\n : DEFAULT_TIMEOUT_MS;\n\n const requestedMaxOutput = Number(args.maxOutputChars);\n const maxOutputChars =\n Number.isFinite(requestedMaxOutput) && requestedMaxOutput > 0\n ? Math.min(requestedMaxOutput, MAX_OUTPUT_CHARS)\n : DEFAULT_MAX_OUTPUT_CHARS;\n\n const actions = getActions();\n const bridgeToken = crypto.randomBytes(32).toString(\"hex\");\n\n // Start bridge server — resolves once the server is listening.\n const {\n bridgePort,\n getUsedTools,\n cleanup: cleanupBridge,\n } = await startBridgeServer(\n bridgeToken,\n actions,\n context,\n DEFAULT_BRIDGE_TOOLS,\n extraBridgeTools,\n );\n\n try {\n // Build scrubbed env — only safe POSIX vars, no secrets. The adapter\n // points TMPDIR/TEMP/TMP at the sandbox's own temp dir.\n const safeEnv: Record<string, string> = {};\n for (const key of [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"TEMP\",\n \"TMP\",\n \"LANG\",\n \"LC_ALL\",\n ]) {\n if (process.env[key]) safeEnv[key] = process.env[key]!;\n }\n\n // Delegate execution to the active sandbox adapter (local child process\n // by default; remote/durable adapters can be registered via\n // ./sandbox). The bridge, env scrub, module, and output formatting stay\n // in the parent regardless of adapter.\n const { stdout, stderr, exitCode, timedOut } =\n await getSandboxAdapter().run({\n moduleSource: buildSandboxModule(code, bridgePort, bridgeToken),\n env: safeEnv,\n timeoutMs,\n bridgePort,\n });\n\n const combined =\n [\n stdout ? `stdout:\\n${stdout}` : \"\",\n stderr ? `stderr:\\n${stderr}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\\n\") || \"(no output)\";\n\n const lines: string[] = [];\n if (timedOut) lines.push(`timedOut: true (${timeoutMs}ms)`);\n if (exitCode !== 0 && exitCode !== null)\n lines.push(`exitCode: ${exitCode}`);\n const usedTools = getUsedTools();\n if (usedTools.length)\n lines.push(`bridgeToolsUsed: ${usedTools.join(\", \")}`);\n lines.push(combined);\n\n const full = lines.join(\"\\n\\n\");\n if (full.length > maxOutputChars) {\n const truncated = full.slice(0, maxOutputChars);\n return `${truncated}\\n\\n...[truncated ${(full.length - maxOutputChars).toLocaleString()} chars]`;\n }\n return full;\n } finally {\n // The active sandbox adapter owns its own temp-file cleanup; the parent\n // only tears down the bridge server here.\n cleanupBridge();\n }\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bridge server\n// ---------------------------------------------------------------------------\n\ninterface BridgeResult {\n server: http.Server;\n bridgePort: number;\n getUsedTools: () => string[];\n cleanup: () => void;\n}\n\nasync function startBridgeServer(\n token: string,\n actions: Record<string, ActionEntry>,\n context: ActionRunContext | undefined,\n defaultTools: Set<string>,\n extraTools: Set<string>,\n): Promise<BridgeResult> {\n const usedTools = new Set<string>();\n const server = http.createServer((req, res) => {\n if (req.method !== \"POST\" || req.url !== \"/tool\") {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n\n // Validate bearer token — must match exactly.\n const authHeader = req.headers.authorization ?? \"\";\n if (authHeader !== `Bearer ${token}`) {\n res.writeHead(401);\n res.end(\"Unauthorized\");\n return;\n }\n\n let body = \"\";\n let receivedBytes = 0;\n let rejected = false;\n req.on(\"data\", (chunk: Buffer) => {\n receivedBytes += chunk.length;\n if (receivedBytes > BRIDGE_MAX_BODY_BYTES) {\n rejected = true;\n res.writeHead(413);\n res.end(\"Payload too large\");\n req.destroy();\n return;\n }\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n if (rejected) return;\n handleBridgeRequest(\n body,\n actions,\n context,\n defaultTools,\n extraTools,\n usedTools,\n res,\n );\n });\n req.on(\"error\", () => {\n res.writeHead(500);\n res.end(\"Request error\");\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve());\n });\n\n const addr = server.address() as { port: number };\n const bridgePort = addr.port;\n\n const cleanup = () => {\n try {\n server.close();\n } catch {}\n };\n\n return {\n server,\n bridgePort,\n getUsedTools: () => Array.from(usedTools).sort(),\n cleanup,\n };\n}\n\nfunction handleBridgeRequest(\n rawBody: string,\n actions: Record<string, ActionEntry>,\n context: ActionRunContext | undefined,\n defaultTools: Set<string>,\n extraTools: Set<string>,\n usedTools: Set<string>,\n res: http.ServerResponse,\n): void {\n let parsed: { tool?: string; args?: Record<string, string> };\n try {\n parsed = JSON.parse(rawBody);\n } catch {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid JSON body\" }));\n return;\n }\n\n const toolName = typeof parsed.tool === \"string\" ? parsed.tool.trim() : \"\";\n if (!toolName) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Missing tool name\" }));\n return;\n }\n\n // Enforce allowlist.\n const entry = actions[toolName];\n const isReadOnlyAction =\n entry?.readOnly === true &&\n entry.agentTool !== false &&\n entry.toolCallable !== false;\n if (\n !defaultTools.has(toolName) &&\n !extraTools.has(toolName) &&\n !isReadOnlyAction\n ) {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Tool \"${toolName}\" is not an agent-exposed read-only action or sandbox bridge allowlisted tool.`,\n }),\n );\n return;\n }\n\n if (!entry) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: `Tool \"${toolName}\" is not registered.` }));\n return;\n }\n\n const toolArgs = parsed.args ?? {};\n usedTools.add(toolName);\n // Run the tool with the parent request context so auth/org/owner resolution\n // works exactly as it does in the normal agent loop.\n entry\n .run(toolArgs, context)\n .then((result: unknown) => {\n const body =\n typeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ result: body }));\n })\n .catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: message }));\n });\n}\n\n// ---------------------------------------------------------------------------\n// Sandbox module template\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap the user's code in an ESM module that:\n * 1. Defines `providerFetch`, `providerRequest`, `providerFetchAll`,\n * `providerSearchAll`, and `webFetch` helpers via the bridge.\n * 2. Runs the user's code as top-level await in an async IIFE.\n */\nfunction buildSandboxModule(\n userCode: string,\n bridgePort: number,\n bridgeToken: string,\n): string {\n return `\nimport { createRequire } from \"node:module\";\nconst require = createRequire(import.meta.url);\n\nconst _bridgeBase = \"http://127.0.0.1:${bridgePort}/tool\";\nconst _bridgeToken = \"${bridgeToken}\";\n\nasync function _bridgeCall(tool, args) {\n const http = await import(\"node:http\");\n return new Promise((resolve, reject) => {\n const body = JSON.stringify({ tool, args });\n const options = {\n hostname: \"127.0.0.1\",\n port: ${bridgePort},\n path: \"/tool\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": Buffer.byteLength(body),\n \"Authorization\": \"Bearer \" + _bridgeToken,\n },\n };\n const req = http.request(options, (res) => {\n let data = \"\";\n res.on(\"data\", (chunk) => { data += chunk; });\n res.on(\"end\", () => {\n try {\n const parsed = JSON.parse(data);\n if (parsed.error) {\n reject(new Error(parsed.error));\n } else {\n resolve(parsed.result);\n }\n } catch (e) {\n reject(new Error(\"Bridge response parse error: \" + e.message));\n }\n });\n });\n req.on(\"error\", reject);\n req.end(body);\n });\n}\n\nfunction _parseBridgeResult(rawResult) {\n if (typeof rawResult !== \"string\") return rawResult;\n try { return JSON.parse(rawResult); } catch { return rawResult; }\n}\n\n/**\n * Call any registered agent-exposed read-only app action/tool via the sandbox bridge.\n * Mutating and explicitly hidden actions are blocked by the parent bridge.\n */\nasync function appAction(name, args = {}) {\n return _parseBridgeResult(await _bridgeCall(name, args));\n}\n\nasync function providerRequest(provider, apiPath, init = {}) {\n const method = (init.method || \"GET\").toUpperCase();\n const rawResult = await _bridgeCall(\"provider-api-request\", {\n provider,\n path: apiPath,\n method,\n ...(init.query ? { query: init.query } : {}),\n ...(init.body ? { body: init.body } : {}),\n ...(init.headers ? { headers: init.headers } : {}),\n ...(init.auth ? { auth: init.auth } : {}),\n ...(init.connectionId ? { connectionId: init.connectionId } : {}),\n ...(init.accountId ? { accountId: init.accountId } : {}),\n ...(init.timeoutMs ? { timeoutMs: init.timeoutMs } : {}),\n ...(init.maxBytes ? { maxBytes: init.maxBytes } : {}),\n ...(init.stageAs ? { stageAs: init.stageAs } : {}),\n ...(init.itemsPath ? { itemsPath: init.itemsPath } : {}),\n ...(init.pagination ? { pagination: init.pagination } : {}),\n ...(init.saveToFile ? { saveToFile: init.saveToFile } : {}),\n ...(init.fetchAllPages ? { fetchAllPages: init.fetchAllPages } : {}),\n });\n return _parseBridgeResult(rawResult);\n}\n\n/**\n * Call a provider API via the authenticated provider-api-request action.\n * Returns the parsed JSON response body (or throws on error).\n */\nasync function providerFetch(provider, apiPath, init = {}) {\n const parsed = await providerRequest(provider, apiPath, init);\n // Unwrap the provider-api-request envelope ({ provider, request, response, guidance })\n // so callers get the actual response body. fetchAllPages / saveToFile results\n // (which have no \\`response\\` field) are returned as-is.\n if (parsed && typeof parsed === \"object\" && parsed.response && typeof parsed.response === \"object\") {\n const r = parsed.response;\n if (typeof r.status === \"number\" && r.status >= 400) {\n const detail = typeof r.text === \"string\" ? r.text : JSON.stringify(r.json ?? \"\");\n throw new Error(\\`Provider request failed (\\${r.status}): \\${String(detail).slice(0, 500)}\\`);\n }\n return r.json !== undefined ? r.json : r.text;\n }\n return parsed;\n}\n\nfunction _cloneJson(value) {\n if (value === undefined || value === null) return value;\n return JSON.parse(JSON.stringify(value));\n}\n\nfunction _pathParts(path) {\n if (!path || typeof path !== \"string\") return [];\n return path\n .replace(/\\\\[(\\\\d+)\\\\]/g, \".$1\")\n .split(\".\")\n .map((part) => part.trim())\n .filter(Boolean);\n}\n\nfunction _getByPath(value, path) {\n let current = value;\n for (const part of _pathParts(path)) {\n if (current === undefined || current === null) return undefined;\n current = current[part];\n }\n return current;\n}\n\nfunction _setByPath(value, path, nextValue) {\n const parts = _pathParts(path);\n if (!parts.length) return value;\n const root = value && typeof value === \"object\" ? _cloneJson(value) : {};\n let current = root;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!current[part] || typeof current[part] !== \"object\") current[part] = {};\n current = current[part];\n }\n current[parts[parts.length - 1]] = nextValue;\n return root;\n}\n\nfunction _extractItems(page, itemsPath) {\n if (itemsPath) {\n const value = _getByPath(page, itemsPath);\n return Array.isArray(value) ? value : [];\n }\n if (Array.isArray(page)) return page;\n if (!page || typeof page !== \"object\") return [];\n for (const key of [\"data\", \"results\", \"items\", \"records\", \"rows\", \"calls\", \"callTranscripts\", \"transcripts\", \"messages\", \"tickets\", \"issues\", \"deals\", \"events\", \"notes\", \"documents\", \"entries\", \"objects\"]) {\n if (Array.isArray(page[key])) return page[key];\n }\n return [];\n}\n\nfunction _withoutProviderFetchAllOptions(init) {\n const {\n pagination: _pagination,\n fetchAllPages: _fetchAllPages,\n stageAs: _stageAs,\n itemsPath: _itemsPath,\n saveToFile: _saveToFile,\n ...rest\n } = init || {};\n return rest;\n}\n\nfunction _asArray(value) {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction _stringifySearchValue(value) {\n if (typeof value === \"string\") return value;\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction _collectStrings(value, basePath = \"\", out = [], limit = 5000) {\n if (out.length >= limit || value === undefined || value === null) return out;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n out.push({ path: basePath || \"$\", text: String(value) });\n return out;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length && out.length < limit; i++) {\n _collectStrings(value[i], basePath ? basePath + \"[\" + i + \"]\" : \"[\" + i + \"]\", out, limit);\n }\n return out;\n }\n if (typeof value === \"object\") {\n for (const key of Object.keys(value)) {\n if (out.length >= limit) break;\n _collectStrings(value[key], basePath ? basePath + \".\" + key : key, out, limit);\n }\n }\n return out;\n}\n\nfunction _collectSearchStrings(item, textPaths, maxFieldsPerItem) {\n const paths = _asArray(textPaths).filter((path) => typeof path === \"string\" && path.trim());\n if (!paths.length) return _collectStrings(item, \"\", [], maxFieldsPerItem);\n const out = [];\n for (const path of paths) {\n const value = _getByPath(item, path);\n if (value !== undefined) _collectStrings(value, path, out, maxFieldsPerItem);\n if (out.length >= maxFieldsPerItem) break;\n }\n return out;\n}\n\nfunction _firstValueByPath(value, paths) {\n for (const path of paths) {\n const found = _getByPath(value, path);\n if (found !== undefined && found !== null && String(found) !== \"\") {\n return { path, value: found };\n }\n }\n return null;\n}\n\nconst _DEFAULT_ID_PATHS = [\n \"id\",\n \"callId\",\n \"callID\",\n \"call_id\",\n \"call.id\",\n \"call.metaData.id\",\n \"metaData.id\",\n \"metadata.id\",\n \"recordId\",\n \"record_id\",\n \"objectId\",\n \"object_id\",\n \"ticketId\",\n \"ticket_id\",\n \"issueId\",\n \"issue_id\",\n \"messageId\",\n \"message_id\",\n \"conversationId\",\n \"conversation_id\",\n \"eventId\",\n \"event_id\",\n \"documentId\",\n \"document_id\",\n \"url\",\n \"webUrl\",\n \"permalink\",\n];\n\nfunction _extractItemIdentity(item, idPaths) {\n const paths = [\n ..._asArray(idPaths).filter((path) => typeof path === \"string\" && path.trim()),\n ..._DEFAULT_ID_PATHS,\n ];\n const found = _firstValueByPath(item, paths);\n if (!found) return { id: null, idPath: null };\n return { id: _stringifySearchValue(found.value), idPath: found.path };\n}\n\nfunction _extractMetadata(item, metadataPaths) {\n const metadata = {};\n for (const path of _asArray(metadataPaths)) {\n if (typeof path !== \"string\" || !path.trim()) continue;\n const value = _getByPath(item, path);\n if (value !== undefined) metadata[path] = value;\n }\n return metadata;\n}\n\nfunction _makeSnippet(text, index, contextChars) {\n const source = String(text);\n const context = Math.max(20, Math.min(Number(contextChars) || 180, 1000));\n const start = Math.max(0, index - context);\n const end = Math.min(source.length, Math.max(index, 0) + context);\n const prefix = start > 0 ? \"...\" : \"\";\n const suffix = end < source.length ? \"...\" : \"\";\n return (prefix + source.slice(start, end) + suffix).replace(/\\\\s+/g, \" \").trim();\n}\n\nfunction _normalizeFlags(flags, caseSensitive) {\n const raw = typeof flags === \"string\" ? flags : \"\";\n const allowed = raw.replace(/[^dgimsuvy]/g, \"\");\n const withoutGlobalOrSticky = allowed.replace(/[gy]/g, \"\");\n const withCase =\n caseSensitive || /i/.test(withoutGlobalOrSticky)\n ? withoutGlobalOrSticky\n : withoutGlobalOrSticky + \"i\";\n return withCase + \"g\";\n}\n\nfunction _normalizedSearchTerms(options) {\n const explicitTerms = _asArray(options.terms)\n .map((term) => String(term).trim())\n .filter(Boolean);\n if (explicitTerms.length) return explicitTerms;\n if (options.matchMode === \"allTerms\" && typeof options.query === \"string\") {\n return options.query\n .split(/\\\\s+/)\n .map((term) => term.trim())\n .filter(Boolean);\n }\n return [];\n}\n\nfunction _findItemWideTermMatch(fields, options) {\n const terms = _normalizedSearchTerms(options);\n if (!terms.length || options.matchMode === \"anyTerm\") return null;\n const caseSensitive = Boolean(options.caseSensitive);\n const normalizedFields = fields.map((field) => ({\n field,\n haystack: caseSensitive ? String(field.text) : String(field.text).toLowerCase(),\n }));\n const termHits = terms.map((term) => {\n const searchTerm = caseSensitive ? term : term.toLowerCase();\n for (const entry of normalizedFields) {\n const index = entry.haystack.indexOf(searchTerm);\n if (index >= 0) return { term, field: entry.field, index };\n }\n return { term, field: null, index: -1 };\n });\n if (termHits.some((hit) => hit.index < 0 || !hit.field)) return null;\n const first = termHits\n .filter((hit) => hit.field)\n .sort((a, b) => {\n const fieldOrder = fields.indexOf(a.field) - fields.indexOf(b.field);\n return fieldOrder || a.index - b.index;\n })[0];\n return {\n field: first.field,\n match: {\n kind: \"allTerms\",\n query: terms.join(\" \"),\n index: first.index,\n match: first.term,\n },\n };\n}\n\nfunction _findSearchMatches(text, options, includeTerms = true) {\n const source = String(text);\n const caseSensitive = Boolean(options.caseSensitive);\n const haystack = caseSensitive ? source : source.toLowerCase();\n const maxMatchesPerField = _boundedNumber(options.maxMatchesPerField, 1000, 1, 100000);\n const matches = [];\n\n const addSubstring = (needle, label, kind) => {\n if (needle === undefined || needle === null) return;\n const rawNeedle = String(needle);\n if (!rawNeedle) return;\n const searchNeedle = caseSensitive ? rawNeedle : rawNeedle.toLowerCase();\n let from = 0;\n while (from <= haystack.length) {\n const index = haystack.indexOf(searchNeedle, from);\n if (index < 0) break;\n matches.push({ kind, query: label ?? rawNeedle, index, match: source.slice(index, index + rawNeedle.length) });\n from = index + Math.max(1, searchNeedle.length);\n if (matches.length >= maxMatchesPerField) break;\n }\n };\n\n if (options.regex) {\n try {\n const regex = new RegExp(String(options.regex), _normalizeFlags(options.regexFlags, caseSensitive));\n let match;\n while ((match = regex.exec(source)) && typeof match.index === \"number\") {\n matches.push({ kind: \"regex\", query: String(options.regex), index: match.index, match: match[0] });\n if (matches.length >= maxMatchesPerField) break;\n if (match[0] === \"\") regex.lastIndex += 1;\n }\n } catch (err) {\n throw new Error(\"providerSearchAll invalid regex: \" + (err?.message || err));\n }\n }\n\n for (const query of _asArray(options.query).concat(_asArray(options.queries))) {\n addSubstring(query, String(query), \"query\");\n }\n\n const terms = includeTerms ? _normalizedSearchTerms(options) : [];\n if (terms.length) {\n const termHits = terms\n .map((term) => {\n const searchTerm = caseSensitive ? term : term.toLowerCase();\n const index = haystack.indexOf(searchTerm);\n return { term, index };\n })\n .filter((hit) => hit.index >= 0);\n const mode = options.matchMode === \"anyTerm\" ? \"anyTerm\" : \"allTerms\";\n if ((mode === \"allTerms\" && termHits.length === terms.length) || (mode === \"anyTerm\" && termHits.length > 0)) {\n const first = termHits.sort((a, b) => a.index - b.index)[0];\n matches.push({ kind: mode, query: terms.join(\" \"), index: first.index, match: first.term });\n }\n }\n\n return matches.sort((a, b) => a.index - b.index);\n}\n\nfunction _boundedNumber(value, defaultValue, min, max) {\n const parsed = Number(value);\n const finite = Number.isFinite(parsed) ? parsed : defaultValue;\n return Math.max(min, Math.min(finite, max));\n}\n\nfunction _hitKey(identity, path, query, index, pageIndex, pageItemIndex) {\n const itemKey =\n identity.id !== null && identity.id !== undefined\n ? \"id:\" + identity.id\n : \"page:\" + String(pageIndex) + \":\" + String(pageItemIndex);\n return [itemKey, path ?? \"\", query ?? \"\", String(index ?? \"\")].join(\"\\\\n\");\n}\n\n/**\n * Stream pages from a provider API and search item text structurally. This is\n * for broad mention searches and absence checks where keeping every raw page\n * in memory or hand-parsing JSON strings is brittle.\n */\nasync function providerSearchAll(provider, apiPath, init = {}, options = {}) {\n const pagination = init.pagination || init.fetchAllPages || {};\n const itemsPath = pagination.itemsPath || init.itemsPath || options.itemsPath;\n const cursorPath = pagination.nextCursorPath || pagination.cursorPath;\n const maxPagesRaw = Number(pagination.maxPages || init.maxPages || options.maxPages || 100);\n const maxPages = Math.max(1, Math.min(Number.isFinite(maxPagesRaw) ? maxPagesRaw : 100, 500));\n const maxHits = _boundedNumber(options.maxHits, 100, 1, 5000);\n const maxHitsPerItem = _boundedNumber(options.maxHitsPerItem, 3, 1, 100);\n const maxFieldsPerItem = _boundedNumber(options.maxFieldsPerItem, 5000, 1, 50000);\n const contextChars = options.contextChars ?? options.snippetChars ?? 180;\n const baseInit = _withoutProviderFetchAllOptions(init);\n let query = _cloneJson(init.query || {});\n let body = _cloneJson(init.body);\n let pageNumber = Number(pagination.startPage || 1);\n let offset = Number(pagination.startOffset || 0);\n let lastCursor = null;\n let stoppedReason = \"completed\";\n let itemCount = 0;\n let matchedItemCount = 0;\n let totalHitCount = 0;\n const hits = [];\n const seenHitKeys = new Set();\n let pageIndex = 0;\n\n for (; pageIndex < maxPages; pageIndex++) {\n if (pagination.pageParam) query = { ...(query || {}), [pagination.pageParam]: pageNumber };\n if (pagination.offsetParam) query = { ...(query || {}), [pagination.offsetParam]: offset };\n\n const page = await providerFetch(provider, apiPath, {\n ...baseInit,\n query,\n ...(body !== undefined ? { body } : {}),\n });\n const nextCursor = cursorPath ? _getByPath(page, cursorPath) : undefined;\n const hasNextCursor =\n nextCursor !== undefined && nextCursor !== null && String(nextCursor) !== \"\";\n if (hasNextCursor && lastCursor !== null && String(nextCursor) === String(lastCursor)) {\n stoppedReason = \"repeated-cursor\";\n break;\n }\n\n const pageItems = _extractItems(page, itemsPath);\n itemCount += pageItems.length;\n\n for (let pageItemIndex = 0; pageItemIndex < pageItems.length; pageItemIndex++) {\n const item = pageItems[pageItemIndex];\n const identity = _extractItemIdentity(item, options.idPaths);\n const metadata = _extractMetadata(item, options.metadataPaths);\n const fields = _collectSearchStrings(item, options.textPaths, maxFieldsPerItem);\n let storedItemHitCount = 0;\n let itemMatched = false;\n\n const addHit = (field, match) => {\n const key = _hitKey(identity, field.path, match.query, match.index, pageIndex, pageItemIndex);\n if (seenHitKeys.has(key)) return false;\n seenHitKeys.add(key);\n totalHitCount += 1;\n if (!itemMatched) {\n matchedItemCount += 1;\n itemMatched = true;\n }\n if (hits.length < maxHits && storedItemHitCount < maxHitsPerItem) {\n storedItemHitCount += 1;\n hits.push({\n id: identity.id,\n idPath: identity.idPath,\n pageIndex,\n pageItemIndex,\n itemIndex: itemCount - pageItems.length + pageItemIndex,\n path: field.path,\n kind: match.kind,\n query: match.query,\n match: match.match,\n snippet: _makeSnippet(field.text, match.index, contextChars),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n });\n }\n return true;\n };\n\n const itemWideTermMatch = _findItemWideTermMatch(fields, options);\n if (itemWideTermMatch) {\n addHit(itemWideTermMatch.field, itemWideTermMatch.match);\n }\n\n for (const field of fields) {\n const fieldMatches = _findSearchMatches(field.text, options, !itemWideTermMatch);\n for (const match of fieldMatches) {\n addHit(field, match);\n }\n }\n }\n\n if (hasNextCursor) {\n lastCursor = nextCursor;\n if (pagination.cursorBodyPath) {\n body = _setByPath(body || {}, pagination.cursorBodyPath, nextCursor);\n } else if (pagination.cursorParam) {\n query = { ...(query || {}), [pagination.cursorParam]: nextCursor };\n } else {\n stoppedReason = \"cursor-found-without-destination\";\n break;\n }\n continue;\n }\n\n lastCursor = null;\n if (pagination.pageParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n pageNumber += 1;\n continue;\n }\n if (pagination.offsetParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n const step = Number(pagination.pageSize || pageItems.length);\n if (!Number.isFinite(step) || step <= 0) {\n stoppedReason = \"invalid-page-size\";\n break;\n }\n offset += step;\n if (pagination.pageSize && pageItems.length < Number(pagination.pageSize)) {\n stoppedReason = \"short-page\";\n break;\n }\n continue;\n }\n\n break;\n }\n\n const pageCount = pageIndex + (pageIndex < maxPages ? 1 : 0);\n const hitPageOrOffsetLimit =\n Boolean(pagination.pageParam || pagination.offsetParam) &&\n stoppedReason === \"completed\" &&\n pageCount >= maxPages;\n const hasMore =\n stoppedReason === \"cursor-found-without-destination\" ||\n (lastCursor !== null && pageCount >= maxPages) || hitPageOrOffsetLimit;\n if (hasMore && stoppedReason === \"completed\") stoppedReason = \"max-pages\";\n\n return {\n hits,\n hitCount: hits.length,\n totalHitCount,\n truncatedHits: totalHitCount > hits.length,\n matchedItemCount,\n itemCount,\n pageCount,\n hasMore,\n lastCursor,\n stoppedReason,\n searched: {\n provider,\n path: apiPath,\n itemsPath: itemsPath || null,\n textPaths: _asArray(options.textPaths),\n idPaths: _asArray(options.idPaths),\n query: options.query ?? null,\n queries: _asArray(options.queries),\n terms: _asArray(options.terms),\n regex: options.regex ?? null,\n matchMode: options.matchMode || (options.terms ? \"allTerms\" : \"query\"),\n caseSensitive: Boolean(options.caseSensitive),\n },\n };\n}\n\n/**\n * Fetch every page from a provider API using generic cursor, page-number, or\n * offset pagination. Prefer this inside run-code when the answer depends on a\n * broad provider corpus rather than a single bounded request.\n */\nasync function providerFetchAll(provider, apiPath, init = {}) {\n const pagination = init.pagination || init.fetchAllPages || {};\n const itemsPath = pagination.itemsPath || init.itemsPath;\n const cursorPath = pagination.nextCursorPath || pagination.cursorPath;\n const maxPagesRaw = Number(pagination.maxPages || init.maxPages || 50);\n const maxPages = Math.max(1, Math.min(Number.isFinite(maxPagesRaw) ? maxPagesRaw : 50, 200));\n const baseInit = _withoutProviderFetchAllOptions(init);\n let query = _cloneJson(init.query || {});\n let body = _cloneJson(init.body);\n let pageNumber = Number(pagination.startPage || 1);\n let offset = Number(pagination.startOffset || 0);\n const pages = [];\n const items = [];\n let lastCursor = null;\n let stoppedReason = \"completed\";\n\n for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {\n if (pagination.pageParam) {\n query = { ...(query || {}), [pagination.pageParam]: pageNumber };\n }\n if (pagination.offsetParam) {\n query = { ...(query || {}), [pagination.offsetParam]: offset };\n }\n\n const page = await providerFetch(provider, apiPath, {\n ...baseInit,\n query,\n ...(body !== undefined ? { body } : {}),\n });\n pages.push(page);\n const pageItems = _extractItems(page, itemsPath);\n items.push(...pageItems);\n\n const nextCursor = cursorPath ? _getByPath(page, cursorPath) : undefined;\n if (nextCursor !== undefined && nextCursor !== null && String(nextCursor) !== \"\") {\n if (lastCursor !== null && String(nextCursor) === String(lastCursor)) {\n stoppedReason = \"repeated-cursor\";\n break;\n }\n lastCursor = nextCursor;\n if (pagination.cursorBodyPath) {\n body = _setByPath(body || {}, pagination.cursorBodyPath, nextCursor);\n } else if (pagination.cursorParam) {\n query = { ...(query || {}), [pagination.cursorParam]: nextCursor };\n } else {\n stoppedReason = \"cursor-found-without-destination\";\n break;\n }\n continue;\n }\n\n lastCursor = null;\n if (pagination.pageParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n pageNumber += 1;\n continue;\n }\n if (pagination.offsetParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n const step = Number(pagination.pageSize || pageItems.length);\n if (!Number.isFinite(step) || step <= 0) {\n stoppedReason = \"invalid-page-size\";\n break;\n }\n offset += step;\n if (pagination.pageSize && pageItems.length < Number(pagination.pageSize)) {\n stoppedReason = \"short-page\";\n break;\n }\n continue;\n }\n\n break;\n }\n\n const hitPageOrOffsetLimit =\n Boolean(pagination.pageParam || pagination.offsetParam) &&\n stoppedReason === \"completed\" &&\n pages.length >= maxPages;\n const hasMore =\n (lastCursor !== null && pages.length >= maxPages) || hitPageOrOffsetLimit;\n if (hasMore) stoppedReason = \"max-pages\";\n return {\n items,\n pages,\n pageCount: pages.length,\n itemCount: items.length,\n hasMore,\n lastCursor,\n stoppedReason,\n };\n}\n\n/**\n * Make an outbound HTTP request via the web-request action.\n * Returns an object \\`{ status, body }\\` where \\`body\\` is the response text.\n */\nasync function webFetch(url, init = {}) {\n const method = (init.method || \"GET\").toUpperCase();\n const rawResult = await _bridgeCall(\"web-request\", {\n url,\n method,\n ...(init.headers ? { headers: typeof init.headers === \"string\" ? init.headers : JSON.stringify(init.headers) } : {}),\n ...(init.body ? { body: typeof init.body === \"string\" ? init.body : JSON.stringify(init.body) } : {}),\n ...(init.responseMode ? { responseMode: init.responseMode } : {}),\n ...(init.extract ? { extract: init.extract } : {}),\n ...(init.includeLinks !== undefined ? { includeLinks: init.includeLinks } : {}),\n ...(init.search ? { search: init.search } : {}),\n ...(init.maxChars ? { maxChars: init.maxChars } : {}),\n ...(init.saveToFile ? { saveToFile: init.saveToFile } : {}),\n });\n // rawResult is \"HTTP <status> <statusText>\\\\n\\\\n<body>\"\n const statusMatch = typeof rawResult === \"string\" ? rawResult.match(/^HTTP (\\\\d+) [^\\\\n]*\\\\n\\\\n/) : null;\n if (statusMatch) {\n return {\n status: Number(statusMatch[1]),\n body: rawResult.slice(statusMatch[0].length),\n };\n }\n return { status: 0, body: rawResult };\n}\n\nasync function webRead(url, init = {}) {\n return webFetch(url, {\n responseMode: \"auto\",\n includeLinks: true,\n ...init,\n });\n}\n\n/**\n * Read a Resources-backed workspace file by path. Returns the file content as\n * a string, or null if not found.\n * Supports optional offset and maxChars for paging large files.\n */\nasync function workspaceRead(path, opts = {}) {\n const parsed = await workspaceReadMeta(path, opts);\n if (parsed && parsed.ok === false) return null;\n return parsed && typeof parsed.content === \"string\" ? parsed.content : null;\n}\n\n/**\n * Read a workspace file by path and return the full metadata envelope.\n * Use this when offset/maxChars paging or truncation status matters.\n */\nasync function workspaceReadMeta(path, opts = {}) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"read\",\n path,\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.maxChars !== undefined ? { maxChars: opts.maxChars } : {}),\n });\n return _parseBridgeResult(rawResult);\n}\n\n/**\n * Write (create or overwrite) a workspace file. Use \\`scratch/...\\` for\n * temporary staging files.\n * \\`content\\` must be a string. Returns metadata { path, sizeBytes, updatedAt }.\n */\nasync function workspaceWrite(path, content, contentType = \"text/plain\") {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"write\",\n path,\n content: typeof content === \"string\" ? content : JSON.stringify(content),\n contentType,\n });\n try { return typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult; } catch { return rawResult; }\n}\n\n/**\n * Append text to a workspace file (creates if absent).\n */\nasync function workspaceAppend(path, content) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"append\",\n path,\n content: typeof content === \"string\" ? content : JSON.stringify(content),\n });\n try { return typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult; } catch { return rawResult; }\n}\n\n/**\n * List workspace files, optionally filtered by path prefix.\n * Returns an array of { path, sizeBytes, contentType, updatedAt }.\n */\nasync function workspaceList(prefix) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"list\",\n ...(prefix ? { path: prefix } : {}),\n });\n const parsed = typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult;\n if (parsed && Array.isArray(parsed.files)) return parsed.files;\n if (Array.isArray(parsed)) return parsed;\n throw new Error(\"workspaceList: unexpected result shape: \" + JSON.stringify(parsed).slice(0, 200));\n}\n\n// Run user code\n(async () => {\n${userCode}\n})().catch((err) => {\n console.error(\"Unhandled error:\", err?.message ?? String(err));\n process.exit(1);\n});\n`;\n}\n"]}
|
|
@@ -49,11 +49,11 @@ export declare const postAwareness: import("h3").EventHandlerWithFetch<import("h
|
|
|
49
49
|
error: string;
|
|
50
50
|
states?: undefined;
|
|
51
51
|
} | {
|
|
52
|
-
error?: undefined;
|
|
53
52
|
states: {
|
|
54
53
|
clientId: number;
|
|
55
54
|
state: string;
|
|
56
55
|
}[];
|
|
56
|
+
error?: undefined;
|
|
57
57
|
}>>;
|
|
58
58
|
/**
|
|
59
59
|
* GET /_agent-native/collab/:docId/users
|
|
@@ -64,10 +64,10 @@ export declare const getActiveUsers: import("h3").EventHandlerWithFetch<import("
|
|
|
64
64
|
error: string;
|
|
65
65
|
users?: undefined;
|
|
66
66
|
} | {
|
|
67
|
-
error?: undefined;
|
|
68
67
|
users: {
|
|
69
68
|
clientId: number;
|
|
70
69
|
lastSeen: number;
|
|
71
70
|
}[];
|
|
71
|
+
error?: undefined;
|
|
72
72
|
}>>;
|
|
73
73
|
//# sourceMappingURL=awareness.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"awareness.d.ts","sourceRoot":"","sources":["../../src/collab/awareness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAS3C,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;CAClB;AAOD,eAAO,MAAM,sBAAsB,EAAG,kBAA2B,CAAC;AAElE,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,WAAW,CAAC;IACpB,IAAI,EAAE,kBAAkB,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,2EAA2E;IAC3E,MAAM,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACnD,gFAAgF;IAChF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sCAAsC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAKD,wBAAgB,mBAAmB,IAAI,YAAY,CAElD;AAED,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,KAAK,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,EAClD,KAAK,CAAC,EAAE,MAAM,EACd,KAAK,CAAC,EAAE,MAAM,GACb,IAAI,CAUN;AAKD,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAO1E;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,EAAE,cA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AAa;;;;;kBAuCa,MAAM;eAAS,MAAM;;;GAa1D,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,cAAc;;;;;kBAWM,MAAM;kBAAY,MAAM;;;GAMvD,CAAC"}
|
package/dist/collab/routes.d.ts
CHANGED
|
@@ -26,8 +26,8 @@ export declare const getCollabState: import("h3").EventHandlerWithFetch<import("
|
|
|
26
26
|
* Body: { update: string (base64), requestSource?: string }
|
|
27
27
|
*/
|
|
28
28
|
export declare const postCollabUpdate: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
|
|
29
|
-
ok?: undefined;
|
|
30
29
|
error: string;
|
|
30
|
+
ok?: undefined;
|
|
31
31
|
} | {
|
|
32
32
|
error?: undefined;
|
|
33
33
|
ok: boolean;
|
|
@@ -3,18 +3,18 @@ declare const _default: import("../../action.js").ActionDefinition<{
|
|
|
3
3
|
url?: string;
|
|
4
4
|
filename?: string;
|
|
5
5
|
}, {
|
|
6
|
-
id?: undefined;
|
|
7
6
|
error: string;
|
|
8
7
|
configured?: undefined;
|
|
9
8
|
connectPath?: undefined;
|
|
10
9
|
url?: undefined;
|
|
10
|
+
id?: undefined;
|
|
11
11
|
provider?: undefined;
|
|
12
12
|
} | {
|
|
13
|
-
id?: undefined;
|
|
14
13
|
error: string;
|
|
15
14
|
configured: boolean;
|
|
16
15
|
connectPath: string;
|
|
17
16
|
url?: undefined;
|
|
17
|
+
id?: undefined;
|
|
18
18
|
provider?: undefined;
|
|
19
19
|
} | {
|
|
20
20
|
error?: undefined;
|
|
@@ -37,6 +37,7 @@ export interface WebhookHandlerOptions {
|
|
|
37
37
|
handled: false;
|
|
38
38
|
}>;
|
|
39
39
|
}
|
|
40
|
+
export declare function resolveIntegrationApiKey(engineOption: WebhookHandlerOptions["engine"], ownerEmail: string, fallbackApiKey: string): Promise<string | undefined>;
|
|
40
41
|
/**
|
|
41
42
|
* Process an incoming webhook from a messaging platform.
|
|
42
43
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webhook-handler.d.ts","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAiBlC,OAAO,KAAK,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAML,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"webhook-handler.d.ts","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAiBlC,OAAO,KAAK,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAML,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;AAoBtC,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AA4BnE,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,eAAe,CAAC;IACzB,oCAAoC;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,mCAAmC;IACnC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACrC,qEAAqE;IACrE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wBAAwB;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,sEAAsE;IACtE,MAAM,CAAC,EACH,WAAW,GACX,MAAM,GACN;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IACtD,kEAAkE;IAClE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,yEAAyE;IACzE,aAAa,CAAC,EAAE,CACd,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,eAAe,KACrB,OAAO,CACR;QACE,OAAO,EAAE,IAAI,CAAC;QACd,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB,GACD;QAAE,OAAO,EAAE,KAAK,CAAA;KAAE,CACrB,CAAC;CACH;AA0BD,wBAAsB,wBAAwB,CAC5C,YAAY,EAAE,qBAAqB,CAAC,QAAQ,CAAC,EAC7C,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAiB7B;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,aAAa,CACjC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC,CAsE5C;AAgHD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAgCrD;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAWf"}
|
|
@@ -13,7 +13,7 @@ import { isLocalDatabase } from "../db/client.js";
|
|
|
13
13
|
import { resolveOrgIdForEmail } from "../org/context.js";
|
|
14
14
|
import { withConfiguredAppBasePath } from "../server/app-base-path.js";
|
|
15
15
|
import { FRAMEWORK_ROUTE_PREFIX } from "../server/core-routes-plugin.js";
|
|
16
|
-
import { readDeployCredentialEnv } from "../server/credential-provider.js";
|
|
16
|
+
import { canUseDeployCredentialFallbackForRequest, readDeployCredentialEnv, } from "../server/credential-provider.js";
|
|
17
17
|
import { runWithRequestContext } from "../server/request-context.js";
|
|
18
18
|
import { A2A_CONTINUATION_QUEUED_MARKER } from "./a2a-continuation-marker.js";
|
|
19
19
|
import { signInternalToken } from "./internal-token.js";
|
|
@@ -52,31 +52,31 @@ function explicitEngineName(engineOption) {
|
|
|
52
52
|
}
|
|
53
53
|
return undefined;
|
|
54
54
|
}
|
|
55
|
-
function isMultiTenantDeploy() {
|
|
56
|
-
if (process.env.NODE_ENV !== "production")
|
|
57
|
-
return false;
|
|
58
|
-
return !isLocalDatabase();
|
|
59
|
-
}
|
|
60
55
|
function collectToolResultSummaries(completedRun) {
|
|
61
56
|
return completedRun.events
|
|
62
57
|
.map((runEvent) => runEvent.event)
|
|
63
58
|
.filter((event) => event.type === "tool_done")
|
|
64
59
|
.map((event) => ({ tool: event.tool, result: event.result }));
|
|
65
60
|
}
|
|
66
|
-
async function resolveIntegrationApiKey(engineOption, ownerEmail, fallbackApiKey) {
|
|
61
|
+
export async function resolveIntegrationApiKey(engineOption, ownerEmail, fallbackApiKey) {
|
|
62
|
+
const canUseDeployFallback = canUseDeployCredentialFallbackForRequest();
|
|
67
63
|
const engineName = explicitEngineName(engineOption);
|
|
68
64
|
if (engineName) {
|
|
69
65
|
const provider = engineToProvider(engineName);
|
|
70
66
|
const userApiKey = await getOwnerApiKey(provider, ownerEmail);
|
|
71
|
-
if (userApiKey
|
|
67
|
+
if (userApiKey)
|
|
72
68
|
return userApiKey;
|
|
69
|
+
if (!canUseDeployFallback)
|
|
70
|
+
return undefined;
|
|
73
71
|
const envVar = PROVIDER_TO_ENV[provider];
|
|
74
72
|
const providerEnvKey = envVar ? readDeployCredentialEnv(envVar) : undefined;
|
|
75
73
|
return providerEnvKey || fallbackApiKey.trim() || undefined;
|
|
76
74
|
}
|
|
77
75
|
const userApiKey = await getOwnerActiveApiKey(ownerEmail);
|
|
78
|
-
if (userApiKey
|
|
76
|
+
if (userApiKey)
|
|
79
77
|
return userApiKey;
|
|
78
|
+
if (!canUseDeployFallback)
|
|
79
|
+
return undefined;
|
|
80
80
|
return fallbackApiKey.trim() || undefined;
|
|
81
81
|
}
|
|
82
82
|
/**
|