@agent-native/core 0.127.1 → 0.128.0
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 +2 -2
- package/corpus/core/CHANGELOG.md +92 -0
- package/corpus/core/README.md +5 -26
- package/corpus/core/docs/content/actions.mdx +47 -4
- package/corpus/core/docs/content/native-chat-ui.mdx +7 -0
- package/corpus/core/docs/content/organizations-teams-permissions.mdx +109 -3
- package/corpus/core/docs/content/template-design-collaboration-and-full-apps.mdx +15 -0
- package/corpus/core/docs/content/toolkit-org-team.mdx +72 -12
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/a2a/artifact-response.ts +36 -29
- package/corpus/core/src/action.ts +83 -2
- package/corpus/core/src/chat-threads/store.ts +48 -43
- package/corpus/core/src/cli/skills-content/design-visual-edit-skill.ts +46 -3
- package/corpus/core/src/cli/template-sync.ts +96 -0
- package/corpus/core/src/client/AgentPanel.tsx +26 -6
- package/corpus/core/src/client/AssistantChat.tsx +63 -7
- package/corpus/core/src/client/DefaultSpinner.tsx +29 -0
- package/corpus/core/src/client/org/TeamPage.tsx +161 -6
- package/corpus/core/src/client/org/hooks.ts +67 -0
- package/corpus/core/src/client/org/index.ts +9 -0
- package/corpus/core/src/client/transcription/use-live-transcription.ts +62 -10
- package/corpus/core/src/db/client.ts +42 -3
- package/corpus/core/src/db/ensure-additive-columns.ts +60 -33
- package/corpus/core/src/deploy/build.ts +31 -2
- package/corpus/core/src/mcp-client/routes.ts +10 -1
- package/corpus/core/src/org/app-roles-handlers.ts +152 -0
- package/corpus/core/src/org/app-roles.ts +355 -0
- package/corpus/core/src/org/index.ts +27 -1
- package/corpus/core/src/org/migrations.ts +22 -0
- package/corpus/core/src/org/plugin.ts +27 -0
- package/corpus/core/src/org/schema.ts +15 -0
- package/corpus/core/src/scripts/docs/search.ts +17 -0
- package/corpus/core/src/scripts/docs/source-search.ts +10 -0
- package/corpus/core/src/server/agent-chat/script-entries.ts +3 -0
- package/corpus/core/src/server/agent-chat-plugin.ts +53 -52
- package/corpus/core/src/server/builder-design-systems.ts +1 -1
- package/corpus/core/src/server/core-routes-plugin.ts +6 -1
- package/corpus/core/src/server/framework-request-handler.ts +44 -6
- package/corpus/core/src/templates/default/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/core/src/templates/default/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/corpus/core/src/templates/default/.agents/skills/security/SKILL.md +31 -0
- package/corpus/core/src/templates/headless/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/authentication/SKILL.md +40 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/security/SKILL.md +31 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/analytics/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/analytics/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/analytics/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/analytics/actions/data-source-status.ts +21 -12
- package/corpus/templates/analytics/app/global.css +7 -7
- package/corpus/templates/analytics/app/i18n-data.ts +30 -0
- package/corpus/templates/analytics/app/lib/data-source-status.ts +2 -1
- package/corpus/templates/analytics/app/pages/DataSources.tsx +54 -10
- package/corpus/templates/analytics/changelog/2026-07-28-analytics-pages-load-reliably-with-large-dashboard-workspaces.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-28-dashboard-loading-shimmer-now-flows-smoothly-in-one-directi.md +6 -0
- package/corpus/templates/analytics/server/lib/first-party-dashboard-repair.ts +5 -4
- package/corpus/templates/analytics/server/plugins/agent-chat.ts +54 -42
- package/corpus/templates/analytics/server/plugins/db.ts +1 -18
- package/corpus/templates/assets/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/assets/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/assets/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/brain/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/brain/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/corpus/templates/brain/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/brain/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/calendar/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/calendar/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/calendar/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/chat/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/chat/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/corpus/templates/chat/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/chat/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/chat/_gitignore +2 -0
- package/corpus/templates/clips/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/clips/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/clips/actions/request-transcript.ts +77 -11
- package/corpus/templates/clips/actions/save-browser-transcript.ts +28 -7
- package/corpus/templates/clips/app/routes/record.tsx +11 -3
- package/corpus/templates/clips/changelog/2026-07-28-browser-recordings-no-longer-save-a-truncated-transcript-as-.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-28-browser-recordings-no-longer-stop-transcribing-partway-throu.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-28-desktop-full-screen-clips-now-get-an-instant-local-transcrip.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-28-long-transcriptions-no-longer-show-a-false-transcription-sto.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-28-restarting-for-an-update-now-installs-the-newest-release-ins.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-28-the-meeting-recording-pill-now-anchors-to-the-right-edge-of-.md +6 -0
- package/corpus/templates/clips/desktop/src/lib/audio-meter.ts +31 -2
- package/corpus/templates/clips/desktop/src/lib/recorder.ts +114 -13
- package/corpus/templates/clips/desktop/src/lib/updater.ts +12 -4
- package/corpus/templates/clips/desktop/src/overlays/live-audio-bars.tsx +40 -15
- package/corpus/templates/clips/desktop/src/styles.css +10 -7
- package/corpus/templates/clips/desktop/src-tauri/src/recording_indicator.rs +21 -14
- package/corpus/templates/clips/shared/transcript-status.ts +10 -0
- package/corpus/templates/content/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/content/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/content/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/crm/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/design/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/design/.agents/skills/design-generation/SKILL.md +23 -0
- package/corpus/templates/design/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/design/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/design/.agents/skills/visual-edit/SKILL.md +46 -3
- package/corpus/templates/design/.generated/bridge/editor-chrome.generated.ts +7 -5
- package/corpus/templates/design/actions/create-file.ts +15 -0
- package/corpus/templates/design/actions/generate-design.ts +40 -0
- package/corpus/templates/design/actions/present-design-variants.ts +16 -0
- package/corpus/templates/design/app/components/design/CanvasContextMenu.tsx +2 -2
- package/corpus/templates/design/app/components/design/bridge/editor-chrome.bridge.ts +7 -4
- package/corpus/templates/design/app/components/design/keyboard-shortcuts.ts +1 -1
- package/corpus/templates/design/app/hooks/useDesignHotkeys.ts +10 -4
- package/corpus/templates/design/app/lib/design-ui-events.ts +5 -0
- package/corpus/templates/design/app/pages/design-editor/save-failure.ts +7 -1
- package/corpus/templates/design/app/root.tsx +18 -1
- package/corpus/templates/design/changelog/2026-07-28-generated-designs-with-malformed-html-are-now-rejected-at-sa.md +6 -0
- package/corpus/templates/design/changelog/2026-07-28-show-or-hide-design-editing-chrome-with-cmd-on-apple-devices.md +6 -0
- package/corpus/templates/design/server/source-workspace.ts +1 -0
- package/corpus/templates/design/shared/html-integrity.ts +608 -18
- package/corpus/templates/dispatch/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/dispatch/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/dispatch/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/forms/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/forms/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/forms/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/macros/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/macros/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/mail/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/mail/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/mail/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/plan/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/plan/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/corpus/templates/plan/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/plan/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/slides/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/slides/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/slides/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/templates/slides/app/components/deck/DeckCard.tsx +2 -6
- package/corpus/templates/tasks/.agents/skills/actions/SKILL.md +32 -0
- package/corpus/templates/tasks/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/corpus/templates/tasks/.agents/skills/security/SKILL.md +31 -0
- package/corpus/templates/tasks/.agents/skills/sharing/SKILL.md +4 -0
- package/dist/a2a/artifact-response.d.ts.map +1 -1
- package/dist/a2a/artifact-response.js +30 -29
- package/dist/a2a/artifact-response.js.map +1 -1
- package/dist/action.d.ts +36 -0
- package/dist/action.d.ts.map +1 -1
- package/dist/action.js +37 -2
- package/dist/action.js.map +1 -1
- package/dist/chat-threads/store.d.ts +12 -0
- package/dist/chat-threads/store.d.ts.map +1 -1
- package/dist/chat-threads/store.js +48 -42
- package/dist/chat-threads/store.js.map +1 -1
- package/dist/cli/skills-content/design-visual-edit-skill.d.ts +1 -1
- package/dist/cli/skills-content/design-visual-edit-skill.d.ts.map +1 -1
- package/dist/cli/skills-content/design-visual-edit-skill.js +46 -3
- package/dist/cli/skills-content/design-visual-edit-skill.js.map +1 -1
- package/dist/cli/template-sync.d.ts.map +1 -1
- package/dist/cli/template-sync.js +88 -0
- package/dist/cli/template-sync.js.map +1 -1
- package/dist/client/AgentPanel.d.ts +3 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +11 -9
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +57 -6
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/DefaultSpinner.d.ts +7 -0
- package/dist/client/DefaultSpinner.d.ts.map +1 -1
- package/dist/client/DefaultSpinner.js +25 -1
- package/dist/client/DefaultSpinner.js.map +1 -1
- package/dist/client/org/TeamPage.d.ts +13 -1
- package/dist/client/org/TeamPage.d.ts.map +1 -1
- package/dist/client/org/TeamPage.js +41 -11
- package/dist/client/org/TeamPage.js.map +1 -1
- package/dist/client/org/hooks.d.ts +37 -0
- package/dist/client/org/hooks.d.ts.map +1 -1
- package/dist/client/org/hooks.js +37 -0
- package/dist/client/org/hooks.js.map +1 -1
- package/dist/client/org/index.d.ts +3 -2
- package/dist/client/org/index.d.ts.map +1 -1
- package/dist/client/org/index.js +1 -1
- package/dist/client/org/index.js.map +1 -1
- package/dist/client/transcription/use-live-transcription.d.ts +8 -0
- package/dist/client/transcription/use-live-transcription.d.ts.map +1 -1
- package/dist/client/transcription/use-live-transcription.js +38 -11
- package/dist/client/transcription/use-live-transcription.js.map +1 -1
- package/dist/collab/routes.d.ts +1 -1
- package/dist/collab/struct-routes.d.ts +1 -1
- package/dist/db/client.d.ts +12 -0
- package/dist/db/client.d.ts.map +1 -1
- package/dist/db/client.js +40 -3
- package/dist/db/client.js.map +1 -1
- package/dist/db/ensure-additive-columns.d.ts.map +1 -1
- package/dist/db/ensure-additive-columns.js +54 -32
- package/dist/db/ensure-additive-columns.js.map +1 -1
- package/dist/deploy/build.d.ts +1 -0
- package/dist/deploy/build.d.ts.map +1 -1
- package/dist/deploy/build.js +23 -2
- package/dist/deploy/build.js.map +1 -1
- package/dist/mcp-client/routes.d.ts +3 -1
- package/dist/mcp-client/routes.d.ts.map +1 -1
- package/dist/mcp-client/routes.js +8 -2
- package/dist/mcp-client/routes.js.map +1 -1
- package/dist/notifications/routes.d.ts +1 -1
- package/dist/observability/routes.d.ts +3 -3
- package/dist/org/app-roles-handlers.d.ts +27 -0
- package/dist/org/app-roles-handlers.d.ts.map +1 -0
- package/dist/org/app-roles-handlers.js +125 -0
- package/dist/org/app-roles-handlers.js.map +1 -0
- package/dist/org/app-roles.d.ts +136 -0
- package/dist/org/app-roles.d.ts.map +1 -0
- package/dist/org/app-roles.js +216 -0
- package/dist/org/app-roles.js.map +1 -0
- package/dist/org/index.d.ts +4 -1
- package/dist/org/index.d.ts.map +1 -1
- package/dist/org/index.js +3 -1
- package/dist/org/index.js.map +1 -1
- package/dist/org/migrations.d.ts.map +1 -1
- package/dist/org/migrations.js +22 -0
- package/dist/org/migrations.js.map +1 -1
- package/dist/org/plugin.d.ts +2 -0
- package/dist/org/plugin.d.ts.map +1 -1
- package/dist/org/plugin.js +20 -0
- package/dist/org/plugin.js.map +1 -1
- package/dist/org/schema.d.ts +143 -0
- package/dist/org/schema.d.ts.map +1 -1
- package/dist/org/schema.js +14 -0
- package/dist/org/schema.js.map +1 -1
- package/dist/provider-api/actions/custom-provider-registration.d.ts +4 -4
- package/dist/provider-api/actions/provider-api.d.ts +12 -12
- package/dist/resources/handlers.d.ts +1 -1
- package/dist/scripts/docs/search.d.ts.map +1 -1
- package/dist/scripts/docs/search.js +15 -0
- package/dist/scripts/docs/search.js.map +1 -1
- package/dist/scripts/docs/source-search.d.ts +7 -0
- package/dist/scripts/docs/source-search.d.ts.map +1 -1
- package/dist/scripts/docs/source-search.js +9 -0
- package/dist/scripts/docs/source-search.js.map +1 -1
- package/dist/server/agent-chat/script-entries.d.ts.map +1 -1
- package/dist/server/agent-chat/script-entries.js +3 -0
- package/dist/server/agent-chat/script-entries.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +46 -48
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/builder-design-systems.js +1 -1
- package/dist/server/builder-design-systems.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +6 -1
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/server/framework-request-handler.d.ts.map +1 -1
- package/dist/server/framework-request-handler.js +42 -6
- package/dist/server/framework-request-handler.js.map +1 -1
- package/dist/server/transcribe-voice.d.ts +1 -1
- package/dist/templates/chat/.agents/skills/actions/SKILL.md +32 -0
- package/dist/templates/chat/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/dist/templates/chat/.agents/skills/security/SKILL.md +31 -0
- package/dist/templates/chat/.agents/skills/sharing/SKILL.md +4 -0
- package/dist/templates/chat/_gitignore +2 -0
- package/dist/templates/default/.agents/skills/actions/SKILL.md +32 -0
- package/dist/templates/default/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/dist/templates/default/.agents/skills/security/SKILL.md +31 -0
- package/dist/templates/headless/.agents/skills/actions/SKILL.md +32 -0
- package/dist/templates/workspace-core/.agents/skills/actions/SKILL.md +32 -0
- package/dist/templates/workspace-core/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/dist/templates/workspace-core/.agents/skills/authentication/SKILL.md +40 -0
- package/dist/templates/workspace-core/.agents/skills/security/SKILL.md +31 -0
- package/dist/templates/workspace-core/.agents/skills/sharing/SKILL.md +4 -0
- package/docs/content/actions.mdx +47 -4
- package/docs/content/native-chat-ui.mdx +7 -0
- package/docs/content/organizations-teams-permissions.mdx +109 -3
- package/docs/content/template-design-collaboration-and-full-apps.mdx +15 -0
- package/docs/content/toolkit-org-team.mdx +72 -12
- package/package.json +1 -1
- package/src/a2a/artifact-response.ts +36 -29
- package/src/action.ts +83 -2
- package/src/chat-threads/store.ts +48 -43
- package/src/cli/skills-content/design-visual-edit-skill.ts +46 -3
- package/src/cli/template-sync.ts +96 -0
- package/src/client/AgentPanel.tsx +26 -6
- package/src/client/AssistantChat.tsx +63 -7
- package/src/client/DefaultSpinner.tsx +29 -0
- package/src/client/org/TeamPage.tsx +161 -6
- package/src/client/org/hooks.ts +67 -0
- package/src/client/org/index.ts +9 -0
- package/src/client/transcription/use-live-transcription.ts +62 -10
- package/src/db/client.ts +42 -3
- package/src/db/ensure-additive-columns.ts +60 -33
- package/src/deploy/build.ts +31 -2
- package/src/mcp-client/routes.ts +10 -1
- package/src/org/app-roles-handlers.ts +152 -0
- package/src/org/app-roles.ts +355 -0
- package/src/org/index.ts +27 -1
- package/src/org/migrations.ts +22 -0
- package/src/org/plugin.ts +27 -0
- package/src/org/schema.ts +15 -0
- package/src/scripts/docs/search.ts +17 -0
- package/src/scripts/docs/source-search.ts +10 -0
- package/src/server/agent-chat/script-entries.ts +3 -0
- package/src/server/agent-chat-plugin.ts +53 -52
- package/src/server/builder-design-systems.ts +1 -1
- package/src/server/core-routes-plugin.ts +6 -1
- package/src/server/framework-request-handler.ts +44 -6
- package/src/templates/chat/.agents/skills/actions/SKILL.md +32 -0
- package/src/templates/chat/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/src/templates/chat/.agents/skills/security/SKILL.md +31 -0
- package/src/templates/chat/.agents/skills/sharing/SKILL.md +4 -0
- package/src/templates/chat/_gitignore +2 -0
- package/src/templates/default/.agents/skills/actions/SKILL.md +32 -0
- package/src/templates/default/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/src/templates/default/.agents/skills/security/SKILL.md +31 -0
- package/src/templates/headless/.agents/skills/actions/SKILL.md +32 -0
- package/src/templates/workspace-core/.agents/skills/actions/SKILL.md +32 -0
- package/src/templates/workspace-core/.agents/skills/adding-a-feature/SKILL.md +7 -0
- package/src/templates/workspace-core/.agents/skills/authentication/SKILL.md +40 -0
- package/src/templates/workspace-core/.agents/skills/security/SKILL.md +31 -0
- package/src/templates/workspace-core/.agents/skills/sharing/SKILL.md +4 -0
- package/corpus/core/src/templates/chat/.agents/skills/actions/SKILL.md +0 -530
- package/corpus/core/src/templates/chat/.agents/skills/adding-a-feature/SKILL.md +0 -191
- package/corpus/core/src/templates/chat/.agents/skills/agent-native-docs/SKILL.md +0 -115
- package/corpus/core/src/templates/chat/.agents/skills/agent-native-toolkit/SKILL.md +0 -177
- package/corpus/core/src/templates/chat/.agents/skills/capture-learnings/SKILL.md +0 -89
- package/corpus/core/src/templates/chat/.agents/skills/create-skill/SKILL.md +0 -221
- package/corpus/core/src/templates/chat/.agents/skills/customizing-agent-native/SKILL.md +0 -220
- package/corpus/core/src/templates/chat/.agents/skills/delegate-to-agent/SKILL.md +0 -263
- package/corpus/core/src/templates/chat/.agents/skills/feature-flags/SKILL.md +0 -169
- package/corpus/core/src/templates/chat/.agents/skills/frontend-design/SKILL.md +0 -174
- package/corpus/core/src/templates/chat/.agents/skills/real-time-sync/SKILL.md +0 -232
- package/corpus/core/src/templates/chat/.agents/skills/security/SKILL.md +0 -282
- package/corpus/core/src/templates/chat/.agents/skills/self-modifying-code/SKILL.md +0 -119
- package/corpus/core/src/templates/chat/.agents/skills/shadcn-ui/SKILL.md +0 -123
- package/corpus/core/src/templates/chat/.agents/skills/upgrade-agent-native/SKILL.md +0 -122
- package/corpus/core/src/templates/chat/.env.example +0 -5
- package/corpus/core/src/templates/chat/.ignore +0 -0
- package/corpus/core/src/templates/chat/.oxfmtrc.json +0 -8
- package/corpus/core/src/templates/chat/AGENTS.md +0 -77
- package/corpus/core/src/templates/chat/CHANGELOG.md +0 -10
- package/corpus/core/src/templates/chat/DEVELOPING.md +0 -185
- package/corpus/core/src/templates/chat/README.md +0 -32
- package/corpus/core/src/templates/chat/_gitignore +0 -44
- package/corpus/core/src/templates/chat/actions/hello.ts +0 -13
- package/corpus/core/src/templates/chat/actions/navigate.ts +0 -41
- package/corpus/core/src/templates/chat/actions/run.ts +0 -2
- package/corpus/core/src/templates/chat/actions/view-screen.ts +0 -31
- package/corpus/core/src/templates/chat/app/components/layout/Header.tsx +0 -60
- package/corpus/core/src/templates/chat/app/components/layout/Layout.tsx +0 -188
- package/corpus/core/src/templates/chat/app/components/layout/Sidebar.tsx +0 -505
- package/corpus/core/src/templates/chat/app/components/ui/button.tsx +0 -1
- package/corpus/core/src/templates/chat/app/components/ui/card.tsx +0 -1
- package/corpus/core/src/templates/chat/app/components/ui/dropdown-menu.tsx +0 -1
- package/corpus/core/src/templates/chat/app/components/ui/input.tsx +0 -1
- package/corpus/core/src/templates/chat/app/components/ui/label.tsx +0 -1
- package/corpus/core/src/templates/chat/app/components/ui/sheet.tsx +0 -1
- package/corpus/core/src/templates/chat/app/components/ui/toolkit-provider.tsx +0 -17
- package/corpus/core/src/templates/chat/app/components/ui/tooltip.tsx +0 -1
- package/corpus/core/src/templates/chat/app/design-system.ts +0 -3
- package/corpus/core/src/templates/chat/app/entry.client.tsx +0 -22
- package/corpus/core/src/templates/chat/app/entry.server.tsx +0 -10
- package/corpus/core/src/templates/chat/app/global.css +0 -93
- package/corpus/core/src/templates/chat/app/hooks/use-navigation-state.ts +0 -93
- package/corpus/core/src/templates/chat/app/i18n/ar-SA.ts +0 -68
- package/corpus/core/src/templates/chat/app/i18n/de-DE.ts +0 -71
- package/corpus/core/src/templates/chat/app/i18n/en-US.ts +0 -70
- package/corpus/core/src/templates/chat/app/i18n/es-ES.ts +0 -71
- package/corpus/core/src/templates/chat/app/i18n/fr-FR.ts +0 -71
- package/corpus/core/src/templates/chat/app/i18n/hi-IN.ts +0 -69
- package/corpus/core/src/templates/chat/app/i18n/index.ts +0 -34
- package/corpus/core/src/templates/chat/app/i18n/ja-JP.ts +0 -70
- package/corpus/core/src/templates/chat/app/i18n/ko-KR.ts +0 -70
- package/corpus/core/src/templates/chat/app/i18n/pt-BR.ts +0 -71
- package/corpus/core/src/templates/chat/app/i18n/zh-CN.ts +0 -66
- package/corpus/core/src/templates/chat/app/i18n/zh-TW.ts +0 -66
- package/corpus/core/src/templates/chat/app/i18n-data.ts +0 -556
- package/corpus/core/src/templates/chat/app/lib/agent-page.tsx +0 -49
- package/corpus/core/src/templates/chat/app/lib/app-config.ts +0 -11
- package/corpus/core/src/templates/chat/app/lib/tab-id.ts +0 -1
- package/corpus/core/src/templates/chat/app/lib/utils.ts +0 -1
- package/corpus/core/src/templates/chat/app/root.tsx +0 -173
- package/corpus/core/src/templates/chat/app/routes/_index.tsx +0 -94
- package/corpus/core/src/templates/chat/app/routes/agent.tsx +0 -24
- package/corpus/core/src/templates/chat/app/routes/chat.$threadId.tsx +0 -1
- package/corpus/core/src/templates/chat/app/routes/database.tsx +0 -17
- package/corpus/core/src/templates/chat/app/routes/extensions.$id.$slug.tsx +0 -2
- package/corpus/core/src/templates/chat/app/routes/extensions.$id.tsx +0 -11
- package/corpus/core/src/templates/chat/app/routes/extensions._index.tsx +0 -11
- package/corpus/core/src/templates/chat/app/routes/extensions.tsx +0 -5
- package/corpus/core/src/templates/chat/app/routes/observability.tsx +0 -19
- package/corpus/core/src/templates/chat/app/routes/settings.tsx +0 -89
- package/corpus/core/src/templates/chat/app/routes/team.tsx +0 -11
- package/corpus/core/src/templates/chat/app/routes.ts +0 -4
- package/corpus/core/src/templates/chat/app/vite-env.d.ts +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-06-27-traditional-chinese-copy-uses-taiwan-terminology.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-06-28-left-sidebar-collapse-motion-and-footer-chrome-are-quieter.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-06-29-chat-layouts-adapt-when-the-agent-sidebar-is-open.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-08-settings-are-cleaner-and-searchable.md +0 -5
- package/corpus/core/src/templates/chat/changelog/2026-07-10-chat-now-makes-ai-connection-setup-clear-without-shifting-th.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-13-a-full-agent-page-now-brings-context-files-connections-jobs-.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-14-chat-opens-reliably-on-hosted-deployments-instead-of-failing.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-14-fixed-chat-template-startup-with-older-core-versions.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-15-chat-navigation-focuses-on-chat-and-agent.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-17-the-agent-chat-sidebar-stays-closed-until-you-open-it-or-sta.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-22-compact-sidebar-footer.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-22-full-page-chat-keeps-the-active-conversation-when-moving-to-.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-22-recent-chats-are-easier-to-scan-and-expand.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-23-full-page-chat-is-better-centered-with-quieter-chat-history-.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-24-borderless-secondary-surfaces.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-24-sidebar-footer-controls-follow-a-consistent-order.md +0 -6
- package/corpus/core/src/templates/chat/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +0 -6
- package/corpus/core/src/templates/chat/components.json +0 -20
- package/corpus/core/src/templates/chat/learnings.defaults.md +0 -5
- package/corpus/core/src/templates/chat/netlify.toml +0 -11
- package/corpus/core/src/templates/chat/package.json +0 -92
- package/corpus/core/src/templates/chat/public/agent-native-icon-dark.svg +0 -10
- package/corpus/core/src/templates/chat/public/agent-native-icon-light.svg +0 -10
- package/corpus/core/src/templates/chat/public/agent-native-logo-dark.svg +0 -21
- package/corpus/core/src/templates/chat/public/agent-native-logo-light.svg +0 -21
- package/corpus/core/src/templates/chat/public/favicon.svg +0 -1
- package/corpus/core/src/templates/chat/public/icon-180.svg +0 -1
- package/corpus/core/src/templates/chat/public/icon-192.svg +0 -1
- package/corpus/core/src/templates/chat/public/icon-512.svg +0 -1
- package/corpus/core/src/templates/chat/public/manifest.json +0 -21
- package/corpus/core/src/templates/chat/react-router.config.ts +0 -7
- package/corpus/core/src/templates/chat/server/middleware/auth.ts +0 -15
- package/corpus/core/src/templates/chat/server/plugins/agent-chat.ts +0 -21
- package/corpus/core/src/templates/chat/server/plugins/auth.ts +0 -17
- package/corpus/core/src/templates/chat/server/routes/[...page].get.ts +0 -5
- package/corpus/core/src/templates/chat/ssr-entry.ts +0 -15
- package/corpus/core/src/templates/chat/tsconfig.json +0 -21
- package/corpus/core/src/templates/chat/vite.config.ts +0 -19
package/dist/action.js
CHANGED
|
@@ -52,12 +52,19 @@ export function defineAction(options) {
|
|
|
52
52
|
"~standard" in options.agentInputSchema) {
|
|
53
53
|
toolParameters = schemaToJsonSchema(options.agentInputSchema, options.description);
|
|
54
54
|
}
|
|
55
|
+
// Authorization sits INSIDE input validation, so a gate that inspects `args`
|
|
56
|
+
// is handed the parsed, coerced value its type promises rather than whatever
|
|
57
|
+
// shape the caller sent. Putting it outside would have every guard reading
|
|
58
|
+
// attacker-shaped input while typed as though it were validated.
|
|
59
|
+
const guardedRun = typeof options.authorize === "function"
|
|
60
|
+
? wrapRunWithAuthorize(options.run, options.authorize)
|
|
61
|
+
: options.run;
|
|
55
62
|
// Wrap run() with INPUT validation when schema is provided.
|
|
56
63
|
// Pass toolParameters so the validation error can echo the expected signature
|
|
57
64
|
// (required vs optional fields) and help the caller self-correct.
|
|
58
65
|
const inputValidatedRun = hasSchema
|
|
59
|
-
? wrapWithValidation(options.schema,
|
|
60
|
-
:
|
|
66
|
+
? wrapWithValidation(options.schema, guardedRun, toolParameters)
|
|
67
|
+
: guardedRun;
|
|
61
68
|
// Then wrap with OUTPUT validation when an outputSchema is provided. This
|
|
62
69
|
// composes AROUND the input-validated run so the order is: validate input →
|
|
63
70
|
// run() → validate output. When no outputSchema is present, the run is passed
|
|
@@ -189,6 +196,34 @@ export function defineAction(options) {
|
|
|
189
196
|
...(auditConfig ? { audit: auditConfig } : {}),
|
|
190
197
|
};
|
|
191
198
|
}
|
|
199
|
+
/**
|
|
200
|
+
* Wrap an action's run with its `authorize` gate.
|
|
201
|
+
*
|
|
202
|
+
* The gate is applied here, around `run`, rather than exposed as a flag on the
|
|
203
|
+
* action entry: `run` is the one thing all six dispatch sites (agent loop, HTTP
|
|
204
|
+
* route, frontend, MCP, A2A, CLI) go through, so there is no caller that can
|
|
205
|
+
* reach the body without passing the check. `needsApproval` took the flag route
|
|
206
|
+
* and is consequently honoured only inside the agent loop.
|
|
207
|
+
*
|
|
208
|
+
* Composed so the full order is: validate input → authorize → run → validate
|
|
209
|
+
* output → audit. The audit wrapper is outermost, so a denial is still recorded
|
|
210
|
+
* as an attempt — which is precisely what an audit trail is for.
|
|
211
|
+
*
|
|
212
|
+
* A guard that throws denies with its own message. A guard that returns `false`
|
|
213
|
+
* denies generically. Anything else — including `undefined` — allows.
|
|
214
|
+
*/
|
|
215
|
+
function wrapRunWithAuthorize(run, authorize) {
|
|
216
|
+
return async function authorizedRun(args, ctx) {
|
|
217
|
+
const verdict = await authorize(args, ctx);
|
|
218
|
+
if (verdict === false) {
|
|
219
|
+
const err = new Error("Not authorized");
|
|
220
|
+
err.name = "ForbiddenError";
|
|
221
|
+
err.statusCode = 403;
|
|
222
|
+
throw err;
|
|
223
|
+
}
|
|
224
|
+
return run(args, ctx);
|
|
225
|
+
};
|
|
226
|
+
}
|
|
192
227
|
/**
|
|
193
228
|
* Wrap an action's (already input/output-validated) run so each call records an
|
|
194
229
|
* audit event after it resolves — on success and on error. Best-effort: the
|
package/dist/action.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,2BAA2B,GAE5B,MAAM,gBAAgB,CAAC;AAMxB,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAyH7E;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACpC,eAAe,GAAG,IAAI,CAAC;IACvB,SAAS,CAAU;IACnB,UAAU,CAAU;IAE7B,YAAY,OAAe,EAAE,OAAO,GAA2B,EAAE;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IACvC,CAAC;CACF;AAED,MAAM,UAAU,sBAAsB,CACpC,GAAY;IAEZ,OAAO,CACL,GAAG,YAAY,oBAAoB;QACnC,OAAO,CACL,GAAG;YACH,OAAO,GAAG,KAAK,QAAQ;YACvB,iBAAiB,IAAI,GAAG;YACvB,GAAqC,CAAC,eAAe,KAAK,IAAI,CAChE,CACF,CAAC;AACJ,CAAC;AA0CD,MAAM,CAAC,MAAM,oBAAoB,GAAG,4BAAqC,CAAC;AAC1E,MAAM,CAAC,MAAM,iBAAiB,GAAG,2BAAoC,CAAC;AACtE,MAAM,CAAC,MAAM,6BAA6B,GAAG,gBAAyB,CAAC;AA6dvE,MAAM,UAAU,YAAY,CAAC,OAAY;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ACJ,CAAC","sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport {\n normalizeActionChatUIConfig,\n type ActionChatUIConfig,\n} from \"./action-ui.js\";\nimport type {\n ActionTool,\n AgentChatAttachment,\n AgentChatEvent,\n} from \"./agent/types.js\";\nimport { normalizeAuditConfig, resolveAuditAttach } from \"./audit/config.js\";\nimport type { ActionAuditConfig } from \"./audit/types.js\";\n\n/**\n * How an action's `run` was invoked. Tagged at each dispatch site so the action\n * (and tracking) can branch on the surface that called it.\n *\n * - `\"tool\"` — the in-app agent loop, sub-agents/agent-teams, or A2A (which\n * drives the same agent loop). All agent tool calls are `\"tool\"`.\n * - `\"http\"` — a programmatic HTTP POST/GET to `/_agent-native/actions/<name>`\n * without the frontend request marker.\n * - `\"frontend\"` — a browser call via `useActionQuery` / `useActionMutation` /\n * `callAction` (tagged with the `X-Request-Source` header).\n * - `\"cli\"` — `pnpm action <name>` (the CLI runner).\n * - `\"mcp\"` — an external agent over the MCP `tools/call` endpoint.\n * - `\"a2a\"` — a direct, explicitly exposed read-only A2A action dispatch.\n * Natural-language A2A delegation still runs through the agent loop and its\n * selected actions are attributed as `\"tool\"`.\n * - `\"automation\"` — an event-triggered automation dispatched from a stored\n * workspace trigger with trusted trigger lineage.\n */\nexport type ActionCaller =\n | \"tool\"\n | \"http\"\n | \"frontend\"\n | \"cli\"\n | \"mcp\"\n | \"a2a\"\n | \"automation\";\n\n/**\n * Trusted automation lineage added by the trigger dispatcher. Action inputs\n * must never be used to create or override this context.\n */\nexport interface ActionAutomationContext {\n triggerId: string;\n triggerName: string;\n policyId?: string;\n}\n\n/**\n * Context passed as the optional second argument to an action's `run`.\n * Carries the resolved request identity and the invocation source so actions\n * can read `ctx.userEmail` / `ctx.orgId` / `ctx.caller` directly instead of\n * calling `getRequestUserEmail()` / `getRequestOrgId()` by hand.\n *\n * Backward compatible: existing 1-arg `run(args)` functions keep working, and\n * callers that only need `send` (the agent loop) can still destructure it.\n */\nexport interface ActionRunContext {\n /**\n * Emit an SSE event to the client. Only meaningful inside the agent tool\n * loop (e.g. `agent_call_text` streaming); `undefined` on every other\n * surface.\n */\n send?: (event: AgentChatEvent) => void;\n /**\n * Resolved request user email, or `undefined` when there is no authenticated\n * identity. NEVER defaulted to a dev identity — actions that need a fallback\n * must apply their own.\n */\n userEmail?: string;\n /** Resolved org id, or `null` when the request has no org. */\n orgId?: string | null;\n /** How this action was invoked. */\n caller: ActionCaller;\n /** Present only for trigger-dispatched automation calls. */\n automation?: ActionAutomationContext;\n /** Verified network lineage for direct delegated action calls. */\n networkProtocol?: \"a2a\" | \"mcp\" | \"provider-api\";\n networkId?: string;\n networkPeer?: string;\n /**\n * Attachments submitted with the current agent turn (pasted text blocks,\n * uploaded files, images), exactly as the server received them — with full,\n * untruncated `text` for text attachments. Populated only inside the agent\n * tool loop (`caller: \"tool\"`); `undefined` on every other surface.\n *\n * Lets an action consume a large pasted artifact BY REFERENCE (e.g.\n * `create-extension`'s `contentFromAttachment`) instead of forcing the model\n * to re-emit the whole file as a tool argument — which frequently gets cut\n * off mid-stream and triggers a continuation loop.\n */\n attachments?: AgentChatAttachment[];\n /**\n * Abort signal for the current agent run. Fires when the run is soft-timed\n * out, user-cancelled, or the server is shutting down. Well-behaved actions\n * can observe this signal to cancel in-flight work early instead of waiting\n * for the per-tool 60-second hard timeout.\n *\n * Populated only inside the agent tool loop (`caller: \"tool\"`); `undefined`\n * on every other surface. Never throws — checking `signal.aborted` or\n * attaching an `\"abort\"` listener is always safe.\n */\n signal?: AbortSignal;\n /**\n * Name of the action being invoked (the registry key, e.g.\n * `delete-recording`). Set at each dispatch site so cross-cutting concerns —\n * notably the audit log — can attribute the call. `undefined` for direct\n * programmatic `run()` calls that bypass the dispatcher.\n */\n actionName?: string;\n /**\n * Agent conversation thread + turn that triggered this call, populated only\n * inside the agent tool loop (`caller: \"tool\"`). Lets the audit log link a\n * mutation to the specific agent run/turn that caused it. `undefined` on\n * every human/programmatic surface.\n */\n threadId?: string;\n /** Concrete execution id for this agent-loop attempt. */\n runId?: string;\n turnId?: string;\n}\n\nexport interface AgentActionStopOptions {\n /** Optional stable code surfaced in run metadata and tests. */\n errorCode?: string;\n /** Optional short tool-result text. Defaults to the user-facing message. */\n toolResult?: string;\n}\n\n/**\n * Throw from an action when the agent should stop the current turn instead of\n * feeding the failure back to the model for another retry.\n */\nexport class AgentActionStopError extends Error {\n readonly agentNativeStop = true;\n readonly errorCode?: string;\n readonly toolResult?: string;\n\n constructor(message: string, options: AgentActionStopOptions = {}) {\n super(message);\n this.name = \"AgentActionStopError\";\n this.errorCode = options.errorCode;\n this.toolResult = options.toolResult;\n }\n}\n\nexport function isAgentActionStopError(\n err: unknown,\n): err is AgentActionStopError {\n return (\n err instanceof AgentActionStopError ||\n Boolean(\n err &&\n typeof err === \"object\" &&\n \"agentNativeStop\" in err &&\n (err as { agentNativeStop?: unknown }).agentNativeStop === true,\n )\n );\n}\n\n/** HTTP exposure config for an action. */\nexport interface ActionHttpConfig {\n /** HTTP method. Default: \"POST\". Use \"GET\" for read-only actions. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n /** Override route path under /_agent-native/actions/. Default: action filename. */\n path?: string;\n}\n\n/** Explicit opt-in metadata for public agent protocols such as MCP or A2A. */\nexport interface PublicAgentActionConfig {\n expose: boolean;\n readOnly: boolean;\n requiresAuth?: boolean;\n isConsequential?: boolean;\n title?: string;\n description?: string;\n}\n\n/** A deep link an external agent (MCP / A2A) can surface to the user so they\n * can open the produced/listed resource in the running app UI. */\nexport interface ActionDeepLink {\n /** App-relative path (e.g. `/_agent-native/open?app=mail&view=inbox&...`)\n * or an absolute URL. The MCP layer prefixes the request origin when this\n * is relative, and may rewrite it to the `agentnative://` desktop scheme. */\n url: string;\n /** Human-readable label, e.g. \"Open draft in Mail\". */\n label: string;\n /** Optional view hint (matches the `navigate` command `view`). */\n view?: string;\n}\n\n/** Builds a deep link from an action's args + result so external agents can\n * surface an \"Open in <app> →\" link. MUST be pure and synchronous — no I/O,\n * no awaits. Best-effort: a throw or null is swallowed and never fails the\n * tool call. See the `external-agents` skill. */\nexport type ActionLinkBuilder = (ctx: {\n args: Record<string, any>;\n result: any;\n}) => ActionDeepLink | null | undefined;\n\nexport const MCP_APP_EXTENSION_ID = \"io.modelcontextprotocol/ui\" as const;\nexport const MCP_APP_MIME_TYPE = \"text/html;profile=mcp-app\" as const;\nexport const MCP_APP_RESOURCE_URI_META_KEY = \"ui/resourceUri\" as const;\n\nexport interface ActionMcpAppCsp {\n connectDomains?: string[];\n resourceDomains?: string[];\n frameDomains?: string[];\n baseUriDomains?: string[];\n}\n\nexport type ActionMcpAppCspBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => ActionMcpAppCsp | Promise<ActionMcpAppCsp>;\n\nexport interface ActionMcpAppPermissions {\n camera?: Record<string, never>;\n microphone?: Record<string, never>;\n geolocation?: Record<string, never>;\n clipboardWrite?: Record<string, never>;\n}\n\nexport interface ActionMcpAppResourceMeta {\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n /**\n * Host-specific sandbox domain hint. Do not set this to the app's normal\n * production URL; app origins belong in CSP/open-link metadata. ChatGPT uses\n * the separate `openai/widgetDomain` compatibility field.\n */\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport type ActionMcpAppHtmlBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => string;\n\nexport interface ActionMcpAppResourceConfig {\n /** `ui://` URI. Defaults to `ui://<app>/<action-name>`. */\n uri?: string;\n /** MCP resource name. Defaults to the action name. */\n name?: string;\n title?: string;\n description?: string;\n /**\n * HTML5 document content for the MCP App resource. Keep this self-contained\n * or declare any external origins in `csp`.\n */\n html: string | ActionMcpAppHtmlBuilder;\n /** Defaults to the MCP Apps HTML MIME type. */\n mimeType?: typeof MCP_APP_MIME_TYPE;\n /** Extra resource/content metadata. `ui` is merged with the fields below. */\n _meta?: Record<string, unknown>;\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n /**\n * Host-specific sandbox domain hint. Do not set this to the app's normal\n * production URL; app origins belong in CSP/open-link metadata. ChatGPT uses\n * the separate `openai/widgetDomain` compatibility field.\n */\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport interface ActionMcpAppConfig {\n /**\n * Optional MCP Apps UI resource for hosts that render inline app iframes.\n * Required when the action should open an interactive app view. Omit when\n * you only need `compactCatalog: true` to keep a non-UI action visible in\n * the compact catalog (e.g. read/update actions that should be callable from\n * Claude.ai / ChatGPT without a dedicated iframe resource).\n */\n resource?: ActionMcpAppResourceConfig;\n /**\n * MCP Apps tool visibility. Defaults to model + app so the LLM can call the\n * action and the app iframe can call it back through the host bridge.\n */\n visibility?: Array<\"model\" | \"app\">;\n /**\n * Rare escape hatch for MCP Apps chat hosts. By default OAuth callers with\n * `mcp:apps` see the generic app tools (`open_app`, `list_apps`, etc.) so\n * hosts do not ingest every action-specific UI resource. Set this only when\n * this specific action must stay visible in that compact catalog.\n */\n compactCatalog?: boolean;\n}\n\n/** Schema definition for a single action parameter (legacy JSON schema style). */\nexport interface ParameterSchema {\n type: string;\n description?: string;\n enum?: string[];\n}\n\n/** Infer runtime parameter types from a legacy parameter schema map. */\ntype InferParams<T extends Record<string, ParameterSchema> | undefined> =\n T extends Record<string, ParameterSchema>\n ? { [K in keyof T]?: string }\n : Record<string, string>;\n\n/**\n * What to do when an action's RETURN value fails `outputSchema` validation.\n *\n * - `\"strict\"` — throw a clear error so a buggy action surfaces loudly.\n * - `\"warn\"` (default) — `console.warn` the issues and return the ORIGINAL\n * result unchanged. Non-breaking: behavior never changes unless the dev\n * opts into `\"strict\"` or `\"fallback\"`.\n * - `\"fallback\"` — return `outputFallback` in place of the invalid result.\n *\n * Mirrors Mastra/Flue structured-output handling, kept on the action layer.\n */\nexport type ActionOutputErrorStrategy = \"strict\" | \"warn\" | \"fallback\";\n\n// ---------------------------------------------------------------------------\n// Schema-based action options (new: Zod / Valibot / ArkType via Standard Schema)\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithSchema<\n TSchema extends StandardSchemaV1,\n TReturn = any,\n TOutputSchema extends StandardSchemaV1 | undefined = undefined,\n> {\n description: string;\n /** Standard Schema-compatible schema (Zod, Valibot, ArkType). Provides runtime\n * validation and full TypeScript type inference for `run()` args. The schema is\n * also converted to JSON Schema for the Claude API tool definition. */\n schema: TSchema;\n /** Legacy parameters — ignored when `schema` is provided. */\n parameters?: never;\n /**\n * Optional alternate Standard Schema (Zod, Valibot, ArkType) used ONLY to\n * build the tool definition advertised to the model — the JSON Schema that\n * lands in the Claude `tools` array (and MCP/A2A tool listings, which read\n * the same `tool.parameters`). Runtime validation always runs against\n * `schema` above via the normal `wrapWithValidation` path; setting this\n * never weakens validation and never changes `run()`'s argument type.\n *\n * Use this when the full input schema is much richer than what the model\n * needs to see up front — the canonical example is a deep discriminated\n * union of block/shape types where a per-call catalog lookup tool (e.g.\n * `get-plan-blocks`) already teaches the full field shapes. Advertise a\n * compact version (e.g. an enum of valid `type` values plus a note to call\n * the lookup tool) instead of embedding every variant's fields in every\n * request. Invalid calls still get the full, actionable validation error\n * (missing/invalid fields, received args) from `schema` — this only trims\n * what is proactively shown, not what is accepted or checked.\n */\n agentInputSchema?: StandardSchemaV1;\n /** Optional Standard Schema-compatible schema (Zod, Valibot, ArkType) the\n * action's RETURN value is validated against AFTER `run()` resolves. Borrowed\n * from Mastra/Flue structured-output. When omitted, behavior is byte-for-byte\n * unchanged. The mismatch handling is governed by `outputErrorStrategy`. */\n outputSchema?: TOutputSchema;\n /** What to do when the result fails `outputSchema`. Default: `\"warn\"`. */\n outputErrorStrategy?: ActionOutputErrorStrategy;\n /** Value returned in place of an invalid result when `outputErrorStrategy` is\n * `\"fallback\"`. Ignored for the other strategies. */\n outputFallback?: TReturn;\n run: (\n args: StandardSchemaV1.InferOutput<TSchema>,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** Whether the HTTP/frontend action route must have an authenticated owner.\n * Defaults to true. Set to false only for metadata/read actions that safely\n * handle `ctx.userEmail` / `getRequestUserEmail()` being undefined. */\n requiresAuth?: boolean;\n /** Max HTTP request body in bytes. When set, the route 413s on the declared\n * `Content-Length` before parsing. Use for public, no-auth POST actions;\n * unset = no route-level cap. */\n maxBodyBytes?: number;\n /** Whether this action is exposed to the agent — the in-app assistant and the\n * app's MCP/A2A tool surfaces — as a callable tool. **Default-allow opt-out**:\n * `undefined` / `true` expose it; only an explicit `false` hides it from every\n * agent tool list while keeping it callable from the frontend / HTTP\n * (`useActionMutation`, `callAction`, `/_agent-native/actions/<name>`). Use\n * this for UI-only or purely programmatic actions you want behind the\n * framework's auth + action surface WITHOUT spending a slot in the model's\n * tool list. Distinct from `toolCallable`, which only governs the sandboxed\n * extension (\"tools\") iframe bridge. See `packages/core/docs/content/actions.mdx`. */\n agentTool?: boolean;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`.\n * Only set this manually when you need to override the inference — e.g. a\n * POST action that only reads data but can't use GET for a protocol reason. */\n readOnly?: boolean;\n /** Set false for read-only tools that should stay available in Act mode but\n * must not run during Plan mode because they perform substantive work\n * rather than lightweight inspection. Defaults to allowed when read-only. */\n allowInPlanMode?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn.\n * Only set this for mutating actions that are internally concurrency-safe\n * and order-independent for same-turn execution. */\n parallelSafe?: boolean;\n /** Set false to exempt a read-only tool from the agent loop's duplicate\n * read-only call guard (per-turn result cache + \"Skipped duplicate...\"\n * repeat detection). Default true (deduped). Use this for volatile/polling\n * reads where an identical call is expected to return a different result\n * each time — e.g. polling a code-execution status by id, or re-fetching\n * current on-screen state. Has no effect on non-read-only actions, which\n * are never deduped in the first place. */\n dedupe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)` — see `packages/core/docs/content/actions.mdx`\n * (\"Tools Callability\"). **Default-allow opt-out**: undefined / `true` both\n * allow tool-iframe calls; only an explicit `false` returns 403. Set to\n * `false` for high-blast-radius admin operations (account deletion, org\n * membership changes, anything that modifies auth state) — used by the\n * framework's `share-resource`, `unshare-resource`, and\n * `set-resource-visibility` for defense-in-depth. Regular UI/agent/CLI/MCP/A2A\n * calls are unaffected. Enforced by the action HTTP route layer — see\n * `packages/core/src/server/action-routes.ts`. Audit reference: H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. Public web routes never imply\n * public MCP/A2A/OpenAPI tool exposure. Actions must opt in here and public\n * protocol mounts must still filter for safe, route-appropriate tools. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. When set, MCP/A2A surfaces append an\n * \"Open in <app> →\" link built from the call's args + result so the\n * external agent can drop the user into the running app at the right\n * view/record. Pure + sync + best-effort. See the `external-agents` skill. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource for hosts that can render inline\n * interactive app iframes. Text/deep-link tool results remain the fallback\n * for CLI and non-UI hosts. */\n mcpApp?: ActionMcpAppConfig;\n /** Optional native Agent-Native chat renderer for this action's structured\n * result. This is first-party React UI, not arbitrary HTML/JS. */\n chatUI?: ActionChatUIConfig;\n /**\n * Per-tool timeout override in milliseconds for agent-loop tool calls. Use\n * sparingly for actions that legitimately wait on slow provider work.\n */\n timeoutMs?: number;\n /** Per-tool result truncation override for agent-loop tool calls. */\n maxResultChars?: number;\n /**\n * Opt-in human-in-the-loop approval gate. **Default off** — the framework\n * intentionally keeps HITL approvals rare; almost every action should run\n * without one. Set this only for high-consequence, outward-facing,\n * hard-to-undo operations (the canonical example is actually sending an\n * email). When `needsApproval` resolves truthy and the agent calls this\n * action, the loop does NOT execute `run()`: it emits an `approval_required`\n * event and stops the turn, waiting for a human to approve. The action runs\n * only once the human re-issues the turn approving this specific call.\n *\n * - `true` — always require approval.\n * - `(args, ctx) => boolean | Promise<boolean>` — require approval only when\n * the predicate returns true (e.g. only for external recipients, only\n * above a dollar threshold). Keep it pure + fast; thrown errors are treated\n * as \"approval required\" (fail closed).\n */\n needsApproval?:\n | boolean\n | ((\n args: StandardSchemaV1.InferOutput<TSchema>,\n ctx?: ActionRunContext,\n ) => boolean | Promise<boolean>);\n /**\n * Audit-log configuration. **Default-on for mutating actions** — you only\n * need this to tune capture: declare the mutated `target` (so the change\n * shows up in the owner's audit trail) and/or a `summary`, opt a read-only\n * action in via `onRead`, or opt a noisy action out via `enabled: false`.\n * See the `audit-log` skill.\n */\n audit?: ActionAuditConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Legacy parameter-based action options\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithParams<\n TParams extends Record<string, ParameterSchema> | undefined =\n | Record<string, ParameterSchema>\n | undefined,\n TReturn = any,\n> {\n description: string;\n /** Flat map of parameter names to their schema. Automatically wrapped in\n * `{ type: \"object\", properties: ... }` for the Claude API. */\n parameters?: TParams;\n /** Standard Schema — not used in this overload. */\n schema?: never;\n /** Advertised-only schema override — not used in this overload (no runtime\n * schema to advertise a compact alternative for). See the schema overload\n * above. */\n agentInputSchema?: never;\n /** Optional Standard Schema-compatible schema the action's RETURN value is\n * validated against AFTER `run()` resolves. See the schema overload above.\n * When omitted, behavior is byte-for-byte unchanged. */\n outputSchema?: StandardSchemaV1;\n /** What to do when the result fails `outputSchema`. Default: `\"warn\"`. */\n outputErrorStrategy?: ActionOutputErrorStrategy;\n /** Value returned in place of an invalid result when `outputErrorStrategy` is\n * `\"fallback\"`. Ignored for the other strategies. */\n outputFallback?: TReturn;\n run: (\n args: InferParams<TParams>,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** Whether the HTTP/frontend action route must have an authenticated owner.\n * Defaults to true. See the schema overload above. */\n requiresAuth?: boolean;\n /** Max HTTP request body in bytes; 413s on `Content-Length` before parsing.\n * See the schema overload above. */\n maxBodyBytes?: number;\n /** Whether this action is exposed to the agent as a callable tool. Only an\n * explicit `false` hides it from every agent tool list while keeping it\n * frontend/HTTP-callable. See the schema overload above and actions.md. */\n agentTool?: boolean;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** Set false for read-only tools that should stay available in Act mode but\n * must not run during Plan mode. See the schema overload above. */\n allowInPlanMode?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn. */\n parallelSafe?: boolean;\n /** Set false to exempt a read-only tool from the duplicate read-only call\n * guard. Default true. See the schema overload above. */\n dedupe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)`. See the schema overload above for details\n * and the `toolCallable` section in actions.md. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. See schema overload above. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. See schema overload above. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource. See schema overload above. */\n mcpApp?: ActionMcpAppConfig;\n /** Optional native Agent-Native chat renderer. See schema overload above. */\n chatUI?: ActionChatUIConfig;\n /** Per-tool timeout override in milliseconds. See schema overload above. */\n timeoutMs?: number;\n /** Per-tool result truncation override. See schema overload above. */\n maxResultChars?: number;\n /** Opt-in human-in-the-loop approval gate (default off). See the schema\n * overload above for full semantics. */\n needsApproval?:\n | boolean\n | ((\n args: InferParams<TParams>,\n ctx?: ActionRunContext,\n ) => boolean | Promise<boolean>);\n /** Audit-log configuration (default-on for mutations). See the schema\n * overload above and the `audit-log` skill. */\n audit?: ActionAuditConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Return type — carries schema-inferred input + run return for client inference\n// ---------------------------------------------------------------------------\n\n/**\n * Opaque typed wrapper returned by `defineAction`. The type parameters carry\n * the schema-inferred input and the `run` return type so that:\n *\n * - The generated `.generated/action-types.d.ts` can extract them via\n * `typeof import(\"../actions/my-action\").default.run` and augment\n * `ActionRegistry` with concrete param/result types.\n * - `useActionQuery` / `useActionMutation` / `callAction` in the client hooks\n * flow the correct types end-to-end without manual generic annotations.\n *\n * Runtime shape is unchanged — this is a declaration-only wrapper.\n */\nexport interface ActionDefinition<TInput, TReturn> {\n /**\n * Typed run function — declaration only; infer input/return from this.\n * `TInput` is the schema's input type (optional defaults allowed at call\n * sites); `TReturn` is the awaited result type of the run callback.\n */\n readonly run: (\n args: TInput,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n /** @internal Framework use only — do not call directly. */\n readonly tool: import(\"./agent/types.js\").ActionTool;\n readonly http?: ActionHttpConfig | false;\n readonly requiresAuth?: boolean;\n readonly maxBodyBytes?: number;\n readonly agentTool?: boolean;\n readonly readOnly?: boolean;\n readonly allowInPlanMode?: boolean;\n readonly parallelSafe?: boolean;\n readonly dedupe?: boolean;\n readonly toolCallable?: boolean;\n readonly publicAgent?: PublicAgentActionConfig;\n readonly link?: ActionLinkBuilder;\n readonly mcpApp?: ActionMcpAppConfig;\n readonly chatUI?: ActionChatUIConfig;\n /** Per-tool timeout override in milliseconds for agent-loop tool calls. */\n readonly timeoutMs?: number;\n /** Per-tool result truncation override for agent-loop tool calls. */\n readonly maxResultChars?: number;\n /** Standard Schema the action's RETURN value is validated against after\n * `run()` resolves. Present only when the caller passed `outputSchema`. */\n readonly outputSchema?: StandardSchemaV1;\n /** Resolved output-mismatch strategy. Present only when `outputSchema` is\n * set; defaults to `\"warn\"`. */\n readonly outputErrorStrategy?: ActionOutputErrorStrategy;\n /** Value substituted for an invalid result under the `\"fallback\"` strategy. */\n readonly outputFallback?: TReturn;\n /** Opt-in human-in-the-loop approval gate (default off). When truthy, the\n * agent loop emits `approval_required` and pauses instead of executing this\n * action until a human approves the specific call. */\n readonly needsApproval?:\n | boolean\n | ((args: TInput, ctx?: ActionRunContext) => boolean | Promise<boolean>);\n /** Resolved audit-log configuration. Present only when the caller passed\n * `audit`. The audit capture wrapper is baked into `run`; this field is for\n * introspection. */\n readonly audit?: ActionAuditConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Define an agent action. Place in `actions/` directory — auto-discovered by the framework.\n *\n * Supports two modes:\n *\n * **Schema mode (recommended)** — pass a Standard Schema-compatible schema (Zod, Valibot,\n * ArkType) for runtime validation and full type inference:\n *\n * ```ts\n * import { defineAction } from \"@agent-native/core\";\n * import { z } from \"zod\";\n *\n * export default defineAction({\n * description: \"Create a form\",\n * schema: z.object({\n * title: z.string().describe(\"Form title\"),\n * status: z.enum([\"draft\", \"published\", \"closed\"]).default(\"draft\"),\n * }),\n * run: async (args) => {\n * // args is { title: string; status: \"draft\" | \"published\" | \"closed\" }\n * // Already validated — invalid inputs never reach here\n * },\n * });\n * ```\n *\n * **Parameters mode (legacy)** — pass raw JSON schema-like parameter definitions:\n *\n * ```ts\n * export default defineAction({\n * description: \"List events\",\n * parameters: {\n * from: { type: \"string\", description: \"Start date\" },\n * },\n * run: async (args) => { ... },\n * });\n * ```\n */\nexport function defineAction<\n TSchema extends StandardSchemaV1,\n TReturn,\n TOutputSchema extends StandardSchemaV1 | undefined = undefined,\n>(\n options: DefineActionWithSchema<TSchema, TReturn, TOutputSchema>,\n): ActionDefinition<StandardSchemaV1.InferInput<TSchema>, TReturn>;\nexport function defineAction<\n TParams extends Record<string, ParameterSchema> | undefined,\n TReturn,\n>(\n options: DefineActionWithParams<TParams, TReturn>,\n): ActionDefinition<InferParams<TParams>, TReturn>;\nexport function defineAction(options: any) {\n const hasSchema = options.schema && \"~standard\" in options.schema;\n\n // Build tool definition for the Claude API\n let toolParameters: ActionTool[\"parameters\"];\n if (hasSchema) {\n // Convert Standard Schema to JSON Schema for Claude\n toolParameters = schemaToJsonSchema(options.schema, options.description);\n } else if (options.parameters) {\n toolParameters = {\n type: \"object\" as const,\n properties: options.parameters,\n };\n }\n\n // `agentInputSchema` swaps in a compact JSON Schema for the ADVERTISED tool\n // definition only (what the model/MCP/A2A tool listings see). It never\n // touches validation below — `wrapWithValidation` is always called with\n // `options.schema`, the full schema, as the source of truth for what's\n // accepted. Passing the same (compact) `toolParameters` into it only\n // affects the top-level \"Expected: { ... }\" hint text and gateway string\n // coercion, both of which only look at top-level property names/types —\n // unaffected by trimming a nested union, so this stays safe either way.\n if (\n hasSchema &&\n options.agentInputSchema &&\n \"~standard\" in options.agentInputSchema\n ) {\n toolParameters = schemaToJsonSchema(\n options.agentInputSchema,\n options.description,\n );\n }\n\n // Wrap run() with INPUT validation when schema is provided.\n // Pass toolParameters so the validation error can echo the expected signature\n // (required vs optional fields) and help the caller self-correct.\n const inputValidatedRun = hasSchema\n ? wrapWithValidation(options.schema, options.run, toolParameters)\n : options.run;\n\n // Then wrap with OUTPUT validation when an outputSchema is provided. This\n // composes AROUND the input-validated run so the order is: validate input →\n // run() → validate output. When no outputSchema is present, the run is passed\n // through untouched and behavior is byte-for-byte unchanged.\n const hasOutputSchema =\n options.outputSchema && \"~standard\" in options.outputSchema;\n const outputErrorStrategy: ActionOutputErrorStrategy =\n options.outputErrorStrategy === \"strict\" ||\n options.outputErrorStrategy === \"warn\" ||\n options.outputErrorStrategy === \"fallback\"\n ? options.outputErrorStrategy\n : \"warn\";\n const run = hasOutputSchema\n ? wrapWithOutputValidation(\n options.outputSchema,\n inputValidatedRun,\n outputErrorStrategy,\n options.outputFallback,\n options.description,\n )\n : inputValidatedRun;\n\n // Auto-infer readOnly from http.method === \"GET\" unless explicitly set.\n // GET actions are idempotent reads; their completion should NOT trigger a\n // screen refresh. Everything else is assumed to mutate — the dispatcher\n // emits a change event on success so the UI auto-refetches its queries.\n const httpConfig = options.http as ActionHttpConfig | false | undefined;\n const inferredReadOnly =\n httpConfig !== false &&\n httpConfig !== undefined &&\n httpConfig.method === \"GET\";\n // Explicit `readOnly` (true OR false) wins. Otherwise infer from http.method.\n // We store the resolved boolean so downstream checks can trust entry.readOnly\n // without re-running method inference — including when a caller explicitly\n // passes readOnly:false to override a GET (rare but valid).\n const readOnly: boolean | undefined =\n typeof options.readOnly === \"boolean\"\n ? options.readOnly\n : inferredReadOnly\n ? true\n : undefined;\n\n // Audit: wrap the validated run so every mutating call records an audit\n // event (who/what/when/from-where, and for the agent which run). Default-on\n // for mutations; read-only actions opt in via `audit.onRead`. The wrapper\n // lazily imports the DB-touching recorder so `action.ts` keeps no static DB\n // dependency.\n const auditConfig = normalizeAuditConfig(options.audit);\n const finalRun = resolveAuditAttach(auditConfig, readOnly)\n ? wrapRunWithAudit(run, auditConfig)\n : run;\n\n // toolCallable: thread through whatever the caller declared. We DO NOT\n // default to `true` here — the absence of an explicit field is meaningful\n // to the tools bridge: it lets us emit a one-shot warning when an action\n // without a declared `toolCallable` flag is invoked from a tool, so the\n // ecosystem can migrate over time. The bridge treats `undefined` as\n // \"implicit allow with a deprecation warning\"; only an explicit `false`\n // refuses the call. See `extensions/routes.ts` and audit H5.\n const toolCallable: boolean | undefined =\n typeof options.toolCallable === \"boolean\"\n ? options.toolCallable\n : undefined;\n // agentTool: default-allow opt-out. Only an explicit `false` hides the action\n // from the agent tool surfaces; undefined is preserved (treated as exposed).\n const agentTool: boolean | undefined =\n typeof options.agentTool === \"boolean\" ? options.agentTool : undefined;\n const parallelSafe: boolean | undefined =\n typeof options.parallelSafe === \"boolean\"\n ? options.parallelSafe\n : undefined;\n const dedupe: boolean | undefined =\n typeof options.dedupe === \"boolean\" ? options.dedupe : undefined;\n const publicAgent: PublicAgentActionConfig | undefined =\n options.publicAgent &&\n typeof options.publicAgent === \"object\" &&\n !Array.isArray(options.publicAgent)\n ? options.publicAgent\n : undefined;\n const link: ActionLinkBuilder | undefined =\n typeof options.link === \"function\" ? options.link : undefined;\n const mcpApp: ActionMcpAppConfig | undefined = (() => {\n if (\n !options.mcpApp ||\n typeof options.mcpApp !== \"object\" ||\n Array.isArray(options.mcpApp)\n ) {\n return undefined;\n }\n // compactCatalog-only: no resource required; just keep the flag.\n if (options.mcpApp.compactCatalog === true && !options.mcpApp.resource) {\n return options.mcpApp as ActionMcpAppConfig;\n }\n // Full resource: validate html is present.\n if (\n options.mcpApp.resource &&\n typeof options.mcpApp.resource === \"object\" &&\n !Array.isArray(options.mcpApp.resource) &&\n (typeof options.mcpApp.resource.html === \"string\" ||\n typeof options.mcpApp.resource.html === \"function\")\n ) {\n return options.mcpApp as ActionMcpAppConfig;\n }\n return undefined;\n })();\n const chatUI = normalizeActionChatUIConfig(options.chatUI);\n\n return {\n tool: {\n description: options.description,\n parameters: toolParameters,\n },\n run: finalRun,\n ...(hasSchema ? { schema: options.schema } : {}),\n ...(options.http !== undefined ? { http: options.http } : {}),\n ...(typeof options.requiresAuth === \"boolean\"\n ? { requiresAuth: options.requiresAuth }\n : {}),\n ...(typeof options.maxBodyBytes === \"number\"\n ? { maxBodyBytes: options.maxBodyBytes }\n : {}),\n ...(typeof agentTool === \"boolean\" ? { agentTool } : {}),\n ...(typeof readOnly === \"boolean\" ? { readOnly } : {}),\n ...(typeof options.allowInPlanMode === \"boolean\"\n ? { allowInPlanMode: options.allowInPlanMode }\n : {}),\n ...(typeof parallelSafe === \"boolean\" ? { parallelSafe } : {}),\n ...(typeof dedupe === \"boolean\" ? { dedupe } : {}),\n ...(typeof toolCallable === \"boolean\" ? { toolCallable } : {}),\n ...(publicAgent ? { publicAgent } : {}),\n ...(link ? { link } : {}),\n ...(mcpApp ? { mcpApp } : {}),\n ...(chatUI ? { chatUI } : {}),\n ...(typeof options.timeoutMs === \"number\"\n ? { timeoutMs: options.timeoutMs }\n : {}),\n ...(typeof options.maxResultChars === \"number\"\n ? { maxResultChars: options.maxResultChars }\n : {}),\n ...(hasOutputSchema\n ? {\n outputSchema: options.outputSchema,\n outputErrorStrategy,\n ...(outputErrorStrategy === \"fallback\"\n ? { outputFallback: options.outputFallback }\n : {}),\n }\n : {}),\n ...(typeof options.needsApproval === \"boolean\" ||\n typeof options.needsApproval === \"function\"\n ? { needsApproval: options.needsApproval }\n : {}),\n ...(auditConfig ? { audit: auditConfig } : {}),\n };\n}\n\n/**\n * Wrap an action's (already input/output-validated) run so each call records an\n * audit event after it resolves — on success and on error. Best-effort: the\n * recorder swallows its own failures and the original result/throw is always\n * preserved, so auditing can never change an action's behavior. The DB-touching\n * recorder is imported lazily so merely defining an action pulls in no DB code.\n */\nfunction wrapRunWithAudit(\n run: (args: any, ctx?: ActionRunContext) => any,\n auditConfig: ActionAuditConfig | undefined,\n): (args: any, ctx?: ActionRunContext) => Promise<any> {\n return async function auditedRun(args: any, ctx?: ActionRunContext) {\n let result: any;\n let error: unknown;\n let threw = false;\n try {\n result = await run(args, ctx);\n } catch (err) {\n error = err;\n threw = true;\n }\n try {\n const { recordActionAudit } = await import(\"./audit/record.js\");\n await recordActionAudit(\n threw\n ? { config: auditConfig, args, ctx, status: \"error\", error }\n : { config: auditConfig, args, ctx, status: \"success\", result },\n );\n } catch {\n // Recorder failed to load/run — never affect the action.\n }\n if (threw) throw error;\n return result;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Schema → JSON Schema conversion\n// ---------------------------------------------------------------------------\n\n// Keywords whose value is a single subschema.\nconst SUBSCHEMA_VALUE_KEYS = [\n \"items\",\n \"additionalItems\",\n \"contains\",\n \"additionalProperties\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n] as const;\n// Keywords whose value is an array of subschemas.\nconst SUBSCHEMA_ARRAY_KEYS = [\n \"allOf\",\n \"anyOf\",\n \"oneOf\",\n \"prefixItems\",\n] as const;\n// Keywords whose value is a map of name → subschema.\nconst SUBSCHEMA_MAP_KEYS = [\n \"properties\",\n \"patternProperties\",\n \"$defs\",\n \"definitions\",\n \"dependentSchemas\",\n] as const;\n\n/**\n * Remove JSON Schema keywords that some providers' function-calling schema\n * validators reject. OpenAI (and Gemini via the Builder gateway) reject\n * `propertyNames` — which Zod v4 emits for `z.record(z.string(), …)` — with a\n * `400 invalid_function_parameters` error, causing the model turn to produce no\n * content (surfacing as an empty assistant response). Anthropic ignores the\n * keyword, so stripping it is safe across providers and keeps action schemas\n * portable. `propertyNames` only constrained object *keys*; the value/shape of\n * the object is unaffected by its removal.\n *\n * Only descends through actual subschema positions (properties, items, union\n * branches, definitions, etc.) — never through value-bearing keywords like\n * `default`, `const`, `enum`, or `examples`, whose objects may legitimately\n * contain a `propertyNames` data key that must be preserved.\n */\nfunction stripUnsupportedSchemaKeywords<T>(node: T): T {\n if (!node || typeof node !== \"object\" || Array.isArray(node)) return node;\n const obj = node as Record<string, unknown>;\n\n delete obj.propertyNames;\n\n for (const key of SUBSCHEMA_VALUE_KEYS) {\n // `items`/`additionalItems` may also be an array of subschemas.\n const value = obj[key];\n if (Array.isArray(value)) {\n for (const sub of value) stripUnsupportedSchemaKeywords(sub);\n } else {\n stripUnsupportedSchemaKeywords(value);\n }\n }\n for (const key of SUBSCHEMA_ARRAY_KEYS) {\n const value = obj[key];\n if (Array.isArray(value)) {\n for (const sub of value) stripUnsupportedSchemaKeywords(sub);\n }\n }\n for (const key of SUBSCHEMA_MAP_KEYS) {\n const value = obj[key];\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n for (const sub of Object.values(value)) {\n stripUnsupportedSchemaKeywords(sub);\n }\n }\n }\n return node;\n}\n\n/**\n * Convert a Standard Schema to JSON Schema for the Claude API.\n * Tries vendor-specific toJSONSchema first (Zod v4), then falls back\n * to a basic introspection of the schema shape.\n */\nfunction schemaToJsonSchema(\n schema: StandardSchemaV1,\n _description?: string,\n): ActionTool[\"parameters\"] {\n const s = schema as any;\n\n // Prefer Zod's own JSON Schema output — it handles descriptions,\n // enums, coerce, and all type wrappers correctly.\n if (s[\"~standard\"]?.jsonSchema?.input) {\n try {\n const result = s[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as any;\n // Strip $schema — the Claude API validates against draft 2020-12\n // and a mismatched $schema declaration can cause rejections.\n if (result && typeof result === \"object\") {\n delete result.$schema;\n }\n return stripUnsupportedSchemaKeywords(result) as ActionTool[\"parameters\"];\n } catch {\n // Fall through to manual converter\n }\n }\n\n // Fallback: manual conversion from Zod v4 internal defs\n if (s._zod?.def) {\n return stripUnsupportedSchemaKeywords(zodDefToJsonSchema(s._zod.def));\n }\n\n // Last resort: empty object schema\n return { type: \"object\" as const, properties: {} };\n}\n\n/**\n * Convert a Zod v4 internal def to JSON Schema.\n * Handles the common types used in action parameters.\n */\nfunction zodDefToJsonSchema(def: any): any {\n const type = def.type;\n\n if (type === \"object\") {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n const shape = def.shape;\n if (shape) {\n for (const [key, fieldSchema] of Object.entries(shape) as any[]) {\n const fieldDef = fieldSchema?._zod?.def;\n if (fieldDef) {\n const prop = zodDefToJsonSchema(fieldDef);\n // Zod v4 stores .describe() on the schema object, not in the def\n const desc = fieldSchema?.description;\n if (desc && !prop.description) prop.description = desc;\n properties[key] = prop;\n if (\n fieldDef.type !== \"optional\" &&\n fieldDef.type !== \"default\" &&\n fieldDef.type !== \"nullable\"\n ) {\n required.push(key);\n }\n }\n }\n }\n const result: any = { type: \"object\", properties };\n if (required.length > 0) result.required = required;\n return result;\n }\n\n if (type === \"string\") {\n const result: any = { type: \"string\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"number\" || type === \"float\" || type === \"int\") {\n const result: any = { type: type === \"int\" ? \"integer\" : \"number\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"boolean\") {\n const result: any = { type: \"boolean\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"enum\") {\n // Zod v4 stores enum entries as an object {a: \"a\", b: \"b\"};\n // JSON Schema requires an array.\n const entries = def.entries;\n const enumValues = Array.isArray(entries)\n ? entries\n : typeof entries === \"object\" && entries !== null\n ? Object.values(entries)\n : entries;\n const result: any = { type: \"string\", enum: enumValues };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"literal\") {\n return { type: typeof def.value, enum: [def.value] };\n }\n\n if (type === \"array\") {\n const result: any = { type: \"array\" };\n if (def.element?._zod?.def) {\n result.items = zodDefToJsonSchema(def.element._zod.def);\n }\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"optional\") {\n if (def.innerType?._zod?.def) {\n return zodDefToJsonSchema(def.innerType._zod.def);\n }\n }\n\n if (type === \"default\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n inner.default =\n typeof def.defaultValue === \"function\"\n ? def.defaultValue()\n : def.defaultValue;\n return inner;\n }\n }\n\n if (type === \"nullable\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n // Surface null as a valid value so the model knows it may pass null\n // (and doesn't treat the field as a non-nullable required string).\n return { anyOf: [inner, { type: \"null\" }] };\n }\n }\n\n if (type === \"union\") {\n if (def.options?.length) {\n // Check if it's a simple enum-like union of literals\n const allLiterals = def.options.every(\n (o: any) => o?._zod?.def?.type === \"literal\",\n );\n if (allLiterals) {\n const values = def.options.map((o: any) => o._zod.def.value);\n const jsonTypeOf = (v: any) =>\n typeof v === \"number\"\n ? \"number\"\n : typeof v === \"boolean\"\n ? \"boolean\"\n : \"string\";\n const uniqueTypes = [...new Set(values.map(jsonTypeOf))];\n if (uniqueTypes.length === 1) {\n // Homogeneous literal union (e.g. all numbers) — derive the JSON\n // type instead of hardcoding \"string\", which would contradict the\n // enum values and make the model coerce/round-trip them wrongly.\n return { type: uniqueTypes[0], enum: values };\n }\n // Mixed literal types: emit anyOf so each branch stays self-consistent.\n return {\n anyOf: values.map((v: any) => ({ type: jsonTypeOf(v), enum: [v] })),\n };\n }\n return {\n anyOf: def.options.map((o: any) =>\n zodDefToJsonSchema(o._zod?.def ?? {}),\n ),\n };\n }\n }\n\n // z.preprocess / z.pipe / .superRefine / .transform all produce a \"pipe\"\n // def with `in` (pre-transform) and `out` (post-transform). For JSON Schema\n // purposes, use `out` — it reflects the validated output shape the model\n // should populate.\n if (type === \"pipe\") {\n if (def.out?._zod?.def) {\n return zodDefToJsonSchema(def.out._zod.def);\n }\n if (def.in?._zod?.def) {\n return zodDefToJsonSchema(def.in._zod.def);\n }\n }\n\n // Fallback\n return { type: \"string\" };\n}\n\n// ---------------------------------------------------------------------------\n// Runtime validation wrapper\n// ---------------------------------------------------------------------------\n\nconst NO_COERCE = Symbol(\"no-coerce\");\n\n/**\n * Coerce a single stringified value to one of the JSON-schema types the field\n * expects. Returns NO_COERCE when nothing safe applies, so the caller leaves\n * the original value untouched and the normal validation error still surfaces.\n */\nfunction coerceStringToSchemaType(raw: string, types: string[]): unknown {\n const trimmed = raw.trim();\n if (types.includes(\"boolean\")) {\n if (trimmed === \"true\") return true;\n if (trimmed === \"false\") return false;\n }\n if (\n (types.includes(\"array\") &&\n trimmed.startsWith(\"[\") &&\n trimmed.endsWith(\"]\")) ||\n (types.includes(\"object\") &&\n trimmed.startsWith(\"{\") &&\n trimmed.endsWith(\"}\"))\n ) {\n try {\n const parsed = JSON.parse(trimmed);\n if (types.includes(\"array\") && Array.isArray(parsed)) return parsed;\n if (\n types.includes(\"object\") &&\n parsed &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ) {\n return parsed;\n }\n } catch {\n // fall through — leave the original so validation reports the real error\n }\n }\n if (\n (types.includes(\"number\") || types.includes(\"integer\")) &&\n trimmed !== \"\" &&\n Number.isFinite(Number(trimmed))\n ) {\n const n = Number(trimmed);\n if (types.includes(\"number\") || Number.isInteger(n)) return n;\n }\n return NO_COERCE;\n}\n\n/**\n * Defensively coerce stringified action arguments to the types the schema\n * expects. Two callers depend on this:\n *\n * 1. Model gateways (notably Builder's Gemini-backed gateway) hand back\n * structured tool-call arguments as JSON strings — an array param arrives\n * as `\"[{...}]\"`, a boolean as `\"true\"`.\n * 2. GET actions called from the browser via `useActionQuery` / `callAction`.\n * Those serialize params into the query string, where `URLSearchParams`\n * stringifies everything — so `includeSeries: true` arrives as the string\n * `\"true\"` and `limit: 5` as `\"5\"` (see `action-routes.ts`).\n *\n * In both cases Standard Schema (zod) `validate` does not coerce, so the call\n * fails validation (\"expected boolean, received string\") — the agent thrashes\n * retrying shapes and the frontend query errors. We only touch a string value\n * when the schema expects a non-string type and the string parses cleanly to\n * it; anything ambiguous (schema also allows string) or unparseable is left\n * as-is. Operates on top-level properties only — once an array/object param is\n * parsed, its nested members are already native and validate normally.\n *\n * Do NOT narrow this to \"gateway-only\": the GET query-string path relies on it\n * too, and `action-routes.spec.ts` guards that round-trip.\n */\nfunction coerceGatewayStringifiedArgs(\n args: unknown,\n parameters?: ActionTool[\"parameters\"],\n): unknown {\n const properties = parameters?.properties as\n | Record<string, { type?: string | string[] }>\n | undefined;\n if (!properties) return args;\n if (!args || typeof args !== \"object\" || Array.isArray(args)) return args;\n let out: Record<string, unknown> | null = null;\n for (const [key, raw] of Object.entries(args as Record<string, unknown>)) {\n if (typeof raw !== \"string\") continue;\n const spec = properties[key];\n if (!spec) continue;\n const types = Array.isArray(spec.type)\n ? spec.type\n : spec.type\n ? [spec.type]\n : [];\n // No declared type, or the field legitimately accepts a string → leave it.\n if (types.length === 0 || types.includes(\"string\")) continue;\n const coerced = coerceStringToSchemaType(raw, types);\n if (coerced === NO_COERCE) continue;\n if (!out) out = { ...(args as Record<string, unknown>) };\n out[key] = coerced;\n }\n return out ?? args;\n}\n\n/**\n * Wrap an action's run function with schema validation.\n * Invalid inputs get a clear error message (including what was actually passed)\n * so the agent can see its own mistake and correct it on the next turn.\n */\nfunction wrapWithValidation(\n schema: StandardSchemaV1,\n run: Function,\n toolParameters?: ActionTool[\"parameters\"],\n): (args: any, ctx?: ActionRunContext) => any {\n return async (args: any, ctx?: ActionRunContext) => {\n args = coerceGatewayStringifiedArgs(args, toolParameters);\n const result = await schema[\"~standard\"].validate(args);\n if (result.issues) {\n // Split issues into \"missing required field\" vs other validation errors\n // so the error message reads naturally rather than as \"fieldName: Required\".\n const missing: string[] = [];\n const other: string[] = [];\n for (const issue of result.issues) {\n const pathStr = issue.path\n ? issue.path.map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\")\n : \"\";\n const msg = String(issue.message ?? \"\");\n // Zod emits \"Required\" for missing fields; other libraries may use\n // similar wording. Treat any variant as \"missing\".\n if (\n pathStr &&\n (msg === \"Required\" ||\n /invalid.*undefined/i.test(msg) ||\n /expected.*received undefined/i.test(msg))\n ) {\n missing.push(pathStr);\n } else {\n other.push(pathStr ? `${pathStr}: ${msg}` : msg);\n }\n }\n\n const parts: string[] = [];\n if (missing.length > 0) {\n parts.push(\n `Missing required parameter${missing.length === 1 ? \"\" : \"s\"}: ${missing.join(\", \")}`,\n );\n }\n if (other.length > 0) {\n parts.push(other.join(\"; \"));\n }\n\n // Echo the args that were actually passed so the caller (usually an\n // agent) can see exactly what it sent and fix its next call.\n let received: string;\n try {\n received = JSON.stringify(args);\n if (received.length > 500) received = received.slice(0, 500) + \"…\";\n } catch {\n received = String(args);\n }\n\n // Also show the EXPECTED signature so the agent doesn't have to guess.\n // Format: `{ deckId*: string, content*: string, slideId?: string, ... }`\n // where `*` = required, `?` = optional.\n let expected = \"\";\n if (toolParameters?.properties) {\n const required = new Set(toolParameters.required ?? []);\n const sig = Object.entries(toolParameters.properties)\n .map(([k, v]) => {\n const mark = required.has(k) ? \"*\" : \"?\";\n const type = (v as { type?: string }).type ?? \"any\";\n return `${k}${mark}: ${type}`;\n })\n .join(\", \");\n if (sig)\n expected = ` Expected: { ${sig} } (where * = required, ? = optional).`;\n }\n\n throw new Error(\n `Invalid action parameters — ${parts.join(\". \")}. Received: ${received}.${expected}`,\n );\n }\n return run((result as StandardSchemaV1.SuccessResult<any>).value, ctx);\n };\n}\n\n/**\n * Wrap an action's run function with RETURN-value validation. Runs AFTER the\n * (already input-validated) `run` resolves and validates the result against\n * `outputSchema` using the Standard Schema `~standard.validate` contract.\n *\n * Behavior is governed by `strategy`:\n * - `\"strict\"` — throw a clear error when the result doesn't match.\n * - `\"warn\"` — `console.warn` the issues and return the ORIGINAL result\n * unchanged (default; never alters runtime behavior).\n * - `\"fallback\"`— return `fallback` in place of the invalid result.\n *\n * On success the validated value is returned (so schema-applied coercion /\n * defaults take effect, mirroring the input path).\n */\nfunction wrapWithOutputValidation(\n outputSchema: StandardSchemaV1,\n run: (args: any, ctx?: ActionRunContext) => any,\n strategy: ActionOutputErrorStrategy,\n fallback: unknown,\n description?: string,\n): (args: any, ctx?: ActionRunContext) => any {\n return async (args: any, ctx?: ActionRunContext) => {\n const output = await run(args, ctx);\n const result = await outputSchema[\"~standard\"].validate(output);\n\n if (!result.issues) {\n // Return the validated value so coercion / defaults defined on the\n // outputSchema are applied, consistent with the input path.\n return (result as StandardSchemaV1.SuccessResult<any>).value;\n }\n\n const issues = result.issues\n .map((issue) => {\n const pathStr = issue.path\n ? issue.path.map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\")\n : \"\";\n const msg = String(issue.message ?? \"\");\n return pathStr ? `${pathStr}: ${msg}` : msg;\n })\n .join(\"; \");\n const label = description ? ` (${description})` : \"\";\n const summary = `Action output did not match outputSchema${label}: ${issues}`;\n\n if (strategy === \"strict\") {\n throw new Error(summary);\n }\n if (strategy === \"fallback\") {\n return fallback;\n }\n // \"warn\" (default): surface the mismatch but never change behavior.\n console.warn(summary);\n return output;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,2BAA2B,GAE5B,MAAM,gBAAgB,CAAC;AAMxB,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAsI7E;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACpC,eAAe,GAAG,IAAI,CAAC;IACvB,SAAS,CAAU;IACnB,UAAU,CAAU;IAE7B,YAAY,OAAe,EAAE,OAAO,GAA2B,EAAE;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,IAAI,CAAC,SAAS,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M,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport {\n normalizeActionChatUIConfig,\n type ActionChatUIConfig,\n} from \"./action-ui.js\";\nimport type {\n ActionTool,\n AgentChatAttachment,\n AgentChatEvent,\n} from \"./agent/types.js\";\nimport { normalizeAuditConfig, resolveAuditAttach } from \"./audit/config.js\";\nimport type { ActionAuditConfig } from \"./audit/types.js\";\n\n/**\n * How an action's `run` was invoked. Tagged at each dispatch site so the action\n * (and tracking) can branch on the surface that called it.\n *\n * - `\"tool\"` — the in-app agent loop, sub-agents/agent-teams, or A2A (which\n * drives the same agent loop). All agent tool calls are `\"tool\"`.\n * - `\"http\"` — a programmatic HTTP POST/GET to `/_agent-native/actions/<name>`\n * without the frontend request marker.\n * - `\"frontend\"` — a browser call via `useActionQuery` / `useActionMutation` /\n * `callAction` (tagged with the `X-Request-Source` header).\n * - `\"cli\"` — `pnpm action <name>` (the CLI runner).\n * - `\"mcp\"` — an external agent over the MCP `tools/call` endpoint.\n * - `\"a2a\"` — a direct, explicitly exposed read-only A2A action dispatch.\n * Natural-language A2A delegation still runs through the agent loop and its\n * selected actions are attributed as `\"tool\"`.\n * - `\"automation\"` — an event-triggered automation dispatched from a stored\n * workspace trigger with trusted trigger lineage.\n */\nexport type ActionCaller =\n | \"tool\"\n | \"http\"\n | \"frontend\"\n | \"cli\"\n | \"mcp\"\n | \"a2a\"\n | \"automation\";\n\n/**\n * Trusted automation lineage added by the trigger dispatcher. Action inputs\n * must never be used to create or override this context.\n */\nexport interface ActionAutomationContext {\n triggerId: string;\n triggerName: string;\n policyId?: string;\n}\n\n/**\n * Context passed as the optional second argument to an action's `run`.\n * Carries the resolved request identity and the invocation source so actions\n * can read `ctx.userEmail` / `ctx.orgId` / `ctx.caller` directly instead of\n * calling `getRequestUserEmail()` / `getRequestOrgId()` by hand.\n *\n * Backward compatible: existing 1-arg `run(args)` functions keep working, and\n * callers that only need `send` (the agent loop) can still destructure it.\n */\nexport interface ActionRunContext {\n /**\n * Emit an SSE event to the client. Only meaningful inside the agent tool\n * loop (e.g. `agent_call_text` streaming); `undefined` on every other\n * surface.\n */\n send?: (event: AgentChatEvent) => void;\n /**\n * Resolved request user email, or `undefined` when there is no authenticated\n * identity. NEVER defaulted to a dev identity — actions that need a fallback\n * must apply their own.\n */\n userEmail?: string;\n /** Resolved org id, or `null` when the request has no org. */\n orgId?: string | null;\n /** How this action was invoked. */\n caller: ActionCaller;\n /** Present only for trigger-dispatched automation calls. */\n automation?: ActionAutomationContext;\n /** Verified network lineage for direct delegated action calls. */\n networkProtocol?: \"a2a\" | \"mcp\" | \"provider-api\";\n networkId?: string;\n networkPeer?: string;\n /**\n * Attachments submitted with the current agent turn (pasted text blocks,\n * uploaded files, images), exactly as the server received them — with full,\n * untruncated `text` for text attachments. Populated only inside the agent\n * tool loop (`caller: \"tool\"`); `undefined` on every other surface.\n *\n * Lets an action consume a large pasted artifact BY REFERENCE (e.g.\n * `create-extension`'s `contentFromAttachment`) instead of forcing the model\n * to re-emit the whole file as a tool argument — which frequently gets cut\n * off mid-stream and triggers a continuation loop.\n */\n attachments?: AgentChatAttachment[];\n /**\n * Abort signal for the current agent run. Fires when the run is soft-timed\n * out, user-cancelled, or the server is shutting down. Well-behaved actions\n * can observe this signal to cancel in-flight work early instead of waiting\n * for the per-tool 60-second hard timeout.\n *\n * Populated only inside the agent tool loop (`caller: \"tool\"`); `undefined`\n * on every other surface. Never throws — checking `signal.aborted` or\n * attaching an `\"abort\"` listener is always safe.\n */\n signal?: AbortSignal;\n /**\n * Name of the action being invoked (the registry key, e.g.\n * `delete-recording`). Set at each dispatch site so cross-cutting concerns —\n * notably the audit log — can attribute the call. `undefined` for direct\n * programmatic `run()` calls that bypass the dispatcher.\n */\n actionName?: string;\n /**\n * Agent conversation thread + turn that triggered this call, populated only\n * inside the agent tool loop (`caller: \"tool\"`). Lets the audit log link a\n * mutation to the specific agent run/turn that caused it. `undefined` on\n * every human/programmatic surface.\n */\n threadId?: string;\n /** Concrete execution id for this agent-loop attempt. */\n runId?: string;\n turnId?: string;\n}\n\n/**\n * Pre-run authorization gate. Throw to deny with a specific message (the\n * framework's `ForbiddenError` carries a 403), or return `false` for a generic\n * denial. Returning `undefined` allows the call — a guard that forgets to\n * return is therefore permissive, which is why `false` is honoured at all:\n * `(args) => someCheck(args)` written against a boolean helper would otherwise\n * pass silently on every denial.\n */\nexport type ActionAuthorize<TArgs> = (\n args: TArgs,\n ctx?: ActionRunContext,\n) => void | boolean | Promise<void | boolean>;\n\nexport interface AgentActionStopOptions {\n /** Optional stable code surfaced in run metadata and tests. */\n errorCode?: string;\n /** Optional short tool-result text. Defaults to the user-facing message. */\n toolResult?: string;\n}\n\n/**\n * Throw from an action when the agent should stop the current turn instead of\n * feeding the failure back to the model for another retry.\n */\nexport class AgentActionStopError extends Error {\n readonly agentNativeStop = true;\n readonly errorCode?: string;\n readonly toolResult?: string;\n\n constructor(message: string, options: AgentActionStopOptions = {}) {\n super(message);\n this.name = \"AgentActionStopError\";\n this.errorCode = options.errorCode;\n this.toolResult = options.toolResult;\n }\n}\n\nexport function isAgentActionStopError(\n err: unknown,\n): err is AgentActionStopError {\n return (\n err instanceof AgentActionStopError ||\n Boolean(\n err &&\n typeof err === \"object\" &&\n \"agentNativeStop\" in err &&\n (err as { agentNativeStop?: unknown }).agentNativeStop === true,\n )\n );\n}\n\n/** HTTP exposure config for an action. */\nexport interface ActionHttpConfig {\n /** HTTP method. Default: \"POST\". Use \"GET\" for read-only actions. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n /** Override route path under /_agent-native/actions/. Default: action filename. */\n path?: string;\n}\n\n/** Explicit opt-in metadata for public agent protocols such as MCP or A2A. */\nexport interface PublicAgentActionConfig {\n expose: boolean;\n readOnly: boolean;\n requiresAuth?: boolean;\n isConsequential?: boolean;\n title?: string;\n description?: string;\n}\n\n/** A deep link an external agent (MCP / A2A) can surface to the user so they\n * can open the produced/listed resource in the running app UI. */\nexport interface ActionDeepLink {\n /** App-relative path (e.g. `/_agent-native/open?app=mail&view=inbox&...`)\n * or an absolute URL. The MCP layer prefixes the request origin when this\n * is relative, and may rewrite it to the `agentnative://` desktop scheme. */\n url: string;\n /** Human-readable label, e.g. \"Open draft in Mail\". */\n label: string;\n /** Optional view hint (matches the `navigate` command `view`). */\n view?: string;\n}\n\n/** Builds a deep link from an action's args + result so external agents can\n * surface an \"Open in <app> →\" link. MUST be pure and synchronous — no I/O,\n * no awaits. Best-effort: a throw or null is swallowed and never fails the\n * tool call. See the `external-agents` skill. */\nexport type ActionLinkBuilder = (ctx: {\n args: Record<string, any>;\n result: any;\n}) => ActionDeepLink | null | undefined;\n\nexport const MCP_APP_EXTENSION_ID = \"io.modelcontextprotocol/ui\" as const;\nexport const MCP_APP_MIME_TYPE = \"text/html;profile=mcp-app\" as const;\nexport const MCP_APP_RESOURCE_URI_META_KEY = \"ui/resourceUri\" as const;\n\nexport interface ActionMcpAppCsp {\n connectDomains?: string[];\n resourceDomains?: string[];\n frameDomains?: string[];\n baseUriDomains?: string[];\n}\n\nexport type ActionMcpAppCspBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => ActionMcpAppCsp | Promise<ActionMcpAppCsp>;\n\nexport interface ActionMcpAppPermissions {\n camera?: Record<string, never>;\n microphone?: Record<string, never>;\n geolocation?: Record<string, never>;\n clipboardWrite?: Record<string, never>;\n}\n\nexport interface ActionMcpAppResourceMeta {\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n /**\n * Host-specific sandbox domain hint. Do not set this to the app's normal\n * production URL; app origins belong in CSP/open-link metadata. ChatGPT uses\n * the separate `openai/widgetDomain` compatibility field.\n */\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport type ActionMcpAppHtmlBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => string;\n\nexport interface ActionMcpAppResourceConfig {\n /** `ui://` URI. Defaults to `ui://<app>/<action-name>`. */\n uri?: string;\n /** MCP resource name. Defaults to the action name. */\n name?: string;\n title?: string;\n description?: string;\n /**\n * HTML5 document content for the MCP App resource. Keep this self-contained\n * or declare any external origins in `csp`.\n */\n html: string | ActionMcpAppHtmlBuilder;\n /** Defaults to the MCP Apps HTML MIME type. */\n mimeType?: typeof MCP_APP_MIME_TYPE;\n /** Extra resource/content metadata. `ui` is merged with the fields below. */\n _meta?: Record<string, unknown>;\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n /**\n * Host-specific sandbox domain hint. Do not set this to the app's normal\n * production URL; app origins belong in CSP/open-link metadata. ChatGPT uses\n * the separate `openai/widgetDomain` compatibility field.\n */\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport interface ActionMcpAppConfig {\n /**\n * Optional MCP Apps UI resource for hosts that render inline app iframes.\n * Required when the action should open an interactive app view. Omit when\n * you only need `compactCatalog: true` to keep a non-UI action visible in\n * the compact catalog (e.g. read/update actions that should be callable from\n * Claude.ai / ChatGPT without a dedicated iframe resource).\n */\n resource?: ActionMcpAppResourceConfig;\n /**\n * MCP Apps tool visibility. Defaults to model + app so the LLM can call the\n * action and the app iframe can call it back through the host bridge.\n */\n visibility?: Array<\"model\" | \"app\">;\n /**\n * Rare escape hatch for MCP Apps chat hosts. By default OAuth callers with\n * `mcp:apps` see the generic app tools (`open_app`, `list_apps`, etc.) so\n * hosts do not ingest every action-specific UI resource. Set this only when\n * this specific action must stay visible in that compact catalog.\n */\n compactCatalog?: boolean;\n}\n\n/** Schema definition for a single action parameter (legacy JSON schema style). */\nexport interface ParameterSchema {\n type: string;\n description?: string;\n enum?: string[];\n}\n\n/** Infer runtime parameter types from a legacy parameter schema map. */\ntype InferParams<T extends Record<string, ParameterSchema> | undefined> =\n T extends Record<string, ParameterSchema>\n ? { [K in keyof T]?: string }\n : Record<string, string>;\n\n/**\n * What to do when an action's RETURN value fails `outputSchema` validation.\n *\n * - `\"strict\"` — throw a clear error so a buggy action surfaces loudly.\n * - `\"warn\"` (default) — `console.warn` the issues and return the ORIGINAL\n * result unchanged. Non-breaking: behavior never changes unless the dev\n * opts into `\"strict\"` or `\"fallback\"`.\n * - `\"fallback\"` — return `outputFallback` in place of the invalid result.\n *\n * Mirrors Mastra/Flue structured-output handling, kept on the action layer.\n */\nexport type ActionOutputErrorStrategy = \"strict\" | \"warn\" | \"fallback\";\n\n// ---------------------------------------------------------------------------\n// Schema-based action options (new: Zod / Valibot / ArkType via Standard Schema)\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithSchema<\n TSchema extends StandardSchemaV1,\n TReturn = any,\n TOutputSchema extends StandardSchemaV1 | undefined = undefined,\n> {\n description: string;\n /** Standard Schema-compatible schema (Zod, Valibot, ArkType). Provides runtime\n * validation and full TypeScript type inference for `run()` args. The schema is\n * also converted to JSON Schema for the Claude API tool definition. */\n schema: TSchema;\n /** Legacy parameters — ignored when `schema` is provided. */\n parameters?: never;\n /**\n * Optional alternate Standard Schema (Zod, Valibot, ArkType) used ONLY to\n * build the tool definition advertised to the model — the JSON Schema that\n * lands in the Claude `tools` array (and MCP/A2A tool listings, which read\n * the same `tool.parameters`). Runtime validation always runs against\n * `schema` above via the normal `wrapWithValidation` path; setting this\n * never weakens validation and never changes `run()`'s argument type.\n *\n * Use this when the full input schema is much richer than what the model\n * needs to see up front — the canonical example is a deep discriminated\n * union of block/shape types where a per-call catalog lookup tool (e.g.\n * `get-plan-blocks`) already teaches the full field shapes. Advertise a\n * compact version (e.g. an enum of valid `type` values plus a note to call\n * the lookup tool) instead of embedding every variant's fields in every\n * request. Invalid calls still get the full, actionable validation error\n * (missing/invalid fields, received args) from `schema` — this only trims\n * what is proactively shown, not what is accepted or checked.\n */\n agentInputSchema?: StandardSchemaV1;\n /** Optional Standard Schema-compatible schema (Zod, Valibot, ArkType) the\n * action's RETURN value is validated against AFTER `run()` resolves. Borrowed\n * from Mastra/Flue structured-output. When omitted, behavior is byte-for-byte\n * unchanged. The mismatch handling is governed by `outputErrorStrategy`. */\n outputSchema?: TOutputSchema;\n /** What to do when the result fails `outputSchema`. Default: `\"warn\"`. */\n outputErrorStrategy?: ActionOutputErrorStrategy;\n /** Value returned in place of an invalid result when `outputErrorStrategy` is\n * `\"fallback\"`. Ignored for the other strategies. */\n outputFallback?: TReturn;\n run: (\n args: StandardSchemaV1.InferOutput<TSchema>,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** Whether the HTTP/frontend action route must have an authenticated owner.\n * Defaults to true. Set to false only for metadata/read actions that safely\n * handle `ctx.userEmail` / `getRequestUserEmail()` being undefined. */\n requiresAuth?: boolean;\n /** Max HTTP request body in bytes. When set, the route 413s on the declared\n * `Content-Length` before parsing. Use for public, no-auth POST actions;\n * unset = no route-level cap. */\n maxBodyBytes?: number;\n /** Whether this action is exposed to the agent — the in-app assistant and the\n * app's MCP/A2A tool surfaces — as a callable tool. **Default-allow opt-out**:\n * `undefined` / `true` expose it; only an explicit `false` hides it from every\n * agent tool list while keeping it callable from the frontend / HTTP\n * (`useActionMutation`, `callAction`, `/_agent-native/actions/<name>`). Use\n * this for UI-only or purely programmatic actions you want behind the\n * framework's auth + action surface WITHOUT spending a slot in the model's\n * tool list. Distinct from `toolCallable`, which only governs the sandboxed\n * extension (\"tools\") iframe bridge. See `packages/core/docs/content/actions.mdx`. */\n agentTool?: boolean;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`.\n * Only set this manually when you need to override the inference — e.g. a\n * POST action that only reads data but can't use GET for a protocol reason. */\n readOnly?: boolean;\n /** Set false for read-only tools that should stay available in Act mode but\n * must not run during Plan mode because they perform substantive work\n * rather than lightweight inspection. Defaults to allowed when read-only. */\n allowInPlanMode?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn.\n * Only set this for mutating actions that are internally concurrency-safe\n * and order-independent for same-turn execution. */\n parallelSafe?: boolean;\n /** Set false to exempt a read-only tool from the agent loop's duplicate\n * read-only call guard (per-turn result cache + \"Skipped duplicate...\"\n * repeat detection). Default true (deduped). Use this for volatile/polling\n * reads where an identical call is expected to return a different result\n * each time — e.g. polling a code-execution status by id, or re-fetching\n * current on-screen state. Has no effect on non-read-only actions, which\n * are never deduped in the first place. */\n dedupe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)` — see `packages/core/docs/content/actions.mdx`\n * (\"Tools Callability\"). **Default-allow opt-out**: undefined / `true` both\n * allow tool-iframe calls; only an explicit `false` returns 403. Set to\n * `false` for high-blast-radius admin operations (account deletion, org\n * membership changes, anything that modifies auth state) — used by the\n * framework's `share-resource`, `unshare-resource`, and\n * `set-resource-visibility` for defense-in-depth. Regular UI/agent/CLI/MCP/A2A\n * calls are unaffected. Enforced by the action HTTP route layer — see\n * `packages/core/src/server/action-routes.ts`. Audit reference: H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. Public web routes never imply\n * public MCP/A2A/OpenAPI tool exposure. Actions must opt in here and public\n * protocol mounts must still filter for safe, route-appropriate tools. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. When set, MCP/A2A surfaces append an\n * \"Open in <app> →\" link built from the call's args + result so the\n * external agent can drop the user into the running app at the right\n * view/record. Pure + sync + best-effort. See the `external-agents` skill. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource for hosts that can render inline\n * interactive app iframes. Text/deep-link tool results remain the fallback\n * for CLI and non-UI hosts. */\n mcpApp?: ActionMcpAppConfig;\n /** Optional native Agent-Native chat renderer for this action's structured\n * result. This is first-party React UI, not arbitrary HTML/JS. */\n chatUI?: ActionChatUIConfig;\n /**\n * Per-tool timeout override in milliseconds for agent-loop tool calls. Use\n * sparingly for actions that legitimately wait on slow provider work.\n */\n timeoutMs?: number;\n /** Per-tool result truncation override for agent-loop tool calls. */\n maxResultChars?: number;\n /**\n * Opt-in human-in-the-loop approval gate. **Default off** — the framework\n * intentionally keeps HITL approvals rare; almost every action should run\n * without one. Set this only for high-consequence, outward-facing,\n * hard-to-undo operations (the canonical example is actually sending an\n * email). When `needsApproval` resolves truthy and the agent calls this\n * action, the loop does NOT execute `run()`: it emits an `approval_required`\n * event and stops the turn, waiting for a human to approve. The action runs\n * only once the human re-issues the turn approving this specific call.\n *\n * - `true` — always require approval.\n * - `(args, ctx) => boolean | Promise<boolean>` — require approval only when\n * the predicate returns true (e.g. only for external recipients, only\n * above a dollar threshold). Keep it pure + fast; thrown errors are treated\n * as \"approval required\" (fail closed).\n */\n needsApproval?:\n | boolean\n | ((\n args: StandardSchemaV1.InferOutput<TSchema>,\n ctx?: ActionRunContext,\n ) => boolean | Promise<boolean>);\n /**\n * Authorization gate that runs before `run()` on **every** caller — agent\n * tool, HTTP, frontend, MCP, A2A, and CLI. It wraps `run` itself rather than\n * hanging off the action entry, because a flag consulted by the dispatcher\n * only guards the dispatchers that remember to consult it.\n *\n * This is *authorization*, not approval: `needsApproval` asks a human to\n * bless one call the caller is already allowed to make, while `authorize`\n * decides whether they are allowed at all. It also does not replace\n * `accessFilter` / `assertAccess` — those scope which rows a permitted caller\n * may see; this decides whether the operation is open to them.\n *\n * ```ts\n * import { coachAccess } from \"../lib/access.js\";\n *\n * export default defineAction({\n * description: \"Archive a training plan.\",\n * schema,\n * authorize: coachAccess.requireAny(\"coach-admin\"),\n * run: async (args) => { ... },\n * });\n * ```\n */\n authorize?: ActionAuthorize<StandardSchemaV1.InferOutput<TSchema>>;\n /**\n * Audit-log configuration. **Default-on for mutating actions** — you only\n * need this to tune capture: declare the mutated `target` (so the change\n * shows up in the owner's audit trail) and/or a `summary`, opt a read-only\n * action in via `onRead`, or opt a noisy action out via `enabled: false`.\n * See the `audit-log` skill.\n */\n audit?: ActionAuditConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Legacy parameter-based action options\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithParams<\n TParams extends Record<string, ParameterSchema> | undefined =\n | Record<string, ParameterSchema>\n | undefined,\n TReturn = any,\n> {\n description: string;\n /** Flat map of parameter names to their schema. Automatically wrapped in\n * `{ type: \"object\", properties: ... }` for the Claude API. */\n parameters?: TParams;\n /** Standard Schema — not used in this overload. */\n schema?: never;\n /** Advertised-only schema override — not used in this overload (no runtime\n * schema to advertise a compact alternative for). See the schema overload\n * above. */\n agentInputSchema?: never;\n /** Optional Standard Schema-compatible schema the action's RETURN value is\n * validated against AFTER `run()` resolves. See the schema overload above.\n * When omitted, behavior is byte-for-byte unchanged. */\n outputSchema?: StandardSchemaV1;\n /** What to do when the result fails `outputSchema`. Default: `\"warn\"`. */\n outputErrorStrategy?: ActionOutputErrorStrategy;\n /** Value returned in place of an invalid result when `outputErrorStrategy` is\n * `\"fallback\"`. Ignored for the other strategies. */\n outputFallback?: TReturn;\n run: (\n args: InferParams<TParams>,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** Whether the HTTP/frontend action route must have an authenticated owner.\n * Defaults to true. See the schema overload above. */\n requiresAuth?: boolean;\n /** Max HTTP request body in bytes; 413s on `Content-Length` before parsing.\n * See the schema overload above. */\n maxBodyBytes?: number;\n /** Whether this action is exposed to the agent as a callable tool. Only an\n * explicit `false` hides it from every agent tool list while keeping it\n * frontend/HTTP-callable. See the schema overload above and actions.md. */\n agentTool?: boolean;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** Set false for read-only tools that should stay available in Act mode but\n * must not run during Plan mode. See the schema overload above. */\n allowInPlanMode?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn. */\n parallelSafe?: boolean;\n /** Set false to exempt a read-only tool from the duplicate read-only call\n * guard. Default true. See the schema overload above. */\n dedupe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)`. See the schema overload above for details\n * and the `toolCallable` section in actions.md. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. See schema overload above. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. See schema overload above. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource. See schema overload above. */\n mcpApp?: ActionMcpAppConfig;\n /** Optional native Agent-Native chat renderer. See schema overload above. */\n chatUI?: ActionChatUIConfig;\n /** Per-tool timeout override in milliseconds. See schema overload above. */\n timeoutMs?: number;\n /** Per-tool result truncation override. See schema overload above. */\n maxResultChars?: number;\n /** Opt-in human-in-the-loop approval gate (default off). See the schema\n * overload above for full semantics. */\n needsApproval?:\n | boolean\n | ((\n args: InferParams<TParams>,\n ctx?: ActionRunContext,\n ) => boolean | Promise<boolean>);\n /** Pre-run authorization gate applied to every caller. See the schema\n * overload above for full semantics. */\n authorize?: ActionAuthorize<InferParams<TParams>>;\n /** Audit-log configuration (default-on for mutations). See the schema\n * overload above and the `audit-log` skill. */\n audit?: ActionAuditConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Return type — carries schema-inferred input + run return for client inference\n// ---------------------------------------------------------------------------\n\n/**\n * Opaque typed wrapper returned by `defineAction`. The type parameters carry\n * the schema-inferred input and the `run` return type so that:\n *\n * - The generated `.generated/action-types.d.ts` can extract them via\n * `typeof import(\"../actions/my-action\").default.run` and augment\n * `ActionRegistry` with concrete param/result types.\n * - `useActionQuery` / `useActionMutation` / `callAction` in the client hooks\n * flow the correct types end-to-end without manual generic annotations.\n *\n * Runtime shape is unchanged — this is a declaration-only wrapper.\n */\nexport interface ActionDefinition<TInput, TReturn> {\n /**\n * Typed run function — declaration only; infer input/return from this.\n * `TInput` is the schema's input type (optional defaults allowed at call\n * sites); `TReturn` is the awaited result type of the run callback.\n */\n readonly run: (\n args: TInput,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n /** @internal Framework use only — do not call directly. */\n readonly tool: import(\"./agent/types.js\").ActionTool;\n readonly http?: ActionHttpConfig | false;\n readonly requiresAuth?: boolean;\n readonly maxBodyBytes?: number;\n readonly agentTool?: boolean;\n readonly readOnly?: boolean;\n readonly allowInPlanMode?: boolean;\n readonly parallelSafe?: boolean;\n readonly dedupe?: boolean;\n readonly toolCallable?: boolean;\n readonly publicAgent?: PublicAgentActionConfig;\n readonly link?: ActionLinkBuilder;\n readonly mcpApp?: ActionMcpAppConfig;\n readonly chatUI?: ActionChatUIConfig;\n /** Per-tool timeout override in milliseconds for agent-loop tool calls. */\n readonly timeoutMs?: number;\n /** Per-tool result truncation override for agent-loop tool calls. */\n readonly maxResultChars?: number;\n /** Standard Schema the action's RETURN value is validated against after\n * `run()` resolves. Present only when the caller passed `outputSchema`. */\n readonly outputSchema?: StandardSchemaV1;\n /** Resolved output-mismatch strategy. Present only when `outputSchema` is\n * set; defaults to `\"warn\"`. */\n readonly outputErrorStrategy?: ActionOutputErrorStrategy;\n /** Value substituted for an invalid result under the `\"fallback\"` strategy. */\n readonly outputFallback?: TReturn;\n /** Opt-in human-in-the-loop approval gate (default off). When truthy, the\n * agent loop emits `approval_required` and pauses instead of executing this\n * action until a human approves the specific call. */\n readonly needsApproval?:\n | boolean\n | ((args: TInput, ctx?: ActionRunContext) => boolean | Promise<boolean>);\n /** Resolved audit-log configuration. Present only when the caller passed\n * `audit`. The audit capture wrapper is baked into `run`; this field is for\n * introspection. */\n readonly audit?: ActionAuditConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Define an agent action. Place in `actions/` directory — auto-discovered by the framework.\n *\n * Supports two modes:\n *\n * **Schema mode (recommended)** — pass a Standard Schema-compatible schema (Zod, Valibot,\n * ArkType) for runtime validation and full type inference:\n *\n * ```ts\n * import { defineAction } from \"@agent-native/core\";\n * import { z } from \"zod\";\n *\n * export default defineAction({\n * description: \"Create a form\",\n * schema: z.object({\n * title: z.string().describe(\"Form title\"),\n * status: z.enum([\"draft\", \"published\", \"closed\"]).default(\"draft\"),\n * }),\n * run: async (args) => {\n * // args is { title: string; status: \"draft\" | \"published\" | \"closed\" }\n * // Already validated — invalid inputs never reach here\n * },\n * });\n * ```\n *\n * **Parameters mode (legacy)** — pass raw JSON schema-like parameter definitions:\n *\n * ```ts\n * export default defineAction({\n * description: \"List events\",\n * parameters: {\n * from: { type: \"string\", description: \"Start date\" },\n * },\n * run: async (args) => { ... },\n * });\n * ```\n */\nexport function defineAction<\n TSchema extends StandardSchemaV1,\n TReturn,\n TOutputSchema extends StandardSchemaV1 | undefined = undefined,\n>(\n options: DefineActionWithSchema<TSchema, TReturn, TOutputSchema>,\n): ActionDefinition<StandardSchemaV1.InferInput<TSchema>, TReturn>;\nexport function defineAction<\n TParams extends Record<string, ParameterSchema> | undefined,\n TReturn,\n>(\n options: DefineActionWithParams<TParams, TReturn>,\n): ActionDefinition<InferParams<TParams>, TReturn>;\nexport function defineAction(options: any) {\n const hasSchema = options.schema && \"~standard\" in options.schema;\n\n // Build tool definition for the Claude API\n let toolParameters: ActionTool[\"parameters\"];\n if (hasSchema) {\n // Convert Standard Schema to JSON Schema for Claude\n toolParameters = schemaToJsonSchema(options.schema, options.description);\n } else if (options.parameters) {\n toolParameters = {\n type: \"object\" as const,\n properties: options.parameters,\n };\n }\n\n // `agentInputSchema` swaps in a compact JSON Schema for the ADVERTISED tool\n // definition only (what the model/MCP/A2A tool listings see). It never\n // touches validation below — `wrapWithValidation` is always called with\n // `options.schema`, the full schema, as the source of truth for what's\n // accepted. Passing the same (compact) `toolParameters` into it only\n // affects the top-level \"Expected: { ... }\" hint text and gateway string\n // coercion, both of which only look at top-level property names/types —\n // unaffected by trimming a nested union, so this stays safe either way.\n if (\n hasSchema &&\n options.agentInputSchema &&\n \"~standard\" in options.agentInputSchema\n ) {\n toolParameters = schemaToJsonSchema(\n options.agentInputSchema,\n options.description,\n );\n }\n\n // Authorization sits INSIDE input validation, so a gate that inspects `args`\n // is handed the parsed, coerced value its type promises rather than whatever\n // shape the caller sent. Putting it outside would have every guard reading\n // attacker-shaped input while typed as though it were validated.\n const guardedRun =\n typeof options.authorize === \"function\"\n ? wrapRunWithAuthorize(options.run, options.authorize)\n : options.run;\n\n // Wrap run() with INPUT validation when schema is provided.\n // Pass toolParameters so the validation error can echo the expected signature\n // (required vs optional fields) and help the caller self-correct.\n const inputValidatedRun = hasSchema\n ? wrapWithValidation(options.schema, guardedRun, toolParameters)\n : guardedRun;\n\n // Then wrap with OUTPUT validation when an outputSchema is provided. This\n // composes AROUND the input-validated run so the order is: validate input →\n // run() → validate output. When no outputSchema is present, the run is passed\n // through untouched and behavior is byte-for-byte unchanged.\n const hasOutputSchema =\n options.outputSchema && \"~standard\" in options.outputSchema;\n const outputErrorStrategy: ActionOutputErrorStrategy =\n options.outputErrorStrategy === \"strict\" ||\n options.outputErrorStrategy === \"warn\" ||\n options.outputErrorStrategy === \"fallback\"\n ? options.outputErrorStrategy\n : \"warn\";\n const run = hasOutputSchema\n ? wrapWithOutputValidation(\n options.outputSchema,\n inputValidatedRun,\n outputErrorStrategy,\n options.outputFallback,\n options.description,\n )\n : inputValidatedRun;\n\n // Auto-infer readOnly from http.method === \"GET\" unless explicitly set.\n // GET actions are idempotent reads; their completion should NOT trigger a\n // screen refresh. Everything else is assumed to mutate — the dispatcher\n // emits a change event on success so the UI auto-refetches its queries.\n const httpConfig = options.http as ActionHttpConfig | false | undefined;\n const inferredReadOnly =\n httpConfig !== false &&\n httpConfig !== undefined &&\n httpConfig.method === \"GET\";\n // Explicit `readOnly` (true OR false) wins. Otherwise infer from http.method.\n // We store the resolved boolean so downstream checks can trust entry.readOnly\n // without re-running method inference — including when a caller explicitly\n // passes readOnly:false to override a GET (rare but valid).\n const readOnly: boolean | undefined =\n typeof options.readOnly === \"boolean\"\n ? options.readOnly\n : inferredReadOnly\n ? true\n : undefined;\n\n // Audit: wrap the validated run so every mutating call records an audit\n // event (who/what/when/from-where, and for the agent which run). Default-on\n // for mutations; read-only actions opt in via `audit.onRead`. The wrapper\n // lazily imports the DB-touching recorder so `action.ts` keeps no static DB\n // dependency.\n const auditConfig = normalizeAuditConfig(options.audit);\n const finalRun = resolveAuditAttach(auditConfig, readOnly)\n ? wrapRunWithAudit(run, auditConfig)\n : run;\n\n // toolCallable: thread through whatever the caller declared. We DO NOT\n // default to `true` here — the absence of an explicit field is meaningful\n // to the tools bridge: it lets us emit a one-shot warning when an action\n // without a declared `toolCallable` flag is invoked from a tool, so the\n // ecosystem can migrate over time. The bridge treats `undefined` as\n // \"implicit allow with a deprecation warning\"; only an explicit `false`\n // refuses the call. See `extensions/routes.ts` and audit H5.\n const toolCallable: boolean | undefined =\n typeof options.toolCallable === \"boolean\"\n ? options.toolCallable\n : undefined;\n // agentTool: default-allow opt-out. Only an explicit `false` hides the action\n // from the agent tool surfaces; undefined is preserved (treated as exposed).\n const agentTool: boolean | undefined =\n typeof options.agentTool === \"boolean\" ? options.agentTool : undefined;\n const parallelSafe: boolean | undefined =\n typeof options.parallelSafe === \"boolean\"\n ? options.parallelSafe\n : undefined;\n const dedupe: boolean | undefined =\n typeof options.dedupe === \"boolean\" ? options.dedupe : undefined;\n const publicAgent: PublicAgentActionConfig | undefined =\n options.publicAgent &&\n typeof options.publicAgent === \"object\" &&\n !Array.isArray(options.publicAgent)\n ? options.publicAgent\n : undefined;\n const link: ActionLinkBuilder | undefined =\n typeof options.link === \"function\" ? options.link : undefined;\n const mcpApp: ActionMcpAppConfig | undefined = (() => {\n if (\n !options.mcpApp ||\n typeof options.mcpApp !== \"object\" ||\n Array.isArray(options.mcpApp)\n ) {\n return undefined;\n }\n // compactCatalog-only: no resource required; just keep the flag.\n if (options.mcpApp.compactCatalog === true && !options.mcpApp.resource) {\n return options.mcpApp as ActionMcpAppConfig;\n }\n // Full resource: validate html is present.\n if (\n options.mcpApp.resource &&\n typeof options.mcpApp.resource === \"object\" &&\n !Array.isArray(options.mcpApp.resource) &&\n (typeof options.mcpApp.resource.html === \"string\" ||\n typeof options.mcpApp.resource.html === \"function\")\n ) {\n return options.mcpApp as ActionMcpAppConfig;\n }\n return undefined;\n })();\n const chatUI = normalizeActionChatUIConfig(options.chatUI);\n\n return {\n tool: {\n description: options.description,\n parameters: toolParameters,\n },\n run: finalRun,\n ...(hasSchema ? { schema: options.schema } : {}),\n ...(options.http !== undefined ? { http: options.http } : {}),\n ...(typeof options.requiresAuth === \"boolean\"\n ? { requiresAuth: options.requiresAuth }\n : {}),\n ...(typeof options.maxBodyBytes === \"number\"\n ? { maxBodyBytes: options.maxBodyBytes }\n : {}),\n ...(typeof agentTool === \"boolean\" ? { agentTool } : {}),\n ...(typeof readOnly === \"boolean\" ? { readOnly } : {}),\n ...(typeof options.allowInPlanMode === \"boolean\"\n ? { allowInPlanMode: options.allowInPlanMode }\n : {}),\n ...(typeof parallelSafe === \"boolean\" ? { parallelSafe } : {}),\n ...(typeof dedupe === \"boolean\" ? { dedupe } : {}),\n ...(typeof toolCallable === \"boolean\" ? { toolCallable } : {}),\n ...(publicAgent ? { publicAgent } : {}),\n ...(link ? { link } : {}),\n ...(mcpApp ? { mcpApp } : {}),\n ...(chatUI ? { chatUI } : {}),\n ...(typeof options.timeoutMs === \"number\"\n ? { timeoutMs: options.timeoutMs }\n : {}),\n ...(typeof options.maxResultChars === \"number\"\n ? { maxResultChars: options.maxResultChars }\n : {}),\n ...(hasOutputSchema\n ? {\n outputSchema: options.outputSchema,\n outputErrorStrategy,\n ...(outputErrorStrategy === \"fallback\"\n ? { outputFallback: options.outputFallback }\n : {}),\n }\n : {}),\n ...(typeof options.needsApproval === \"boolean\" ||\n typeof options.needsApproval === \"function\"\n ? { needsApproval: options.needsApproval }\n : {}),\n ...(auditConfig ? { audit: auditConfig } : {}),\n };\n}\n\n/**\n * Wrap an action's run with its `authorize` gate.\n *\n * The gate is applied here, around `run`, rather than exposed as a flag on the\n * action entry: `run` is the one thing all six dispatch sites (agent loop, HTTP\n * route, frontend, MCP, A2A, CLI) go through, so there is no caller that can\n * reach the body without passing the check. `needsApproval` took the flag route\n * and is consequently honoured only inside the agent loop.\n *\n * Composed so the full order is: validate input → authorize → run → validate\n * output → audit. The audit wrapper is outermost, so a denial is still recorded\n * as an attempt — which is precisely what an audit trail is for.\n *\n * A guard that throws denies with its own message. A guard that returns `false`\n * denies generically. Anything else — including `undefined` — allows.\n */\nfunction wrapRunWithAuthorize(\n run: (args: any, ctx?: ActionRunContext) => any,\n authorize: ActionAuthorize<any>,\n): (args: any, ctx?: ActionRunContext) => Promise<any> {\n return async function authorizedRun(args: any, ctx?: ActionRunContext) {\n const verdict = await authorize(args, ctx);\n if (verdict === false) {\n const err = new Error(\"Not authorized\") as Error & { statusCode: number };\n err.name = \"ForbiddenError\";\n err.statusCode = 403;\n throw err;\n }\n return run(args, ctx);\n };\n}\n\n/**\n * Wrap an action's (already input/output-validated) run so each call records an\n * audit event after it resolves — on success and on error. Best-effort: the\n * recorder swallows its own failures and the original result/throw is always\n * preserved, so auditing can never change an action's behavior. The DB-touching\n * recorder is imported lazily so merely defining an action pulls in no DB code.\n */\nfunction wrapRunWithAudit(\n run: (args: any, ctx?: ActionRunContext) => any,\n auditConfig: ActionAuditConfig | undefined,\n): (args: any, ctx?: ActionRunContext) => Promise<any> {\n return async function auditedRun(args: any, ctx?: ActionRunContext) {\n let result: any;\n let error: unknown;\n let threw = false;\n try {\n result = await run(args, ctx);\n } catch (err) {\n error = err;\n threw = true;\n }\n try {\n const { recordActionAudit } = await import(\"./audit/record.js\");\n await recordActionAudit(\n threw\n ? { config: auditConfig, args, ctx, status: \"error\", error }\n : { config: auditConfig, args, ctx, status: \"success\", result },\n );\n } catch {\n // Recorder failed to load/run — never affect the action.\n }\n if (threw) throw error;\n return result;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Schema → JSON Schema conversion\n// ---------------------------------------------------------------------------\n\n// Keywords whose value is a single subschema.\nconst SUBSCHEMA_VALUE_KEYS = [\n \"items\",\n \"additionalItems\",\n \"contains\",\n \"additionalProperties\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n] as const;\n// Keywords whose value is an array of subschemas.\nconst SUBSCHEMA_ARRAY_KEYS = [\n \"allOf\",\n \"anyOf\",\n \"oneOf\",\n \"prefixItems\",\n] as const;\n// Keywords whose value is a map of name → subschema.\nconst SUBSCHEMA_MAP_KEYS = [\n \"properties\",\n \"patternProperties\",\n \"$defs\",\n \"definitions\",\n \"dependentSchemas\",\n] as const;\n\n/**\n * Remove JSON Schema keywords that some providers' function-calling schema\n * validators reject. OpenAI (and Gemini via the Builder gateway) reject\n * `propertyNames` — which Zod v4 emits for `z.record(z.string(), …)` — with a\n * `400 invalid_function_parameters` error, causing the model turn to produce no\n * content (surfacing as an empty assistant response). Anthropic ignores the\n * keyword, so stripping it is safe across providers and keeps action schemas\n * portable. `propertyNames` only constrained object *keys*; the value/shape of\n * the object is unaffected by its removal.\n *\n * Only descends through actual subschema positions (properties, items, union\n * branches, definitions, etc.) — never through value-bearing keywords like\n * `default`, `const`, `enum`, or `examples`, whose objects may legitimately\n * contain a `propertyNames` data key that must be preserved.\n */\nfunction stripUnsupportedSchemaKeywords<T>(node: T): T {\n if (!node || typeof node !== \"object\" || Array.isArray(node)) return node;\n const obj = node as Record<string, unknown>;\n\n delete obj.propertyNames;\n\n for (const key of SUBSCHEMA_VALUE_KEYS) {\n // `items`/`additionalItems` may also be an array of subschemas.\n const value = obj[key];\n if (Array.isArray(value)) {\n for (const sub of value) stripUnsupportedSchemaKeywords(sub);\n } else {\n stripUnsupportedSchemaKeywords(value);\n }\n }\n for (const key of SUBSCHEMA_ARRAY_KEYS) {\n const value = obj[key];\n if (Array.isArray(value)) {\n for (const sub of value) stripUnsupportedSchemaKeywords(sub);\n }\n }\n for (const key of SUBSCHEMA_MAP_KEYS) {\n const value = obj[key];\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n for (const sub of Object.values(value)) {\n stripUnsupportedSchemaKeywords(sub);\n }\n }\n }\n return node;\n}\n\n/**\n * Convert a Standard Schema to JSON Schema for the Claude API.\n * Tries vendor-specific toJSONSchema first (Zod v4), then falls back\n * to a basic introspection of the schema shape.\n */\nfunction schemaToJsonSchema(\n schema: StandardSchemaV1,\n _description?: string,\n): ActionTool[\"parameters\"] {\n const s = schema as any;\n\n // Prefer Zod's own JSON Schema output — it handles descriptions,\n // enums, coerce, and all type wrappers correctly.\n if (s[\"~standard\"]?.jsonSchema?.input) {\n try {\n const result = s[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as any;\n // Strip $schema — the Claude API validates against draft 2020-12\n // and a mismatched $schema declaration can cause rejections.\n if (result && typeof result === \"object\") {\n delete result.$schema;\n }\n return stripUnsupportedSchemaKeywords(result) as ActionTool[\"parameters\"];\n } catch {\n // Fall through to manual converter\n }\n }\n\n // Fallback: manual conversion from Zod v4 internal defs\n if (s._zod?.def) {\n return stripUnsupportedSchemaKeywords(zodDefToJsonSchema(s._zod.def));\n }\n\n // Last resort: empty object schema\n return { type: \"object\" as const, properties: {} };\n}\n\n/**\n * Convert a Zod v4 internal def to JSON Schema.\n * Handles the common types used in action parameters.\n */\nfunction zodDefToJsonSchema(def: any): any {\n const type = def.type;\n\n if (type === \"object\") {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n const shape = def.shape;\n if (shape) {\n for (const [key, fieldSchema] of Object.entries(shape) as any[]) {\n const fieldDef = fieldSchema?._zod?.def;\n if (fieldDef) {\n const prop = zodDefToJsonSchema(fieldDef);\n // Zod v4 stores .describe() on the schema object, not in the def\n const desc = fieldSchema?.description;\n if (desc && !prop.description) prop.description = desc;\n properties[key] = prop;\n if (\n fieldDef.type !== \"optional\" &&\n fieldDef.type !== \"default\" &&\n fieldDef.type !== \"nullable\"\n ) {\n required.push(key);\n }\n }\n }\n }\n const result: any = { type: \"object\", properties };\n if (required.length > 0) result.required = required;\n return result;\n }\n\n if (type === \"string\") {\n const result: any = { type: \"string\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"number\" || type === \"float\" || type === \"int\") {\n const result: any = { type: type === \"int\" ? \"integer\" : \"number\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"boolean\") {\n const result: any = { type: \"boolean\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"enum\") {\n // Zod v4 stores enum entries as an object {a: \"a\", b: \"b\"};\n // JSON Schema requires an array.\n const entries = def.entries;\n const enumValues = Array.isArray(entries)\n ? entries\n : typeof entries === \"object\" && entries !== null\n ? Object.values(entries)\n : entries;\n const result: any = { type: \"string\", enum: enumValues };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"literal\") {\n return { type: typeof def.value, enum: [def.value] };\n }\n\n if (type === \"array\") {\n const result: any = { type: \"array\" };\n if (def.element?._zod?.def) {\n result.items = zodDefToJsonSchema(def.element._zod.def);\n }\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"optional\") {\n if (def.innerType?._zod?.def) {\n return zodDefToJsonSchema(def.innerType._zod.def);\n }\n }\n\n if (type === \"default\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n inner.default =\n typeof def.defaultValue === \"function\"\n ? def.defaultValue()\n : def.defaultValue;\n return inner;\n }\n }\n\n if (type === \"nullable\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n // Surface null as a valid value so the model knows it may pass null\n // (and doesn't treat the field as a non-nullable required string).\n return { anyOf: [inner, { type: \"null\" }] };\n }\n }\n\n if (type === \"union\") {\n if (def.options?.length) {\n // Check if it's a simple enum-like union of literals\n const allLiterals = def.options.every(\n (o: any) => o?._zod?.def?.type === \"literal\",\n );\n if (allLiterals) {\n const values = def.options.map((o: any) => o._zod.def.value);\n const jsonTypeOf = (v: any) =>\n typeof v === \"number\"\n ? \"number\"\n : typeof v === \"boolean\"\n ? \"boolean\"\n : \"string\";\n const uniqueTypes = [...new Set(values.map(jsonTypeOf))];\n if (uniqueTypes.length === 1) {\n // Homogeneous literal union (e.g. all numbers) — derive the JSON\n // type instead of hardcoding \"string\", which would contradict the\n // enum values and make the model coerce/round-trip them wrongly.\n return { type: uniqueTypes[0], enum: values };\n }\n // Mixed literal types: emit anyOf so each branch stays self-consistent.\n return {\n anyOf: values.map((v: any) => ({ type: jsonTypeOf(v), enum: [v] })),\n };\n }\n return {\n anyOf: def.options.map((o: any) =>\n zodDefToJsonSchema(o._zod?.def ?? {}),\n ),\n };\n }\n }\n\n // z.preprocess / z.pipe / .superRefine / .transform all produce a \"pipe\"\n // def with `in` (pre-transform) and `out` (post-transform). For JSON Schema\n // purposes, use `out` — it reflects the validated output shape the model\n // should populate.\n if (type === \"pipe\") {\n if (def.out?._zod?.def) {\n return zodDefToJsonSchema(def.out._zod.def);\n }\n if (def.in?._zod?.def) {\n return zodDefToJsonSchema(def.in._zod.def);\n }\n }\n\n // Fallback\n return { type: \"string\" };\n}\n\n// ---------------------------------------------------------------------------\n// Runtime validation wrapper\n// ---------------------------------------------------------------------------\n\nconst NO_COERCE = Symbol(\"no-coerce\");\n\n/**\n * Coerce a single stringified value to one of the JSON-schema types the field\n * expects. Returns NO_COERCE when nothing safe applies, so the caller leaves\n * the original value untouched and the normal validation error still surfaces.\n */\nfunction coerceStringToSchemaType(raw: string, types: string[]): unknown {\n const trimmed = raw.trim();\n if (types.includes(\"boolean\")) {\n if (trimmed === \"true\") return true;\n if (trimmed === \"false\") return false;\n }\n if (\n (types.includes(\"array\") &&\n trimmed.startsWith(\"[\") &&\n trimmed.endsWith(\"]\")) ||\n (types.includes(\"object\") &&\n trimmed.startsWith(\"{\") &&\n trimmed.endsWith(\"}\"))\n ) {\n try {\n const parsed = JSON.parse(trimmed);\n if (types.includes(\"array\") && Array.isArray(parsed)) return parsed;\n if (\n types.includes(\"object\") &&\n parsed &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ) {\n return parsed;\n }\n } catch {\n // fall through — leave the original so validation reports the real error\n }\n }\n if (\n (types.includes(\"number\") || types.includes(\"integer\")) &&\n trimmed !== \"\" &&\n Number.isFinite(Number(trimmed))\n ) {\n const n = Number(trimmed);\n if (types.includes(\"number\") || Number.isInteger(n)) return n;\n }\n return NO_COERCE;\n}\n\n/**\n * Defensively coerce stringified action arguments to the types the schema\n * expects. Two callers depend on this:\n *\n * 1. Model gateways (notably Builder's Gemini-backed gateway) hand back\n * structured tool-call arguments as JSON strings — an array param arrives\n * as `\"[{...}]\"`, a boolean as `\"true\"`.\n * 2. GET actions called from the browser via `useActionQuery` / `callAction`.\n * Those serialize params into the query string, where `URLSearchParams`\n * stringifies everything — so `includeSeries: true` arrives as the string\n * `\"true\"` and `limit: 5` as `\"5\"` (see `action-routes.ts`).\n *\n * In both cases Standard Schema (zod) `validate` does not coerce, so the call\n * fails validation (\"expected boolean, received string\") — the agent thrashes\n * retrying shapes and the frontend query errors. We only touch a string value\n * when the schema expects a non-string type and the string parses cleanly to\n * it; anything ambiguous (schema also allows string) or unparseable is left\n * as-is. Operates on top-level properties only — once an array/object param is\n * parsed, its nested members are already native and validate normally.\n *\n * Do NOT narrow this to \"gateway-only\": the GET query-string path relies on it\n * too, and `action-routes.spec.ts` guards that round-trip.\n */\nfunction coerceGatewayStringifiedArgs(\n args: unknown,\n parameters?: ActionTool[\"parameters\"],\n): unknown {\n const properties = parameters?.properties as\n | Record<string, { type?: string | string[] }>\n | undefined;\n if (!properties) return args;\n if (!args || typeof args !== \"object\" || Array.isArray(args)) return args;\n let out: Record<string, unknown> | null = null;\n for (const [key, raw] of Object.entries(args as Record<string, unknown>)) {\n if (typeof raw !== \"string\") continue;\n const spec = properties[key];\n if (!spec) continue;\n const types = Array.isArray(spec.type)\n ? spec.type\n : spec.type\n ? [spec.type]\n : [];\n // No declared type, or the field legitimately accepts a string → leave it.\n if (types.length === 0 || types.includes(\"string\")) continue;\n const coerced = coerceStringToSchemaType(raw, types);\n if (coerced === NO_COERCE) continue;\n if (!out) out = { ...(args as Record<string, unknown>) };\n out[key] = coerced;\n }\n return out ?? args;\n}\n\n/**\n * Wrap an action's run function with schema validation.\n * Invalid inputs get a clear error message (including what was actually passed)\n * so the agent can see its own mistake and correct it on the next turn.\n */\nfunction wrapWithValidation(\n schema: StandardSchemaV1,\n run: Function,\n toolParameters?: ActionTool[\"parameters\"],\n): (args: any, ctx?: ActionRunContext) => any {\n return async (args: any, ctx?: ActionRunContext) => {\n args = coerceGatewayStringifiedArgs(args, toolParameters);\n const result = await schema[\"~standard\"].validate(args);\n if (result.issues) {\n // Split issues into \"missing required field\" vs other validation errors\n // so the error message reads naturally rather than as \"fieldName: Required\".\n const missing: string[] = [];\n const other: string[] = [];\n for (const issue of result.issues) {\n const pathStr = issue.path\n ? issue.path.map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\")\n : \"\";\n const msg = String(issue.message ?? \"\");\n // Zod emits \"Required\" for missing fields; other libraries may use\n // similar wording. Treat any variant as \"missing\".\n if (\n pathStr &&\n (msg === \"Required\" ||\n /invalid.*undefined/i.test(msg) ||\n /expected.*received undefined/i.test(msg))\n ) {\n missing.push(pathStr);\n } else {\n other.push(pathStr ? `${pathStr}: ${msg}` : msg);\n }\n }\n\n const parts: string[] = [];\n if (missing.length > 0) {\n parts.push(\n `Missing required parameter${missing.length === 1 ? \"\" : \"s\"}: ${missing.join(\", \")}`,\n );\n }\n if (other.length > 0) {\n parts.push(other.join(\"; \"));\n }\n\n // Echo the args that were actually passed so the caller (usually an\n // agent) can see exactly what it sent and fix its next call.\n let received: string;\n try {\n received = JSON.stringify(args);\n if (received.length > 500) received = received.slice(0, 500) + \"…\";\n } catch {\n received = String(args);\n }\n\n // Also show the EXPECTED signature so the agent doesn't have to guess.\n // Format: `{ deckId*: string, content*: string, slideId?: string, ... }`\n // where `*` = required, `?` = optional.\n let expected = \"\";\n if (toolParameters?.properties) {\n const required = new Set(toolParameters.required ?? []);\n const sig = Object.entries(toolParameters.properties)\n .map(([k, v]) => {\n const mark = required.has(k) ? \"*\" : \"?\";\n const type = (v as { type?: string }).type ?? \"any\";\n return `${k}${mark}: ${type}`;\n })\n .join(\", \");\n if (sig)\n expected = ` Expected: { ${sig} } (where * = required, ? = optional).`;\n }\n\n throw new Error(\n `Invalid action parameters — ${parts.join(\". \")}. Received: ${received}.${expected}`,\n );\n }\n return run((result as StandardSchemaV1.SuccessResult<any>).value, ctx);\n };\n}\n\n/**\n * Wrap an action's run function with RETURN-value validation. Runs AFTER the\n * (already input-validated) `run` resolves and validates the result against\n * `outputSchema` using the Standard Schema `~standard.validate` contract.\n *\n * Behavior is governed by `strategy`:\n * - `\"strict\"` — throw a clear error when the result doesn't match.\n * - `\"warn\"` — `console.warn` the issues and return the ORIGINAL result\n * unchanged (default; never alters runtime behavior).\n * - `\"fallback\"`— return `fallback` in place of the invalid result.\n *\n * On success the validated value is returned (so schema-applied coercion /\n * defaults take effect, mirroring the input path).\n */\nfunction wrapWithOutputValidation(\n outputSchema: StandardSchemaV1,\n run: (args: any, ctx?: ActionRunContext) => any,\n strategy: ActionOutputErrorStrategy,\n fallback: unknown,\n description?: string,\n): (args: any, ctx?: ActionRunContext) => any {\n return async (args: any, ctx?: ActionRunContext) => {\n const output = await run(args, ctx);\n const result = await outputSchema[\"~standard\"].validate(output);\n\n if (!result.issues) {\n // Return the validated value so coercion / defaults defined on the\n // outputSchema are applied, consistent with the input path.\n return (result as StandardSchemaV1.SuccessResult<any>).value;\n }\n\n const issues = result.issues\n .map((issue) => {\n const pathStr = issue.path\n ? issue.path.map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\")\n : \"\";\n const msg = String(issue.message ?? \"\");\n return pathStr ? `${pathStr}: ${msg}` : msg;\n })\n .join(\"; \");\n const label = description ? ` (${description})` : \"\";\n const summary = `Action output did not match outputSchema${label}: ${issues}`;\n\n if (strategy === \"strict\") {\n throw new Error(summary);\n }\n if (strategy === \"fallback\") {\n return fallback;\n }\n // \"warn\" (default): surface the mismatch but never change behavior.\n console.warn(summary);\n return output;\n };\n}\n"]}
|
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
import { type AccessContext } from "../sharing/access.js";
|
|
2
2
|
import { type ShareRole } from "../sharing/schema.js";
|
|
3
3
|
export declare function withThreadDataLock<T>(threadId: string, fn: () => Promise<T>): Promise<T>;
|
|
4
|
+
/**
|
|
5
|
+
* Explicitly repair `message_count` for legacy rows written before the count
|
|
6
|
+
* was maintained. This must never run from table/bootstrap initialization:
|
|
7
|
+
* serverless isolates would each scan the full `thread_data` blob column on
|
|
8
|
+
* cold start. Operators may invoke it once when upgrading an old database.
|
|
9
|
+
*/
|
|
10
|
+
export declare function repairLegacyChatThreadMessageCounts(options?: {
|
|
11
|
+
batchSize?: number;
|
|
12
|
+
}): Promise<{
|
|
13
|
+
scanned: number;
|
|
14
|
+
updated: number;
|
|
15
|
+
}>;
|
|
4
16
|
/**
|
|
5
17
|
* A resource the chat is bound to, e.g. `{ type: "deck", id: "deck-abc" }`.
|
|
6
18
|
* The framework is opaque to the type string — each template chooses what
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/chat-threads/store.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAEzE,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,sBAAsB,CAAC;AA+BrE,wBAAgB,kBAAkB,CAAC,CAAC,EAClC,QAAQ,EAAE,MAAM,EAChB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CAeZ;
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/chat-threads/store.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAEzE,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,sBAAsB,CAAC;AA+BrE,wBAAgB,kBAAkB,CAAC,CAAC,EACl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