eve 0.31.2 → 0.32.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/CHANGELOG.md +30 -0
- package/dist/src/chunks/{use-eve-agent-CF5D6jSV.js → use-eve-agent-CX87G1vU.js} +30 -5
- package/dist/src/chunks/{use-eve-agent-DbYZLG0h.js → use-eve-agent-DwyRde1N.js} +30 -5
- package/dist/src/cli/commands/integration-connect.d.ts +1 -0
- package/dist/src/cli/commands/integration-connect.js +1 -1
- package/dist/src/cli/commands/integration-setup.d.ts +4 -0
- package/dist/src/cli/commands/integration-setup.js +1 -1
- package/dist/src/cli/commands/register-integration-commands.js +1 -1
- package/dist/src/cli/commands/register-registry-commands.js +1 -1
- package/dist/src/cli/commands/registry-declared-setups.d.ts +23 -0
- package/dist/src/cli/commands/registry-declared-setups.js +1 -0
- package/dist/src/cli/commands/registry-metadata.d.ts +69 -0
- package/dist/src/cli/commands/registry-metadata.js +1 -1
- package/dist/src/cli/commands/registry-package.d.ts +3 -3
- package/dist/src/cli/commands/registry-package.js +1 -1
- package/dist/src/cli/commands/registry-presentation.d.ts +20 -0
- package/dist/src/cli/commands/registry-presentation.js +7 -0
- package/dist/src/cli/commands/registry-search-presentation.d.ts +16 -0
- package/dist/src/cli/commands/registry-search-presentation.js +6 -0
- package/dist/src/cli/commands/registry-setup-command.d.ts +5 -2
- package/dist/src/cli/commands/registry-setup-command.js +1 -2
- package/dist/src/cli/commands/registry.d.ts +16 -7
- package/dist/src/cli/commands/registry.js +1 -6
- package/dist/src/cli/commands/setup-answers.d.ts +2 -0
- package/dist/src/cli/commands/setup-answers.js +1 -0
- package/dist/src/cli/commands/setup-headless.d.ts +79 -0
- package/dist/src/cli/commands/setup-headless.js +1 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.js +3 -3
- package/dist/src/cli/dev/tui/setup-flow.d.ts +8 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +1 -1
- package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
- package/dist/src/client/url.d.ts +5 -0
- package/dist/src/client/url.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +8 -8
- package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +33 -13
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +4 -2
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +50 -3
- package/dist/src/compiled/@ai-sdk/google/index.js +7 -7
- package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +33 -3
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.d.ts +140 -9
- package/dist/src/compiled/@ai-sdk/openai/index.js +9 -6
- package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/provider/index.d.ts +300 -6
- package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +70 -20
- package/dist/src/compiled/@opentelemetry/api/index.d.ts +2 -1
- package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.js +1 -1
- package/dist/src/compiled/@vercel/otel/index.d.ts +6 -0
- package/dist/src/compiled/@vercel/sandbox/index.js +1 -1
- package/dist/src/compiled/_chunks/node/undici-CUIybhQ2.js +95 -0
- package/dist/src/compiled/_chunks/workflow/dist-eUxFublw.js +77 -0
- package/dist/src/compiled/shadcn-registry/index.js +309 -215
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/build-callback-context.js +1 -1
- package/dist/src/execution/authorization-callback-match.d.ts +14 -0
- package/dist/src/execution/authorization-callback-match.js +1 -0
- package/dist/src/execution/next-driver-action.d.ts +1 -0
- package/dist/src/execution/parked-delivery-wait.d.ts +16 -1
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/sandbox/abort-bound-session.d.ts +1 -1
- package/dist/src/execution/sandbox/bindings/docker.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-runtime.d.ts +1 -0
- package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/session-command-inbox.d.ts +26 -1
- package/dist/src/execution/session-command-inbox.js +1 -1
- package/dist/src/execution/turn-execution-cursor.d.ts +1 -0
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +3 -4
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/authorization.d.ts +24 -11
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/input-extraction.js +1 -1
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/provider-tools.d.ts +1 -1
- package/dist/src/harness/provider-tools.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/routes.d.ts +8 -6
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/linear/linearChannel.d.ts +2 -0
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/linear/verify.js +1 -1
- package/dist/src/public/channels/slack/attachments.js +1 -1
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/public/channels/slack/hitl.d.ts +14 -1
- package/dist/src/public/channels/slack/hitl.js +2 -2
- package/dist/src/public/connections/index.d.ts +1 -0
- package/dist/src/public/definitions/callback-context.d.ts +2 -2
- package/dist/src/public/definitions/connections/mcp.d.ts +9 -0
- package/dist/src/public/definitions/connections/openapi.d.ts +9 -0
- package/dist/src/public/definitions/connections/tool-call.d.ts +21 -0
- package/dist/src/public/definitions/connections/tool-call.js +1 -0
- package/dist/src/public/definitions/sandbox.d.ts +1 -1
- package/dist/src/public/definitions/tool.d.ts +9 -9
- package/dist/src/public/sandbox/index.d.ts +1 -1
- package/dist/src/public/tools/web-search.d.ts +2 -2
- package/dist/src/runtime/connections/callback-route.d.ts +4 -5
- package/dist/src/runtime/connections/callback-route.js +1 -1
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/openapi-client.js +1 -1
- package/dist/src/runtime/connections/provided-arguments.d.ts +9 -0
- package/dist/src/runtime/connections/provided-arguments.js +1 -0
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
- package/dist/src/runtime/framework-tools/todo.js +1 -1
- package/dist/src/runtime/input/types.d.ts +1 -4
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/types.d.ts +2 -0
- package/dist/src/sandbox/state.d.ts +1 -0
- package/dist/src/setup/ask-editable.d.ts +22 -0
- package/dist/src/setup/ask-editable.js +1 -0
- package/dist/src/setup/ask-signals.d.ts +23 -0
- package/dist/src/setup/ask-signals.js +1 -0
- package/dist/src/setup/ask.d.ts +24 -25
- package/dist/src/setup/ask.js +1 -1
- package/dist/src/setup/boxes/deploy-project.js +1 -1
- package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
- package/dist/src/setup/connection-connector.js +3 -2
- package/dist/src/setup/flows/registry-session.d.ts +33 -0
- package/dist/src/setup/flows/registry-session.js +1 -0
- package/dist/src/setup/flows/registry.d.ts +16 -0
- package/dist/src/setup/flows/registry.js +1 -1
- package/dist/src/setup/index.js +1 -1
- package/dist/src/setup/integrations/discord/setup.d.ts +19 -7
- package/dist/src/setup/integrations/discord/setup.js +4 -3
- package/dist/src/setup/integrations/github/setup.d.ts +36 -7
- package/dist/src/setup/integrations/github/setup.js +2 -2
- package/dist/src/setup/integrations/linear/setup.d.ts +21 -9
- package/dist/src/setup/integrations/linear/setup.js +2 -2
- package/dist/src/setup/integrations/photon/management.d.ts +8 -1
- package/dist/src/setup/integrations/photon/management.js +1 -1
- package/dist/src/setup/integrations/photon/setup-flow.d.ts +28 -24
- package/dist/src/setup/integrations/photon/setup-flow.js +3 -3
- package/dist/src/setup/integrations/photon/setup.d.ts +1 -3
- package/dist/src/setup/integrations/photon/setup.js +1 -1
- package/dist/src/setup/integrations/registry.d.ts +1 -1
- package/dist/src/setup/integrations/registry.js +1 -1
- package/dist/src/setup/integrations/runner.d.ts +14 -11
- package/dist/src/setup/integrations/runner.js +1 -1
- package/dist/src/setup/integrations/shared/prerequisite.d.ts +17 -0
- package/dist/src/setup/integrations/shared/prerequisite.js +1 -0
- package/dist/src/setup/integrations/shared/ui.d.ts +22 -15
- package/dist/src/setup/integrations/shared/ui.js +2 -2
- package/dist/src/setup/integrations/shared/vercel-project.d.ts +11 -0
- package/dist/src/setup/integrations/shared/vercel-project.js +1 -0
- package/dist/src/setup/integrations/slack/setup.d.ts +25 -10
- package/dist/src/setup/integrations/slack/setup.js +1 -1
- package/dist/src/setup/integrations/types.d.ts +43 -13
- package/dist/src/setup/integrations/types.js +1 -1
- package/dist/src/setup/integrations/web/setup.d.ts +22 -3
- package/dist/src/setup/integrations/web/setup.js +1 -1
- package/dist/src/setup/prompter.d.ts +8 -0
- package/dist/src/setup/question-options.d.ts +15 -0
- package/dist/src/setup/question-options.js +1 -0
- package/dist/src/setup/registry-setup-client.d.ts +3 -4
- package/dist/src/setup/registry-setup-client.js +2 -2
- package/dist/src/setup/registry-setup-completion.d.ts +3 -0
- package/dist/src/setup/registry-setup-completion.js +1 -0
- package/dist/src/setup/registry-setup-protocol.d.ts +22 -3
- package/dist/src/setup/registry-setup-protocol.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +55 -3
- package/dist/src/setup/scaffold/update/channels.js +1 -1
- package/dist/src/setup/setup-question-wire.d.ts +48 -0
- package/dist/src/setup/setup-question-wire.js +1 -0
- package/dist/src/setup/slackbot.d.ts +5 -1
- package/dist/src/setup/slackbot.js +1 -1
- package/dist/src/setup/state.d.ts +2 -2
- package/dist/src/shared/sandbox-backend.d.ts +6 -0
- package/dist/src/shared/sandbox-session.d.ts +15 -0
- package/dist/src/shared/tool-definition.d.ts +2 -2
- package/dist/src/shared/tool-schema.d.ts +5 -4
- package/dist/src/shared/tool-schema.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tracing/agent-otel-provider.d.ts +5 -38
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-span-id-generator.d.ts +15 -0
- package/dist/src/tracing/agent-span-id-generator.js +1 -0
- package/dist/src/tracing/agent-trace-context-store.d.ts +1 -1
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/agent-trace-state.d.ts +41 -0
- package/dist/src/tracing/agent-trace-state.js +1 -0
- package/dist/src/tracing/local-instrumentation-runtime.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/chat-sdk.mdx +1 -1
- package/docs/channels/github.mdx +1 -1
- package/docs/channels/linear.mdx +4 -2
- package/docs/channels/overview.mdx +2 -2
- package/docs/channels/slack.mdx +154 -40
- package/docs/concepts/default-harness.md +3 -3
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/connections/mcp.mdx +35 -1
- package/docs/connections/openapi.mdx +24 -0
- package/docs/guides/dev-tui.md +58 -142
- package/docs/guides/dynamic-workflows.md +2 -0
- package/docs/guides/frontend/overview.mdx +4 -2
- package/docs/guides/hooks.md +25 -3
- package/docs/guides/session-context.md +18 -0
- package/docs/install-integrations.mdx +2 -0
- package/docs/reference/cli.md +5 -3
- package/docs/reference/typescript-api.md +1 -1
- package/docs/sandbox.mdx +25 -5
- package/docs/skills.mdx +12 -1
- package/docs/subagents.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +1 -1
- package/docs/tutorial/ship-it.mdx +1 -1
- package/package.json +10 -10
- package/dist/src/compiled/_chunks/node/undici-DWL_MYmT.js +0 -95
- package/dist/src/compiled/_chunks/workflow/dist-CZxNEvEs.js +0 -79
|
@@ -69,9 +69,9 @@ export declare function createEveDevDispatchSchedulePath(scheduleId: string): st
|
|
|
69
69
|
* Stable framework-owned route pattern for receiving inbound IdP redirects
|
|
70
70
|
* during in-turn interactive connection authorization.
|
|
71
71
|
*
|
|
72
|
-
* `:name` is the connection name
|
|
73
|
-
*
|
|
74
|
-
* via `resumeHook(token, payload)`.
|
|
72
|
+
* `:name` is the connection name, `:attemptId` identifies the exact challenge,
|
|
73
|
+
* and `:token` is the workflow hook token minted by the workflow body so the
|
|
74
|
+
* route handler can resume the suspended turn via `resumeHook(token, payload)`.
|
|
75
75
|
*
|
|
76
76
|
* The route is unauthenticated by design: an OAuth IdP follows this URL
|
|
77
77
|
* via a 3xx redirect from the user's browser with no eve credentials
|
|
@@ -79,7 +79,9 @@ export declare function createEveDevDispatchSchedulePath(scheduleId: string): st
|
|
|
79
79
|
* resume; anyone who has it can deliver the callback payload, which is
|
|
80
80
|
* exactly what the IdP needs to do.
|
|
81
81
|
*/
|
|
82
|
-
export declare const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = "/eve/v1/connections/:name/callback/:token";
|
|
82
|
+
export declare const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = "/eve/v1/connections/:name/callback/:attemptId/:token";
|
|
83
|
+
/** Callback shape minted by deployments before authorization attempt IDs. */
|
|
84
|
+
export declare const EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN = "/eve/v1/connections/:name/callback/:token";
|
|
83
85
|
/**
|
|
84
86
|
* Stable framework-owned route pattern for terminal session callbacks.
|
|
85
87
|
*
|
|
@@ -101,7 +103,7 @@ export declare function createEveSessionResetRoutePath(sessionId: string): strin
|
|
|
101
103
|
export declare function createEveSessionStreamRoutePath(sessionId: string): string;
|
|
102
104
|
/**
|
|
103
105
|
* Creates the stable framework-owned connection callback route path for
|
|
104
|
-
* one (`name`, `token`)
|
|
106
|
+
* one (`name`, `attemptId`, `token`) tuple.
|
|
105
107
|
*
|
|
106
108
|
* The workflow body builds this path against {@link EVE_ROUTE_PREFIX} when
|
|
107
109
|
* minting the redirect URL it hands to the IdP via `startAuthorization`.
|
|
@@ -109,7 +111,7 @@ export declare function createEveSessionStreamRoutePath(sessionId: string): stri
|
|
|
109
111
|
* pattern and forwards the projected request payload into
|
|
110
112
|
* `resumeHook(token, payload)`.
|
|
111
113
|
*/
|
|
112
|
-
export declare function createEveConnectionCallbackRoutePath(name: string, token: string): string;
|
|
114
|
+
export declare function createEveConnectionCallbackRoutePath(name: string, attemptId: string, token: string): string;
|
|
113
115
|
/**
|
|
114
116
|
* Creates the stable framework-owned terminal callback route path.
|
|
115
117
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const EVE_ROUTE_PREFIX=`/eve/v1`,EVE_HEALTH_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/health`,EVE_INFO_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/info`,EVE_SESSION_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/session`,EVE_SESSION_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId`,EVE_SESSION_CANCEL_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/cancel`,EVE_SESSION_COMPACT_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/compact`,EVE_SESSION_CLEAR_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/clear`,EVE_SESSION_RESET_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/reset`,EVE_SESSION_STREAM_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/stream`,EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/dev/schedules/:scheduleId`,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/dev/runtime-artifacts`,EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/rebuild`,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/suspend`,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/resume`;function createEveDevDispatchSchedulePath(t){return`${EVE_ROUTE_PREFIX}/dev/schedules/${encodeURIComponent(t)}`}const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,EVE_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/callback/:token`;function createEveSessionRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}`}function createEveSessionCancelRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/cancel`}function createEveSessionCompactRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/compact`}function createEveSessionClearRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/clear`}function createEveSessionResetRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/reset`}function createEveSessionStreamRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/stream`}function createEveConnectionCallbackRoutePath(t,n){return`${EVE_ROUTE_PREFIX}/connections/${encodeURIComponent(t)}/callback/${encodeURIComponent(n)}`}function createEveCallbackRoutePath(t){return`${EVE_ROUTE_PREFIX}/callback/${encodeURIComponent(t)}`}export{EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,createEveCallbackRoutePath,createEveConnectionCallbackRoutePath,createEveDevDispatchSchedulePath,createEveSessionCancelRoutePath,createEveSessionClearRoutePath,createEveSessionCompactRoutePath,createEveSessionResetRoutePath,createEveSessionRoutePath,createEveSessionStreamRoutePath};
|
|
1
|
+
const EVE_ROUTE_PREFIX=`/eve/v1`,EVE_HEALTH_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/health`,EVE_INFO_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/info`,EVE_SESSION_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/session`,EVE_SESSION_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId`,EVE_SESSION_CANCEL_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/cancel`,EVE_SESSION_COMPACT_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/compact`,EVE_SESSION_CLEAR_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/clear`,EVE_SESSION_RESET_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/reset`,EVE_SESSION_STREAM_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/stream`,EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/dev/schedules/:scheduleId`,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/dev/runtime-artifacts`,EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/rebuild`,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/suspend`,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/resume`;function createEveDevDispatchSchedulePath(t){return`${EVE_ROUTE_PREFIX}/dev/schedules/${encodeURIComponent(t)}`}const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/connections/:name/callback/:attemptId/:token`,EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,EVE_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/callback/:token`;function createEveSessionRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}`}function createEveSessionCancelRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/cancel`}function createEveSessionCompactRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/compact`}function createEveSessionClearRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/clear`}function createEveSessionResetRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/reset`}function createEveSessionStreamRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/stream`}function createEveConnectionCallbackRoutePath(t,n,r){return`${EVE_ROUTE_PREFIX}/connections/${encodeURIComponent(t)}/callback/${encodeURIComponent(n)}/${encodeURIComponent(r)}`}function createEveCallbackRoutePath(t){return`${EVE_ROUTE_PREFIX}/callback/${encodeURIComponent(t)}`}export{EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,createEveCallbackRoutePath,createEveConnectionCallbackRoutePath,createEveDevDispatchSchedulePath,createEveSessionCancelRoutePath,createEveSessionClearRoutePath,createEveSessionCompactRoutePath,createEveSessionResetRoutePath,createEveSessionRoutePath,createEveSessionStreamRoutePath};
|
|
@@ -126,6 +126,8 @@ export interface LinearChannelConfig {
|
|
|
126
126
|
readonly api?: LinearApiOptions;
|
|
127
127
|
readonly credentials?: LinearChannelCredentials;
|
|
128
128
|
readonly events?: LinearChannelEvents;
|
|
129
|
+
/** Max allowed webhook timestamp skew in milliseconds. Defaults to 60 seconds. */
|
|
130
|
+
readonly maxSkewMs?: number;
|
|
129
131
|
readonly route?: string;
|
|
130
132
|
/** Inbound Agent Session hook. Defaults to dispatching `created` and `prompted` events. */
|
|
131
133
|
onAgentSession?(ctx: LinearSessionContext, event: LinearAgentSessionEvent): LinearInboundResultOrPromise;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{isObject,readNonEmptyString}from"#shared/guards.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{createLinearAgentActivity,createLinearAgentSessionOnComment,createLinearAgentSessionOnIssue,listLinearAgentSessionActivities,updateLinearAgentSession}from"#public/channels/linear/api.js";import{LINEAR_CHANNEL_DEFAULT_ROUTE}from"#public/channels/linear/constants.js";import{createDefaultEvents,defaultOnAgentSession}from"#public/channels/linear/defaults.js";import{formatLinearContextBlock,linearContinuationToken,messageFromLinearAgentSessionEvent,parseLinearWebhookEvent}from"#public/channels/linear/inbound.js";import{verifyLinearRequest}from"#public/channels/linear/verify.js";import{attachLinearInboundImages}from"#public/channels/linear/inbound-images.js";const log=createLogger(`linear.channel`);function linearChannel(e={}){let t=e.onAgentSession??defaultOnAgentSession,o={...createDefaultEvents({api:e.api,credentials:e.credentials}),...e.events};return defineChannel({kindHint:`linear`,state:initialLinearState(),metadata(e){return{agentSessionId:e.agentSessionId,commentId:e.commentId??null,issueId:e.issueId??null,issueIdentifier:e.issueIdentifier??null,organizationId:e.organizationId??null}},context(t,n){return rebuildLinearContext(t,n,e)},routes:[POST(e.route??LINEAR_CHANNEL_DEFAULT_ROUTE,async(n,{from:r,waitUntil:i})=>{let a=await verifyInbound(n,e.credentials);if(a===null)return new Response(`unauthorized`,{status:401});let o;try{o=parseLinearWebhookEvent({body:a,headers:n.headers})}catch(e){return log.warn(`inbound Linear body is not valid JSON`,{error:e}),jsonOk({ignored:!0,ok:!0})}return o===null?jsonOk({ignored:!0,ok:!0}):o.kind===`agent_session`?(i(dispatchAgentSession({config:e,event:o,from:r,onAgentSession:t})),jsonOk({ok:!0})):e.onDataWebhook===void 0?jsonOk({ignored:!0,ok:!0}):(i(Promise.resolve(e.onDataWebhook(o))),jsonOk({ok:!0}))})],async receive(t,{from:r}){let i=t.target,o=await resolveReceiveSession(i,e),s=readNonEmptyString(i.initialActivity);return s!==void 0&&await createLinearAgentActivity({api:e.api,credentials:e.credentials,activity:{agentSessionId:o.id,content:{body:s,type:`thought`}}}),r(linearContinuationToken(o.id)).send(t.message,{auth:t.auth,state:stateFromAgentSession(o)})},events:o})}function rebuildLinearContext(e,t,n){return{linear:buildLinearHandle({agentSessionId:e.agentSessionId??``,config:n}),state:e}}function buildLinearHandle(e){return{agentSessionId:e.agentSessionId,createActivity(t,n){return createLinearAgentActivity({api:e.config.api,credentials:e.config.credentials,activity:{agentSessionId:e.agentSessionId,content:t,ephemeral:n?.ephemeral,signal:n?.signal,signalMetadata:n?.signalMetadata}})},listActivities(t){return listLinearAgentSessionActivities({api:e.config.api,credentials:e.config.credentials,agentSessionId:e.agentSessionId,last:t?.last})},updateSession(t){return updateLinearAgentSession({api:e.config.api,credentials:e.config.credentials,id:e.agentSessionId,update:t})}}}async function dispatchAgentSession(e){let{event:t}=e,n={delivery:t.delivery,linear:buildLinearHandle({agentSessionId:t.agentSession.id,config:e.config}),session:t.agentSession},r=await e.onAgentSession(n,t);if(r===null)return;let i=await attachLinearInboundImages({content:messageFromLinearAgentSessionEvent(t),credentials:e.config.credentials,fetch:e.config.api?.fetch});await e.from(linearContinuationToken(t.agentSession.id)).send(i,{auth:r.auth,context:[formatLinearContextBlock(t),...t.previousComments,...r.context??[]],state:stateFromAgentSession(t.agentSession)})}async function resolveReceiveSession(e,t){if(hasString(e,`agentSessionId`))return{id:e.agentSessionId};if(hasString(e,`issueId`))return createLinearAgentSessionOnIssue({api:t.api,credentials:t.credentials,externalLink:readNonEmptyString(e.externalLink),externalUrls:readExternalUrls(e.externalUrls),issueId:e.issueId});if(hasString(e,`commentId`))return createLinearAgentSessionOnComment({api:t.api,credentials:t.credentials,commentId:e.commentId,externalLink:readNonEmptyString(e.externalLink),externalUrls:readExternalUrls(e.externalUrls)});throw Error(`linearChannel().receive requires target.agentSessionId, issueId, or commentId.`)}function stateFromAgentSession(e){return{agentSessionId:e.id,agentSessionUrl:e.url??null,commentId:e.commentId??null,issueId:e.issueId??e.issue?.id??null,issueIdentifier:e.issue?.identifier??null,issueTitle:e.issue?.title??null,issueUrl:e.issue?.url??null,organizationId:`organizationId`in e?e.organizationId??null:null,pendingToolCallMessage:null,sourceCommentId:e.sourceCommentId??null}}function initialLinearState(){return{agentSessionId:null,agentSessionUrl:null,commentId:null,issueId:null,issueIdentifier:null,issueTitle:null,issueUrl:null,organizationId:null,pendingToolCallMessage:null,sourceCommentId:null}}async function verifyInbound(e,t){try{return await verifyLinearRequest(e,{webhookSecret:t?.webhookSecret,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`linear inbound verification failed`,{error:e}),null}}function hasString(e,t){return typeof e[t]==`string`&&e[t].length>0}function readExternalUrls(e){if(!Array.isArray(e))return;let n=e.filter(e=>isObject(e)&&typeof e.label==`string`&&typeof e.url==`string`);return n.length>0?n:void 0}function jsonOk(e){return new Response(JSON.stringify(e),{headers:{"content-type":`application/json; charset=utf-8`},status:200})}export{linearChannel};
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{isObject,readNonEmptyString}from"#shared/guards.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{createLinearAgentActivity,createLinearAgentSessionOnComment,createLinearAgentSessionOnIssue,listLinearAgentSessionActivities,updateLinearAgentSession}from"#public/channels/linear/api.js";import{LINEAR_CHANNEL_DEFAULT_ROUTE}from"#public/channels/linear/constants.js";import{createDefaultEvents,defaultOnAgentSession}from"#public/channels/linear/defaults.js";import{formatLinearContextBlock,linearContinuationToken,messageFromLinearAgentSessionEvent,parseLinearWebhookEvent}from"#public/channels/linear/inbound.js";import{verifyLinearRequest}from"#public/channels/linear/verify.js";import{attachLinearInboundImages}from"#public/channels/linear/inbound-images.js";const log=createLogger(`linear.channel`);function linearChannel(e={}){let t=e.onAgentSession??defaultOnAgentSession,o={...createDefaultEvents({api:e.api,credentials:e.credentials}),...e.events};return defineChannel({kindHint:`linear`,state:initialLinearState(),metadata(e){return{agentSessionId:e.agentSessionId,commentId:e.commentId??null,issueId:e.issueId??null,issueIdentifier:e.issueIdentifier??null,organizationId:e.organizationId??null}},context(t,n){return rebuildLinearContext(t,n,e)},routes:[POST(e.route??LINEAR_CHANNEL_DEFAULT_ROUTE,async(n,{from:r,waitUntil:i})=>{let a=await verifyInbound(n,e.credentials,e.maxSkewMs);if(a===null)return new Response(`unauthorized`,{status:401});let o;try{o=parseLinearWebhookEvent({body:a,headers:n.headers})}catch(e){return log.warn(`inbound Linear body is not valid JSON`,{error:e}),jsonOk({ignored:!0,ok:!0})}return o===null?jsonOk({ignored:!0,ok:!0}):o.kind===`agent_session`?(i(dispatchAgentSession({config:e,event:o,from:r,onAgentSession:t})),jsonOk({ok:!0})):e.onDataWebhook===void 0?jsonOk({ignored:!0,ok:!0}):(i(Promise.resolve(e.onDataWebhook(o))),jsonOk({ok:!0}))})],async receive(t,{from:r}){let i=t.target,o=await resolveReceiveSession(i,e),s=readNonEmptyString(i.initialActivity);return s!==void 0&&await createLinearAgentActivity({api:e.api,credentials:e.credentials,activity:{agentSessionId:o.id,content:{body:s,type:`thought`}}}),r(linearContinuationToken(o.id)).send(t.message,{auth:t.auth,state:stateFromAgentSession(o)})},events:o})}function rebuildLinearContext(e,t,n){return{linear:buildLinearHandle({agentSessionId:e.agentSessionId??``,config:n}),state:e}}function buildLinearHandle(e){return{agentSessionId:e.agentSessionId,createActivity(t,n){return createLinearAgentActivity({api:e.config.api,credentials:e.config.credentials,activity:{agentSessionId:e.agentSessionId,content:t,ephemeral:n?.ephemeral,signal:n?.signal,signalMetadata:n?.signalMetadata}})},listActivities(t){return listLinearAgentSessionActivities({api:e.config.api,credentials:e.config.credentials,agentSessionId:e.agentSessionId,last:t?.last})},updateSession(t){return updateLinearAgentSession({api:e.config.api,credentials:e.config.credentials,id:e.agentSessionId,update:t})}}}async function dispatchAgentSession(e){let{event:t}=e,n={delivery:t.delivery,linear:buildLinearHandle({agentSessionId:t.agentSession.id,config:e.config}),session:t.agentSession},r=await e.onAgentSession(n,t);if(r===null)return;let i=await attachLinearInboundImages({content:messageFromLinearAgentSessionEvent(t),credentials:e.config.credentials,fetch:e.config.api?.fetch});await e.from(linearContinuationToken(t.agentSession.id)).send(i,{auth:r.auth,context:[formatLinearContextBlock(t),...t.previousComments,...r.context??[]],state:stateFromAgentSession(t.agentSession)})}async function resolveReceiveSession(e,t){if(hasString(e,`agentSessionId`))return{id:e.agentSessionId};if(hasString(e,`issueId`))return createLinearAgentSessionOnIssue({api:t.api,credentials:t.credentials,externalLink:readNonEmptyString(e.externalLink),externalUrls:readExternalUrls(e.externalUrls),issueId:e.issueId});if(hasString(e,`commentId`))return createLinearAgentSessionOnComment({api:t.api,credentials:t.credentials,commentId:e.commentId,externalLink:readNonEmptyString(e.externalLink),externalUrls:readExternalUrls(e.externalUrls)});throw Error(`linearChannel().receive requires target.agentSessionId, issueId, or commentId.`)}function stateFromAgentSession(e){return{agentSessionId:e.id,agentSessionUrl:e.url??null,commentId:e.commentId??null,issueId:e.issueId??e.issue?.id??null,issueIdentifier:e.issue?.identifier??null,issueTitle:e.issue?.title??null,issueUrl:e.issue?.url??null,organizationId:`organizationId`in e?e.organizationId??null:null,pendingToolCallMessage:null,sourceCommentId:e.sourceCommentId??null}}function initialLinearState(){return{agentSessionId:null,agentSessionUrl:null,commentId:null,issueId:null,issueIdentifier:null,issueTitle:null,issueUrl:null,organizationId:null,pendingToolCallMessage:null,sourceCommentId:null}}async function verifyInbound(e,t,n){try{return await verifyLinearRequest(e,{maxSkewMs:n,webhookSecret:t?.webhookSecret,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`linear inbound verification failed`,{error:e}),null}}function hasString(e,t){return typeof e[t]==`string`&&e[t].length>0}function readExternalUrls(e){if(!Array.isArray(e))return;let n=e.filter(e=>isObject(e)&&typeof e.label==`string`&&typeof e.url==`string`);return n.length>0?n:void 0}function jsonOk(e){return new Response(JSON.stringify(e),{headers:{"content-type":`application/json; charset=utf-8`},status:200})}export{linearChannel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHmac,timingSafeEqual}from"node:crypto";import{createLogger}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{resolveLinearWebhookSecret}from"#public/channels/linear/auth.js";const log=createLogger(`linear.verify`);async function verifyLinearRequest(e,t){let n=await e.text();if(t.webhookVerifier!==void 0){let r=await t.webhookVerifier(e,n);if(!r)throw Error(`linearChannel: inbound webhook verifier rejected the request.`);return typeof r==`string`?r:n}let r=await resolveLinearWebhookSecret(t.webhookSecret),a=e.headers.get(`linear-signature`)??``;if(!a)throw Error(`linearChannel: inbound request missing Linear-Signature.`);if(!constantTimeCompare(signLinearWebhookBody(n,r),a))throw Error(`linearChannel: inbound request signature mismatch.`);return verifyWebhookTimestamp(n,t.maxSkewMs??6e4),n}function signLinearWebhookBody(t,n){return createHmac(`sha256`,n).update(t).digest(`hex`)}function verifyWebhookTimestamp(e,t){let n;try{n=JSON.parse(e)}catch{throw Error(`linearChannel: inbound request body is not valid JSON.`)}let i=isObject(n)?n.webhookTimestamp:void 0;if(typeof i!=`number`||!Number.isFinite(i))throw Error(`linearChannel: inbound request missing webhookTimestamp.`);if(Math.abs(Date.now()-i)>t)throw Error(`linearChannel: inbound request timestamp outside allowed skew.`)}function constantTimeCompare(e,n){if(e.length!==n.length)return!1;try{return timingSafeEqual(Buffer.from(e),Buffer.from(n))}catch(e){return log.debug(`timingSafeEqual threw`,{error:e}),!1}}export{signLinearWebhookBody,verifyLinearRequest};
|
|
1
|
+
import{createHmac,timingSafeEqual}from"node:crypto";import{createLogger}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{resolveLinearWebhookSecret}from"#public/channels/linear/auth.js";const log=createLogger(`linear.verify`);async function verifyLinearRequest(e,t){let n=await e.text();if(t.webhookVerifier!==void 0){let r=await t.webhookVerifier(e,n);if(!r)throw Error(`linearChannel: inbound webhook verifier rejected the request.`);return typeof r==`string`?r:n}let r=await resolveLinearWebhookSecret(t.webhookSecret),a=e.headers.get(`linear-signature`)??``;if(!a)throw Error(`linearChannel: inbound request missing Linear-Signature.`);if(!constantTimeCompare(signLinearWebhookBody(n,r),a))throw Error(`linearChannel: inbound request signature mismatch.`);return verifyWebhookTimestamp(n,t.maxSkewMs??6e4),n}function signLinearWebhookBody(t,n){return createHmac(`sha256`,n).update(t).digest(`hex`)}function verifyWebhookTimestamp(e,t){if(!Number.isFinite(t)||t<0)throw Error(`linearChannel: maxSkewMs must be a non-negative finite number.`);let n;try{n=JSON.parse(e)}catch{throw Error(`linearChannel: inbound request body is not valid JSON.`)}let i=isObject(n)?n.webhookTimestamp:void 0;if(typeof i!=`number`||!Number.isFinite(i))throw Error(`linearChannel: inbound request missing webhookTimestamp.`);if(Math.abs(Date.now()-i)>t)throw Error(`linearChannel: inbound request timestamp outside allowed skew.`)}function constantTimeCompare(e,n){if(e.length!==n.length)return!1;try{return timingSafeEqual(Buffer.from(e),Buffer.from(n))}catch(e){return log.debug(`timingSafeEqual threw`,{error:e}),!1}}export{signLinearWebhookBody,verifyLinearRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{evaluateFilePart,formatUploadPolicyViolation,isUploadsDisabled}from"#public/channels/upload-policy.js";import{resolveSlackBotToken}from"#public/channels/slack/api.js";const log=createLogger(`slack.attachments`);function collectSlackFileParts(e,r){let i=[];for(let o of e??[]){let e=toSlackFilePart(o,i.length);if(e===null)continue;let s=evaluateFilePart(e,r);if(s!==null){log.warn(`dropped attachment — ${formatUploadPolicyViolation(s)}`,{name:o.name});continue}i.push(e)}return i}function toSlackFilePart(e,t){return e.type===`audio`||e.type===`video`?null:e.url?{type:`file`,mediaType:e.mimeType??`application/octet-stream`,filename:e.name??`attachment-${t}`,data:new URL(e.url)}:(log.warn(`dropped attachment — no url available`,{name:e.name}),null)}async function collectInboundFileParts(e){let t=collectSlackFileParts(e.mention.attachments,e.policy);if(t.length>0)return t;if(isUploadsDisabled(e.policy))return[];if(e.thread.recentMessages.length===0)try{await e.thread.refresh()}catch(e){return log.warn(`slack thread refresh failed for attachment collection`,{error:e}),[]}let n=e.thread.recentMessages;for(let t=n.length-1;t>=0;--t){let r=n[t];if(!r||r.isMe)continue;let i=r.raw,a=collectSlackFileParts(extractAttachmentsFromRaw(i?.files),e.policy);return a.length>0?a:[]}return[]}function extractAttachmentsFromRaw(e){return Array.isArray(e)?e.map(e=>{let t=typeof e.mimetype==`string`?e.mimetype:void 0;return{id:typeof e.id==`string`?e.id:``,type:inferAttachmentType(t),url:typeof e.url_private==`string`?e.url_private:void 0,name:typeof e.name==`string`?e.name:void 0,mimeType:t,size:typeof e.size==`number`?e.size:void 0}}):[]}function inferAttachmentType(e){return e===void 0?`file`:e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`file`}function buildSlackTurnMessage(e,t){return t.length===0?e:e.trim().length===0?[...t]:[{type:`text`,text:e},...t]}function createSlackFetchFile(e){return async t=>{if(!isSlackFileUrl(t))return null;let n=await resolveSlackBotToken(e.botToken),r=await fetch(t,{headers:{authorization:`Bearer ${n}`}});if(!r.ok)throw Error(`Slack file fetch returned HTTP ${r.status} for ${t}.`);return{bytes:Buffer.from(await r.arrayBuffer()),mediaType:
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{evaluateFilePart,formatUploadPolicyViolation,isUploadsDisabled}from"#public/channels/upload-policy.js";import{resolveSlackBotToken}from"#public/channels/slack/api.js";const log=createLogger(`slack.attachments`);function collectSlackFileParts(e,r){let i=[];for(let o of e??[]){let e=toSlackFilePart(o,i.length);if(e===null)continue;let s=evaluateFilePart(e,r);if(s!==null){log.warn(`dropped attachment — ${formatUploadPolicyViolation(s)}`,{name:o.name});continue}i.push(e)}return i}function toSlackFilePart(e,t){return e.type===`audio`||e.type===`video`?null:e.url?{type:`file`,mediaType:e.mimeType??`application/octet-stream`,filename:e.name??`attachment-${t}`,data:new URL(e.url)}:(log.warn(`dropped attachment — no url available`,{name:e.name}),null)}async function collectInboundFileParts(e){let t=collectSlackFileParts(e.mention.attachments,e.policy);if(t.length>0)return t;if(isUploadsDisabled(e.policy))return[];if(e.thread.recentMessages.length===0)try{await e.thread.refresh()}catch(e){return log.warn(`slack thread refresh failed for attachment collection`,{error:e}),[]}let n=e.thread.recentMessages;for(let t=n.length-1;t>=0;--t){let r=n[t];if(!r||r.isMe)continue;let i=r.raw,a=collectSlackFileParts(extractAttachmentsFromRaw(i?.files),e.policy);return a.length>0?a:[]}return[]}function extractAttachmentsFromRaw(e){return Array.isArray(e)?e.map(e=>{let t=typeof e.mimetype==`string`?e.mimetype:void 0;return{id:typeof e.id==`string`?e.id:``,type:inferAttachmentType(t),url:typeof e.url_private==`string`?e.url_private:void 0,name:typeof e.name==`string`?e.name:void 0,mimeType:t,size:typeof e.size==`number`?e.size:void 0}}):[]}function inferAttachmentType(e){return e===void 0?`file`:e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`file`}function buildSlackTurnMessage(e,t){return t.length===0?e:e.trim().length===0?[...t]:[{type:`text`,text:e},...t]}function createSlackFetchFile(e){return async t=>{if(!isSlackFileUrl(t))return null;let n=await resolveSlackBotToken(e.botToken),r=await fetch(t,{headers:{authorization:`Bearer ${n}`}});if(!r.ok)throw Error(`Slack file fetch returned HTTP ${r.status} for ${t}.`);let a=r.headers.get(`content-type`)??void 0;if(a?.split(`;`,1)[0]?.trim().toLowerCase()===`text/html`)throw Error(`Slack file fetch returned an HTML sign-in page instead of file bytes for ${t}. The bot token may be missing the files:read scope. Add the scope, reinstall the Slack app, and retry.`);return{bytes:Buffer.from(await r.arrayBuffer()),mediaType:a}}}function isSlackFileUrl(e){let t=URL.parse(e);return t?.protocol===`https:`?t.hostname===`files.slack.com`||(t.hostname===`enterprise.slack.com`||t.hostname.endsWith(`.enterprise.slack.com`))&&t.pathname.startsWith(`/files/`):!1}export{buildSlackTurnMessage,collectInboundFileParts,collectSlackFileParts,createSlackFetchFile};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{SLACK_MAX_BLOCKS_PER_MESSAGE,truncateMessageText,truncateTypingStatus}from"#public/channels/slack/limits.js";import{describeActionRequests}from"#public/channels/slack/action-status.js";import{buildSlackAuthContext,slackUserIdFromAuthContext}from"#public/channels/slack/auth.js";import{buildAuthCompletedText,buildAuthEphemeralBlocks,buildAuthRequiredPublicText,formatConnectionDisplayName}from"#public/channels/slack/connections.js";import{
|
|
1
|
+
import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{SLACK_MAX_BLOCKS_PER_MESSAGE,truncateMessageText,truncateTypingStatus}from"#public/channels/slack/limits.js";import{describeActionRequests}from"#public/channels/slack/action-status.js";import{buildSlackAuthContext,slackUserIdFromAuthContext}from"#public/channels/slack/auth.js";import{buildAuthCompletedText,buildAuthEphemeralBlocks,buildAuthRequiredPublicText,formatConnectionDisplayName}from"#public/channels/slack/connections.js";import{renderInputRequestPostParts}from"#public/channels/slack/hitl.js";const log=createLogger(`slack.defaults`);function defaultSlackAuth(e,t){let n=e.author;return n?buildSlackAuthContext({channelId:t.slack.channelId,fullName:n.fullName,isBot:n.isBot,teamId:e.teamId,threadTs:t.slack.threadTs,userId:n.userId,userName:n.userName}):null}async function defaultOnAppMention(e,t){return await e.thread.startTyping(`Thinking...`),{auth:defaultSlackAuth(t,e)}}async function defaultOnDirectMessage(e,t){return await e.thread.startTyping(`Thinking...`),{auth:defaultSlackAuth(t,e)}}function firstNonEmptyLine(e){for(let t of e.split(/\r?\n/u)){let e=t.trim();if(e.length>0)return e}}function defaultInputRequestedHandler(){return async(e,t,n)=>{for(let n of buildInputRequestPosts(e.requests))await t.thread.post(n)}}function buildInputRequestPosts(e){let t=[],n=[];for(let r of e){let e=renderInputRequestPostParts(r);e.details&&t.push(e.details),n.push(e.controls)}return[...groupInputRequestPostParts(t),...groupInputRequestPostParts(n)]}function groupInputRequestPostParts(e){let t=[];for(let n of e){let e=t.at(-1);e&&e.blocks.length+n.blocks.length<=SLACK_MAX_BLOCKS_PER_MESSAGE?(e.blocks.push(...n.blocks),e.fallbacks.push(n.text)):t.push({blocks:[...n.blocks],fallbacks:[n.text]})}return t.map(e=>({blocks:e.blocks,text:truncateMessageText(e.fallbacks.join(`
|
|
2
2
|
`))}))}const defaultEvents={async"turn.started"(e,t,n){t.state.pendingToolCallMessage=null,t.state.lastReasoningTypingAtMs=null,t.state.lastReasoningTypingStatus=null,await t.thread.startTyping(`Working...`)},async"reasoning.appended"(e,t,n){let r=firstNonEmptyLine(e.reasoningSoFar);if(r===void 0)return;let i=truncateTypingStatus(r),o=t.state.lastReasoningTypingStatus,s=o!=null&&i.startsWith(o)&&i.length>=o.length+4,c=Date.now(),l=t.state.lastReasoningTypingAtMs;if(!s&&l!=null){let e=c-l;if(e>=0&&e<5e3)return}await t.thread.startTyping(i),t.state.lastReasoningTypingAtMs=c,t.state.lastReasoningTypingStatus=i},async"actions.requested"(e,t,n){let r=t.state.pendingToolCallMessage;if(t.state.pendingToolCallMessage=null,r){await t.thread.startTyping(truncateTypingStatus(r));return}await t.thread.startTyping(truncateTypingStatus(describeActionRequests(e.actions)))},async"message.completed"(e,t,n){if(e.finishReason===`tool-calls`){t.state.pendingToolCallMessage=e.message?firstNonEmptyLine(e.message)??null:null;return}if(t.state.pendingToolCallMessage=null,!e.message){await t.thread.startTyping();return}await t.thread.post(e.message)},async"turn.failed"(e,r,i){let a=formatErrorHint(e),o=extractErrorId(e.details);await r.thread.post([`I hit an error while handling your request${a}.`,``,`Please try again, rephrase, or reach out if it keeps failing.`,...o?[``,`_Error id: \`${o}\`_`]:[]].join(`
|
|
3
3
|
`))},async"session.failed"(e,r){let i=formatErrorHint(e),a=extractErrorId(e.details);await r.thread.post([`This session couldn't recover from an error${i}.`,``,`Start a new thread to continue — I can't pick this one back up.`,...a?[``,`_Error id: \`${a}\`_`]:[]].join(`
|
|
4
4
|
`))},async"authorization.required"(e,t,n){let r=e.authorization?.displayName??formatConnectionDisplayName(e.name),i=slackUserIdFromAuthContext(n.session.auth.current)??t.state.triggeringUserId??null,a=e.authorization?.url,o=t.state.pendingAuthMessageTs??{};if(o[e.name]===void 0){let n=buildAuthRequiredPublicText({displayName:r,hasUser:i!==null});try{let r=await t.thread.post(n);r.id&&(t.state.pendingAuthMessageTs={...o,[e.name]:r.id})}catch(t){log.error(`Slack auth public message delivery failed`,{name:e.name,error:t})}}if(i&&a){let n=e.authorization?.userCode;try{await t.thread.postEphemeral(i,{blocks:buildAuthEphemeralBlocks({displayName:r,url:a,userCode:n}),text:n?`Sign in with ${r}: ${a} (code: ${n})`:`Sign in with ${r}: ${a}`})}catch(t){log.error(`Slack auth ephemeral delivery failed`,{name:e.name,error:t})}}},async"authorization.completed"(e,t,n){let r=e.authorization?.displayName??formatConnectionDisplayName(e.name);e.outcome===`authorized`&&await t.thread.startTyping(`Connected to ${r}. Resuming...`);let i=t.state.pendingAuthMessageTs??{},a=i[e.name];if(a===void 0)return;let o=buildAuthCompletedText({displayName:r,outcome:e.outcome,reason:e.reason});try{await t.slack.request(`chat.update`,{channel:t.slack.channelId,ts:a,text:o})}catch(t){log.error(`Slack auth status edit failed`,{name:e.name,error:t})}let s={...i};delete s[e.name],t.state.pendingAuthMessageTs=s}};export{defaultEvents,defaultInputRequestedHandler,defaultOnAppMention,defaultOnDirectMessage,defaultSlackAuth};
|
|
@@ -81,7 +81,7 @@ export declare function isHitlAction(actionId: string): boolean;
|
|
|
81
81
|
* - `display === "select"` with more options → `static_select`
|
|
82
82
|
* dropdown so the picker stays scrollable.
|
|
83
83
|
* - Anything else with options → Slack `card` blocks with action
|
|
84
|
-
* buttons. Best for visually distinct choices (
|
|
84
|
+
* buttons. Best for visually distinct choices (allow / cancel /
|
|
85
85
|
* cancel).
|
|
86
86
|
* - No options (or `allowFreeform: true`) → a single "Type your answer"
|
|
87
87
|
* button that opens a Slack modal with a plain_text_input. The modal
|
|
@@ -91,6 +91,19 @@ export declare function isHitlAction(actionId: string): boolean;
|
|
|
91
91
|
* Always emits at least the prompt section.
|
|
92
92
|
*/
|
|
93
93
|
export declare function renderInputRequestBlocks(request: InputRequest): unknown[];
|
|
94
|
+
export interface SlackInputRequestPostPart {
|
|
95
|
+
readonly blocks: unknown[];
|
|
96
|
+
readonly text: string;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Splits approval details from their interactive controls. Slack includes the
|
|
100
|
+
* originating message in `block_actions`, so putting large tool input beside
|
|
101
|
+
* the buttons makes the callback body grow with model-authored input.
|
|
102
|
+
*/
|
|
103
|
+
export declare function renderInputRequestPostParts(request: InputRequest): {
|
|
104
|
+
readonly controls: SlackInputRequestPostPart;
|
|
105
|
+
readonly details?: SlackInputRequestPostPart;
|
|
106
|
+
};
|
|
94
107
|
/**
|
|
95
108
|
* Creates the fallback text for one HITL request. Slack clients use this
|
|
96
109
|
* outside the rich Block Kit surface, so include the same approval details
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{SLACK_SECTION_TEXT_MAX_LENGTH,truncateCardBodyText,truncateModalTitle,truncatePlainText,truncateSectionText}from"#public/channels/slack/limits.js";const HITL_ACTION_PREFIX=`eve_input:`,HITL_FREEFORM_ACTION_PREFIX=`eve_input_freeform:`,HITL_FREEFORM_MODAL_CALLBACK_ID=`eve_input_freeform_submit`,HITL_FREEFORM_MODAL_BLOCK_ID=`eve_freeform_block`,HITL_FREEFORM_MODAL_ACTION_ID=`eve_freeform_text`,BUTTON_ACTION_ID_RE=/^(?<requestId>.+):button:\d+$/u,TOOL_INPUT_SUFFIX="\n```";function deriveHitlResponse(e){if(!e.actionId.startsWith(`eve_input:`))return null;let t=e.actionId.slice(10);if(e.selectedOptionValue!==void 0)return t?{optionId:e.selectedOptionValue,requestId:t}:null;if(e.value!==void 0){let n=BUTTON_ACTION_ID_RE.exec(t)?.groups?.requestId;return n?{optionId:e.value,requestId:n}:null}return null}function isHitlAction(e){return e.startsWith(HITL_ACTION_PREFIX)}function renderInputRequestBlocks(e){let t={text:{text:truncateSectionText(e.prompt),type:`mrkdwn`},type:`section`},n=renderInputRequestDetailBlocks(e),r=`${HITL_ACTION_PREFIX}${e.requestId}`,a=e.options,o=e.allowFreeform===!0||!a||a.length===0;if(a&&a.length>0&&e.display===`select`){let e=a.length<=6?{type:`radio_buttons`,action_id:r,options:a.map(buildOption)}:{type:`static_select`,action_id:r,options:a.map(buildOption),placeholder:{type:`plain_text`,text:`Choose an option`}};return[t,...n,{type:`actions`,elements:[e]}]}if(a&&a.length>0){let t=renderInputRequestCardBlock(e,r),n=renderToolInputContainerBlock(e);return n===void 0?[t]:[t,n]}return o?[t,...n,{type:`actions`,elements:[{type:`button`,action_id:`${HITL_FREEFORM_ACTION_PREFIX}${e.requestId}`,text:{type:`plain_text`,text:`Type your answer`},style:`primary`,value:e.requestId}]}]:[t]}function formatInputRequestFallbackText(e){let t=formatToolInputDetails(e);return t===void 0?e.prompt:`${e.prompt}\n${t}`}function buildFreeformModalView(e){let t=e.prompt?truncateModalTitle(e.prompt):`Your answer`,r=e.prompt?[{type:`section`,text:{type:`mrkdwn`,text:truncateSectionText(e.prompt)}}]:[];return{type:`modal`,callback_id:HITL_FREEFORM_MODAL_CALLBACK_ID,private_metadata:JSON.stringify(e.metadata),title:{type:`plain_text`,text:t},submit:{type:`plain_text`,text:`Submit`},close:{type:`plain_text`,text:`Cancel`},blocks:[...r,{type:`input`,block_id:HITL_FREEFORM_MODAL_BLOCK_ID,element:{type:`plain_text_input`,action_id:HITL_FREEFORM_MODAL_ACTION_ID,multiline:!0,placeholder:{type:`plain_text`,text:`Type your answer here...`}},label:{type:`plain_text`,text:`Answer`}}]}}function isFreeformAction(e){return e.startsWith(HITL_FREEFORM_ACTION_PREFIX)}function freeformRequestIdFromActionId(e){if(!isFreeformAction(e))return;let t=e.slice(19);return t.length>0?t:void 0}function buildCardButton(e,t,n){let i={type:`button`,text:{type:`plain_text`,text:truncatePlainText(e.label),emoji:!1},action_id:`${t}:button:${n}`,value:e.id};return(e.style===`primary`||e.style===`danger`)&&(i.style=e.style),i}function buildOption(e){let t={text:{text:truncatePlainText(e.label),type:`plain_text`},value:e.id},n=truncatePlainText(e.description);return n&&n.length>0&&(t.description={text:n,type:`plain_text`}),t}function renderInputRequestCardBlock(e,n){return{type:`card`,body:{type:`mrkdwn`,text:truncateCardBodyText(`*${e.prompt}*`),verbatim:!1},actions:cardButtonOptions(e).map((e,t)=>buildCardButton(e,n,t))}}function cardButtonOptions(e){let t=e.options??[];if(!isApprovalRequest(e))return t.map(toCardButtonOption);let n=t.find(e=>e.id===`approve`),r=t.find(e=>e.id===`
|
|
1
|
+
import{SLACK_SECTION_TEXT_MAX_LENGTH,truncateCardBodyText,truncateModalTitle,truncatePlainText,truncateSectionText}from"#public/channels/slack/limits.js";const HITL_ACTION_PREFIX=`eve_input:`,HITL_FREEFORM_ACTION_PREFIX=`eve_input_freeform:`,HITL_FREEFORM_MODAL_CALLBACK_ID=`eve_input_freeform_submit`,HITL_FREEFORM_MODAL_BLOCK_ID=`eve_freeform_block`,HITL_FREEFORM_MODAL_ACTION_ID=`eve_freeform_text`,BUTTON_ACTION_ID_RE=/^(?<requestId>.+):button:\d+$/u,TOOL_INPUT_SUFFIX="\n```";function deriveHitlResponse(e){if(!e.actionId.startsWith(`eve_input:`))return null;let t=e.actionId.slice(10);if(e.selectedOptionValue!==void 0)return t?{optionId:e.selectedOptionValue,requestId:t}:null;if(e.value!==void 0){let n=BUTTON_ACTION_ID_RE.exec(t)?.groups?.requestId;return n?{optionId:e.value,requestId:n}:null}return null}function isHitlAction(e){return e.startsWith(HITL_ACTION_PREFIX)}function renderInputRequestBlocks(e){let t={text:{text:truncateSectionText(e.prompt),type:`mrkdwn`},type:`section`},n=renderInputRequestDetailBlocks(e),r=`${HITL_ACTION_PREFIX}${e.requestId}`,a=e.options,o=e.allowFreeform===!0||!a||a.length===0;if(a&&a.length>0&&e.display===`select`){let e=a.length<=6?{type:`radio_buttons`,action_id:r,options:a.map(buildOption)}:{type:`static_select`,action_id:r,options:a.map(buildOption),placeholder:{type:`plain_text`,text:`Choose an option`}};return[t,...n,{type:`actions`,elements:[e]}]}if(a&&a.length>0){let t=renderInputRequestCardBlock(e,r),n=renderToolInputContainerBlock(e);return n===void 0?[t]:[t,n]}return o?[t,...n,{type:`actions`,elements:[{type:`button`,action_id:`${HITL_FREEFORM_ACTION_PREFIX}${e.requestId}`,text:{type:`plain_text`,text:`Type your answer`},style:`primary`,value:e.requestId}]}]:[t]}function renderInputRequestPostParts(e){let t=renderInputRequestBlocks(e),n=t[0];return!isApprovalRequest(e)||!isBlockType(n,`card`)||t.length===1?{controls:{blocks:t,text:formatInputRequestFallbackText(e)}}:{controls:{blocks:[n],text:e.prompt},details:{blocks:t.slice(1),text:formatInputRequestFallbackText(e)}}}function formatInputRequestFallbackText(e){let t=formatToolInputDetails(e);return t===void 0?e.prompt:`${e.prompt}\n${t}`}function buildFreeformModalView(e){let t=e.prompt?truncateModalTitle(e.prompt):`Your answer`,r=e.prompt?[{type:`section`,text:{type:`mrkdwn`,text:truncateSectionText(e.prompt)}}]:[];return{type:`modal`,callback_id:HITL_FREEFORM_MODAL_CALLBACK_ID,private_metadata:JSON.stringify(e.metadata),title:{type:`plain_text`,text:t},submit:{type:`plain_text`,text:`Submit`},close:{type:`plain_text`,text:`Cancel`},blocks:[...r,{type:`input`,block_id:HITL_FREEFORM_MODAL_BLOCK_ID,element:{type:`plain_text_input`,action_id:HITL_FREEFORM_MODAL_ACTION_ID,multiline:!0,placeholder:{type:`plain_text`,text:`Type your answer here...`}},label:{type:`plain_text`,text:`Answer`}}]}}function isFreeformAction(e){return e.startsWith(HITL_FREEFORM_ACTION_PREFIX)}function freeformRequestIdFromActionId(e){if(!isFreeformAction(e))return;let t=e.slice(19);return t.length>0?t:void 0}function buildCardButton(e,t,n){let i={type:`button`,text:{type:`plain_text`,text:truncatePlainText(e.label),emoji:!1},action_id:`${t}:button:${n}`,value:e.id};return(e.style===`primary`||e.style===`danger`)&&(i.style=e.style),i}function buildOption(e){let t={text:{text:truncatePlainText(e.label),type:`plain_text`},value:e.id},n=truncatePlainText(e.description);return n&&n.length>0&&(t.description={text:n,type:`plain_text`}),t}function renderInputRequestCardBlock(e,n){return{type:`card`,body:{type:`mrkdwn`,text:truncateCardBodyText(`*${e.prompt}*`),verbatim:!1},actions:cardButtonOptions(e).map((e,t)=>buildCardButton(e,n,t))}}function cardButtonOptions(e){let t=e.options??[];if(!isApprovalRequest(e))return t.map(toCardButtonOption);let n=t.find(e=>e.id===`approve`),r=t.find(e=>e.id===`cancel`);return!n||!r?t.map(toCardButtonOption):[{id:r.id,label:`Cancel`},{id:n.id,label:`Approve`,style:`primary`}]}function toCardButtonOption(e){let t={id:e.id,label:e.label};return e.style===`primary`||e.style===`danger`?{...t,style:e.style}:t}function buildAnsweredBlocks(t){let n=[];for(let e of t.promptBlocks)e!=null&&n.push(e);let r=truncateWithEllipsis(t.answerLabel,SLACK_SECTION_TEXT_MAX_LENGTH-20-1);return n.push({type:`section`,text:{type:`mrkdwn`,text:`:white_check_mark: *${r}*`}}),t.userId&&t.userId.length>0&&n.push({type:`context`,elements:[{type:`mrkdwn`,text:`Answered by <@${t.userId}>`}]}),n}function renderInputRequestDetailBlocks(e){let t=formatToolInputDetails(e);return t===void 0?[]:[{type:`section`,text:{type:`mrkdwn`,text:t}}]}function renderToolInputContainerBlock(e){let t=formatToolInputContainerText(e);if(t!==void 0)return{type:`container`,title:{type:`plain_text`,text:`Tool input`},is_collapsible:!0,default_collapsed:!1,child_blocks:[{type:`section`,text:{type:`mrkdwn`,text:t}}]}}function formatToolInputContainerText(t){if(!isApprovalRequest(t))return;let n=JSON.stringify(t.action.input,null,2);return n===`{}`?void 0:`\`\`\`
|
|
2
2
|
${truncateWithEllipsis(n,SLACK_SECTION_TEXT_MAX_LENGTH-4-4)}${TOOL_INPUT_SUFFIX}`}function formatToolInputDetails(t){if(!isApprovalRequest(t))return;let n=JSON.stringify(t.action.input,null,2);return n===`{}`?void 0:`*Tool input*
|
|
3
3
|
\`\`\`
|
|
4
|
-
${truncateWithEllipsis(n,SLACK_SECTION_TEXT_MAX_LENGTH-17-4)}${TOOL_INPUT_SUFFIX}`}function truncateWithEllipsis(e,t){if(e.length<=t)return e;let n=Math.max(0,t-3);return`${e.slice(0,n).trimEnd()}...`}function isApprovalRequest(e){return e.kind===`tool-approval`}export{HITL_ACTION_PREFIX,HITL_FREEFORM_ACTION_PREFIX,HITL_FREEFORM_MODAL_ACTION_ID,HITL_FREEFORM_MODAL_BLOCK_ID,HITL_FREEFORM_MODAL_CALLBACK_ID,buildAnsweredBlocks,buildFreeformModalView,deriveHitlResponse,formatInputRequestFallbackText,freeformRequestIdFromActionId,isFreeformAction,isHitlAction,renderInputRequestBlocks};
|
|
4
|
+
${truncateWithEllipsis(n,SLACK_SECTION_TEXT_MAX_LENGTH-17-4)}${TOOL_INPUT_SUFFIX}`}function truncateWithEllipsis(e,t){if(e.length<=t)return e;let n=Math.max(0,t-3);return`${e.slice(0,n).trimEnd()}...`}function isBlockType(e,t){return typeof e==`object`&&!!e&&e.type===t}function isApprovalRequest(e){return e.kind===`tool-approval`}export{HITL_ACTION_PREFIX,HITL_FREEFORM_ACTION_PREFIX,HITL_FREEFORM_MODAL_ACTION_ID,HITL_FREEFORM_MODAL_BLOCK_ID,HITL_FREEFORM_MODAL_CALLBACK_ID,buildAnsweredBlocks,buildFreeformModalView,deriveHitlResponse,formatInputRequestFallbackText,freeformRequestIdFromActionId,isFreeformAction,isHitlAction,renderInputRequestBlocks,renderInputRequestPostParts};
|
|
@@ -5,5 +5,6 @@ export type { AuthorizationCallback, AuthorizationDefinition, ConnectionAuthDefi
|
|
|
5
5
|
export { defineInteractiveAuthorization } from "#runtime/connections/types.js";
|
|
6
6
|
export type { JsonValue } from "#public/types/json.js";
|
|
7
7
|
export { defineMcpClientConnection, type McpClientConnectionDefinition, } from "#public/definitions/connections/mcp.js";
|
|
8
|
+
export type { ConnectionToolCallDefinition, ProvidedArgumentContext, ProvidedArgumentsDefinition, ProvidedArgumentValue, } from "#public/definitions/connections/tool-call.js";
|
|
8
9
|
export { defineOpenAPIConnection, type OpenAPIConnectionDefinition, type OpenAPISpecSource, } from "#public/definitions/connections/openapi.js";
|
|
9
10
|
export { type ConnectionAuthorizationChallenge, ConnectionAuthorizationFailedError, type ConnectionAuthorizationFailedErrorOptions, ConnectionAuthorizationRequiredError, type ConnectionAuthorizationRequiredErrorOptions, isConnectionAuthorizationFailedError, isConnectionAuthorizationRequiredError, } from "#public/connections/errors.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SkillHandle } from "#execution/skills/types.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { RuntimeSandboxSession } from "#shared/sandbox-session.js";
|
|
3
3
|
import type { SessionAuth, SessionParent, SessionTurn } from "#context/keys.js";
|
|
4
4
|
export type { SessionAuth, SessionParent, SessionTurn };
|
|
5
5
|
/**
|
|
@@ -24,7 +24,7 @@ export interface SessionContext {
|
|
|
24
24
|
* Resolves the session's sandbox. Throws when no sandbox is available
|
|
25
25
|
* in the current authored runtime context.
|
|
26
26
|
*/
|
|
27
|
-
getSandbox(): Promise<
|
|
27
|
+
getSandbox(): Promise<RuntimeSandboxSession>;
|
|
28
28
|
/**
|
|
29
29
|
* Returns a {@link SkillHandle} for the named authored skill.
|
|
30
30
|
*/
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ConnectionAuthDefinition, HeadersDefinition, ToolFilterDefinition } from "#runtime/connections/types.js";
|
|
2
|
+
import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";
|
|
2
3
|
import type { Approval } from "#public/definitions/approval.js";
|
|
3
4
|
/**
|
|
4
5
|
* Public definition for an MCP client connection authored in
|
|
@@ -64,6 +65,14 @@ export interface McpClientConnectionDefinition {
|
|
|
64
65
|
* session context.
|
|
65
66
|
*/
|
|
66
67
|
headers?: HeadersDefinition;
|
|
68
|
+
/**
|
|
69
|
+
* Per-call behavior for tools exposed by this MCP connection.
|
|
70
|
+
*
|
|
71
|
+
* Use `providedArguments` for application-owned values that should not be
|
|
72
|
+
* controlled by the model. eve removes configured keys from the model-facing
|
|
73
|
+
* input schema and adds their resolved values immediately before execution.
|
|
74
|
+
*/
|
|
75
|
+
toolCall?: ConnectionToolCallDefinition;
|
|
67
76
|
/**
|
|
68
77
|
* Client-side tool filter. When set, the model sees only tools
|
|
69
78
|
* whose names pass the filter; `connection_search` drops all
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ConnectionAuthDefinition, HeadersDefinition, ToolFilterDefinition } from "#runtime/connections/types.js";
|
|
2
2
|
import type { Approval } from "#public/definitions/approval.js";
|
|
3
|
+
import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";
|
|
3
4
|
/**
|
|
4
5
|
* The OpenAPI document backing the connection: either an HTTPS URL the
|
|
5
6
|
* runtime fetches on first use, or an already-parsed OpenAPI 3.x /
|
|
@@ -82,6 +83,14 @@ export interface OpenAPIConnectionDefinition {
|
|
|
82
83
|
* values may be callbacks that receive the active session context.
|
|
83
84
|
*/
|
|
84
85
|
headers?: HeadersDefinition;
|
|
86
|
+
/**
|
|
87
|
+
* Per-call behavior for operations exposed by this OpenAPI connection.
|
|
88
|
+
*
|
|
89
|
+
* Use `providedArguments` for application-owned operation parameters. eve
|
|
90
|
+
* removes configured keys from the model-facing input schema and adds their
|
|
91
|
+
* resolved values immediately before building the HTTP request.
|
|
92
|
+
*/
|
|
93
|
+
toolCall?: ConnectionToolCallDefinition;
|
|
85
94
|
/**
|
|
86
95
|
* Operation filter keyed on `operationId`. When set, the model sees
|
|
87
96
|
* only operations whose id passes the filter; `connection_search`
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
2
|
+
import type { JsonValue } from "#public/types/json.js";
|
|
3
|
+
/** Context available while resolving an application-provided connection tool argument. */
|
|
4
|
+
export type ProvidedArgumentContext = SessionContext & {
|
|
5
|
+
/** Bare tool or operation name published by the remote connection. */
|
|
6
|
+
readonly toolName: string;
|
|
7
|
+
};
|
|
8
|
+
/** A static or per-call value for one application-provided connection tool argument. */
|
|
9
|
+
export type ProvidedArgumentValue = JsonValue | Promise<JsonValue> | ((ctx: ProvidedArgumentContext) => JsonValue | Promise<JsonValue>);
|
|
10
|
+
/**
|
|
11
|
+
* Connection tool argument values supplied by the application instead of the model.
|
|
12
|
+
*
|
|
13
|
+
* Configured keys are removed from remote input schemas before the schemas are
|
|
14
|
+
* exposed to the model, then resolved and added to every outgoing tool call.
|
|
15
|
+
*/
|
|
16
|
+
export type ProvidedArgumentsDefinition = Readonly<Record<string, ProvidedArgumentValue>>;
|
|
17
|
+
/** Per-call behavior shared by tools exposed through a connection. */
|
|
18
|
+
export interface ConnectionToolCallDefinition {
|
|
19
|
+
/** Application-owned arguments hidden from the model and added at execution time. */
|
|
20
|
+
readonly providedArguments?: ProvidedArgumentsDefinition;
|
|
21
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Optional } from "#shared/optional.js";
|
|
2
2
|
import type { SandboxDefinitionWithBootstrap as SharedSandboxDefinitionWithBootstrap, SandboxDefinitionWithoutBootstrap as SharedSandboxDefinitionWithoutBootstrap } from "#shared/sandbox-definition.js";
|
|
3
|
-
export type { SandboxCommandResult, SandboxProcess, SandboxReadBinaryFileOptions, SandboxReadFileOptions, SandboxRemovePathOptions, SandboxReadTextFileOptions, SandboxRunOptions, SandboxSession, SandboxSpawnOptions, SandboxWriteBinaryFileOptions, SandboxWriteFileOptions, SandboxWriteTextFileOptions, } from "#shared/sandbox-session.js";
|
|
3
|
+
export type { SandboxCommandResult, SandboxProcess, SandboxReadBinaryFileOptions, SandboxReadFileOptions, SandboxRemovePathOptions, SandboxReadTextFileOptions, SandboxRunOptions, SandboxSession, RuntimeSandboxSession, SandboxSpawnOptions, SandboxWriteBinaryFileOptions, SandboxWriteFileOptions, SandboxWriteTextFileOptions, } from "#shared/sandbox-session.js";
|
|
4
4
|
export type { SandboxBootstrapUseFn, SandboxRevalidationKeyFn, SandboxSessionUseFn, SandboxBootstrapContext, SandboxSessionContext, } from "#shared/sandbox-definition.js";
|
|
5
5
|
/**
|
|
6
6
|
* The shape passed to {@link defineSandbox}: a discriminated union over
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
|
|
1
|
+
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
|
|
2
2
|
import type { PublicToolDefinition, ToolModelOutput } from "#shared/tool-definition.js";
|
|
3
3
|
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
4
4
|
import type { Approval } from "#public/definitions/approval.js";
|
|
@@ -122,22 +122,22 @@ type ToolDefinitionWithExecuteReturn<TInput, TOutput, TReturn> = ToolDefinition<
|
|
|
122
122
|
* For static tools, the runtime tool name is the filename slug. `defineTool`
|
|
123
123
|
* stamps a brand that lifecycle code validates; it rejects raw object literals.
|
|
124
124
|
*/
|
|
125
|
-
export declare function defineTool<TInputSchema extends StandardJSONSchemaV1<unknown, unknown>, TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn extends Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>>(definition: {
|
|
125
|
+
export declare function defineTool<TInputSchema extends StandardSchemaV1<unknown, unknown> | StandardJSONSchemaV1<unknown, unknown>, TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn extends Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>>(definition: {
|
|
126
126
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
127
127
|
inputSchema: TInputSchema;
|
|
128
128
|
outputSchema: TOutputSchema;
|
|
129
|
-
execute(input:
|
|
130
|
-
approval?: ToolDefinition<
|
|
129
|
+
execute(input: StandardSchemaV1.InferOutput<TInputSchema>, ctx: ToolContext): TReturn;
|
|
130
|
+
approval?: ToolDefinition<StandardSchemaV1.InferOutput<TInputSchema>, unknown>["approval"];
|
|
131
131
|
toModelOutput?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["toModelOutput"];
|
|
132
|
-
}): ToolDefinitionWithExecuteReturn<
|
|
133
|
-
export declare function defineTool<TSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn>(definition: {
|
|
132
|
+
}): ToolDefinitionWithExecuteReturn<StandardSchemaV1.InferOutput<TInputSchema>, StandardJSONSchemaV1.InferOutput<TOutputSchema>, TReturn>;
|
|
133
|
+
export declare function defineTool<TSchema extends StandardSchemaV1<unknown, unknown> | StandardJSONSchemaV1<unknown, unknown>, TReturn>(definition: {
|
|
134
134
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
135
135
|
inputSchema: TSchema;
|
|
136
136
|
outputSchema?: JsonObject;
|
|
137
|
-
execute(input:
|
|
138
|
-
approval?: ToolDefinition<
|
|
137
|
+
execute(input: StandardSchemaV1.InferOutput<TSchema>, ctx: ToolContext): TReturn;
|
|
138
|
+
approval?: ToolDefinition<StandardSchemaV1.InferOutput<TSchema>, unknown>["approval"];
|
|
139
139
|
toModelOutput?: ToolDefinition<unknown, ToolOutputFromExecuteReturn<TReturn>>["toModelOutput"];
|
|
140
|
-
}): ToolDefinitionWithExecuteReturn<
|
|
140
|
+
}): ToolDefinitionWithExecuteReturn<StandardSchemaV1.InferOutput<TSchema>, ToolOutputFromExecuteReturn<TReturn>, TReturn>;
|
|
141
141
|
export declare function defineTool<TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn extends Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>>(definition: {
|
|
142
142
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
143
143
|
inputSchema: JsonObject;
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Sandbox authoring helpers for `agent/sandbox.ts` (or
|
|
3
3
|
* `agent/sandbox/sandbox.ts` when paired with a `workspace/` folder).
|
|
4
4
|
*/
|
|
5
|
-
export { defineSandbox, type SandboxBootstrapContext, type SandboxBootstrapUseFn, type SandboxCommandResult, type SandboxDefinition, type SandboxProcess, type SandboxReadBinaryFileOptions, type SandboxReadFileOptions, type SandboxReadTextFileOptions, type SandboxRevalidationKeyFn, type SandboxRunOptions, type SandboxSession, type SandboxSpawnOptions, type SandboxSessionContext, type SandboxSessionUseFn, type SandboxWriteBinaryFileOptions, type SandboxWriteFileOptions, type SandboxWriteTextFileOptions, } from "#public/definitions/sandbox.js";
|
|
5
|
+
export { defineSandbox, type SandboxBootstrapContext, type SandboxBootstrapUseFn, type SandboxCommandResult, type SandboxDefinition, type SandboxProcess, type SandboxReadBinaryFileOptions, type SandboxReadFileOptions, type SandboxReadTextFileOptions, type SandboxRevalidationKeyFn, type SandboxRunOptions, type SandboxSession, type RuntimeSandboxSession, type SandboxSpawnOptions, type SandboxSessionContext, type SandboxSessionUseFn, type SandboxWriteBinaryFileOptions, type SandboxWriteFileOptions, type SandboxWriteTextFileOptions, } from "#public/definitions/sandbox.js";
|
|
6
6
|
export type { SandboxBackend, SandboxBackendCreateInput, SandboxBackendHandle, SandboxBackendPrewarmInput, SandboxBackendRuntimeContext, SandboxBackendSessionState, SandboxSeedFile, } from "#public/definitions/sandbox-backend.js";
|
|
7
7
|
export type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
|
|
8
8
|
export { SandboxTemplateNotProvisionedError } from "#public/definitions/sandbox-backend.js";
|
|
@@ -20,7 +20,7 @@ export interface WebSearchToolDefinition {
|
|
|
20
20
|
/**
|
|
21
21
|
* Configures the framework-provided `web_search` tool.
|
|
22
22
|
*
|
|
23
|
-
* When no configuration file is present, eve uses
|
|
23
|
+
* When no configuration file is present, eve uses Exa for AI Gateway
|
|
24
24
|
* models.
|
|
25
25
|
*
|
|
26
26
|
* @example
|
|
@@ -28,7 +28,7 @@ export interface WebSearchToolDefinition {
|
|
|
28
28
|
* // agent/tools/web_search.ts
|
|
29
29
|
* import { webSearch } from "eve/tools";
|
|
30
30
|
*
|
|
31
|
-
* export default webSearch({ provider: "
|
|
31
|
+
* export default webSearch({ provider: "parallel" });
|
|
32
32
|
* ```
|
|
33
33
|
*/
|
|
34
34
|
export declare function webSearch(input: WebSearchToolInput): WebSearchToolDefinition;
|
|
@@ -33,11 +33,10 @@ export declare const HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX = "eve/v1/conn
|
|
|
33
33
|
* Returns the framework-shipped channel definitions that mount the
|
|
34
34
|
* connection callback route at {@link EVE_CONNECTION_CALLBACK_ROUTE_PATTERN}.
|
|
35
35
|
*
|
|
36
|
-
* Returns one definition per accepted HTTP method
|
|
37
|
-
*
|
|
38
|
-
* `(method, urlPath)` pair as a
|
|
39
|
-
*
|
|
40
|
-
* model.
|
|
36
|
+
* Returns one definition per accepted HTTP method and route generation. The
|
|
37
|
+
* legacy shape remains mounted for callbacks minted by already-pinned runs.
|
|
38
|
+
* The framework channel resolver mounts each `(method, urlPath)` pair as a
|
|
39
|
+
* separate Nitro route.
|
|
41
40
|
*/
|
|
42
41
|
export declare function getConnectionCallbackChannelDefinitions(): readonly ResolvedChannelDefinition[];
|
|
43
42
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_CONNECTION_CALLBACK_ROUTE_PATTERN}from"#protocol/routes.js";import{resumeHook}from"#internal/workflow/runtime.js";import{buildAuthorizationCompletePage}from"#runtime/connections/authorization-complete-page.js";const HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX=`eve/v1/connections/callback`,HANDLED_METHODS=[`GET`,`POST`];function getConnectionCallbackChannelDefinitions(){return HANDLED_METHODS.map(
|
|
1
|
+
import{EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN}from"#protocol/routes.js";import{resumeHook}from"#internal/workflow/runtime.js";import{buildAuthorizationCompletePage}from"#runtime/connections/authorization-complete-page.js";const HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX=`eve/v1/connections/callback`,HANDLED_METHODS=[`GET`,`POST`],ROUTE_KINDS=[`attempt`,`legacy`];function getConnectionCallbackChannelDefinitions(){return ROUTE_KINDS.flatMap(e=>HANDLED_METHODS.map(t=>buildCallbackChannelDefinition(t,e)))}function getConnectionCallbackChannelNames(){return new Set(getConnectionCallbackChannelDefinitions().map(e=>e.name))}function buildCallbackChannelDefinition(n,r){let i=channelNameForMethod(n,r);return{name:i,method:n,urlPath:r===`attempt`?EVE_CONNECTION_CALLBACK_ROUTE_PATTERN:EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,fetch:r===`attempt`?handleConnectionCallbackRequest:handleLegacyConnectionCallbackRequest,logicalPath:`framework://channels/${i}`,sourceId:`eve:framework:connection-callback-${r}-${n.toLowerCase()}`,sourceKind:`module`}}function channelNameForMethod(e,t){let n=e.toLowerCase();return t===`attempt`?`${HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX}/${n}`:`${HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX}/legacy/${n}`}async function handleConnectionCallbackRequest(e,t){return handleCallbackRequest(e,t,!1)}async function handleLegacyConnectionCallbackRequest(e,t){return handleCallbackRequest(e,t,!0)}async function handleCallbackRequest(e,t,i){let a=t.params.name,o=t.params.attemptId,s=t.params.token;if(typeof a!=`string`||a.length===0)return Response.json({error:`Missing connection name.`,ok:!1},{status:400});if(typeof s!=`string`||s.length===0)return Response.json({error:`Missing callback token.`,ok:!1},{status:400});if(!i&&(typeof o!=`string`||o.length===0))return Response.json({error:`Missing authorization attempt ID.`,ok:!1},{status:400});let c=await projectAuthorizationCallback(e);try{await resumeHook(s,{kind:`deliver`,payloads:[{authorizationCallback:i?{callback:c,connectionName:a,legacy:!0}:{attemptId:o,callback:c,connectionName:a}}]})}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return buildAuthorizationCompletePage()}async function projectAuthorizationCallback(e){let t={};for(let[n,r]of new URL(e.url).searchParams)t[n]=r;let n;if(e.method!==`GET`&&e.method!==`HEAD`){try{n=await e.text()}catch{n=void 0}let r=e.headers.get(`content-type`)??``;if(n&&r.includes(`application/x-www-form-urlencoded`))for(let[e,r]of new URLSearchParams(n))t[e]=r}return n===void 0?{params:t,method:e.method}:{params:t,method:e.method,body:n}}export{HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX,getConnectionCallbackChannelDefinitions,getConnectionCallbackChannelNames,handleConnectionCallbackRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{ConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{evictScopedToken,resolveScopedToken}from"#runtime/connections/scoped-authorization.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";var McpConnectionClient=class{#e;#t;#n;#r;#i;constructor(e){this.#i=e}async connect(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#a();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#a(){let e=await resolveHeaders(this.#i),t=this.#i.url;try{return await createMCPClient({transport:{type:`http`,url:t,headers:e}})}catch(n){if(!isMcpHttpFallbackRetryableError(n))throw n;return await createMCPClient({transport:{type:`sse`,url:t,headers:e}})}}async getToolMetadata(){return(await this.#o()).metadata}async getTools(){return(await this.#o()).tools}async executeTool(e,t,n){try{let{tools:r}=await this.#o(),i=r[e];if(i?.execute===void 0)throw Error(`Tool "${e}" not found in connection "${this.#i.connectionName}".`);return await i.execute(
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{ConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{evictScopedToken,resolveScopedToken}from"#runtime/connections/scoped-authorization.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";var McpConnectionClient=class{#e;#t;#n;#r;#i;constructor(e){this.#i=e}async connect(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#a();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#a(){let e=await resolveHeaders(this.#i),t=this.#i.url;try{return await createMCPClient({transport:{type:`http`,url:t,headers:e}})}catch(n){if(!isMcpHttpFallbackRetryableError(n))throw n;return await createMCPClient({transport:{type:`sse`,url:t,headers:e}})}}async getToolMetadata(){return(await this.#o()).metadata}async getTools(){return(await this.#o()).tools}async executeTool(e,t,n){try{let{tools:r}=await this.#o(),i=r[e];if(i?.execute===void 0)throw Error(`Tool "${e}" not found in connection "${this.#i.connectionName}".`);let a=await resolveProvidedArguments({args:t,connection:this.#i,toolName:e});return await i.execute(a,{abortSignal:n?.abortSignal})}catch(e){return await this.#l(e)}}async#o(){if(this.#r!==void 0)return this.#r;if(this.#n!==void 0)return this.#n;this.#n=this.#s();try{return this.#r=await this.#n,this.#r}catch(e){throw this.#n=void 0,e}}async#s(){try{return await this.#c()}catch(e){return await this.#l(e)}}async#c(){let e=await this.connect(),t=await e.listTools(),n=this.#i.tools,r=n===void 0?t.tools:t.tools.filter(e=>passesToolFilter(e.name,n)),i=Object.keys(this.#i.toolCall?.providedArguments??{}),a=r.map(e=>({...e,inputSchema:omitProvidedArgumentsFromSchema(e.inputSchema,i)})),o=e.toolsFromDefinitions({tools:a});return{metadata:a.map(e=>({annotations:e.annotations,description:e.description??``,inputSchema:e.inputSchema??{},name:e.name,outputSchema:`outputSchema`in e&&e.outputSchema!==void 0?e.outputSchema:void 0})),tools:o}}async close(){this.#t!==void 0&&(await this.#t.close(),this.#t=void 0),this.#e=void 0,this.#n=void 0,this.#r=void 0}async#l(e){throw isMcpAuthRequiredError(e)?(await this.#u(),await this.close(),new ConnectionAuthorizationRequiredError(this.#i.connectionName,{message:`Connection "${this.#i.connectionName}" requires authorization (the server rejected the token).`})):e}async#u(){let e=await resolveConnectionAuthorization(this.#i);e!==void 0&&await evictScopedToken({authorization:e,connection:{url:this.#i.url},scope:this.#i.connectionName})}};function isMcpAuthRequiredError(e){return readHttpStatus(e)===401}function isMcpHttpFallbackRetryableError(e){let t=readHttpStatus(e);return t===400||t===404||t===405}function readHttpStatus(t){for(let n of walkErrorChain(t)){if(!isObject(n))continue;let t=readStatusField(n);if(t!==void 0)return t;let r=n.response;if(isObject(r)){let e=readStatusField(r);if(e!==void 0)return e}if(typeof n.message==`string`){let e=/\bHTTP\s+(\d{3})\b/u.exec(n.message);if(e?.[1]!==void 0)return Number(e[1])}}}function readStatusField(e){if(typeof e.status==`number`)return e.status;if(typeof e.statusCode==`number`)return e.statusCode}function*walkErrorChain(t){let n=t,r=new Set;for(;n!=null&&!r.has(n);){if(r.add(n),yield n,!isObject(n)||!(`cause`in n))return;n=n.cause}}function passesToolFilter(e,t){return t===void 0?!0:`allow`in t?t.allow.includes(e):!t.block.includes(e)}async function resolveHeaders(e){let n={},r,getCallbackContext=()=>r??=buildCallbackContext(),i=await resolveConnectionAuthorization(e,typeof e.authorization==`function`?getCallbackContext():void 0);if(i!==void 0&&(n.Authorization=`Bearer ${(await resolveToken(e,i)).token}`),e.headers!==void 0){let t=await resolveHeadersDefinition(e.headers,getCallbackContext);for(let[r,a]of Object.entries(t)){if(i!==void 0&&r.toLowerCase()===`authorization`)throw Error(`Connection "${e.connectionName}" headers must not include an "Authorization" key when "authorization" is also provided.`);n[r]=a}}return n}async function resolveToken(e,t){return await resolveScopedToken({authorization:t,connection:{url:e.url},scope:e.connectionName})}async function resolveHeadersDefinition(e,t){if(typeof e==`function`)return{...await e(t())};let n={},r=Object.entries(e);for(let[e,i]of r)n[e]=await resolveHeaderValue(i,t);return n}async function resolveHeaderValue(e,t){return typeof e==`function`?await e(t()):await e}export{McpConnectionClient,isMcpAuthRequiredError,passesToolFilter,resolveHeaders};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isObject}from"#shared/guards.js";import{toInputSchema}from"#shared/tool-schema.js";import{tool}from"ai";import{passesToolFilter,resolveHeaders}from"#runtime/connections/mcp-client.js";import{HTTP_METHODS,operationDescription,operationName,uniqueName}from"#runtime/connections/openapi-operations.js";import{buildInputSchema,deref,derefSchema,isArray}from"#runtime/connections/openapi-schema.js";import{applySecurity,resolveSecurity}from"#runtime/connections/openapi-security.js";import{extractServerUrl,parseSpecDocument}from"#runtime/connections/openapi-spec.js";const log=createLogger(`runtime.connections.openapi-client`),SWAGGER_PARAMETER_SCHEMA_KEYS=[`default`,`enum`,`exclusiveMaximum`,`exclusiveMinimum`,`format`,`items`,`maximum`,`maxItems`,`maxLength`,`minimum`,`minItems`,`minLength`,`multipleOf`,`pattern`,`type`,`uniqueItems`];var OpenApiConnectionClient=class{#e;#t;#n;constructor(e){this.#n=e}async connect(){return this.#r()}async getToolMetadata(){return(await this.#r()).metadata}async getTools(){return(await this.#r()).tools}async executeTool(e,t,r){let i=await this.#r(),a=i.operations.get(e);if(a===void 0)throw Error(`Tool "${e}" not found in connection "${this.#n.connectionName}".`);return this.#f(a,i.baseUrl,isObject(t)?t:{},{abortSignal:r?.abortSignal})}async close(){this.#e=void 0,this.#t=void 0}async#r(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#i();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#i(){let e=await this.#o(),t=this.#a(e),o=this.#s(e),
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isObject}from"#shared/guards.js";import{toInputSchema}from"#shared/tool-schema.js";import{tool}from"ai";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";import{passesToolFilter,resolveHeaders}from"#runtime/connections/mcp-client.js";import{HTTP_METHODS,operationDescription,operationName,uniqueName}from"#runtime/connections/openapi-operations.js";import{buildInputSchema,deref,derefSchema,isArray}from"#runtime/connections/openapi-schema.js";import{applySecurity,resolveSecurity}from"#runtime/connections/openapi-security.js";import{extractServerUrl,parseSpecDocument}from"#runtime/connections/openapi-spec.js";const log=createLogger(`runtime.connections.openapi-client`),SWAGGER_PARAMETER_SCHEMA_KEYS=[`default`,`enum`,`exclusiveMaximum`,`exclusiveMinimum`,`format`,`items`,`maximum`,`maxItems`,`maxLength`,`minimum`,`minItems`,`minLength`,`multipleOf`,`pattern`,`type`,`uniqueItems`];var OpenApiConnectionClient=class{#e;#t;#n;constructor(e){this.#n=e}async connect(){return this.#r()}async getToolMetadata(){return(await this.#r()).metadata}async getTools(){return(await this.#r()).tools}async executeTool(e,t,r){let i=await this.#r(),a=i.operations.get(e);if(a===void 0)throw Error(`Tool "${e}" not found in connection "${this.#n.connectionName}".`);return this.#f(a,i.baseUrl,isObject(t)?t:{},{abortSignal:r?.abortSignal})}async close(){this.#e=void 0,this.#t=void 0}async#r(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#i();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#i(){let e=await this.#o(),t=this.#a(e),o=this.#s(e),c=this.#n.tools,l=c===void 0?o:o.filter(e=>passesToolFilter(e.toolName,c)),u=[],d=new Map,f={},p=Object.keys(this.#n.toolCall?.providedArguments??{});for(let e of l){let o=omitProvidedArgumentsFromSchema(e.inputSchema,p),s;try{s=toInputSchema(o)}catch(t){log.warn(`omitting OpenAPI operation with an invalid input schema`,{connectionName:this.#n.connectionName,error:t,toolName:e.toolName});continue}d.set(e.toolName,e),u.push({description:e.description,inputSchema:o,name:e.toolName}),f[e.toolName]=tool({description:e.description,inputSchema:s,execute:async(r,i)=>this.#f(e,t,isObject(r)?r:{},{abortSignal:i?.abortSignal})})}return{metadata:u,operations:d,tools:f,baseUrl:t}}#a(e){let t=this.#n.url,n=typeof t==`string`&&t.trim().length>0?t:extractServerUrl(e,this.#n.spec);if(n===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" has no base URL: set "baseUrl" or ensure the document declares an absolute "servers" entry or Swagger "host".`);return assertSecureUrl(n,this.#n.connectionName,`base`),n}async#o(){let e=this.#n.spec;if(e===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" is missing its "spec" source.`);if(typeof e!=`string`)return e;assertSecureUrl(e,this.#n.connectionName,`spec`);let t;try{t=await fetch(e,{headers:{accept:`application/json, application/yaml, text/yaml, */*`}})}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": ${String(t)}`)}if(t.redirected&&assertSecureUrl(t.url,this.#n.connectionName,`spec`),!t.ok)throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": HTTP ${t.status}.`);let r=await t.text(),i;try{i=parseSpecDocument(r)}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" could not be parsed as JSON or YAML: ${String(t)}`)}if(!isObject(i))throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" is not an OpenAPI document object.`);return i}#s(e){let t=e.paths;if(!isObject(t))return[];let r=[],i=new Set;for(let[a,o]of Object.entries(t)){if(!isObject(o))continue;let t=isArray(o.parameters)?o.parameters:[];for(let s of HTTP_METHODS){let c=o[s];if(!isObject(c))continue;let l=uniqueName(operationName(c,s,a),i),m=isArray(c.parameters)?c.parameters:[],h=[...t,...m],g=this.#c(e,h),_=this.#l(e,c.requestBody,h);r.push({toolName:l,method:s,pathTemplate:a,description:operationDescription(c),parameters:g,requestBody:_,inputSchema:buildInputSchema(g,_),security:resolveSecurity(e,c)})}}return r}#c(e,t){let r=[];for(let i of t){let t=isObject(i)?deref(e,i):i;if(!isObject(t))continue;let a=t.in;if(a!==`path`&&a!==`query`&&a!==`header`&&a!==`cookie`||typeof t.name!=`string`)continue;let o=this.#u(e,t);r.push({name:t.name,location:a,required:t.required===!0||a===`path`,schema:o,description:typeof t.description==`string`?t.description:void 0})}return r}#l(e,t,r=[]){if(isObject(t)){let r=deref(e,t);if(isObject(r)&&isObject(r.content)){let t=r.content,i=`application/json`in t?`application/json`:Object.keys(t)[0];if(i!==void 0){let a=t[i],o=isObject(a)&&isObject(a.schema)?derefSchema(e,a.schema):{};return{required:r.required===!0,contentType:i,schema:o}}}}return this.#d(e,r)}#u(e,t){if(isObject(t.schema))return derefSchema(e,t.schema);let r={};for(let e of SWAGGER_PARAMETER_SCHEMA_KEYS)t[e]!==void 0&&(r[e]=t[e]);return derefSchema(e,r)}#d(e,t){for(let r of t){let t=isObject(r)?deref(e,r):r;if(!isObject(t)||t.in!==`body`)continue;let i=isObject(t.schema)?derefSchema(e,t.schema):{};return{required:t.required===!0,contentType:`application/json`,schema:i}}}async#f(e,t,n,r){let i=await resolveProvidedArguments({args:n,connection:this.#n,toolName:e.toolName}),a=await resolveHeaders(this.#n),s=e.pathTemplate,l=new URLSearchParams,u=[];for(let t of e.parameters){let e=i[t.name];e!=null&&(t.location===`path`?s=s.replace(`{${t.name}}`,encodeURIComponent(String(e))):t.location===`query`?appendQuery(l,t.name,e):t.location===`cookie`?u.push(`${t.name}=${encodeURIComponent(String(e))}`):a[t.name]=String(e))}if(applySecurity(e.security,this.#n,a,l,u),u.length>0){let e=a.cookie??a.Cookie;delete a.Cookie,a.cookie=[e,...u].filter(e=>!!e).join(`; `)}let d=new URL(joinPath(t,s));d.search=l.toString();let f;e.requestBody!==void 0&&i.body!==void 0&&(f=JSON.stringify(i.body),a[`content-type`]=e.requestBody.contentType);let p=await fetch(d,{method:e.method.toUpperCase(),headers:a,body:f,signal:r?.abortSignal});return{status:p.status,statusText:p.statusText,body:await readResponseBody(p)}}};function appendQuery(e,t,n){if(isArray(n)){for(let r of n)e.append(t,String(r));return}e.append(t,String(n))}function joinPath(e,t){return`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`}function assertSecureUrl(e,n,r){let i;try{i=new URL(e)}catch{throw Error(`OpenAPI connection "${n}" has an invalid ${r} URL "${e}".`)}if(i.protocol!==`https:`&&!(i.protocol===`http:`&&isLoopbackHostname(i.hostname)))throw Error(`OpenAPI connection "${n}" must use https for its ${r} (got "${i.protocol}//${i.host}").`)}async function readResponseBody(e){let t=await e.text();if(t.length===0)return null;if((e.headers.get(`content-type`)??``).includes(`application/json`))try{return JSON.parse(t)}catch{return t}return t}export{OpenApiConnectionClient};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
|
|
2
|
+
/** Resolves and merges application-provided arguments, with application values winning. */
|
|
3
|
+
export declare function resolveProvidedArguments(input: {
|
|
4
|
+
readonly args: unknown;
|
|
5
|
+
readonly connection: ResolvedConnectionDefinition;
|
|
6
|
+
readonly toolName: string;
|
|
7
|
+
}): Promise<Record<string, unknown>>;
|
|
8
|
+
/** Removes application-provided top-level properties from a remote tool schema. */
|
|
9
|
+
export declare function omitProvidedArgumentsFromSchema<TSchema extends Record<string, unknown>>(schema: TSchema, names: readonly string[]): TSchema;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{parseJsonValue}from"#shared/json.js";import{buildCallbackContext}from"#context/build-callback-context.js";async function resolveProvidedArguments(r){if(!isObject(r.args))throw Error(`Tool "${r.toolName}" in connection "${r.connection.connectionName}" expected object arguments.`);let i=r.connection.toolCall?.providedArguments;if(i===void 0||Object.keys(i).length===0)return r.args;let a,getContext=()=>a??={...buildCallbackContext(),toolName:r.toolName},o={};for(let[e,n]of Object.entries(i)){let i=typeof n==`function`?await n(getContext()):await n;try{o[e]=parseJsonValue(i)}catch{throw Error(`Connection "${r.connection.connectionName}" provided argument "${e}" must resolve to a JSON-serializable value.`)}}return{...r.args,...o}}function omitProvidedArgumentsFromSchema(t,n){if(n.length===0)return t;let r=new Set(n),i={...t};return isObject(t.properties)&&(i.properties=Object.fromEntries(Object.entries(t.properties).filter(([e])=>!r.has(e)))),Array.isArray(t.required)&&(i.required=t.required.filter(e=>typeof e!=`string`||!r.has(e))),i}export{omitProvidedArgumentsFromSchema,resolveProvidedArguments};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage,loadContext}from"#context/container.js";import{consumeAuthorizationResult,
|
|
1
|
+
import{contextStorage,loadContext}from"#context/container.js";import{consumeAuthorizationResult,createAuthorizationAttempt,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES=new Set([`127.0.0.1`,`[::1]`]);async function resolveScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore(),o=resolveConnectionPrincipal(n,r,a);if(a===void 0)return await r.getToken({connection:i,principal:o});let u=principalKey(o),d=readCachedToken(a,n,u);if(d!==void 0)return d;let f=await r.getToken({connection:i,principal:o});return writeCachedToken(a,n,u,f),f}async function evictScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore();if(a===void 0)return;let s;try{s=resolveConnectionPrincipal(n,r,a),evictCachedToken(a,n,principalKey(s))}catch{return}try{await r.evict?.({connection:i,principal:s})}catch{}}async function completeScopedAuthorization(e){let{scope:r,authorization:i,connection:o}=e;if(!supportsInteractiveAuthorization(i))return!1;let s=consumeAuthorizationResult(r);if(s===void 0)return!1;let u=i,d=loadContext(),f=s.principal??resolveConnectionPrincipal(r,u,d),p=await u.completeAuthorization({callbackUrl:s.hookUrl,connection:o,principal:f,resume:s.resume,callback:s.callback});return writeCachedToken(d,r,principalKey(f),p),!0}async function startScopedAuthorization(e){let{scope:t,authorization:n,connection:o}=e;if(!supportsInteractiveAuthorization(n))return;let s=createAuthorizationAttempt(t);if(s===void 0)return;let c=n,l=resolveConnectionPrincipal(t,c),u=resolveAuthorizationCallbackUrl({authorization:n,callbackUrl:s.hookUrl}),{challenge:d,resume:f}=await c.startAuthorization({callbackUrl:u,connection:o,principal:l});return requestAuthorization([{attemptId:s.attemptId,challenge:stampChallengeDisplayName(d,n),hookUrl:u,name:t,principal:l,resume:f}])}function resolveAuthorizationCallbackUrl(e){if(e.authorization.vercelConnect===void 0)return e.callbackUrl;let t;try{t=new URL(e.callbackUrl)}catch{return e.callbackUrl}return t.protocol!==`http:`||!LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES.has(t.hostname)?e.callbackUrl:(t.hostname=`localhost`,t.toString())}function stampChallengeDisplayName(e,t){let n=t.displayName??e.displayName;return n===e.displayName?e:{...e,displayName:n}}export{completeScopedAuthorization,evictScopedToken,resolveAuthorizationCallbackUrl,resolveScopedToken,stampChallengeDisplayName,startScopedAuthorization};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{consumeAuthorizationResult,
|
|
2
|
-
`));d.sort((e,t)=>t.score-e.score);let _=d.slice(0,o).map(e=>e.item);if(_.length>0){let e=[..._,...f],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of _)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return p.map(e=>f.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}const connectionSearchDynamicDefinition=defineDynamic({events:{"step.started":async(e,t)=>{let n=loadContext().get(ConnectionRegistryKey);if(!n||n.getConnections().length===0)return null;let i=n.getConnections().map(e=>e.connectionName),o=extractDiscoveredTools(t.messages),s=loadContext().get(ConnectionSearchResultsKey)??[],c=new Map;for(let e of s)e.qualifiedName&&c.set(e.qualifiedName,e);for(let e of o)e.qualifiedName&&c.set(e.qualifiedName,e);let l=[...c.values()],u={};u.connection_search=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${i.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,execute:async e=>await __eve_dynamic_exec_0({},e),__executeStepFn:__eve_dynamic_exec_0,__closureVars:{},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});for(let e of l){let r=e.connection,i=e.tool,a=n.getConnectionApproval(r);u[qualifiedConnectionToolName(r,i)]=defineTool({description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:a,outputSchema:e.outputSchema,execute:async(e,n)=>await __eve_dynamic_exec_1({ctx:t,connectionName:r,toolName:i},e,n),__executeStepFn:__eve_dynamic_exec_1,__closureVars:{ctx:t,connectionName:r,toolName:i}})}return u}}});async function __eve_dynamic_exec_0(e,t){return executeConnectionSearch(t)}async function __eve_dynamic_exec_1(e,t,n){let{ctx:i,connectionName:s,toolName:d}=e,f=loadContext().get(ConnectionRegistryKey),p=f.getConnections().find(e=>e.connectionName===s),m=await resolveInteractiveAuth(f,s),_=!1;if(m){let e=consumeAuthorizationResult(s);if(e){_=!0;let t=loadContext(),n=resolveConnectionPrincipal(s,m),i=await m.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:p?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,s,principalKey(n),i)}}try{return await f.getClient(s).executeTool(d,t,{abortSignal:n.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!m)throw e;if(_)throw new ConnectionAuthorizationFailedError(s,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${s}" rejected the token immediately after authorization.`});let t=
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{consumeAuthorizationResult,createAuthorizationAttempt,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{defineDynamic,defineTool}from"#public/definitions/tool.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";var __eveStepRegistrySym=Symbol.for(`@workflow/core//registeredSteps`);globalThis[__eveStepRegistrySym]||(globalThis[__eveStepRegistrySym]=new Map);var __eveStepRegistry=globalThis[__eveStepRegistrySym];const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=z.strictObject({connection:z.string().describe(`Optional: limit search to a specific connection name.`).optional(),keywords:z.string().describe(`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`),limit:z.number().describe(`Max results to return. Default 10.`).optional()}),connectionSchema=z.looseObject({}),CONNECTION_SEARCH_RESULT_ITEM_SCHEMA=z.strictObject({connection:z.string(),description:z.string(),error:z.string().optional(),inputSchema:connectionSchema.optional(),needsAuthorization:z.boolean().optional(),outputSchema:connectionSchema.optional(),qualifiedName:z.string().optional(),tool:z.string().optional()}),CONNECTION_SEARCH_OUTPUT_SCHEMA=z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e,t){let n=loadContext(),i=new Set;for(let r of t){let t=consumeAuthorizationResult(r.connectionName);if(!t)continue;let a=await resolveInteractiveAuth(e,r.connectionName);if(!a)continue;let o=t.principal??resolveConnectionPrincipal(r.connectionName,a),s=await a.completeAuthorization({callbackUrl:t.hookUrl,connection:{url:r.url??``},principal:o,resume:t.resume,callback:t.callback});writeCachedToken(n,r.connectionName,principalKey(o),s),i.add(r.connectionName)}return i}async function executeConnectionSearch(e){let t=loadContext(),i=t.get(ConnectionRegistryKey);if(i===void 0)return[];let o=e.limit??10,l=tokenize(e.keywords),d=[],f=[],p=e.connection!==void 0&&e.connection!==``?i.getConnections().filter(t=>t.connectionName===e.connection):i.getConnections();if(e.connection&&p.length===0)throw Error(`Connection "${e.connection}" is not registered. Available connections: ${i.getConnectionNames().join(`, `)}.`);let m=await completePendingAuthorizations(i,p),h=[];for(let e of p){let t;try{t=await i.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(m.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),f.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(i,e.connectionName);if(t){let r=createAuthorizationAttempt(e.connectionName);if(r){let i=resolveConnectionPrincipal(e.connectionName,t),a=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:r.hookUrl});try{let{challenge:n,resume:o}=await t.startAuthorization({callbackUrl:a,connection:{url:e.url??``},principal:i});h.push({attemptId:r.attemptId,name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:a,principal:i,resume:o})}catch(t){let r=toError(t);logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:r}),f.push({connection:e.connectionName,description:e.description,error:`Failed to start authorization for "${e.connectionName}": ${r.message}`});continue}}}f.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),f.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let r=toError(t);logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:r}),f.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${r.message}`});continue}for(let n of t){let t=scoreMatch(l,n);t>0&&d.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(h.length>0)return requestAuthorization(h);let g=f.filter(e=>e.error!==void 0);if(p.length>0&&g.length===p.length)throw Error(g.map(e=>e.error).join(`
|
|
2
|
+
`));d.sort((e,t)=>t.score-e.score);let _=d.slice(0,o).map(e=>e.item);if(_.length>0){let e=[..._,...f],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of _)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return p.map(e=>f.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}const connectionSearchDynamicDefinition=defineDynamic({events:{"step.started":async(e,t)=>{let n=loadContext().get(ConnectionRegistryKey);if(!n||n.getConnections().length===0)return null;let i=n.getConnections().map(e=>e.connectionName),o=extractDiscoveredTools(t.messages),s=loadContext().get(ConnectionSearchResultsKey)??[],c=new Map;for(let e of s)e.qualifiedName&&c.set(e.qualifiedName,e);for(let e of o)e.qualifiedName&&c.set(e.qualifiedName,e);let l=[...c.values()],u={};u.connection_search=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${i.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,execute:async e=>await __eve_dynamic_exec_0({},e),__executeStepFn:__eve_dynamic_exec_0,__closureVars:{},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});for(let e of l){let r=e.connection,i=e.tool,a=n.getConnectionApproval(r);u[qualifiedConnectionToolName(r,i)]=defineTool({description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:a,outputSchema:e.outputSchema,execute:async(e,n)=>await __eve_dynamic_exec_1({ctx:t,connectionName:r,toolName:i},e,n),__executeStepFn:__eve_dynamic_exec_1,__closureVars:{ctx:t,connectionName:r,toolName:i}})}return u}}});async function __eve_dynamic_exec_0(e,t){return executeConnectionSearch(t)}async function __eve_dynamic_exec_1(e,t,n){let{ctx:i,connectionName:s,toolName:d}=e,f=loadContext().get(ConnectionRegistryKey),p=f.getConnections().find(e=>e.connectionName===s),m=await resolveInteractiveAuth(f,s),_=!1;if(m){let e=consumeAuthorizationResult(s);if(e){_=!0;let t=loadContext(),n=e.principal??resolveConnectionPrincipal(s,m),i=await m.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:p?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,s,principalKey(n),i)}}try{return await f.getClient(s).executeTool(d,t,{abortSignal:n.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!m)throw e;if(_)throw new ConnectionAuthorizationFailedError(s,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${s}" rejected the token immediately after authorization.`});let t=createAuthorizationAttempt(s);if(!t)throw e;let n=resolveConnectionPrincipal(s,m),r=resolveAuthorizationCallbackUrl({authorization:m,callbackUrl:t.hookUrl}),{challenge:i,resume:a}=await m.startAuthorization({callbackUrl:r,connection:{url:p?.url??``},principal:n});return requestAuthorization([{attemptId:t.attemptId,name:s,challenge:stampChallengeDisplayName(i,m),hookUrl:r,principal:n,resume:a}])}}__eve_dynamic_exec_0.stepId=`eve:dynamic-tool//__eve_dynamic_exec_0`,__eveStepRegistry.set(`eve:dynamic-tool//__eve_dynamic_exec_0`,__eve_dynamic_exec_0),__eve_dynamic_exec_1.stepId=`eve:dynamic-tool//__eve_dynamic_exec_1`,__eveStepRegistry.set(`eve:dynamic-tool//__eve_dynamic_exec_1`,__eve_dynamic_exec_1);export{connectionSearchDynamicDefinition as default,extractDiscoveredTools};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{z}from"#compiled/zod/index.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{TODO_COMPACTION_PRESERVATION_LABEL}from"#harness/compaction-prompt.js";const TodoStateKey=new ContextKey(`eve.todo`);function formatTodoSummary(e){return e.items.length===0?void 0:`${TODO_COMPACTION_PRESERVATION_LABEL}\n${e.items.map(e=>`- [${e.status===`completed`?`x`:e.status===`cancelled`?`-`:` `}] [${e.priority}] ${e.content}`).join(`
|
|
2
|
-
`)}`}function getTodoCompactionMessage(){let e=loadContext().get(TodoStateKey);if(e===void 0
|
|
2
|
+
`)}`}function getTodoCompactionMessage(){let e=loadContext().get(TodoStateKey);if(e===void 0||!e.items.some(e=>e.status===`pending`||e.status===`in_progress`))return;let n=formatTodoSummary(e);if(n!==void 0)return{content:n,role:`user`}}function formatTodoResult(e){let{items:t}=e,n={cancelled:0,completed:0,in_progress:0,pending:0,total:t.length};for(let e of t)n[e.status]++;return{counts:n,todos:t}}function executeTodoTool(e){let n=loadContext(),{todos:r}=e??{};if(r!==void 0){let e={items:[...r]};return n.set(TodoStateKey,e),formatTodoResult(e)}return formatTodoResult(n.ensure(TodoStateKey,()=>({items:[]})))}const TODO_ITEM_SCHEMA=z.strictObject({content:z.string().describe(`Brief description of the task.`),priority:z.enum([`high`,`medium`,`low`]).describe(`Priority level of the task.`),status:z.enum([`pending`,`in_progress`,`completed`,`cancelled`]).describe(`Current status of the task.`)}),TODO_INPUT_SCHEMA=z.strictObject({todos:z.array(TODO_ITEM_SCHEMA).describe(`The updated todo list. Omit to read the current list without modifying it.`).optional()}),countSchema=z.number().int().min(0),TODO_OUTPUT_SCHEMA=z.strictObject({counts:z.strictObject({cancelled:countSchema,completed:countSchema,in_progress:countSchema,pending:countSchema,total:countSchema}),todos:z.array(TODO_ITEM_SCHEMA)}),TODO_TOOL_DEFINITION={description:[`Use this tool to create and manage a structured task list for the current session.`,`This helps you track progress, organize complex tasks, and demonstrate thoroughness.`,``,`When to use:`,`- Complex multistep tasks requiring 3 or more distinct steps`,`- When the user provides multiple tasks or a numbered list`,`- After receiving new instructions, to capture requirements`,`- After completing a task, to mark it complete and add follow-ups`,``,`When NOT to use:`,`- Single, straightforward tasks that need no tracking`,`- Purely conversational or informational requests`,``,`Usage:`,"- Call with `todos` to replace the entire list (full replacement write)","- Call without `todos` to read the current list",`- Both return the full current list with status counts`,`- Mark tasks in_progress when you start, completed when done`,`- Only have ONE task in_progress at a time`].join(`
|
|
3
3
|
`),execute:async e=>executeTodoTool(e??{}),inputSchema:TODO_INPUT_SCHEMA,logicalPath:`eve:framework/todo`,name:`todo`,outputSchema:TODO_OUTPUT_SCHEMA,sourceId:`eve:todo-tool`,sourceKind:`module`};export{TODO_INPUT_SCHEMA,TODO_OUTPUT_SCHEMA,TODO_TOOL_DEFINITION,TodoStateKey,executeTodoTool,getTodoCompactionMessage};
|