@agent-native/core 0.7.81 → 0.7.83
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/dist/action.d.ts +8 -0
- package/dist/action.d.ts.map +1 -1
- package/dist/action.js +4 -0
- package/dist/action.js.map +1 -1
- package/dist/agent/production-agent.d.ts +12 -2
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +58 -20
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/run-manager.d.ts +8 -1
- package/dist/agent/run-manager.d.ts.map +1 -1
- package/dist/agent/run-manager.js +11 -12
- package/dist/agent/run-manager.js.map +1 -1
- package/dist/agent/thread-data-builder.d.ts.map +1 -1
- package/dist/agent/thread-data-builder.js +13 -17
- package/dist/agent/thread-data-builder.js.map +1 -1
- package/dist/agent/types.d.ts +4 -0
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/types.js.map +1 -1
- package/dist/application-state/handlers.d.ts.map +1 -1
- package/dist/application-state/handlers.js +3 -8
- package/dist/application-state/handlers.js.map +1 -1
- package/dist/application-state/script-helpers.d.ts +2 -4
- package/dist/application-state/script-helpers.d.ts.map +1 -1
- package/dist/application-state/script-helpers.js +10 -47
- package/dist/application-state/script-helpers.js.map +1 -1
- package/dist/cli/create.d.ts +1 -1
- package/dist/cli/create.d.ts.map +1 -1
- package/dist/cli/create.js +35 -10
- package/dist/cli/create.js.map +1 -1
- package/dist/cli/workspace-dev.js +78 -15
- package/dist/cli/workspace-dev.js.map +1 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +6 -2
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/AssistantChat.d.ts +0 -15
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +69 -57
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/ConnectBuilderCard.d.ts +7 -1
- package/dist/client/ConnectBuilderCard.d.ts.map +1 -1
- package/dist/client/ConnectBuilderCard.js +46 -5
- package/dist/client/ConnectBuilderCard.js.map +1 -1
- package/dist/client/ErrorBoundary.d.ts.map +1 -1
- package/dist/client/ErrorBoundary.js +20 -5
- package/dist/client/ErrorBoundary.js.map +1 -1
- package/dist/client/FeedbackButton.d.ts +3 -2
- package/dist/client/FeedbackButton.d.ts.map +1 -1
- package/dist/client/FeedbackButton.js +23 -15
- package/dist/client/FeedbackButton.js.map +1 -1
- package/dist/client/agent-chat-adapter.d.ts.map +1 -1
- package/dist/client/agent-chat-adapter.js +303 -169
- package/dist/client/agent-chat-adapter.js.map +1 -1
- package/dist/client/builder-frame.d.ts +36 -0
- package/dist/client/builder-frame.d.ts.map +1 -1
- package/dist/client/builder-frame.js +80 -9
- package/dist/client/builder-frame.js.map +1 -1
- package/dist/client/composer/ComposerPlusMenu.d.ts.map +1 -1
- package/dist/client/composer/ComposerPlusMenu.js +7 -2
- package/dist/client/composer/ComposerPlusMenu.js.map +1 -1
- package/dist/client/composer/PastedTextChip.d.ts +9 -0
- package/dist/client/composer/PastedTextChip.d.ts.map +1 -0
- package/dist/client/composer/PastedTextChip.js +47 -0
- package/dist/client/composer/PastedTextChip.js.map +1 -0
- package/dist/client/composer/PromptComposer.d.ts +4 -2
- package/dist/client/composer/PromptComposer.d.ts.map +1 -1
- package/dist/client/composer/PromptComposer.js +33 -5
- package/dist/client/composer/PromptComposer.js.map +1 -1
- package/dist/client/composer/TiptapComposer.d.ts +13 -1
- package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
- package/dist/client/composer/TiptapComposer.js +61 -16
- package/dist/client/composer/TiptapComposer.js.map +1 -1
- package/dist/client/composer/VoiceButton.d.ts.map +1 -1
- package/dist/client/composer/VoiceButton.js +5 -1
- package/dist/client/composer/VoiceButton.js.map +1 -1
- package/dist/client/composer/pasted-text.d.ts +6 -0
- package/dist/client/composer/pasted-text.d.ts.map +1 -0
- package/dist/client/composer/pasted-text.js +49 -0
- package/dist/client/composer/pasted-text.js.map +1 -0
- package/dist/client/composer/useVoiceDictation.d.ts +1 -0
- package/dist/client/composer/useVoiceDictation.d.ts.map +1 -1
- package/dist/client/composer/useVoiceDictation.js +18 -0
- package/dist/client/composer/useVoiceDictation.js.map +1 -1
- package/dist/client/index.d.ts +0 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +0 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/integrations/IntegrationCard.d.ts.map +1 -1
- package/dist/client/integrations/IntegrationCard.js +14 -2
- package/dist/client/integrations/IntegrationCard.js.map +1 -1
- package/dist/client/integrations/IntegrationsPanel.d.ts.map +1 -1
- package/dist/client/integrations/IntegrationsPanel.js +23 -4
- package/dist/client/integrations/IntegrationsPanel.js.map +1 -1
- package/dist/client/notifications/NotificationsBell.d.ts.map +1 -1
- package/dist/client/notifications/NotificationsBell.js +4 -42
- package/dist/client/notifications/NotificationsBell.js.map +1 -1
- package/dist/client/org/OrgSwitcher.d.ts +4 -6
- package/dist/client/org/OrgSwitcher.d.ts.map +1 -1
- package/dist/client/org/OrgSwitcher.js +84 -74
- package/dist/client/org/OrgSwitcher.js.map +1 -1
- package/dist/client/org/TeamPage.d.ts.map +1 -1
- package/dist/client/org/TeamPage.js +3 -154
- package/dist/client/org/TeamPage.js.map +1 -1
- package/dist/client/resources/ResourcesPanel.d.ts.map +1 -1
- package/dist/client/resources/ResourcesPanel.js +13 -35
- package/dist/client/resources/ResourcesPanel.js.map +1 -1
- package/dist/client/settings/SettingsPanel.js +1 -1
- package/dist/client/settings/SettingsPanel.js.map +1 -1
- package/dist/client/settings/useBuilderStatus.d.ts +6 -0
- package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
- package/dist/client/settings/useBuilderStatus.js +3 -0
- package/dist/client/settings/useBuilderStatus.js.map +1 -1
- package/dist/client/sse-event-processor.d.ts +15 -1
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +58 -54
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/client/tools/ToolEditor.d.ts.map +1 -1
- package/dist/client/tools/ToolEditor.js +34 -4
- package/dist/client/tools/ToolEditor.js.map +1 -1
- package/dist/client/tools/ToolViewer.d.ts.map +1 -1
- package/dist/client/tools/ToolViewer.js +20 -1
- package/dist/client/tools/ToolViewer.js.map +1 -1
- package/dist/client/tools/ToolsListPage.d.ts.map +1 -1
- package/dist/client/tools/ToolsListPage.js +2 -1
- package/dist/client/tools/ToolsListPage.js.map +1 -1
- package/dist/client/tools/ToolsSidebarSection.js +1 -1
- package/dist/client/tools/ToolsSidebarSection.js.map +1 -1
- package/dist/client/transcription/BuilderTranscriptionCta.js +1 -1
- package/dist/client/transcription/BuilderTranscriptionCta.js.map +1 -1
- package/dist/client/use-chat-threads.d.ts.map +1 -1
- package/dist/client/use-chat-threads.js +7 -2
- package/dist/client/use-chat-threads.js.map +1 -1
- package/dist/collab/client.d.ts.map +1 -1
- package/dist/collab/client.js +26 -7
- package/dist/collab/client.js.map +1 -1
- package/dist/jobs/scheduler.js +0 -4
- package/dist/jobs/scheduler.js.map +1 -1
- package/dist/oauth-tokens/store.d.ts +0 -4
- package/dist/oauth-tokens/store.d.ts.map +1 -1
- package/dist/oauth-tokens/store.js +3 -24
- package/dist/oauth-tokens/store.js.map +1 -1
- package/dist/observability/routes.d.ts.map +1 -1
- package/dist/observability/routes.js +1 -9
- package/dist/observability/routes.js.map +1 -1
- package/dist/onboarding/default-steps.js +1 -1
- package/dist/onboarding/default-steps.js.map +1 -1
- package/dist/onboarding/plugin.d.ts.map +1 -1
- package/dist/onboarding/plugin.js +1 -8
- package/dist/onboarding/plugin.js.map +1 -1
- package/dist/org/accept-pending.d.ts.map +1 -1
- package/dist/org/accept-pending.js +1 -2
- package/dist/org/accept-pending.js.map +1 -1
- package/dist/org/context.d.ts +0 -2
- package/dist/org/context.d.ts.map +1 -1
- package/dist/org/context.js +0 -5
- package/dist/org/context.js.map +1 -1
- package/dist/resources/script-helpers.d.ts +3 -4
- package/dist/resources/script-helpers.d.ts.map +1 -1
- package/dist/resources/script-helpers.js +8 -15
- package/dist/resources/script-helpers.js.map +1 -1
- package/dist/scripts/chat/search-chats.d.ts.map +1 -1
- package/dist/scripts/chat/search-chats.js +4 -4
- package/dist/scripts/chat/search-chats.js.map +1 -1
- package/dist/scripts/manage-agent-loop-settings.js +2 -2
- package/dist/scripts/manage-agent-loop-settings.js.map +1 -1
- package/dist/scripts/resources/delete-memory.d.ts.map +1 -1
- package/dist/scripts/resources/delete-memory.js +4 -2
- package/dist/scripts/resources/delete-memory.js.map +1 -1
- package/dist/scripts/resources/delete.d.ts.map +1 -1
- package/dist/scripts/resources/delete.js +11 -4
- package/dist/scripts/resources/delete.js.map +1 -1
- package/dist/scripts/resources/list.d.ts.map +1 -1
- package/dist/scripts/resources/list.js +5 -3
- package/dist/scripts/resources/list.js.map +1 -1
- package/dist/scripts/resources/migrate-learnings.d.ts.map +1 -1
- package/dist/scripts/resources/migrate-learnings.js +5 -2
- package/dist/scripts/resources/migrate-learnings.js.map +1 -1
- package/dist/scripts/resources/read.d.ts.map +1 -1
- package/dist/scripts/resources/read.js +4 -2
- package/dist/scripts/resources/read.js.map +1 -1
- package/dist/scripts/resources/save-memory.d.ts.map +1 -1
- package/dist/scripts/resources/save-memory.js +4 -2
- package/dist/scripts/resources/save-memory.js.map +1 -1
- package/dist/scripts/resources/write.d.ts.map +1 -1
- package/dist/scripts/resources/write.js +11 -4
- package/dist/scripts/resources/write.js.map +1 -1
- package/dist/secrets/onboarding.d.ts.map +1 -1
- package/dist/secrets/onboarding.js +1 -9
- package/dist/secrets/onboarding.js.map +1 -1
- package/dist/secrets/routes.d.ts.map +1 -1
- package/dist/secrets/routes.js +2 -7
- package/dist/secrets/routes.js.map +1 -1
- package/dist/server/action-discovery.d.ts +15 -0
- package/dist/server/action-discovery.d.ts.map +1 -1
- package/dist/server/action-discovery.js +49 -0
- package/dist/server/action-discovery.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts +5 -0
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +81 -20
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-discovery.d.ts.map +1 -1
- package/dist/server/agent-discovery.js +5 -7
- package/dist/server/agent-discovery.js.map +1 -1
- package/dist/server/auth.d.ts +16 -20
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +115 -333
- package/dist/server/auth.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +23 -16
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +1 -2
- package/dist/server/credential-provider.js.map +1 -1
- package/dist/server/google-oauth.d.ts +14 -2
- package/dist/server/google-oauth.d.ts.map +1 -1
- package/dist/server/google-oauth.js +32 -10
- package/dist/server/google-oauth.js.map +1 -1
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/oauth-helpers.d.ts +2 -4
- package/dist/server/oauth-helpers.d.ts.map +1 -1
- package/dist/server/oauth-helpers.js +2 -4
- package/dist/server/oauth-helpers.js.map +1 -1
- package/dist/server/transcribe-voice.d.ts.map +1 -1
- package/dist/server/transcribe-voice.js +2 -4
- package/dist/server/transcribe-voice.js.map +1 -1
- package/dist/triggers/dispatcher.d.ts.map +1 -1
- package/dist/triggers/dispatcher.js +0 -3
- package/dist/triggers/dispatcher.js.map +1 -1
- package/dist/vite/client.d.ts.map +1 -1
- package/dist/vite/client.js +13 -0
- package/dist/vite/client.js.map +1 -1
- package/docs/content/actions.md +1 -0
- package/docs/content/authentication.md +3 -20
- package/docs/content/creating-templates.md +1 -1
- package/docs/content/deployment.md +0 -1
- package/docs/content/security.md +0 -1
- package/docs/content/template-analytics.md +10 -0
- package/docs/content/template-calendar.md +10 -0
- package/docs/content/template-clips.md +10 -0
- package/docs/content/template-content.md +11 -1
- package/docs/content/template-dispatch.md +10 -0
- package/docs/content/template-forms.md +10 -0
- package/docs/content/template-mail.md +10 -0
- package/docs/content/template-slides.md +11 -1
- package/docs/content/template-starter.md +11 -1
- package/docs/content/template-video.md +10 -0
- package/package.json +1 -1
- package/dist/client/dev-mode.d.ts +0 -14
- package/dist/client/dev-mode.d.ts.map +0 -1
- package/dist/client/dev-mode.js +0 -14
- package/dist/client/dev-mode.js.map +0 -1
- package/dist/server/local-migration.d.ts +0 -41
- package/dist/server/local-migration.d.ts.map +0 -1
- package/dist/server/local-migration.js +0 -235
- package/dist/server/local-migration.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useBuilderStatus.js","sourceRoot":"","sources":["../../../src/client/settings/useBuilderStatus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AA4BhD;;;GAGG;AACH,MAAM,UAAU,gBAAgB;IAC9B,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAuB,IAAI,CAAC,CAAC;IACjE,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IAE7C,MAAM,WAAW,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACzC,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,eAAe,CAAC,+BAA+B,CAAC,CAAC,CAAC;YAC1E,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;gBACZ,SAAS,CAAC,IAAI,CAAC,CAAC;gBAChB,OAAO;YACT,CAAC;YACD,SAAS,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,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AAQ,CAAC,CAAC,CAAC;IAEf,OAAO;QACL,UAAU;QACV,UAAU;QACV,OAAO;QACP,UAAU;QACV,KAAK;QACL,gBAAgB;QAChB,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import { agentNativePath } from \"../api-path.js\";\nimport { useState, useEffect, useCallback, useRef } from \"react\";\nimport { getCallbackOrigin } from \"../frame.js\";\n\nexport interface BuilderStatus {\n configured: boolean;\n builderEnabled: boolean;\n /**\n * True when `BUILDER_PRIVATE_KEY` is set at the deploy level. Every user\n * of this deploy shares the operator's Builder identity and per-user\n * connect/disconnect is disabled. UIs must hide connect prompts and\n * disconnect buttons when this is true.\n */\n envManaged?: boolean;\n connectUrl: string;\n appHost: string;\n apiHost: string;\n publicKeyConfigured: boolean;\n privateKeyConfigured: boolean;\n userId?: string;\n orgName?: string;\n orgKind?: string;\n /**\n * Set when the OAuth callback ran but failed to persist credentials.\n * Surfaced as a one-shot row by the server so the connect-flow polling\n * can stop with a clear message instead of timing out at 5min.\n */\n connectError?: { message: string; at: number };\n}\n\n/**\n * Fetches Builder connection status from /_agent-native/builder/status.\n * Re-fetches on window focus to detect post-redirect state changes.\n */\nexport function useBuilderStatus() {\n const [status, setStatus] = useState<BuilderStatus | null>(null);\n const [loading, setLoading] = useState(true);\n\n const fetchStatus = useCallback(async () => {\n try {\n const res = await fetch(agentNativePath(\"/_agent-native/builder/status\"));\n if (!res.ok) {\n setStatus(null);\n return;\n }\n setStatus(await res.json());\n } catch {\n setStatus(null);\n } finally {\n setLoading(false);\n }\n }, []);\n\n useEffect(() => {\n fetchStatus();\n\n function onFocus() {\n fetchStatus();\n }\n function onVisibility() {\n if (document.visibilityState === \"visible\") fetchStatus();\n }\n window.addEventListener(\"focus\", onFocus);\n document.addEventListener(\"visibilitychange\", onVisibility);\n // Engine connect/disconnect actions (e.g. the Builder disconnect button)\n // dispatch this event so dependent cards refresh without a full reload.\n window.addEventListener(\"agent-engine:configured-changed\", fetchStatus);\n return () => {\n window.removeEventListener(\"focus\", onFocus);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n window.removeEventListener(\n \"agent-engine:configured-changed\",\n fetchStatus,\n );\n };\n }, [fetchStatus]);\n\n return { status, loading, refetch: fetchStatus };\n}\n\n// ─── useBuilderConnectFlow ──────────────────────────────────────────────────\n//\n// Shared state machine for the \"open Builder CLI-auth popup + poll\n// /builder/status until credentials land\" interaction. Replaces three\n// near-duplicate inline implementations: `BuilderCliAuthMethod` in\n// OnboardingPanel, `ConnectBuilderCard`, and `BuilderConnectCta` in\n// AssistantChat. Each consumer supplies its own popup URL / completion\n// behavior; the hook owns the polling + timeout + focus refresh.\n//\n// `popupUrl` is what we pass to `window.open`. The default\n// `/_agent-native/builder/connect` is a server-side 302 to the real\n// cli-auth URL — using it keeps the click handler synchronous so popup\n// blockers don't downgrade the open to same-tab navigation. Pass an\n// explicit `popupUrl` (e.g. the already-computed cli-auth URL) if your\n// caller already has it in hand.\n\nexport interface BuilderConnectFlowOptions {\n /** URL to synchronously open on start(). Defaults to the 302 shortcut. */\n popupUrl?: string;\n /** Invoked after the status poll first sees `configured: true`. */\n onConnected?: (state: { orgName: string | null }) => void | Promise<void>;\n}\n\nexport interface BuilderConnectFlow {\n configured: boolean;\n /**\n * True when the deploy has BUILDER_PRIVATE_KEY set. UIs should treat\n * Builder as connected for everyone in this mode and hide all connect /\n * disconnect controls — `start()` will be a no-op.\n */\n envManaged: boolean;\n orgName: string | null;\n connecting: boolean;\n error: string | null;\n /**\n * True once the first `/builder/status` fetch has completed (successfully\n * or not). Consumers that accept an `initialConfigured` prop (e.g. agent\n * tool-call results rendered with server-side state) should treat\n * `configured`/`orgName` as authoritative only once this flips true —\n * otherwise the hook's starting `false` defaults would cause a flash\n * back to \"Connect Builder\" on first paint.\n */\n hasFetchedStatus: boolean;\n /** Open the popup and begin polling. Must be called from a user-gesture handler. */\n start: () => void;\n}\n\nconst POLL_INTERVAL_MS = 2000;\nconst POLL_TIMEOUT_MS = 5 * 60 * 1000;\n\nexport function useBuilderConnectFlow(\n opts: BuilderConnectFlowOptions = {},\n): BuilderConnectFlow {\n const { popupUrl, onConnected } = opts;\n const [configured, setConfigured] = useState(false);\n const [envManaged, setEnvManaged] = useState(false);\n const [orgName, setOrgName] = useState<string | null>(null);\n const [connecting, setConnecting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [hasFetchedStatus, setHasFetchedStatus] = useState(false);\n const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);\n const mountedRef = useRef(true);\n // Keep onConnected in a ref so start() doesn't need to re-create when the\n // caller passes an inline arrow function.\n const onConnectedRef = useRef(onConnected);\n onConnectedRef.current = onConnected;\n\n const stopPoll = useCallback(() => {\n if (pollRef.current) {\n clearInterval(pollRef.current);\n pollRef.current = null;\n }\n }, []);\n\n const fetchStatus = useCallback(async () => {\n const origin = getCallbackOrigin() || window.location.origin;\n try {\n const r = await fetch(\n new URL(agentNativePath(\"/_agent-native/builder/status\"), origin).href,\n );\n if (!r.ok) return null;\n return (await r.json()) as {\n configured: boolean;\n envManaged?: boolean;\n orgName?: string | null;\n connectError?: { message: string; at: number };\n };\n } catch {\n return null;\n }\n }, []);\n\n // Initial fetch + focus/visibility refresh so if the user completed the\n // flow in another tab (or a downgraded same-tab nav) we notice it. Also\n // listen for `agent-engine:configured-changed` so a Disconnect click in\n // Settings propagates to any connect-CTA cards rendered elsewhere in\n // the app without waiting for the next focus event.\n useEffect(() => {\n mountedRef.current = true;\n let cancelled = false;\n const refresh = async () => {\n const s = await fetchStatus();\n if (cancelled || !mountedRef.current) return;\n // Flip `hasFetchedStatus` even when the fetch failed — the caller's\n // \"use initial props until the hook has an answer\" pattern wants to\n // stop waiting after we've tried, regardless of network outcome.\n setHasFetchedStatus(true);\n if (!s) return;\n setConfigured(!!s.configured);\n setEnvManaged(!!s.envManaged);\n setOrgName(s.orgName ?? null);\n };\n refresh();\n const onVisible = () => {\n if (document.visibilityState === \"visible\") refresh();\n };\n window.addEventListener(\"focus\", refresh);\n document.addEventListener(\"visibilitychange\", onVisible);\n window.addEventListener(\"agent-engine:configured-changed\", refresh);\n return () => {\n cancelled = true;\n mountedRef.current = false;\n window.removeEventListener(\"focus\", refresh);\n document.removeEventListener(\"visibilitychange\", onVisible);\n window.removeEventListener(\"agent-engine:configured-changed\", refresh);\n stopPoll();\n };\n }, [fetchStatus, stopPoll]);\n\n const start = useCallback(() => {\n // In env-managed mode, per-user OAuth is disabled — `/builder/connect`\n // returns 409. Skip the popup and just refresh state so the UI flips\n // to its \"connected via deployment\" rendering.\n if (envManaged) return;\n stopPoll();\n setConnecting(true);\n setError(null);\n\n // Open SYNCHRONOUSLY inside the caller's click handler — any await\n // before window.open lets the user-gesture token expire, which causes\n // popup blockers to block entirely or fall back to same-tab navigation.\n const origin = getCallbackOrigin() || window.location.origin;\n const url =\n popupUrl ??\n new URL(agentNativePath(\"/_agent-native/builder/connect\"), origin).href;\n try {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n } catch {\n // Fall through — polling still detects completion if the user\n // opens the URL themselves.\n }\n\n const started = Date.now();\n pollRef.current = setInterval(async () => {\n const s = await fetchStatus();\n if (!mountedRef.current) {\n stopPoll();\n return;\n }\n if (s?.configured) {\n stopPoll();\n setConfigured(true);\n const org = s.orgName ?? null;\n setOrgName(org);\n setConnecting(false);\n try {\n await onConnectedRef.current?.({ orgName: org });\n } catch {\n // Consumer's callback failed; we've already flipped the UI state\n // to connected. Swallow so we don't re-arm the flow.\n }\n } else if (s?.connectError?.message) {\n // OAuth callback ran but writeBuilderCredentials threw — surface the\n // real error instead of letting the user wait 5 minutes for timeout.\n stopPoll();\n setConnecting(false);\n setError(\n `Couldn't save Builder credentials: ${s.connectError.message}. Try again or contact support.`,\n );\n } else if (Date.now() - started > POLL_TIMEOUT_MS) {\n stopPoll();\n setConnecting(false);\n setError(\n \"Didn't hear back from Builder in 5 minutes. Allow popups and try again.\",\n );\n }\n }, POLL_INTERVAL_MS);\n }, [envManaged, fetchStatus, popupUrl, stopPoll]);\n\n // Popup-side fast path: the error page broadcasts a message so we stop\n // polling immediately rather than waiting for the next 2s tick.\n //\n // We listen on BroadcastChannel (same-origin, works with noopener popups)\n // AND on window.message (legacy path for environments without BC or for\n // popups that still have opener access). Both paths are safe to have open\n // simultaneously \\u2014 the first one to fire wins and the error is deduplicated\n // by the stopPoll() call which is idempotent.\n useEffect(() => {\n let channel: BroadcastChannel | null = null;\n const handleError = (message: string) => {\n stopPoll();\n setConnecting(false);\n setError(`Couldn't save Builder credentials: ${message}.`);\n };\n\n try {\n channel = new BroadcastChannel(`builder-connect:${window.location.host}`);\n channel.onmessage = (e: MessageEvent) => {\n const data = e.data as { type?: string; message?: string } | undefined;\n if (data?.type !== \"builder-connect-error\") return;\n if (typeof data.message !== \"string\" || !data.message) return;\n handleError(data.message);\n };\n } catch {\n // BroadcastChannel not available (rare) \\u2014 fall through to postMessage.\n }\n\n const handler = (e: MessageEvent) => {\n if (e.origin !== window.location.origin) return;\n const data = e.data as { type?: string; message?: string } | undefined;\n if (data?.type !== \"builder-connect-error\") return;\n if (typeof data.message !== \"string\" || !data.message) return;\n handleError(data.message);\n };\n window.addEventListener(\"message\", handler);\n\n return () => {\n channel?.close();\n window.removeEventListener(\"message\", handler);\n };\n }, [stopPoll]);\n\n return {\n configured,\n envManaged,\n orgName,\n connecting,\n error,\n hasFetchedStatus,\n start,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"useBuilderStatus.js","sourceRoot":"","sources":["../../../src/client/settings/useBuilderStatus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AA4BhD;;;GAGG;AACH,MAAM,UAAU,gBAAgB;IAC9B,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ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AAI,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,QAAQ,CAAC,MAAM;gBAAE,OAAO;YAChD,MAAM,IAAI,GAAG,CAAC,CAAC,IAAuD,CAAC;YACvE,IAAI,IAAI,EAAE,IAAI,KAAK,uBAAuB;gBAAE,OAAO;YACnD,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,IAAI,CAAC,OAAO;gBAAE,OAAO;YAC9D,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5B,CAAC,CAAC;QACF,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAE5C,OAAO,GAAG,EAAE;YACV,OAAO,EAAE,KAAK,EAAE,CAAC;YACjB,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACjD,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAEf,OAAO;QACL,UAAU;QACV,UAAU;QACV,cAAc;QACd,OAAO;QACP,UAAU;QACV,KAAK;QACL,gBAAgB;QAChB,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import { agentNativePath } from \"../api-path.js\";\nimport { useState, useEffect, useCallback, useRef } from \"react\";\nimport { getCallbackOrigin } from \"../frame.js\";\n\nexport interface BuilderStatus {\n configured: boolean;\n builderEnabled: boolean;\n /**\n * True when `BUILDER_PRIVATE_KEY` is set at the deploy level. Every user\n * of this deploy shares the operator's Builder identity and per-user\n * connect/disconnect is disabled. UIs must hide connect prompts and\n * disconnect buttons when this is true.\n */\n envManaged?: boolean;\n connectUrl: string;\n appHost: string;\n apiHost: string;\n publicKeyConfigured: boolean;\n privateKeyConfigured: boolean;\n userId?: string;\n orgName?: string;\n orgKind?: string;\n /**\n * Set when the OAuth callback ran but failed to persist credentials.\n * Surfaced as a one-shot row by the server so the connect-flow polling\n * can stop with a clear message instead of timing out at 5min.\n */\n connectError?: { message: string; at: number };\n}\n\n/**\n * Fetches Builder connection status from /_agent-native/builder/status.\n * Re-fetches on window focus to detect post-redirect state changes.\n */\nexport function useBuilderStatus() {\n const [status, setStatus] = useState<BuilderStatus | null>(null);\n const [loading, setLoading] = useState(true);\n\n const fetchStatus = useCallback(async () => {\n try {\n const res = await fetch(agentNativePath(\"/_agent-native/builder/status\"));\n if (!res.ok) {\n setStatus(null);\n return;\n }\n setStatus(await res.json());\n } catch {\n setStatus(null);\n } finally {\n setLoading(false);\n }\n }, []);\n\n useEffect(() => {\n fetchStatus();\n\n function onFocus() {\n fetchStatus();\n }\n function onVisibility() {\n if (document.visibilityState === \"visible\") fetchStatus();\n }\n window.addEventListener(\"focus\", onFocus);\n document.addEventListener(\"visibilitychange\", onVisibility);\n // Engine connect/disconnect actions (e.g. the Builder disconnect button)\n // dispatch this event so dependent cards refresh without a full reload.\n window.addEventListener(\"agent-engine:configured-changed\", fetchStatus);\n return () => {\n window.removeEventListener(\"focus\", onFocus);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n window.removeEventListener(\n \"agent-engine:configured-changed\",\n fetchStatus,\n );\n };\n }, [fetchStatus]);\n\n return { status, loading, refetch: fetchStatus };\n}\n\n// ─── useBuilderConnectFlow ──────────────────────────────────────────────────\n//\n// Shared state machine for the \"open Builder CLI-auth popup + poll\n// /builder/status until credentials land\" interaction. Replaces three\n// near-duplicate inline implementations: `BuilderCliAuthMethod` in\n// OnboardingPanel, `ConnectBuilderCard`, and `BuilderConnectCta` in\n// AssistantChat. Each consumer supplies its own popup URL / completion\n// behavior; the hook owns the polling + timeout + focus refresh.\n//\n// `popupUrl` is what we pass to `window.open`. The default\n// `/_agent-native/builder/connect` is a server-side 302 to the real\n// cli-auth URL — using it keeps the click handler synchronous so popup\n// blockers don't downgrade the open to same-tab navigation. Pass an\n// explicit `popupUrl` (e.g. the already-computed cli-auth URL) if your\n// caller already has it in hand.\n\nexport interface BuilderConnectFlowOptions {\n /** URL to synchronously open on start(). Defaults to the 302 shortcut. */\n popupUrl?: string;\n /** Invoked after the status poll first sees `configured: true`. */\n onConnected?: (state: { orgName: string | null }) => void | Promise<void>;\n}\n\nexport interface BuilderConnectFlow {\n configured: boolean;\n /**\n * True when the deploy has BUILDER_PRIVATE_KEY set. UIs should treat\n * Builder as connected for everyone in this mode and hide all connect /\n * disconnect controls — `start()` will be a no-op.\n */\n envManaged: boolean;\n /**\n * True when ENABLE_BUILDER (or a BUILDER_BRANCH_PROJECT_ID) is set on the\n * deploy, gating Builder cloud branch creation. When false, the card\n * surfaces a \"coming soon\" waitlist CTA instead of a Send button.\n */\n builderEnabled: boolean;\n orgName: string | null;\n connecting: boolean;\n error: string | null;\n /**\n * True once the first `/builder/status` fetch has completed (successfully\n * or not). Consumers that accept an `initialConfigured` prop (e.g. agent\n * tool-call results rendered with server-side state) should treat\n * `configured`/`orgName` as authoritative only once this flips true —\n * otherwise the hook's starting `false` defaults would cause a flash\n * back to \"Connect Builder\" on first paint.\n */\n hasFetchedStatus: boolean;\n /** Open the popup and begin polling. Must be called from a user-gesture handler. */\n start: () => void;\n}\n\nconst POLL_INTERVAL_MS = 2000;\nconst POLL_TIMEOUT_MS = 5 * 60 * 1000;\n\nexport function useBuilderConnectFlow(\n opts: BuilderConnectFlowOptions = {},\n): BuilderConnectFlow {\n const { popupUrl, onConnected } = opts;\n const [configured, setConfigured] = useState(false);\n const [envManaged, setEnvManaged] = useState(false);\n const [builderEnabled, setBuilderEnabled] = useState(false);\n const [orgName, setOrgName] = useState<string | null>(null);\n const [connecting, setConnecting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [hasFetchedStatus, setHasFetchedStatus] = useState(false);\n const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);\n const mountedRef = useRef(true);\n // Keep onConnected in a ref so start() doesn't need to re-create when the\n // caller passes an inline arrow function.\n const onConnectedRef = useRef(onConnected);\n onConnectedRef.current = onConnected;\n\n const stopPoll = useCallback(() => {\n if (pollRef.current) {\n clearInterval(pollRef.current);\n pollRef.current = null;\n }\n }, []);\n\n const fetchStatus = useCallback(async () => {\n const origin = getCallbackOrigin() || window.location.origin;\n try {\n const r = await fetch(\n new URL(agentNativePath(\"/_agent-native/builder/status\"), origin).href,\n );\n if (!r.ok) return null;\n return (await r.json()) as {\n configured: boolean;\n envManaged?: boolean;\n builderEnabled?: boolean;\n orgName?: string | null;\n connectError?: { message: string; at: number };\n };\n } catch {\n return null;\n }\n }, []);\n\n // Initial fetch + focus/visibility refresh so if the user completed the\n // flow in another tab (or a downgraded same-tab nav) we notice it. Also\n // listen for `agent-engine:configured-changed` so a Disconnect click in\n // Settings propagates to any connect-CTA cards rendered elsewhere in\n // the app without waiting for the next focus event.\n useEffect(() => {\n mountedRef.current = true;\n let cancelled = false;\n const refresh = async () => {\n const s = await fetchStatus();\n if (cancelled || !mountedRef.current) return;\n // Flip `hasFetchedStatus` even when the fetch failed — the caller's\n // \"use initial props until the hook has an answer\" pattern wants to\n // stop waiting after we've tried, regardless of network outcome.\n setHasFetchedStatus(true);\n if (!s) return;\n setConfigured(!!s.configured);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n setOrgName(s.orgName ?? null);\n };\n refresh();\n const onVisible = () => {\n if (document.visibilityState === \"visible\") refresh();\n };\n window.addEventListener(\"focus\", refresh);\n document.addEventListener(\"visibilitychange\", onVisible);\n window.addEventListener(\"agent-engine:configured-changed\", refresh);\n return () => {\n cancelled = true;\n mountedRef.current = false;\n window.removeEventListener(\"focus\", refresh);\n document.removeEventListener(\"visibilitychange\", onVisible);\n window.removeEventListener(\"agent-engine:configured-changed\", refresh);\n stopPoll();\n };\n }, [fetchStatus, stopPoll]);\n\n const start = useCallback(() => {\n // In env-managed mode, per-user OAuth is disabled — `/builder/connect`\n // returns 409. Skip the popup and just refresh state so the UI flips\n // to its \"connected via deployment\" rendering.\n if (envManaged) return;\n stopPoll();\n setConnecting(true);\n setError(null);\n\n // Open SYNCHRONOUSLY inside the caller's click handler — any await\n // before window.open lets the user-gesture token expire, which causes\n // popup blockers to block entirely or fall back to same-tab navigation.\n const origin = getCallbackOrigin() || window.location.origin;\n const url =\n popupUrl ??\n new URL(agentNativePath(\"/_agent-native/builder/connect\"), origin).href;\n try {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n } catch {\n // Fall through — polling still detects completion if the user\n // opens the URL themselves.\n }\n\n const started = Date.now();\n pollRef.current = setInterval(async () => {\n const s = await fetchStatus();\n if (!mountedRef.current) {\n stopPoll();\n return;\n }\n if (s?.configured) {\n stopPoll();\n setConfigured(true);\n const org = s.orgName ?? null;\n setOrgName(org);\n setConnecting(false);\n try {\n await onConnectedRef.current?.({ orgName: org });\n } catch {\n // Consumer's callback failed; we've already flipped the UI state\n // to connected. Swallow so we don't re-arm the flow.\n }\n } else if (s?.connectError?.message) {\n // OAuth callback ran but writeBuilderCredentials threw — surface the\n // real error instead of letting the user wait 5 minutes for timeout.\n stopPoll();\n setConnecting(false);\n setError(\n `Couldn't save Builder credentials: ${s.connectError.message}. Try again or contact support.`,\n );\n } else if (Date.now() - started > POLL_TIMEOUT_MS) {\n stopPoll();\n setConnecting(false);\n setError(\n \"Didn't hear back from Builder in 5 minutes. Allow popups and try again.\",\n );\n }\n }, POLL_INTERVAL_MS);\n }, [envManaged, fetchStatus, popupUrl, stopPoll]);\n\n // Popup-side fast path: the error page broadcasts a message so we stop\n // polling immediately rather than waiting for the next 2s tick.\n //\n // We listen on BroadcastChannel (same-origin, works with noopener popups)\n // AND on window.message (legacy path for environments without BC or for\n // popups that still have opener access). Both paths are safe to have open\n // simultaneously \\u2014 the first one to fire wins and the error is deduplicated\n // by the stopPoll() call which is idempotent.\n useEffect(() => {\n let channel: BroadcastChannel | null = null;\n const handleError = (message: string) => {\n stopPoll();\n setConnecting(false);\n setError(`Couldn't save Builder credentials: ${message}.`);\n };\n\n try {\n channel = new BroadcastChannel(`builder-connect:${window.location.host}`);\n channel.onmessage = (e: MessageEvent) => {\n const data = e.data as { type?: string; message?: string } | undefined;\n if (data?.type !== \"builder-connect-error\") return;\n if (typeof data.message !== \"string\" || !data.message) return;\n handleError(data.message);\n };\n } catch {\n // BroadcastChannel not available (rare) \\u2014 fall through to postMessage.\n }\n\n const handler = (e: MessageEvent) => {\n if (e.origin !== window.location.origin) return;\n const data = e.data as { type?: string; message?: string } | undefined;\n if (data?.type !== \"builder-connect-error\") return;\n if (typeof data.message !== \"string\" || !data.message) return;\n handleError(data.message);\n };\n window.addEventListener(\"message\", handler);\n\n return () => {\n channel?.close();\n window.removeEventListener(\"message\", handler);\n };\n }, [stopPoll]);\n\n return {\n configured,\n envManaged,\n builderEnabled,\n orgName,\n connecting,\n error,\n hasFetchedStatus,\n start,\n };\n}\n"]}
|
|
@@ -20,6 +20,7 @@ export interface SSEEvent {
|
|
|
20
20
|
seq?: number;
|
|
21
21
|
agent?: string;
|
|
22
22
|
status?: string;
|
|
23
|
+
reason?: string;
|
|
23
24
|
taskId?: string;
|
|
24
25
|
threadId?: string;
|
|
25
26
|
description?: string;
|
|
@@ -32,6 +33,15 @@ export interface SSEEvent {
|
|
|
32
33
|
recoverable?: boolean;
|
|
33
34
|
maxIterations?: number;
|
|
34
35
|
}
|
|
36
|
+
export type AgentAutoContinueReason = "run_timeout" | "loop_limit" | "stream_ended";
|
|
37
|
+
export declare class AgentAutoContinueSignal extends Error {
|
|
38
|
+
readonly reason: AgentAutoContinueReason;
|
|
39
|
+
readonly maxIterations?: number;
|
|
40
|
+
constructor(options: {
|
|
41
|
+
reason: AgentAutoContinueReason;
|
|
42
|
+
maxIterations?: number;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
35
45
|
/**
|
|
36
46
|
* Process a single SSE event and update the content accumulator.
|
|
37
47
|
* Returns: "continue" to keep going, "done" to stop, or a yield-ready result.
|
|
@@ -39,8 +49,12 @@ export interface SSEEvent {
|
|
|
39
49
|
export declare function processEvent(ev: SSEEvent, content: ContentPart[], toolCallCounter: {
|
|
40
50
|
value: number;
|
|
41
51
|
}, tabId: string | undefined): {
|
|
42
|
-
action: "continue" | "done" | "yield" | "error" | "missing_api_key";
|
|
52
|
+
action: "continue" | "done" | "yield" | "error" | "missing_api_key" | "auto_continue";
|
|
43
53
|
result?: ChatModelRunResult;
|
|
54
|
+
autoContinue?: {
|
|
55
|
+
reason: AgentAutoContinueReason;
|
|
56
|
+
maxIterations?: number;
|
|
57
|
+
};
|
|
44
58
|
};
|
|
45
59
|
/**
|
|
46
60
|
* Read and process SSE events from a ReadableStream response body.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sse-event-processor.d.ts","sourceRoot":"","sources":["../../src/client/sse-event-processor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAG9D,MAAM,MAAM,WAAW,GACnB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IACE,IAAI,EAAE,WAAW,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEN,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAA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AE;QACb,MAAM,EAAE,uBAAuB,CAAC;QAChC,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;CACH,CA6PA;AAED;;;;;;;;GAQG;AACH,wBAAuB,aAAa,CAClC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,EAChC,OAAO,EAAE,WAAW,EAAE,EACtB,eAAe,EAAE;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,EAClC,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,EAC7B,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,GACpB,cAAc,CAAC,kBAAkB,CAAC,CAoFpC;AAED;;;;;GAKG;AACH,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,EAChC,OAAO,EAAE,WAAW,EAAE,EACtB,eAAe,EAAE;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,EAClC,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,QAAQ,EAAE,CAAC,OAAO,EAAE,WAAW,EAAE,KAAK,IAAI,GACzC,OAAO,CAAC,IAAI,CAAC,CA2Df"}
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
import { formatChatErrorText, normalizeChatError } from "./error-format.js";
|
|
2
|
+
export class AgentAutoContinueSignal extends Error {
|
|
3
|
+
reason;
|
|
4
|
+
maxIterations;
|
|
5
|
+
constructor(options) {
|
|
6
|
+
super(`Agent run needs automatic continuation: ${options.reason}`);
|
|
7
|
+
this.name = "AgentAutoContinueSignal";
|
|
8
|
+
this.reason = options.reason;
|
|
9
|
+
this.maxIterations = options.maxIterations;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
2
12
|
/**
|
|
3
13
|
* Process a single SSE event and update the content accumulator.
|
|
4
14
|
* Returns: "continue" to keep going, "done" to stop, or a yield-ready result.
|
|
@@ -134,33 +144,50 @@ export function processEvent(ev, content, toolCallCounter, tabId) {
|
|
|
134
144
|
}
|
|
135
145
|
if (ev.type === "loop_limit") {
|
|
136
146
|
const maxIterations = typeof ev.maxIterations === "number" ? ev.maxIterations : undefined;
|
|
137
|
-
content.push({
|
|
138
|
-
type: "text",
|
|
139
|
-
text: maxIterations
|
|
140
|
-
? `I reached the ${maxIterations}-step limit before finishing.`
|
|
141
|
-
: "I reached the step limit before finishing.",
|
|
142
|
-
});
|
|
143
|
-
if (typeof window !== "undefined") {
|
|
144
|
-
window.dispatchEvent(new CustomEvent("agent-chat:loop-limit", {
|
|
145
|
-
detail: { tabId, maxIterations },
|
|
146
|
-
}));
|
|
147
|
-
}
|
|
148
147
|
return {
|
|
149
|
-
action: "
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
148
|
+
action: "auto_continue",
|
|
149
|
+
autoContinue: {
|
|
150
|
+
reason: "loop_limit",
|
|
151
|
+
...(maxIterations ? { maxIterations } : {}),
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
if (ev.type === "auto_continue") {
|
|
156
|
+
const reason = ev.reason === "stream_ended" ||
|
|
157
|
+
ev.reason === "loop_limit" ||
|
|
158
|
+
ev.reason === "run_timeout"
|
|
159
|
+
? ev.reason
|
|
160
|
+
: ev.errorCode === "stream_ended" ||
|
|
161
|
+
ev.errorCode === "loop_limit" ||
|
|
162
|
+
ev.errorCode === "run_timeout"
|
|
163
|
+
? ev.errorCode
|
|
164
|
+
: ev.error === "stream_ended" ||
|
|
165
|
+
ev.error === "loop_limit" ||
|
|
166
|
+
ev.error === "run_timeout"
|
|
167
|
+
? ev.error
|
|
168
|
+
: ev.status === "stream_ended" ||
|
|
169
|
+
ev.status === "loop_limit" ||
|
|
170
|
+
ev.status === "run_timeout"
|
|
171
|
+
? ev.status
|
|
172
|
+
: "run_timeout";
|
|
173
|
+
return {
|
|
174
|
+
action: "auto_continue",
|
|
175
|
+
autoContinue: {
|
|
176
|
+
reason,
|
|
177
|
+
...(typeof ev.maxIterations === "number"
|
|
178
|
+
? { maxIterations: ev.maxIterations }
|
|
179
|
+
: {}),
|
|
159
180
|
},
|
|
160
181
|
};
|
|
161
182
|
}
|
|
162
183
|
if (ev.type === "error") {
|
|
163
184
|
const errMsg = ev.error ?? "Unknown error";
|
|
185
|
+
if (ev.errorCode === "run_timeout" && ev.recoverable) {
|
|
186
|
+
return {
|
|
187
|
+
action: "auto_continue",
|
|
188
|
+
autoContinue: { reason: "run_timeout" },
|
|
189
|
+
};
|
|
190
|
+
}
|
|
164
191
|
const normalized = normalizeChatError(errMsg);
|
|
165
192
|
if (errMsg.includes("apiKey") ||
|
|
166
193
|
errMsg.includes("authToken") ||
|
|
@@ -271,9 +298,12 @@ export async function* readSSEStream(body, content, toolCallCounter, tabId, onSe
|
|
|
271
298
|
if (ev.seq !== undefined && onSeq) {
|
|
272
299
|
onSeq(ev.seq);
|
|
273
300
|
}
|
|
274
|
-
const { action, result } = processEvent(ev, content, toolCallCounter, tabId);
|
|
301
|
+
const { action, result, autoContinue } = processEvent(ev, content, toolCallCounter, tabId);
|
|
275
302
|
if (result)
|
|
276
303
|
yield withRunId(result);
|
|
304
|
+
if (action === "auto_continue") {
|
|
305
|
+
throw new AgentAutoContinueSignal(autoContinue ?? { reason: "stream_ended" });
|
|
306
|
+
}
|
|
277
307
|
if (action === "done" ||
|
|
278
308
|
action === "error" ||
|
|
279
309
|
action === "missing_api_key") {
|
|
@@ -287,25 +317,7 @@ export async function* readSSEStream(body, content, toolCallCounter, tabId, onSe
|
|
|
287
317
|
}
|
|
288
318
|
// Stream ended without explicit done event
|
|
289
319
|
if (content.length > 0) {
|
|
290
|
-
|
|
291
|
-
message: "The response stream ended before the agent sent a completion signal. You can continue from the partial work or retry.",
|
|
292
|
-
errorCode: "stream_ended",
|
|
293
|
-
recoverable: true,
|
|
294
|
-
};
|
|
295
|
-
if (typeof window !== "undefined") {
|
|
296
|
-
window.dispatchEvent(new CustomEvent("agent-chat:run-error", {
|
|
297
|
-
detail: { ...runError, tabId },
|
|
298
|
-
}));
|
|
299
|
-
}
|
|
300
|
-
content.push({
|
|
301
|
-
type: "text",
|
|
302
|
-
text: `Error: ${runError.message}`,
|
|
303
|
-
});
|
|
304
|
-
yield withRunId({
|
|
305
|
-
content: [...content],
|
|
306
|
-
status: { type: "incomplete", reason: "error" },
|
|
307
|
-
metadata: { custom: { runError } },
|
|
308
|
-
});
|
|
320
|
+
throw new AgentAutoContinueSignal({ reason: "stream_ended" });
|
|
309
321
|
}
|
|
310
322
|
}
|
|
311
323
|
/**
|
|
@@ -347,6 +359,10 @@ export async function readSSEStreamRaw(body, content, toolCallCounter, tabId, on
|
|
|
347
359
|
action === "missing_api_key") {
|
|
348
360
|
updated = true;
|
|
349
361
|
}
|
|
362
|
+
if (action === "auto_continue") {
|
|
363
|
+
onUpdate([...content]);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
350
366
|
if (action === "done" ||
|
|
351
367
|
action === "error" ||
|
|
352
368
|
action === "missing_api_key") {
|
|
@@ -362,19 +378,7 @@ export async function readSSEStreamRaw(body, content, toolCallCounter, tabId, on
|
|
|
362
378
|
finally {
|
|
363
379
|
reader.releaseLock();
|
|
364
380
|
}
|
|
365
|
-
if (content.length > 0)
|
|
366
|
-
const runError = {
|
|
367
|
-
message: "The response stream ended before the agent sent a completion signal. You can continue from the partial work or retry.",
|
|
368
|
-
errorCode: "stream_ended",
|
|
369
|
-
recoverable: true,
|
|
370
|
-
};
|
|
371
|
-
if (typeof window !== "undefined") {
|
|
372
|
-
window.dispatchEvent(new CustomEvent("agent-chat:run-error", {
|
|
373
|
-
detail: { ...runError, tabId },
|
|
374
|
-
}));
|
|
375
|
-
}
|
|
376
|
-
content.push({ type: "text", text: `Error: ${runError.message}` });
|
|
381
|
+
if (content.length > 0)
|
|
377
382
|
onUpdate([...content]);
|
|
378
|
-
}
|
|
379
383
|
}
|
|
380
384
|
//# sourceMappingURL=sse-event-processor.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sse-event-processor.js","sourceRoot":"","sources":["../../src/client/sse-event-processor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAuC5E;;;GAGG;AACH,MAAM,UAAU,YAAY,CAC1B,EAAY,EACZ,OAAsB,EACtB,eAAkC,EAClC,KAAyB;IAKzB,IAAI,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACxB,gFAAgF;QAChF,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;QACnB,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAChC,CAAC;IAED,IAAI,EAAE,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QACvB,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC7C,IAAI,QAAQ,IAAI,QAAQ,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YACzC,QAAQ,CAAC,IAAI,IAAI,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC;QACjC,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,EAAE,EAAE,CAAC,CAAC;QACtD,CAAC;QACD,OAAO;YACL,MAAM,EAAE,OAAO;YACf,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,EAAwB;SACxD,CAAC;IACJ,CAAC;IAED,IAAI,EAAE,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;QAC7B,MAAM,UAAU,GAAG,MAAM,EAAE,eAAe,CAAC,KAAK,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG,CAAC,EAAE,CAAC,KAAK,IAAI,EAAE,CAA2B,CAAC;QACxD,IAAI,OAAO,MAA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,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACnE,QAAQ,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IACzB,CAAC;AACH,CAAC","sourcesContent":["import type { ChatModelRunResult } from \"@assistant-ui/react\";\nimport { formatChatErrorText, normalizeChatError } from \"./error-format.js\";\n\nexport type ContentPart =\n | { type: \"text\"; text: string }\n | {\n type: \"tool-call\";\n toolCallId: string;\n toolName: string;\n argsText: string;\n args: Record<string, string>;\n result?: string;\n };\n\nexport interface SSEEvent {\n type: string;\n text?: string;\n tool?: string;\n input?: Record<string, string>;\n result?: string;\n error?: string;\n seq?: number;\n agent?: string;\n status?: string;\n // Agent task fields\n taskId?: string;\n threadId?: string;\n description?: string;\n preview?: string;\n currentStep?: string;\n summary?: string;\n // Structured error metadata — Builder gateway sets these on quota/auth/setup\n // failures so the UI can render a CTA alongside the error text.\n errorCode?: string;\n upgradeUrl?: string;\n details?: string;\n recoverable?: boolean;\n maxIterations?: number;\n}\n\n/**\n * Process a single SSE event and update the content accumulator.\n * Returns: \"continue\" to keep going, \"done\" to stop, or a yield-ready result.\n */\nexport function processEvent(\n ev: SSEEvent,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n): {\n action: \"continue\" | \"done\" | \"yield\" | \"error\" | \"missing_api_key\";\n result?: ChatModelRunResult;\n} {\n if (ev.type === \"clear\") {\n // Server is retrying — discard partial text/tool output from the failed attempt\n content.length = 0;\n return { action: \"continue\" };\n }\n\n if (ev.type === \"text\") {\n const lastPart = content[content.length - 1];\n if (lastPart && lastPart.type === \"text\") {\n lastPart.text += ev.text ?? \"\";\n } else {\n content.push({ type: \"text\", text: ev.text ?? \"\" });\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"tool_start\") {\n const toolCallId = `tc_${++toolCallCounter.value}`;\n const args = (ev.input ?? {}) as Record<string, string>;\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-native:tool-start\", {\n detail: { tool: ev.tool ?? \"unknown\", input: args },\n }),\n );\n }\n content.push({\n type: \"tool-call\",\n toolCallId,\n toolName: ev.tool ?? \"unknown\",\n argsText: JSON.stringify(args),\n args,\n });\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"tool_done\") {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-native:tool-done\", {\n detail: { tool: ev.tool ?? \"unknown\", result: ev.result },\n }),\n );\n }\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === ev.tool &&\n part.result === undefined\n ) {\n part.result = ev.result ?? \"\";\n break;\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"agent_call\") {\n const agentName = ev.agent ?? \"agent\";\n if (ev.status === \"start\") {\n const toolCallId = `tc_${++toolCallCounter.value}`;\n content.push({\n type: \"tool-call\",\n toolCallId,\n toolName: `agent:${agentName}`,\n argsText: \"\",\n args: {},\n });\n } else if (ev.status === \"done\" || ev.status === \"error\") {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === `agent:${agentName}` &&\n part.result === undefined\n ) {\n part.result = ev.status === \"error\" ? \"Error calling agent\" : \"Done\";\n break;\n }\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"agent_call_text\") {\n const agentName = ev.agent ?? \"agent\";\n // Find the in-progress agent tool-call and append streaming text to argsText\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === `agent:${agentName}` &&\n part.result === undefined\n ) {\n part.argsText += ev.text ?? \"\";\n break;\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n // ─── Agent task events (sub-agent chips) ─────────────────────────\n // These events are dispatched as CustomEvents so AgentTaskCard components\n // can listen for updates to their specific taskId.\n if (\n ev.type === \"agent_task\" ||\n ev.type === \"agent_task_update\" ||\n ev.type === \"agent_task_complete\"\n ) {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"agent-task-event\", { detail: ev }));\n }\n // Don't add to content — the agent-teams tool call handles rendering\n return { action: \"continue\" };\n }\n\n if (ev.type === \"missing_api_key\") {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"agent-chat:missing-api-key\"));\n }\n content.push({ type: \"text\", text: \"\" });\n return {\n action: \"missing_api_key\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"loop_limit\") {\n const maxIterations =\n typeof ev.maxIterations === \"number\" ? ev.maxIterations : undefined;\n content.push({\n type: \"text\",\n text: maxIterations\n ? `I reached the ${maxIterations}-step limit before finishing.`\n : \"I reached the step limit before finishing.\",\n });\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:loop-limit\", {\n detail: { tabId, maxIterations },\n }),\n );\n }\n return {\n action: \"done\",\n result: {\n content: [...content],\n metadata: {\n custom: {\n loopLimit: {\n ...(maxIterations ? { maxIterations } : {}),\n },\n },\n },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"error\") {\n const errMsg = ev.error ?? \"Unknown error\";\n const normalized = normalizeChatError(errMsg);\n if (\n errMsg.includes(\"apiKey\") ||\n errMsg.includes(\"authToken\") ||\n errMsg.includes(\"ANTHROPIC_API_KEY\") ||\n errMsg.includes(\"authentication\")\n ) {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"agent-chat:missing-api-key\"));\n }\n content.push({ type: \"text\", text: \"\" });\n return {\n action: \"missing_api_key\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n } as ChatModelRunResult,\n };\n }\n const runError = {\n message: normalized.message,\n ...(normalized.details || ev.details\n ? { details: ev.details ?? normalized.details }\n : {}),\n ...(ev.errorCode ? { errorCode: ev.errorCode } : {}),\n ...(ev.recoverable ? { recoverable: ev.recoverable } : {}),\n };\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:run-error\", {\n detail: { ...runError, tabId },\n }),\n );\n }\n content.push({\n type: \"text\",\n text: formatChatErrorText(errMsg, ev.upgradeUrl, ev.errorCode),\n });\n return {\n action: \"error\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n metadata: { custom: { runError } },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"done\") {\n return {\n action: \"done\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n return { action: \"continue\" };\n}\n\n/**\n * Read and process SSE events from a ReadableStream response body.\n * Yields ChatModelRunResult for each meaningful event.\n *\n * When `runId` is provided, every yielded result carries\n * `metadata.custom.runId` so the UI can expose the trace ID via\n * \"Copy Request ID\" — including mid-stream, so users can grab it before\n * the run completes (or if the run hangs / ends prematurely).\n */\nexport async function* readSSEStream(\n body: ReadableStream<Uint8Array>,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n onSeq?: (seq: number) => void,\n runId?: string | null,\n): AsyncGenerator<ChatModelRunResult> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = \"\";\n\n const withRunId = (r: ChatModelRunResult): ChatModelRunResult => {\n if (!runId) return r;\n const metadata = (r.metadata ?? {}) as Record<string, unknown>;\n const custom =\n metadata.custom && typeof metadata.custom === \"object\"\n ? (metadata.custom as Record<string, unknown>)\n : {};\n const runError =\n custom.runError && typeof custom.runError === \"object\"\n ? {\n ...(custom.runError as Record<string, unknown>),\n runId,\n }\n : custom.runError;\n return {\n ...r,\n metadata: {\n ...metadata,\n custom: { ...custom, runId, ...(runError ? { runError } : {}) },\n },\n };\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const raw = line.slice(6).trim();\n if (!raw) continue;\n\n let ev: SSEEvent;\n try {\n ev = JSON.parse(raw);\n } catch {\n continue;\n }\n\n // Track sequence number for reconnection\n if (ev.seq !== undefined && onSeq) {\n onSeq(ev.seq);\n }\n\n const { action, result } = processEvent(\n ev,\n content,\n toolCallCounter,\n tabId,\n );\n\n if (result) yield withRunId(result);\n if (\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n return;\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n // Stream ended without explicit done event\n if (content.length > 0) {\n const runError = {\n message:\n \"The response stream ended before the agent sent a completion signal. You can continue from the partial work or retry.\",\n errorCode: \"stream_ended\",\n recoverable: true,\n };\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:run-error\", {\n detail: { ...runError, tabId },\n }),\n );\n }\n content.push({\n type: \"text\",\n text: `Error: ${runError.message}`,\n });\n yield withRunId({\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n metadata: { custom: { runError } },\n } as ChatModelRunResult);\n }\n}\n\n/**\n * Read raw SSE events from a ReadableStream and process them into ContentPart[].\n * Unlike readSSEStream, this doesn't yield ChatModelRunResult — it updates the\n * content array in-place and calls onUpdate for each meaningful change.\n * Designed for reconnection scenarios where we render outside assistant-ui's runtime.\n */\nexport async function readSSEStreamRaw(\n body: ReadableStream<Uint8Array>,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n onUpdate: (content: ContentPart[]) => void,\n): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n\n let updated = false;\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const raw = line.slice(6).trim();\n if (!raw) continue;\n\n let ev: SSEEvent;\n try {\n ev = JSON.parse(raw);\n } catch {\n continue;\n }\n\n const { action } = processEvent(ev, content, toolCallCounter, tabId);\n\n if (\n action === \"yield\" ||\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n updated = true;\n }\n if (\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n onUpdate([...content]);\n return;\n }\n }\n\n if (updated) {\n onUpdate([...content]);\n }\n }\n } finally {\n reader.releaseLock();\n }\n if (content.length > 0) {\n const runError = {\n message:\n \"The response stream ended before the agent sent a completion signal. You can continue from the partial work or retry.\",\n errorCode: \"stream_ended\",\n recoverable: true,\n };\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:run-error\", {\n detail: { ...runError, tabId },\n }),\n );\n }\n content.push({ type: \"text\", text: `Error: ${runError.message}` });\n onUpdate([...content]);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sse-event-processor.js","sourceRoot":"","sources":["../../src/client/sse-event-processor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AA6C5E,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IACvC,MAAM,CAA0B;IAChC,aAAa,CAAU;IAEhC,YAAY,OAGX;QACC,KAAK,CAAC,2CAA2C,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QACnE,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC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port { formatChatErrorText, normalizeChatError } from \"./error-format.js\";\n\nexport type ContentPart =\n | { type: \"text\"; text: string }\n | {\n type: \"tool-call\";\n toolCallId: string;\n toolName: string;\n argsText: string;\n args: Record<string, string>;\n result?: string;\n };\n\nexport interface SSEEvent {\n type: string;\n text?: string;\n tool?: string;\n input?: Record<string, string>;\n result?: string;\n error?: string;\n seq?: number;\n agent?: string;\n status?: string;\n reason?: string;\n // Agent task fields\n taskId?: string;\n threadId?: string;\n description?: string;\n preview?: string;\n currentStep?: string;\n summary?: string;\n // Structured error metadata — Builder gateway sets these on quota/auth/setup\n // failures so the UI can render a CTA alongside the error text.\n errorCode?: string;\n upgradeUrl?: string;\n details?: string;\n recoverable?: boolean;\n maxIterations?: number;\n}\n\nexport type AgentAutoContinueReason =\n | \"run_timeout\"\n | \"loop_limit\"\n | \"stream_ended\";\n\nexport class AgentAutoContinueSignal extends Error {\n readonly reason: AgentAutoContinueReason;\n readonly maxIterations?: number;\n\n constructor(options: {\n reason: AgentAutoContinueReason;\n maxIterations?: number;\n }) {\n super(`Agent run needs automatic continuation: ${options.reason}`);\n this.name = \"AgentAutoContinueSignal\";\n this.reason = options.reason;\n this.maxIterations = options.maxIterations;\n }\n}\n\n/**\n * Process a single SSE event and update the content accumulator.\n * Returns: \"continue\" to keep going, \"done\" to stop, or a yield-ready result.\n */\nexport function processEvent(\n ev: SSEEvent,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n): {\n action:\n | \"continue\"\n | \"done\"\n | \"yield\"\n | \"error\"\n | \"missing_api_key\"\n | \"auto_continue\";\n result?: ChatModelRunResult;\n autoContinue?: {\n reason: AgentAutoContinueReason;\n maxIterations?: number;\n };\n} {\n if (ev.type === \"clear\") {\n // Server is retrying — discard partial text/tool output from the failed attempt\n content.length = 0;\n return { action: \"continue\" };\n }\n\n if (ev.type === \"text\") {\n const lastPart = content[content.length - 1];\n if (lastPart && lastPart.type === \"text\") {\n lastPart.text += ev.text ?? \"\";\n } else {\n content.push({ type: \"text\", text: ev.text ?? \"\" });\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"tool_start\") {\n const toolCallId = `tc_${++toolCallCounter.value}`;\n const args = (ev.input ?? {}) as Record<string, string>;\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-native:tool-start\", {\n detail: { tool: ev.tool ?? \"unknown\", input: args },\n }),\n );\n }\n content.push({\n type: \"tool-call\",\n toolCallId,\n toolName: ev.tool ?? \"unknown\",\n argsText: JSON.stringify(args),\n args,\n });\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"tool_done\") {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-native:tool-done\", {\n detail: { tool: ev.tool ?? \"unknown\", result: ev.result },\n }),\n );\n }\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === ev.tool &&\n part.result === undefined\n ) {\n part.result = ev.result ?? \"\";\n break;\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"agent_call\") {\n const agentName = ev.agent ?? \"agent\";\n if (ev.status === \"start\") {\n const toolCallId = `tc_${++toolCallCounter.value}`;\n content.push({\n type: \"tool-call\",\n toolCallId,\n toolName: `agent:${agentName}`,\n argsText: \"\",\n args: {},\n });\n } else if (ev.status === \"done\" || ev.status === \"error\") {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === `agent:${agentName}` &&\n part.result === undefined\n ) {\n part.result = ev.status === \"error\" ? \"Error calling agent\" : \"Done\";\n break;\n }\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"agent_call_text\") {\n const agentName = ev.agent ?? \"agent\";\n // Find the in-progress agent tool-call and append streaming text to argsText\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === `agent:${agentName}` &&\n part.result === undefined\n ) {\n part.argsText += ev.text ?? \"\";\n break;\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n // ─── Agent task events (sub-agent chips) ─────────────────────────\n // These events are dispatched as CustomEvents so AgentTaskCard components\n // can listen for updates to their specific taskId.\n if (\n ev.type === \"agent_task\" ||\n ev.type === \"agent_task_update\" ||\n ev.type === \"agent_task_complete\"\n ) {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"agent-task-event\", { detail: ev }));\n }\n // Don't add to content — the agent-teams tool call handles rendering\n return { action: \"continue\" };\n }\n\n if (ev.type === \"missing_api_key\") {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"agent-chat:missing-api-key\"));\n }\n content.push({ type: \"text\", text: \"\" });\n return {\n action: \"missing_api_key\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"loop_limit\") {\n const maxIterations =\n typeof ev.maxIterations === \"number\" ? ev.maxIterations : undefined;\n return {\n action: \"auto_continue\",\n autoContinue: {\n reason: \"loop_limit\",\n ...(maxIterations ? { maxIterations } : {}),\n },\n };\n }\n\n if (ev.type === \"auto_continue\") {\n const reason =\n ev.reason === \"stream_ended\" ||\n ev.reason === \"loop_limit\" ||\n ev.reason === \"run_timeout\"\n ? ev.reason\n : ev.errorCode === \"stream_ended\" ||\n ev.errorCode === \"loop_limit\" ||\n ev.errorCode === \"run_timeout\"\n ? ev.errorCode\n : ev.error === \"stream_ended\" ||\n ev.error === \"loop_limit\" ||\n ev.error === \"run_timeout\"\n ? ev.error\n : ev.status === \"stream_ended\" ||\n ev.status === \"loop_limit\" ||\n ev.status === \"run_timeout\"\n ? ev.status\n : \"run_timeout\";\n return {\n action: \"auto_continue\",\n autoContinue: {\n reason,\n ...(typeof ev.maxIterations === \"number\"\n ? { maxIterations: ev.maxIterations }\n : {}),\n },\n };\n }\n\n if (ev.type === \"error\") {\n const errMsg = ev.error ?? \"Unknown error\";\n if (ev.errorCode === \"run_timeout\" && ev.recoverable) {\n return {\n action: \"auto_continue\",\n autoContinue: { reason: \"run_timeout\" },\n };\n }\n const normalized = normalizeChatError(errMsg);\n if (\n errMsg.includes(\"apiKey\") ||\n errMsg.includes(\"authToken\") ||\n errMsg.includes(\"ANTHROPIC_API_KEY\") ||\n errMsg.includes(\"authentication\")\n ) {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"agent-chat:missing-api-key\"));\n }\n content.push({ type: \"text\", text: \"\" });\n return {\n action: \"missing_api_key\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n } as ChatModelRunResult,\n };\n }\n const runError = {\n message: normalized.message,\n ...(normalized.details || ev.details\n ? { details: ev.details ?? normalized.details }\n : {}),\n ...(ev.errorCode ? { errorCode: ev.errorCode } : {}),\n ...(ev.recoverable ? { recoverable: ev.recoverable } : {}),\n };\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:run-error\", {\n detail: { ...runError, tabId },\n }),\n );\n }\n content.push({\n type: \"text\",\n text: formatChatErrorText(errMsg, ev.upgradeUrl, ev.errorCode),\n });\n return {\n action: \"error\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n metadata: { custom: { runError } },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"done\") {\n return {\n action: \"done\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n return { action: \"continue\" };\n}\n\n/**\n * Read and process SSE events from a ReadableStream response body.\n * Yields ChatModelRunResult for each meaningful event.\n *\n * When `runId` is provided, every yielded result carries\n * `metadata.custom.runId` so the UI can expose the trace ID via\n * \"Copy Request ID\" — including mid-stream, so users can grab it before\n * the run completes (or if the run hangs / ends prematurely).\n */\nexport async function* readSSEStream(\n body: ReadableStream<Uint8Array>,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n onSeq?: (seq: number) => void,\n runId?: string | null,\n): AsyncGenerator<ChatModelRunResult> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = \"\";\n\n const withRunId = (r: ChatModelRunResult): ChatModelRunResult => {\n if (!runId) return r;\n const metadata = (r.metadata ?? {}) as Record<string, unknown>;\n const custom =\n metadata.custom && typeof metadata.custom === \"object\"\n ? (metadata.custom as Record<string, unknown>)\n : {};\n const runError =\n custom.runError && typeof custom.runError === \"object\"\n ? {\n ...(custom.runError as Record<string, unknown>),\n runId,\n }\n : custom.runError;\n return {\n ...r,\n metadata: {\n ...metadata,\n custom: { ...custom, runId, ...(runError ? { runError } : {}) },\n },\n };\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const raw = line.slice(6).trim();\n if (!raw) continue;\n\n let ev: SSEEvent;\n try {\n ev = JSON.parse(raw);\n } catch {\n continue;\n }\n\n // Track sequence number for reconnection\n if (ev.seq !== undefined && onSeq) {\n onSeq(ev.seq);\n }\n\n const { action, result, autoContinue } = processEvent(\n ev,\n content,\n toolCallCounter,\n tabId,\n );\n\n if (result) yield withRunId(result);\n if (action === \"auto_continue\") {\n throw new AgentAutoContinueSignal(\n autoContinue ?? { reason: \"stream_ended\" },\n );\n }\n if (\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n return;\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n // Stream ended without explicit done event\n if (content.length > 0) {\n throw new AgentAutoContinueSignal({ reason: \"stream_ended\" });\n }\n}\n\n/**\n * Read raw SSE events from a ReadableStream and process them into ContentPart[].\n * Unlike readSSEStream, this doesn't yield ChatModelRunResult — it updates the\n * content array in-place and calls onUpdate for each meaningful change.\n * Designed for reconnection scenarios where we render outside assistant-ui's runtime.\n */\nexport async function readSSEStreamRaw(\n body: ReadableStream<Uint8Array>,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n onUpdate: (content: ContentPart[]) => void,\n): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n\n let updated = false;\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const raw = line.slice(6).trim();\n if (!raw) continue;\n\n let ev: SSEEvent;\n try {\n ev = JSON.parse(raw);\n } catch {\n continue;\n }\n\n const { action } = processEvent(ev, content, toolCallCounter, tabId);\n\n if (\n action === \"yield\" ||\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n updated = true;\n }\n if (action === \"auto_continue\") {\n onUpdate([...content]);\n return;\n }\n if (\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n onUpdate([...content]);\n return;\n }\n }\n\n if (updated) {\n onUpdate([...content]);\n }\n }\n } finally {\n reader.releaseLock();\n }\n if (content.length > 0) onUpdate([...content]);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolEditor.d.ts","sourceRoot":"","sources":["../../../src/client/tools/ToolEditor.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ToolEditor.d.ts","sourceRoot":"","sources":["../../../src/client/tools/ToolEditor.tsx"],"names":[],"mappings":"AA+BA,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,UAAU,CAAC,EAAE,MAAM,EAAE,EAAE,eAAe,2CAmUrD"}
|
|
@@ -3,7 +3,8 @@ import { agentNativePath } from "../api-path.js";
|
|
|
3
3
|
import { useState, useEffect } from "react";
|
|
4
4
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
5
5
|
import { Link, useNavigate } from "react-router";
|
|
6
|
-
import { IconArrowLeft, IconDeviceFloppy, IconTrash, } from "@tabler/icons-react";
|
|
6
|
+
import { IconArrowLeft, IconDeviceFloppy, IconDots, IconTrash, IconX, } from "@tabler/icons-react";
|
|
7
|
+
import { Popover, PopoverContent, PopoverTrigger, } from "../components/ui/popover.js";
|
|
7
8
|
import { cn } from "../utils.js";
|
|
8
9
|
export function ToolEditor({ toolId }) {
|
|
9
10
|
const navigate = useNavigate();
|
|
@@ -14,7 +15,18 @@ export function ToolEditor({ toolId }) {
|
|
|
14
15
|
const [content, setContent] = useState("");
|
|
15
16
|
const [saving, setSaving] = useState(false);
|
|
16
17
|
const [deleting, setDeleting] = useState(false);
|
|
17
|
-
const [
|
|
18
|
+
const [menuOpen, setMenuOpen] = useState(false);
|
|
19
|
+
const [confirmingDelete, setConfirmingDelete] = useState(false);
|
|
20
|
+
const { data: slots = [] } = useQuery({
|
|
21
|
+
queryKey: ["tool-slots", toolId],
|
|
22
|
+
queryFn: async () => {
|
|
23
|
+
const res = await fetch(agentNativePath(`/_agent-native/slots/tool/${toolId}`));
|
|
24
|
+
if (!res.ok)
|
|
25
|
+
return [];
|
|
26
|
+
return res.json();
|
|
27
|
+
},
|
|
28
|
+
enabled: isEdit && menuOpen,
|
|
29
|
+
});
|
|
18
30
|
const { data: existingTool } = useQuery({
|
|
19
31
|
queryKey: ["tool", toolId],
|
|
20
32
|
queryFn: async () => {
|
|
@@ -87,13 +99,31 @@ export function ToolEditor({ toolId }) {
|
|
|
87
99
|
throw new Error("Delete failed");
|
|
88
100
|
}
|
|
89
101
|
queryClient.invalidateQueries({ queryKey: ["tools"] });
|
|
102
|
+
slots.forEach((s) => queryClient.invalidateQueries({
|
|
103
|
+
queryKey: ["slot-installs", s.slotId],
|
|
104
|
+
}));
|
|
90
105
|
navigate("/tools");
|
|
91
106
|
}
|
|
92
107
|
finally {
|
|
93
108
|
setDeleting(false);
|
|
94
|
-
|
|
109
|
+
setConfirmingDelete(false);
|
|
110
|
+
setMenuOpen(false);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const handleRemoveFromSlot = async (slotId) => {
|
|
114
|
+
if (!toolId)
|
|
115
|
+
return;
|
|
116
|
+
try {
|
|
117
|
+
await fetch(agentNativePath(`/_agent-native/slots/${encodeURIComponent(slotId)}/install/${encodeURIComponent(toolId)}`), { method: "DELETE" });
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
queryClient.invalidateQueries({ queryKey: ["slot-installs", slotId] });
|
|
95
121
|
}
|
|
96
122
|
};
|
|
97
|
-
return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsxs("header", { className: "flex items-center justify-between border-b px-4 py-3", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(Link, { to: isEdit ? `/tools/${toolId}` : "/tools", className: "inline-flex cursor-pointer items-center justify-center rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-accent-foreground", "aria-label": "Back", children: _jsx(IconArrowLeft, { className: "h-4 w-4" }) }), _jsx("h1", { className: "text-sm font-semibold", children: isEdit ? "Edit Tool" : "New Tool" })] }), _jsxs("div", { className: "flex items-center gap-2", children: [
|
|
123
|
+
return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsxs("header", { className: "flex items-center justify-between border-b px-4 py-3", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(Link, { to: isEdit ? `/tools/${toolId}` : "/tools", className: "inline-flex cursor-pointer items-center justify-center rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-accent-foreground", "aria-label": "Back", children: _jsx(IconArrowLeft, { className: "h-4 w-4" }) }), _jsx("h1", { className: "text-sm font-semibold", children: isEdit ? "Edit Tool" : "New Tool" })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs("button", { type: "button", onClick: handleSave, disabled: saving || !name.trim(), className: cn("inline-flex cursor-pointer items-center justify-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground hover:bg-primary/90", (saving || !name.trim()) && "opacity-60"), children: [_jsx(IconDeviceFloppy, { className: "h-3.5 w-3.5" }), saving ? "Saving..." : isEdit ? "Save" : "Create"] }), isEdit && (_jsxs(Popover, { open: menuOpen, onOpenChange: (o) => {
|
|
124
|
+
setMenuOpen(o);
|
|
125
|
+
if (!o)
|
|
126
|
+
setConfirmingDelete(false);
|
|
127
|
+
}, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx("button", { type: "button", className: "inline-flex h-8 w-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground", title: "More options", "aria-label": "More options", children: _jsx(IconDots, { className: "h-4 w-4" }) }) }), _jsx(PopoverContent, { align: "end", sideOffset: 4, className: "w-72 p-0", children: !confirmingDelete ? (_jsxs(_Fragment, { children: [_jsxs("div", { className: "px-3 py-2 border-b border-border/40", children: [_jsx("p", { className: "text-[12px] font-medium", children: "Appears in" }), slots.length === 0 ? (_jsx("p", { className: "text-[11px] text-muted-foreground/70 mt-0.5", children: "Not installed in any widget areas. Ask the agent to add it somewhere." })) : (_jsxs("p", { className: "text-[11px] text-muted-foreground/70 mt-0.5", children: ["This tool can render in ", slots.length, " widget area", slots.length === 1 ? "" : "s", "."] }))] }), slots.length > 0 && (_jsx("div", { className: "max-h-48 overflow-y-auto py-1", children: slots.map((s) => (_jsxs("div", { className: "flex items-center gap-2 px-3 py-1.5 text-[12px]", children: [_jsx("span", { className: "flex-1 truncate font-mono text-[11px] text-muted-foreground", children: s.slotId }), _jsx("button", { type: "button", onClick: () => handleRemoveFromSlot(s.slotId), className: "rounded p-1 text-muted-foreground/60 hover:bg-accent hover:text-foreground cursor-pointer", title: "Remove from this widget area (for me)", "aria-label": "Remove from this widget area", children: _jsx(IconX, { className: "h-3.5 w-3.5" }) })] }, s.id))) })), _jsx("div", { className: "border-t border-border/40 p-1", children: _jsxs("button", { type: "button", onClick: () => setConfirmingDelete(true), className: "flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-[12px] text-destructive hover:bg-destructive/10 cursor-pointer text-left", children: [_jsx(IconTrash, { className: "h-3.5 w-3.5" }), _jsx("span", { children: "Delete tool\u2026" })] }) })] })) : (_jsxs("div", { className: "flex flex-col gap-2 p-3", children: [_jsxs("p", { className: "text-[12px]", children: ["Delete ", _jsx("span", { className: "font-medium", children: name }), "? This removes the tool everywhere, for everyone it's shared with."] }), _jsxs("div", { className: "flex justify-end gap-1", children: [_jsx("button", { type: "button", onClick: () => setConfirmingDelete(false), className: "rounded-md px-2 py-1 text-[12px] hover:bg-accent cursor-pointer", children: "Cancel" }), _jsx("button", { type: "button", onClick: handleDelete, disabled: deleting, className: cn("rounded-md bg-destructive px-2 py-1 text-[12px] text-destructive-foreground hover:bg-destructive/90 cursor-pointer", deleting && "opacity-60"), children: deleting ? "Deleting…" : "Delete" })] })] })) })] }))] })] }), _jsxs("div", { className: "flex flex-1 overflow-hidden", children: [_jsxs("div", { className: "flex w-1/2 flex-col gap-4 overflow-auto border-r p-4", children: [_jsxs("div", { children: [_jsx("label", { className: "mb-1.5 block text-sm font-medium text-foreground", children: "Name" }), _jsx("input", { type: "text", value: name, onChange: (e) => setName(e.target.value), placeholder: "My Tool", className: "h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background" })] }), _jsxs("div", { children: [_jsx("label", { className: "mb-1.5 block text-sm font-medium text-foreground", children: "Description" }), _jsx("textarea", { value: description, onChange: (e) => setDescription(e.target.value), placeholder: "What does this tool do?", rows: 2, className: "w-full resize-none rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background" })] }), _jsxs("div", { className: "flex flex-1 flex-col", children: [_jsx("label", { className: "mb-1.5 block text-sm font-medium text-foreground", children: "Content" }), _jsx("textarea", { value: content, onChange: (e) => setContent(e.target.value), placeholder: "<html>...</html>", className: "flex-1 resize-none rounded-md border border-input bg-background p-3 font-mono text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background", spellCheck: false })] })] }), _jsx("div", { className: "w-1/2", children: content ? (_jsx("iframe", { srcDoc: content, className: "h-full w-full border-0", sandbox: "allow-scripts allow-forms", title: "Tool preview" })) : (_jsx("div", { className: "flex h-full items-center justify-center text-sm text-muted-foreground", children: "Preview will appear here" })) })] })] }));
|
|
98
128
|
}
|
|
99
129
|
//# sourceMappingURL=ToolEditor.js.map
|