eve 1.0.0-rc.4 → 1.0.0-rc.6
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 +23 -20
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/delivery.js +1 -1
- package/dist/src/channel/schedule.js +1 -1
- package/dist/src/channel/session-not-active-error.d.ts +2 -2
- package/dist/src/channel/sign-in.js +1 -1
- package/dist/src/channel/types.d.ts +6 -2
- package/dist/src/chunks/{use-eve-agent-DDcyFI0d.js → use-eve-agent-Cmg8590o.js} +3 -1
- package/dist/src/chunks/{use-eve-agent-CEu59mUQ.js → use-eve-agent-ycPyvX_c.js} +3 -1
- package/dist/src/client/session-store.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +7 -7
- package/dist/src/compiled/@vercel/agent-runs/core/content-policy.d.ts +8 -0
- package/dist/src/compiled/@vercel/agent-runs/core/types.d.ts +15 -6
- package/dist/src/compiled/@vercel/agent-runs/index.d.ts +1 -1
- package/dist/src/compiled/@vercel/agent-runs/index.js +2 -1
- package/dist/src/compiled/@vercel/agent-runs/operations.d.ts +12 -4
- package/dist/src/compiled/@vercel/agent-runs/otel.js +1 -1
- package/dist/src/compiled/@workflow/core/create-hook.d.ts +15 -0
- package/dist/src/compiled/@workflow/core/events-consumer.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/private.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/private.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime/after-terminal-write.d.ts +33 -0
- package/dist/src/compiled/@workflow/core/runtime/child-run-completion-notify.d.ts +36 -0
- package/dist/src/compiled/@workflow/core/runtime/child-run-completion.d.ts +45 -0
- package/dist/src/compiled/@workflow/core/runtime/delivery.d.ts +5 -2
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +9 -1
- package/dist/src/compiled/@workflow/core/runtime/helpers.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime/out-of-band-observation.d.ts +6 -0
- package/dist/src/compiled/@workflow/core/runtime/quickjs-runtime.d.ts +5 -2
- package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +9 -1
- package/dist/src/compiled/@workflow/core/runtime/run.d.ts +25 -2
- package/dist/src/compiled/@workflow/core/runtime/runs.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/runtime/start-hook-binding.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/runtime/start-hook-delivery.d.ts +3 -3
- package/dist/src/compiled/@workflow/core/runtime/start-hook-holder.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/runtime/start.d.ts +5 -5
- package/dist/src/compiled/@workflow/core/runtime.js +1 -1
- package/dist/src/compiled/@workflow/core/serialization/types.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/serialization.js +1 -1
- package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +9 -9
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/ansi.d.ts +57 -0
- package/dist/src/compiled/@workflow/errors/ansi.js +8 -0
- package/dist/src/compiled/@workflow/errors/index.js +3 -1
- package/dist/src/compiled/@workflow/world/index.js +1 -1
- package/dist/src/compiled/@workflow/world-local/index.d.ts +1 -0
- package/dist/src/compiled/@workflow/world-local/index.js +5 -5
- package/dist/src/compiled/@workflow/world-vercel/index.js +1 -1
- package/dist/src/compiled/_chunks/workflow/attribute-changes-CZ1IbpSN.js +6 -0
- package/dist/src/compiled/_chunks/workflow/delivery-DpGLtB6b.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{dist-BSEKQ8u2.js → dist-C3TM5_NG.js} +18 -18
- package/dist/src/compiled/_chunks/workflow/helpers-DWfdYiCu.js +1 -0
- package/dist/src/compiled/_chunks/workflow/mcp-LeXvhyIJ.js +5 -0
- package/dist/src/compiled/_chunks/workflow/private-D07opN0n.js +1 -0
- package/dist/src/compiled/_chunks/workflow/resume-hook-ZanR4XtL.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-D_ZgaSHx.js +34 -0
- package/dist/src/compiled/_chunks/workflow/serialization-BsJ0NayH.js +12 -0
- package/dist/src/compiled/_chunks/workflow/signal-exit-DlWTrAfZ.js +95 -0
- package/dist/src/compiled/_chunks/workflow/sleep-C8DQfwTV.js +1 -0
- package/dist/src/compiled/_chunks/workflow/suspension-hooks-B4vCJhLa.js +3 -0
- package/dist/src/compiled/_chunks/workflow/{token-CAXqMDzD.js → token-DJ4jrYrW.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{token-BgwBCNd5.js → token-DVg7xSMC.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{token-util-BIUPjVKe.js → token-util-6qJrYbu1.js} +1 -1
- package/dist/src/connections/errors.d.ts +5 -0
- package/dist/src/context/build-callback-context.js +1 -1
- package/dist/src/context/schedule-collection-tools.js +1 -1
- package/dist/src/definitions/frame.js +1 -1
- package/dist/src/execution/agent-sessions/context.js +1 -1
- package/dist/src/execution/agent-sessions/session.js +1 -1
- package/dist/src/execution/agent-sessions/steps.d.ts +2 -0
- package/dist/src/execution/agent-sessions/steps.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/legacy-session/interrupt-step.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/publish-session-events.d.ts +2 -3
- package/dist/src/execution/publish-session-events.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/session/entry-input.d.ts +17 -14
- package/dist/src/execution/session/entry.js +1 -1
- package/dist/src/execution/session/handoff-steps.d.ts +2 -4
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +4 -6
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/timeout-steps.js +1 -1
- package/dist/src/execution/session-inbox/address.d.ts +0 -5
- package/dist/src/execution/session-inbox/address.js +1 -1
- package/dist/src/execution/session-inbox/inbox.d.ts +7 -4
- package/dist/src/execution/session-inbox/inbox.js +1 -1
- package/dist/src/execution/session-inbox/resume.d.ts +18 -15
- package/dist/src/execution/session-inbox/resume.js +1 -1
- package/dist/src/execution/session-prewarm.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/channel-to.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +11 -16
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/extensions/git/extension/lib/connect-user-auth.js +1 -1
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/hitl/sign-ins.d.ts +3 -3
- package/dist/src/harness/hitl/sign-ins.js +1 -1
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/usage-sink.js +1 -1
- package/dist/src/instrumentation/dispatch.js +1 -1
- package/dist/src/instrumentation/lifecycle.d.ts +15 -3
- package/dist/src/instrumentation/native-events.d.ts +5 -0
- package/dist/src/instrumentation/native-events.js +1 -1
- package/dist/src/instrumentation/runtime-context.js +1 -1
- package/dist/src/instrumentation/runtime.d.ts +1 -0
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/instrumentation/scope.d.ts +12 -0
- package/dist/src/instrumentation/scope.js +1 -1
- package/dist/src/internal/application/compiled-artifacts.d.ts +5 -0
- package/dist/src/internal/application/compiled-artifacts.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-asset-import-plugin.d.ts +2 -0
- package/dist/src/internal/authored-asset-import-plugin.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +5 -1
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/authored-package-boundary.d.ts +15 -0
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/authored-package-tsconfig-paths.d.ts +2 -0
- package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
- package/dist/src/internal/authored-relative-extension-resolver.d.ts +2 -0
- package/dist/src/internal/authored-relative-extension-resolver.js +1 -1
- package/dist/src/internal/authored-runtime-modules.d.ts +4 -0
- package/dist/src/internal/authored-runtime-modules.js +1 -1
- package/dist/src/internal/bundler/authored-plugins.d.ts +6 -0
- package/dist/src/internal/bundler/authored-plugins.js +1 -1
- package/dist/src/internal/host-traced-dependencies.d.ts +16 -0
- package/dist/src/internal/host-traced-dependencies.js +1 -0
- package/dist/src/internal/installed-packages.d.ts +14 -0
- package/dist/src/internal/installed-packages.js +1 -0
- package/dist/src/internal/nitro/host/create-host-nitro.js +1 -1
- package/dist/src/internal/nitro/host/externals-policy.js +1 -1
- package/dist/src/internal/nitro/host/host-plugins.d.ts +2 -0
- package/dist/src/internal/nitro/host/host-plugins.js +1 -1
- package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
- package/dist/src/internal/workflow/development-world-client.js +1 -1
- package/dist/src/internal/workflow/development-world-server.js +1 -1
- package/dist/src/internal/workflow/local-world-delivery-auth.js +1 -1
- package/dist/src/internal/workflow/local-world-recovery.d.ts +23 -0
- package/dist/src/internal/workflow/local-world-recovery.js +1 -0
- package/dist/src/internal/workflow/start-claim.d.ts +16 -0
- package/dist/src/internal/workflow/start-claim.js +1 -0
- package/dist/src/internal/workflow-bundle/workflow-core-shim.d.ts +3 -7
- package/dist/src/internal/workflow-bundle/workflow-core-shim.js +1 -1
- package/dist/src/models/auto.d.ts +5 -8
- package/dist/src/models/auto.js +2 -2
- package/dist/src/models/options.d.ts +33 -0
- package/dist/src/models/options.js +1 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
- package/dist/src/public/channels/slack/connections.js +1 -1
- package/dist/src/public/channels/slack/sign-in-cancel.js +1 -1
- package/dist/src/public/channels/slack/task-card.js +1 -1
- package/dist/src/public/experimental/schedules/client.js +1 -1
- package/dist/src/public/schedules/providers/vercel.js +1 -1
- package/dist/src/public/schedules/subscription.d.ts +1 -1
- package/dist/src/public/tools/agent.d.ts +49 -7
- package/dist/src/public/tools/agent.js +2 -1
- package/dist/src/runtime/agent/resolve-model.js +1 -1
- package/dist/src/runtime/connections/events/owner.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/resolve-sandbox.js +1 -1
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/schedules/collection-client.js +1 -1
- package/dist/src/runtime/subagents/workflow.d.ts +9 -5
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +5 -0
- package/dist/src/subagents/parent-notification.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/agent-models.d.ts +7 -0
- package/dist/src/tools/agent-models.js +1 -0
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tracing/eve/agent-approval-instrumentation.d.ts +7 -2
- package/dist/src/tracing/eve/agent-approval-instrumentation.js +1 -1
- package/dist/src/tracing/eve/agent-memory-instrumentation.js +1 -1
- package/dist/src/tracing/eve/agent-otel-provider.js +1 -1
- package/dist/src/tracing/eve/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/eve/policy.js +1 -1
- package/dist/src/tracing/eve/session.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/custom.mdx +1 -1
- package/docs/channels/eve.mdx +5 -6
- package/docs/code-extension.mdx +5 -5
- package/docs/concepts/built-in-tools.md +19 -6
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/connections/index.mdx +4 -0
- package/docs/experimental/dynamic-schedules.mdx +8 -12
- package/docs/guides/client/messages.mdx +2 -2
- package/docs/guides/deployment/workflow-worlds.md +5 -1
- package/docs/guides/frontend/use-eve-agent/index.mdx +2 -2
- package/docs/guides/instrumentation/instrumentation.mdx +10 -10
- package/docs/guides/instrumentation/otel.mdx +5 -3
- package/docs/guides/upgrade/clients.md +1 -1
- package/docs/reference/cli/index.md +1 -1
- package/docs/subagents/index.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +2 -0
- package/docs/tools/workflows.mdx +6 -2
- package/package.json +5 -5
- package/dist/src/compiled/_chunks/workflow/attribute-changes-AOnel6r3.js +0 -6
- package/dist/src/compiled/_chunks/workflow/delivery-DS_fO4NK.js +0 -1
- package/dist/src/compiled/_chunks/workflow/dist-C32arEh7.js +0 -3
- package/dist/src/compiled/_chunks/workflow/helpers-9AgMPjGd.js +0 -1
- package/dist/src/compiled/_chunks/workflow/mcp-DyzJqSIB.js +0 -5
- package/dist/src/compiled/_chunks/workflow/private-CPx_GgTs.js +0 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-XRKdnxa4.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-CfkXT03M.js +0 -32
- package/dist/src/compiled/_chunks/workflow/serialization-bMKNKGL1.js +0 -15
- package/dist/src/compiled/_chunks/workflow/sleep-rBxEVIeO.js +0 -1
- package/dist/src/compiled/_chunks/workflow/suspension-hooks-RNPAbmnS.js +0 -5
- package/dist/src/compiled/_chunks/workflow/undici-DKqj707r.js +0 -95
- package/dist/src/compiled/_chunks/workflow/wait-until-RI3P9oYt.js +0 -1
- package/dist/src/execution/session-inbox/release-step.d.ts +0 -5
- package/dist/src/execution/session-inbox/release-step.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,30 +1,33 @@
|
|
|
1
|
-
# eve 1.0.0-rc.
|
|
1
|
+
# eve 1.0.0-rc.6
|
|
2
2
|
|
|
3
|
-
Released 2026-11-
|
|
3
|
+
Released 2026-11-05 · [Compare with 1.0.0-rc.5](https://github.com/vercel/eve/compare/eve%401.0.0-rc.5...eve%401.0.0-rc.6)
|
|
4
4
|
|
|
5
5
|
## Breaking Changes
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
`
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`
|
|
12
|
-
|
|
13
|
-
A
|
|
14
|
-
`
|
|
15
|
-
eve no longer adds a "Tool execution" note about parallel tool calls to every agent's system prompt. Tool calls in one response still run in parallel. Without the note, Sonnet 5.5 solved a concurrency task in 93% of replayed eve-code runs instead of 75%, matching how pi, which runs tool calls in parallel without telling the model, performs.
|
|
16
|
-
Thanks @badlogic for pi, whose MIT-licensed `edit` tool `edit_file` adapts. ([#5892](https://github.com/vercel/eve/pull/5892))
|
|
7
|
+
- Replace `agentWithModel` with `agent({ models })` from `eve/tools/agent`, which lists the models a root-copy task may run on.
|
|
8
|
+
`agentWithModel` let the model pass any AI Gateway model ID and did not tell it which models exist. `agent({ models })` takes the same entries as `auto()` from `eve/models`: a string entry is the description, and its key is the AI Gateway model ID; an object entry holds an AI Gateway model ID or an AI SDK model, with its description and optional `reasoning`, `modelContextWindowTokens`, and `modelOptions`. The model sees each key with its description and can choose only those keys. A call without `model` runs on the current model, and `agent()` with no `models` is the default tool, with no `model` input. A task keeps the model it started with, so a continuation can omit `model`. Copies and declared subagents never get this tool.
|
|
9
|
+
To migrate, replace `export { agentWithModel as default } from "eve/tools/agent"` with `export default agent({ models: { "<gateway-model-id>": "<when to use it>" } })`. `agent` is now this function; re-export `default` from `eve/tools/agent` to keep the default tool object. ([#5959](https://github.com/vercel/eve/pull/5959))
|
|
10
|
+
- New sessions now claim an address as they start, so racing first messages to a channel address reach one session, keyed sends and `create()` respond without waiting for the session to boot, and a session accepts commands as soon as it is created.
|
|
11
|
+
Previously, two unkeyed first messages to the same new address could each get a receipt naming a different session: the losing run forwarded its message and exited, but its caller kept the dead session's ID. A cancel or `end()` sent by session ID before the session finished booting was answered with "no active turn" or "no active session" while the session kept running, and an early send had to retry `409 session_not_ready`. A send by session ID to a session that is shutting down now gets `409 session_not_active` at once instead of `session_not_ready` retries.
|
|
12
|
+
eve now requires a Workflow world with atomic start hooks: the local world, Vercel Workflow, or `@workflow/world-postgres` 5.1.1 or later. On another world, starting a session fails with an error that names the requirement. Upgrade `@workflow/world-postgres` and run its `bootstrap` command before deploying this release.
|
|
13
|
+
A session can no longer move to this release from an owner on eve before 0.83, which released its addresses before handing off. Finish or end those sessions before upgrading.
|
|
14
|
+
`useEveAgent` and the other framework bindings now send `end()`, `clear()`, and `compact()` called while the store is still creating its session to that session, instead of throwing `SessionNotActiveError`. ([#5948](https://github.com/vercel/eve/pull/5948))
|
|
17
15
|
|
|
18
16
|
## Features
|
|
19
17
|
|
|
20
|
-
-
|
|
21
|
-
- `
|
|
18
|
+
- Record an `agent.approval` span for every wait on a person, including questions, budget prompts, and connection sign-ins, not just tool approvals.
|
|
19
|
+
`agent.approval.kind` is `tool-approval`, `question`, `budget`, or `sign-in`. A wait sits under the tool call it's about, or under the turn when no call owns it, and a sign-in names its connection in `eve.connection.name`. Instrumentation providers now receive sign-ins on `interaction.opened` and `interaction.settled`, with `signIn.name` naming the connection or tool; the sign-in URL and code stay out of the event. Questions and sign-ins from workflow tools such as `ask_question` now reach providers too, reported by the session that owns the tool call; a request a subagent asks is still reported once, by that session. `@vercel/agent-runs` adds `TurnOperation.approval` and `findApproval`, and an optional `kind` and `connectionName` on approvals. ([#6004](https://github.com/vercel/eve/pull/6004))
|
|
22
20
|
|
|
23
21
|
## Bug Fixes
|
|
24
22
|
|
|
25
|
-
-
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
23
|
+
- A cancelled sign-in is no longer asked for again in the same turn, and a scheduled run never asks for a sign-in.
|
|
24
|
+
When a new message cancels an open sign-in, later calls in that turn that need the same grant fail with `reason: "sign_in_cancelled"` instead of posting another sign-in prompt. A turn a schedule started, including a scheduled send into an existing conversation, fails calls that need a sign-in with `reason: "sign_in_unavailable"`. In both cases the model is told to say the action needs that access. A later message from the person asks again. ([#6003](https://github.com/vercel/eve/pull/6003))
|
|
25
|
+
- Reword the GitHub sign-in failure message so it says plainly that the person does not have access yet and how to get it. ([#5998](https://github.com/vercel/eve/pull/5998))
|
|
26
|
+
- Allow dynamic schedules on Vercel preview and custom-environment deployments instead of rejecting operations outside production.
|
|
27
|
+
The default Vercel provider uses the deployment's OIDC credentials to access its own schedule track. Preview schedules remain separate from production schedules. ([#5946](https://github.com/vercel/eve/pull/5946))
|
|
28
|
+
- Report a sign-in the runtime cancelled (withdrawn, interrupted, or abandoned) as "sign-in cancelled" in Slack and other channels, instead of a red error with the internal reason code, such as `(turn-cancelled)`.
|
|
29
|
+
The GitHub sign-in's failure message now tells the person how to retry. ([#5994](https://github.com/vercel/eve/pull/5994))
|
|
30
|
+
- Remove a Slack sign-in prompt when its Cancel button is clicked after the held turn has already ended, and log when Slack refuses to delete the prompt. ([#5995](https://github.com/vercel/eve/pull/5995))
|
|
31
|
+
- Drop the redundant "Only you can see this message" from the Slack sign-in card; Slack already labels ephemeral messages "Only visible to you". ([#6002](https://github.com/vercel/eve/pull/6002))
|
|
32
|
+
|
|
33
|
+
For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%401.0.0-rc.6/packages/eve/CHANGELOG.md).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSession,sessionCallbackToTurnCaller}from"#channel/session.js";import{commandDelivery}from"#channel/delivery.js";import{seedChannelState}from"#channel/adapter.js";import{validateDeliveryIdempotencyKey}from"#channel/delivery-idempotency.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{normalizeSendInput,serializeFilePartsInMessage}from"#channel/send-input.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{SessionStrandedError,describeStrandedSession}from"#channel/session-stranded-error.js";import{DEFAULT_TURN_POLICY,controlCommand}from"#channel/types.js";import{isReservedSessionCommandToken}from"#execution/session-inbox/address.js";import{validateSessionHistory}from"#shared/session-history.js";function createChannelAddress(e){let t=e.metadata??{},n=`${e.channelName}:${e.continuationToken}`;if(isReservedSessionCommandToken(n))throw Error(`Channel address "${n}" uses eve's reserved session namespace.`);return{continuationToken:e.continuationToken,async deliver(r,i){validateDeliveryIdempotencyKey(i.idempotencyKey);let a=createChannelDeliveryMetadata({channelKind:`channel:${e.channelName}`,channelName:e.channelName,...t}),o=withValidatedHistory(normalizeSendInput(r)),s=sessionCallbackToTurnCaller(i.callback),c={idempotencyKey:i.idempotencyKey,auth:i.auth,delivery:a,kind:`send`,payload:{...o,message:serializeFilePartsInMessage(o.message)},requestId:t.requestId,turnPolicy:o.message===void 0?void 0:i.turnPolicy??e.turnPolicy??DEFAULT_TURN_POLICY},
|
|
1
|
+
import{createSession,sessionCallbackToTurnCaller}from"#channel/session.js";import{commandDelivery}from"#channel/delivery.js";import{seedChannelState}from"#channel/adapter.js";import{validateDeliveryIdempotencyKey}from"#channel/delivery-idempotency.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{normalizeSendInput,serializeFilePartsInMessage}from"#channel/send-input.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{SessionStrandedError,describeStrandedSession}from"#channel/session-stranded-error.js";import{DEFAULT_TURN_POLICY,controlCommand}from"#channel/types.js";import{isReservedSessionCommandToken}from"#execution/session-inbox/address.js";import{contextStorage}from"#context/container.js";import{readSessionSchedule}from"#context/session-schedule.js";import{validateSessionHistory}from"#shared/session-history.js";function createChannelAddress(e){let t=e.metadata??{},n=`${e.channelName}:${e.continuationToken}`;if(isReservedSessionCommandToken(n))throw Error(`Channel address "${n}" uses eve's reserved session namespace.`);return{continuationToken:e.continuationToken,async deliver(r,i){validateDeliveryIdempotencyKey(i.idempotencyKey);let a=createChannelDeliveryMetadata({channelKind:`channel:${e.channelName}`,channelName:e.channelName,...t}),o=withValidatedHistory(normalizeSendInput(r)),s=sessionCallbackToTurnCaller(i.callback),c=contextStorage.getStore(),l=c===void 0?void 0:readSessionSchedule(c),u={...l!==void 0&&{schedule:l},idempotencyKey:i.idempotencyKey,auth:i.auth,delivery:a,kind:`send`,payload:{...o,message:serializeFilePartsInMessage(o.message)},requestId:t.requestId,turnPolicy:o.message===void 0?void 0:i.turnPolicy??e.turnPolicy??DEFAULT_TURN_POLICY},d=s===void 0?u:{...u,caller:s},f=i.state,p={...e.adapter,state:seedChannelState(e.adapter.state,f)},m={idempotencyKey:i.idempotencyKey,adapter:p,auth:i.auth,capabilities:{requestInput:!0},callback:i.callback,channelName:e.channelName,continuationConflictCommand:d,continuationToken:n,delivery:a,initiatorAuth:i.initiatorAuth,input:{context:o.context,history:o.history,message:serializeFilePartsInMessage(o.message)??``,outputSchema:o.outputSchema,state:o.state},requestId:t.requestId,title:i.title},h=await e.runtime.dispatchContinuation({command:d,continuationToken:n,successor:m});if(h.status===`accepted`)return commandDelivery(e.runtime,h,a.deliveryId);if(o.answers&&o.answers.length>0)throw new SessionNotActiveError;let g=await e.runtime.createSession(m);return commandDelivery(e.runtime,{status:`accepted`,sessionId:g.sessionId},a.deliveryId)},async create(r){let i=validateSessionHistory(r.history),toSession=n=>createSession(n,e.runtime,{...t,turnPolicy:e.turnPolicy}),a;try{a=await e.runtime.resolveContinuation(n,{runnable:!0})}catch(e){throw SessionStrandedError.is(e)?new SessionStrandedError(e.owner,describeStrandedSession(e.owner,`Call end() on the address, then create() again to start a session from your history.`)):e}if(a!==void 0)return{created:!1,session:toSession(a.sessionId)};let o=r.state,s=await e.runtime.createSession({adapter:{...e.adapter,state:seedChannelState(e.adapter.state,o)},auth:r.auth,capabilities:{requestInput:!0},channelName:e.channelName,continuationToken:n,initiatorAuth:r.initiatorAuth,input:i===void 0?{}:{history:i},requestId:t.requestId,title:r.title});return{created:s.claimedContinuation!==!1,session:toSession(s.sessionId)}},async send(e,t){return await this.deliver({message:e},t)},async respond(e,t){if(e===void 0||e.length===0)throw Error(`respond() requires at least one answer.`);return await this.deliver({answers:e},t)},async cancel(t){let r=controlCommand({kind:`cancel`,turnId:t?.turnId},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async compact(t){let r=controlCommand({kind:`compact`},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async clear(t){let r=controlCommand({kind:`clear`},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId)},async end(t){let r=controlCommand({kind:`reset`,reason:t?.reason},t),i=await e.runtime.dispatchContinuation({command:r,continuationToken:n});return commandDelivery(e.runtime,i,r.deliveryId,{follow:!1})},async resolveSession(){let r=await e.runtime.resolveContinuation(n);return r===void 0?void 0:createSession(r.sessionId,e.runtime,{...t,turnPolicy:e.turnPolicy})}}}function createChannelAddressFn(e){return t=>createChannelAddress({...e,continuationToken:t})}function withValidatedHistory(e){let{history:t,...n}=e,r=validateSessionHistory(t);return r===void 0?n:{...n,history:r}}export{createChannelAddress,createChannelAddressFn};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{StreamDelivery}from"#client/delivery.js";import{deliveryEvents}from"#client/delivery-events.js";function commandDelivery(e,t,n,r={}){if(t.status!==`accepted`&&t.status!==`reset`)throw new SessionNotActiveError
|
|
1
|
+
import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{StreamDelivery}from"#client/delivery.js";import{deliveryEvents}from"#client/delivery-events.js";function commandDelivery(e,t,n,r={}){if(t.status!==`accepted`&&t.status!==`reset`)throw new SessionNotActiveError;let i=t.status===`reset`?t.previousSessionId:t.sessionId;return new StreamDelivery({inbox:`inbox`in t?t.inbox:void 0,sessionId:i,deliveryId:n,createStream:async function*(t){yield*deliveryEvents(await e.getEventStream(i,{...r,signal:t?.signal}),n,t?.signal)}})}export{commandDelivery};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,randomUUID}from"node:crypto";import{commandDelivery}from"#channel/delivery.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{scheduleDisplayName}from"#runtime/schedules/record.js";import{SCHEDULE_APP_AUTH,SCHEDULE_APP_AUTH as SCHEDULE_APP_AUTH$1}from"#channel/schedule-auth.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";import{commandDelivery}from"#channel/delivery.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{ContextContainer,contextStorage}from"#context/container.js";import{scheduleDisplayName}from"#runtime/schedules/record.js";import{SCHEDULE_APP_AUTH,SCHEDULE_APP_AUTH as SCHEDULE_APP_AUTH$1}from"#channel/schedule-auth.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{AuthKey,OccurrenceIdKey,ScheduleIdKey,ScheduleInstanceKey}from"#context/keys.js";import{expectFunction}from"#internal/authored-module.js";import{parseSchedulePayload,validateSchedulePayload}from"#runtime/schedules/payload.js";const SCHEDULE_ADAPTER_KIND=`schedule`,SCHEDULE_ADAPTER={kind:SCHEDULE_ADAPTER_KIND};var ScheduleDispatcher=class{runtime;channels;constructor(e){this.runtime=e.runtime,this.channels=e.channels}async trigger(e){let t=new ContextContainer;return t.set(ScheduleIdKey,e.scheduleId),await contextStorage.run(t,()=>this.triggerInScope(e))}async triggerCollection(e){let{envelope:t}=parseSchedulePayload(e.payload,{application:e.payload.eve.application,collection:e.collectionId}),{definition:n}=e,r={...e.occurrence,displayName:scheduleDisplayName(e.occurrence.name)},i=n.preparePayload===void 0?await validateSchedulePayload(n.inputSchema,t.payload):t.payload;await e.verifyDelivery?.();let a=await n.auth({principal:t.principal,payload:i,occurrence:r});if(a===null)throw Error(`Scheduled execution is no longer authorized.`);if(a.principalId!==t.principal.principalId||a.principalType!==t.principal.type||a.authenticator!==t.principal.authenticator||a.issuer!==t.principal.issuer||a.subject!==t.principal.subject)throw Error(`Scheduled execution auth must resolve the schedule creator.`);let o=a,s=new ContextContainer;s.set(ScheduleIdKey,e.collectionId),s.set(AuthKey,o),s.set(OccurrenceIdKey,r.executionId),s.set(ScheduleInstanceKey,r.name);let scheduledToken=(e,t)=>t===void 0?`eve-scheduled-send:${randomUUID()}`:`eve-scheduled-send:${createHash(`sha256`).update(JSON.stringify([r.scheduleId,e,t])).digest(`hex`)}`,freshRun=e=>({...e,auth:o,initiatorAuth:o,capabilities:{requestInput:!1},continuationToken:scheduledToken(e.continuationToken,e.idempotencyKey),continuationConflictCommand:e.idempotencyKey===void 0?void 0:e.continuationConflictCommand});return await contextStorage.run(s,async()=>{let e={...this.runtime,resolveContinuation:async()=>void 0,dispatchContinuation:async e=>{if(e.command.kind!==`send`)throw Error(`Scheduled channel receive can only start a fresh session.`);return{status:`session_not_active`}},createSession:async e=>await this.runtime.createSession(freshRun(e))},{args:t,sessions:a,waitUntilTasks:s}=this.createHandlerContext(e);return await n.run({payload:i,occurrence:r,auth:o,to:(e,n)=>({send:(r,i)=>t.to(e,n).send(r,{...i,auth:o})}),waitUntil:t.waitUntil}),await Promise.all(s),{sessions:a,waitUntilTasks:s}})}async triggerInScope(e){let{args:t,sessions:n,waitUntilTasks:r}=this.createHandlerContext();if(e.run)await e.run(t);else if(e.markdown!==void 0)n.push(await this.runMarkdown(e.markdown));else throw Error(`Schedule "${e.scheduleId}" has neither "run" nor "markdown" — at least one must be set.`);return{sessions:n,waitUntilTasks:r}}createHandlerContext(e=this.runtime){let t=[],n=[],r=createCrossChannelToFn(e,toCrossChannelTargets(this.channels),{acceptedDeploymentId:process.env.VERCEL_DEPLOYMENT_ID?.trim()||void 0});return{args:{appAuth:SCHEDULE_APP_AUTH$1,to(e,n){let i=r(e,n);return{async send(e,n){let r=await i.send(e,n);return t.push(r),r}}},waitUntil(e){n.push(e)}},sessions:t,waitUntilTasks:n}}async runMarkdown(e){let t=createChannelDeliveryMetadata({channelKind:`schedule`,channelName:`schedule`}),n=await this.runtime.createSession({delivery:t,adapter:SCHEDULE_ADAPTER,auth:SCHEDULE_APP_AUTH$1,input:{message:e}});return commandDelivery(this.runtime,{status:`accepted`,sessionId:n.sessionId},t.deliveryId)}};function expectScheduleRun(e,t,n){let r=e;if(typeof r!=`object`||!r)throw Error(`Schedule export "${n??`default`}" from "${t}" must be an object.`);return expectFunction(r.run,`Expected the schedule export "${n??`default`}" from "${t}" to export a \`run\` handler function.`)}export{SCHEDULE_ADAPTER,SCHEDULE_ADAPTER_KIND,SCHEDULE_APP_AUTH,ScheduleDispatcher,expectScheduleRun};
|
|
@@ -2,8 +2,8 @@ import { EveError } from "#shared/eve-error.js";
|
|
|
2
2
|
/**
|
|
3
3
|
* A session could not accept a command. No delivery was accepted.
|
|
4
4
|
*
|
|
5
|
-
* `code` is the HTTP channel's `409` code: `session_not_ready` (with `retryable: true`)
|
|
6
|
-
*
|
|
5
|
+
* `code` is the HTTP channel's `409` code: `session_not_ready` (with `retryable: true`) when a
|
|
6
|
+
* new session's address kept changing owners, otherwise `session_not_active`.
|
|
7
7
|
*/
|
|
8
8
|
export declare class SessionNotActiveError extends EveError {
|
|
9
9
|
static readonly errorName = "SessionNotActiveError";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{signInEnding}from"#protocol/session-projection/reader.js";import{interactionOwner}from"#protocol/session-projection/selectors.js";import{displayProperName}from"#protocol/session-projection/display-name.js";function signInOf(e,t){let n=e.interactions[t];if(n===void 0||n.request.kind!==`sign-in`)return;let r=n.request.signIn,i=r?.name??t,a=n.audience?.principalIds[0],o=interactionOwner(e,n).turnId;return{displayName:r?.displayName??displayProperName(i),interactionId:t,name:i,...r?.url!==void 0&&{url:r.url},...r?.userCode!==void 0&&{userCode:r.userCode},...r?.instructions!==void 0&&{instructions:r.instructions},...a!==void 0&&{principalId:a},...`responseId`in n.subject&&{responseId:n.subject.responseId},...o!==void 0&&{turnId:o}}}function signInChallengeText(e){return[`Authorization required for ${e.displayName}.`,e.instructions,e.userCode===void 0?void 0:`Code: ${e.userCode}`,e.url].filter(e=>e!==void 0&&e.length>0).join(`
|
|
2
2
|
|
|
3
|
-
`)}function signInEndedText(e){if(e.outcome===`accepted`)return`${e.displayName} connected.`;if(e.outcome===`declined`)return`${e.displayName} sign-in cancelled.`;let
|
|
3
|
+
`)}function signInEndedText(e){if(e.outcome===`accepted`)return`${e.displayName} connected.`;let t=signInEnding(e.outcome);if(e.outcome===`declined`||t===`cancelled`)return`${e.displayName} sign-in cancelled.`;let n=e.reason===void 0?``:` (${e.reason})`;return`${e.displayName} sign-in ${t}${n}.`}async function showSignIn(e,t,n){let r=signInOf(e,t);if(r===void 0||r.responseId!==void 0||n.posted.get(r.name)!==void 0)return;let i;if(n.private)i=await n.postChallenge(r);else{let e=await n.deliverPrivately?.(r)===!0;i=n.postStatus===void 0?await n.post(e?`Authorization required for ${r.displayName}. I sent you the sign-in details privately.`:`Authorization required for ${r.displayName}. Continue in a direct message with this agent.`):await n.postStatus(r,e)}n.posted.set(r.name,i??``)}async function settleSignIn(e,t,n){let r=signInOf(e,t.interactionId);if(r===void 0||r.responseId!==void 0)return;let i=n.posted.get(r.name);if(i===void 0)return;n.posted.set(r.name,void 0);let a=signInEndedText({...r,outcome:t.outcome,reason:t.reason});i!==``&&n.edit!==void 0?await n.edit(i,a):await n.post(a),t.outcome===`accepted`&&await n.typing?.(`Connected. Resuming...`)}function postedIn(e,t){return{get:n=>e[t]?.[n],set(n,r){let{[n]:i,...a}=e[t]??{};e[t]=r===void 0?a:{...a,[n]:r}}}}export{postedIn,settleSignIn,showSignIn,signInChallengeText,signInEndedText,signInOf};
|
|
@@ -203,8 +203,6 @@ export type SessionSendCommandResult = {
|
|
|
203
203
|
readonly inbox?: string;
|
|
204
204
|
} | {
|
|
205
205
|
readonly status: "session_not_active";
|
|
206
|
-
/** The workflow exists but its inbox is not yet available; no delivery was accepted. */
|
|
207
|
-
readonly retryable?: boolean;
|
|
208
206
|
};
|
|
209
207
|
/** Result of ending a session. The `"reset"` status is kept for wire compatibility. */
|
|
210
208
|
export type EndSessionResult = {
|
|
@@ -527,6 +525,12 @@ export interface RunHandle {
|
|
|
527
525
|
* key on it: workflow-backed runs expose the workflow run id.
|
|
528
526
|
*/
|
|
529
527
|
readonly sessionId: string;
|
|
528
|
+
/**
|
|
529
|
+
* For a start with a continuation token: `true` when this start's run took
|
|
530
|
+
* the address, `false` when a session already held it and `sessionId` names
|
|
531
|
+
* that session. Absent for a start without one.
|
|
532
|
+
*/
|
|
533
|
+
readonly claimedContinuation?: boolean;
|
|
530
534
|
}
|
|
531
535
|
/**
|
|
532
536
|
* Runtime interface consumed by routes and the subagent tool wrapper.
|
|
@@ -4674,9 +4674,11 @@ var SessionStore = class {
|
|
|
4674
4674
|
return this.#control((session) => session.end());
|
|
4675
4675
|
}
|
|
4676
4676
|
async #control(dispatch) {
|
|
4677
|
+
const lifetime = this.#controller;
|
|
4678
|
+
if (this.#session === void 0 && this.#creation !== void 0) await waitWithSignal(this.#creation.catch(() => void 0), lifetime.signal);
|
|
4679
|
+
throwIfAborted(lifetime.signal);
|
|
4677
4680
|
const session = this.#session;
|
|
4678
4681
|
if (session === void 0) throw new SessionNotActiveError();
|
|
4679
|
-
const lifetime = this.#controller;
|
|
4680
4682
|
this.#posting += 1;
|
|
4681
4683
|
this.#ensureStream();
|
|
4682
4684
|
this.#publish();
|
|
@@ -4673,9 +4673,11 @@ var SessionStore = class {
|
|
|
4673
4673
|
return this.#control((session) => session.end());
|
|
4674
4674
|
}
|
|
4675
4675
|
async #control(dispatch) {
|
|
4676
|
+
const lifetime = this.#controller;
|
|
4677
|
+
if (this.#session === void 0 && this.#creation !== void 0) await waitWithSignal(this.#creation.catch(() => void 0), lifetime.signal);
|
|
4678
|
+
throwIfAborted(lifetime.signal);
|
|
4676
4679
|
const session = this.#session;
|
|
4677
4680
|
if (session === void 0) throw new SessionNotActiveError();
|
|
4678
|
-
const lifetime = this.#controller;
|
|
4679
4681
|
this.#posting += 1;
|
|
4680
4682
|
this.#ensureStream();
|
|
4681
4683
|
this.#publish();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{activeTurn,failure,idle}from"#protocol/session-projection/selectors.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{StreamDelivery}from"#client/delivery.js";import{toError}from"#shared/errors.js";import{assertAnswerable,assertExclusiveTurnInput,isAbortError}from"#client/session-store-helpers.js";import{throwIfAborted}from"#client/abort-signal.js";import{Client}from"#client/client.js";import{OptimisticMessageSubmissions}from"#client/optimistic-message-submissions.js";import{ConversationClient}from"#client/conversation-client.js";import{waitWithSignal}from"#shared/wait-with-signal.js";const detachStore=Symbol(`detachSessionStore`),attachStore=Symbol(`attachSessionStore`);var SessionStore=class{#e;#t;#n;#r;#i;#a=new Set;#o=new Set;#s;#c;#l=new Set;#u=new Set;#d=!1;#f=!1;#p=0;#m=!1;#h={};#g=new AbortController;#_;#v;#y;#b;#x;#S;#C;#w;#T=!1;#E=0;#D=0;#O=new Set;#k=[];constructor(e){this.#t=e.prewarm??!1,this.#n=e.followAgents??!1,this.#r=e.followWhile??(()=>!0),this.#i=e.session!==void 0,this.#e=this.#i?void 0:e.client??new Client({auth:e.auth,headers:e.headers,baseUrl:e.baseUrl??``}),this.#s=new ConversationClient(()=>this.#Z()),this.#S=(e.initialEvents??[]).filter(e=>this.#s.hydrate(e)),this.#c=new OptimisticMessageSubmissions(e=>this.#s.showSubmissions(e),e.optimistic??!0),this.#b=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex,inbox:e.initialSession.inbox})),this.#x=this.#q(),this.#C=this.#X()}get snapshot(){return this.#C}observe(){this.#p+=1,this.#M();let e=!1;return()=>{e||(e=!0,--this.#p,!this.#f&&this.#p===0&&this.#N())}}setCallbacks(e){this.#h=e}subscribe(e){return this.#a.add(e),()=>void this.#a.delete(e)}async prewarm(){if(this.#b!==void 0)return await this.#L(this.#b);let e=this.#g;try{await this.#I()}catch(t){throw e===this.#g&&!isAbortError(t)&&this.#l.size===0&&this.#J(t),t}e===this.#g&&this.#r(this.#s.conversation.view)&&this.#z()}async send(e){if(this.#y!==void 0)throw Error(`eve session is resuming.`);assertExclusiveTurnInput(e),assertAnswerable(e,this.#s.conversation);let t=this.#g,n=e.signal?AbortSignal.any([t.signal,e.signal]):t.signal,r=Promise.withResolvers();this.#l.add(r.promise),this.#x=void 0;let i=this.#c.submit(e,e.turnPolicy===`steer`?activeTurn(this.#s.view)?.turnId:void 0),a=this.#s.projectAnswers(e.answers);this.#Z();let o=!1;try{let s=this.#h.prepareSend===void 0?e:await waitWithSignal(Promise.resolve(this.#h.prepareSend(e)),n);throwIfAborted(n),assertExclusiveTurnInput(s),s!==e&&(i=this.#c.resubmit(i,s),a=this.#s.replaceAnswers(a,s),this.#Z()),o=!0,this.#E+=1;let c=await this.#R({...s,signal:n});throwIfAborted(n);let l=c.deliveryId;if(l===void 0)throw Error(`The server did not identify the accepted delivery.`);return a?.accept(l),a=void 0,t===this.#g&&(i!==void 0&&(this.#s.confirmSubmission(i,l),this.#c.correlate(i,l)),this.#H(l),this.#h.onSessionChange?.(this.#Y)),r.resolve(l),new StreamDelivery({sessionId:c.sessionId,deliveryId:l,createStream:e=>c.stream(e)})}catch(e){throw t===this.#g&&(a?.(),this.#c.fail(toError(e),i),isAbortError(e)||this.#J(e)),e}finally{r.resolve(void 0),t===this.#g&&(this.#l.delete(r.promise),o&&--this.#E,this.#Z(),this.#G())}}follow(e){if(this.#b===void 0)throw Error(`An eve session is required before following.`);if(e.sessionId!==this.#b.id)throw Error(`The delivery belongs to a different eve session.`);let t=this.#s.view,n=t.deliveries[e.deliveryId];t.session.status!==`ended`&&n?.status!==`settled`&&(this.#x=void 0,this.#H(e.deliveryId),this.#u.has(e.deliveryId)&&this.#z(),this.#Z())}resume(){if(this.#y!==void 0)return this.#y;if(this.#b===void 0)return Promise.reject(Error(`An eve session is required before resuming.`));if(this.#l.size>0)return Promise.reject(Error(`eve session has pending submissions.`));let e=this.#g;this.#x=void 0;let t=this.#z({startIndex:this.#s.view.position}).caughtUp.then(()=>{e===this.#g&&(this.#x??=this.#q())}).finally(()=>{e===this.#g&&(this.#y=void 0,this.#Z(),this.#G())});return this.#y=t,this.#Z(!0),t}async cancel(){let e=this.#g,t=activeTurn(this.#s.view)?.turnId??await this.#A(e.signal);return throwIfAborted(e.signal),this.#j(e=>e.cancel({turnId:t??null}))}async#A(e){let t=new Set(this.#u.keys()),n=[...this.#l],r=n.length,i=Promise.withResolvers(),check=()=>{let e=this.#s.view;if(e.session.status===`ended`)return i.resolve(void 0);for(let n of t){let r=e.deliveries[n],a=r?.turnId===void 0?void 0:e.turns[r.turnId];if(a?.status===`running`)return i.resolve(a.turnId);(r?.status===`settled`||a?.status===`settled`)&&t.delete(n)}r===0&&t.size===0?i.resolve(void 0):this.#x!==void 0&&i.reject(this.#x)};this.#o.add(check);for(let e of n)e.then(e=>{--r,e!==void 0&&t.add(e),check()});try{return check(),await waitWithSignal(i.promise,e)}finally{this.#o.delete(check)}}compact(){return this.#j(e=>e.compact())}clear(){return this.#j(e=>e.clear())}end(){return this.#j(e=>e.end())}async#j(e){let t=this.#b;if(t===void 0)throw new SessionNotActiveError;let n=this.#g;this.#E+=1,this.#z(),this.#Z();try{let r=await e(t);return throwIfAborted(n.signal),this.#H(r.deliveryId),r}finally{n===this.#g&&(--this.#E,this.#Z(),this.#G())}}[attachStore](){this.#f=!0,this.#M()}#M(){if(this.#d)return;this.#d=!0,this.#B();let e=this.#m&&this.#r(this.#s.conversation.view);this.#m=!1,this.#b!==void 0&&(this.#W||e)&&this.#z(),this.#t&&this.#b===void 0&&this.prewarm().catch(()=>{})}[detachStore](){this.#f=!1,this.#p===0&&this.#N()}#N(){this.#d=!1,this.#m=this.#s.streaming,this.#P()}newSession(){this.#P(),this.#i||(this.#b=void 0),this.#u.clear(),this.#O.clear(),this.#S=[],this.#s.reset(),this.#c.reset(),this.#x=void 0,this.#d&&this.#B(),this.#h.onSessionChange?.(this.#Y),this.#Z(),this.#t&&this.#d&&this.prewarm().catch(()=>{})}#P(){this.#s.stop(),this.#g.abort(),this.#g=new AbortController,this.#_=void 0,this.#y=void 0,this.#l.clear(),this.#E=0,this.#D=0,this.#F()}#F(){this.#s.closeStream();let e=this.#S.length;for(;e>0&&this.#S[e-1].meta.endOfLine===!1;)--e;e<this.#S.length&&(this.#S=this.#S.slice(0,e)),this.#k=[],this.#T=!1}#I(e){if(this.#_!==void 0)return this.#_;let t=this.#e;if(t===void 0)return Promise.reject(Error(`This store cannot create a session.`));let n=this.#g,r=e?.signal??n.signal,i=(async()=>{let i,a;return e?.message===void 0?{session:i}=await t.sessions.create({signal:r}):{session:i,delivery:a}=await t.sessions.create({...e,message:e.message,signal:r}),throwIfAborted(n.signal),this.#b=i,this.#x=void 0,this.#h.onSessionChange?.(this.#Y),this.#B(),this.#Z(),a})();this.#_=i;let clear=()=>{this.#_===i&&(this.#_=void 0)};return i.then(clear,clear),i}#L(e){let t=this.#g;if(this.#v?.lifetime===t)return this.#v.promise;let n=e.prewarm({signal:t.signal}).then(()=>void 0),r={lifetime:t,promise:n};this.#v=r;let clear=()=>{this.#v===r&&(this.#v=void 0)};return n.then(clear,clear),n}async#R(e){if(this.#_!==void 0&&await waitWithSignal(this.#_.catch(()=>void 0),e.signal),throwIfAborted(e.signal),this.#b===void 0){if(e.message===void 0)throw Error(`Cannot answer before the session starts.`);let t=await this.#I(e);if(this.#z(e),t===void 0)throw Error(`The session was created without accepting a message.`);return t}return this.#z(e),e.answers===void 0?await this.#b.send(e.message,e):await this.#b.respond(e.answers,e)}#z(e={}){if(this.#b===void 0)throw Error(`A session is required before opening its stream.`);this.#B();let t=this.#g;return this.#s.stream(this.#b,{startIndex:this.#s.view.position,...e,onEvent:(e,n)=>{t===this.#g&&this.#V(e,n)},onError:e=>{t===this.#g&&(this.#F(),this.#J(e))}})}#B(){this.#n&&this.#b&&this.#s.follow(this.#b,this.#n)}#V(e,t){let n=this.#g;if(this.#T=e.meta.endOfLine===!1,!this.#s.observe(e,{notify:!1})||(this.#S=[...this.#S,e],this.#h.onEvent?.(e),n!==this.#g)||(e.type===`turn.started`&&!t&&(this.#x=void 0),(e.type===`turn.settled`||e.type===`session.ended`)&&this.#k.push({event:e,historical:t}),this.#T))return;let r=this.#s.view,i=new Set([...this.#u].map(e=>r.deliveries[e]?.turnId).filter(e=>e!==void 0));this.#U();for(let e of this.#k.splice(0)){if(e.event.type===`turn.settled`)e.historical?i.has(e.event.data.turnId)&&this.#l.size===0&&(this.#x??=this.#q(e.event.data.turnId)):this.#K(e.event.data.turnId);else if(e.event.data.outcome===`failed`){let t=Object.assign(Error(e.event.data.error?.message??`The session failed.`),{name:e.event.data.error?.code??`SESSION_FAILED`});e.historical?this.#l.size===0&&(this.#x??=t):this.#J(t)}if(n!==this.#g)return}for(let e of this.#o)e();this.#h.onSessionChange?.(this.#Y),n===this.#g&&(this.#Z(),n===this.#g&&(this.#s.reconcileFollowing(),n===this.#g&&this.#G()))}#H(e){this.#u.add(e),this.#U();let t=this.#s.view,n=t.deliveries[e]?.turnId;n!==void 0&&t.turns[n]?.status===`settled`&&(this.#x??=this.#q(n)),t.session.status===`ended`&&(this.#x??=this.#q())}#U(){let e=this.#s.view;e.session.status===`ended`&&this.#u.clear(),this.#c.reconcile(e);for(let t of this.#u)e.deliveries[t]?.status===`settled`&&this.#u.delete(t)}get#W(){return this.#y!==void 0||this.#E>0||this.#l.size>0||this.#u.size>0}#G(){this.#T||this.#W||this.#r(this.#s.conversation.view)||this.#s.closeStream()}#K(e){if(this.#O.has(e)||this.#s.view.turns[e]?.status!==`settled`)return;this.#O.add(e),this.#D+=1;let t=failure(this.#s.view,e);t!==void 0&&this.#J(Object.assign(Error(t.message),{name:t.code}))}#q(e=this.#s.view.session.latestTurnId){let t=this.#s.view,n=failure(t,e);return n===void 0?void 0:Object.assign(Error(n.message),{name:n.code})}#J(e){let t=this.#x!==void 0;this.#x=toError(e);for(let e of this.#o)e();t||this.#h.onError?.(this.#x),this.#Z()}get#Y(){if(this.#b===void 0)return this.#w=void 0;let e=this.#b.id,t=this.#s.view.position,{inbox:n}=this.#b.state;return(this.#w?.sessionId!==e||this.#w.streamIndex!==t||this.#w.inbox!==n)&&(this.#w={sessionId:e,streamIndex:t,inbox:n}),this.#w}#X(){this.#s.holdUnconfirmedMessages(this.#E>0&&this.#c.awaitingReceipt);let e=this.#s.conversation,{view:t}=e;return{...e,view:t,error:this.#x,events:this.#S,session:this.#Y,status:this.#y===void 0?this.#W||!idle(this.#s.view)?`busy`:`idle`:`resuming`}}#Z(e=!1){if(this.#y!==void 0&&!e)return;if(this.#T){if(this.#x===void 0&&!this.#W)return;this.#C={...this.#C,error:this.#x,status:this.#y===void 0?this.#W?`busy`:this.#C.status:`resuming`};for(let e of this.#a)e();return}this.#C=this.#X();let t=this.#D,n=this.#g;this.#D=0;for(let e of this.#a)e();for(let e=0;e<t&&n===this.#g;e+=1)this.#h.onFinish?.(this.#C)}};function detachSessionStore(e){e[detachStore]()}function attachSessionStore(e){e[attachStore]()}export{SessionStore,attachSessionStore,detachSessionStore};
|
|
1
|
+
import{activeTurn,failure,idle}from"#protocol/session-projection/selectors.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{StreamDelivery}from"#client/delivery.js";import{toError}from"#shared/errors.js";import{assertAnswerable,assertExclusiveTurnInput,isAbortError}from"#client/session-store-helpers.js";import{throwIfAborted}from"#client/abort-signal.js";import{Client}from"#client/client.js";import{OptimisticMessageSubmissions}from"#client/optimistic-message-submissions.js";import{ConversationClient}from"#client/conversation-client.js";import{waitWithSignal}from"#shared/wait-with-signal.js";const detachStore=Symbol(`detachSessionStore`),attachStore=Symbol(`attachSessionStore`);var SessionStore=class{#e;#t;#n;#r;#i;#a=new Set;#o=new Set;#s;#c;#l=new Set;#u=new Set;#d=!1;#f=!1;#p=0;#m=!1;#h={};#g=new AbortController;#_;#v;#y;#b;#x;#S;#C;#w;#T=!1;#E=0;#D=0;#O=new Set;#k=[];constructor(e){this.#t=e.prewarm??!1,this.#n=e.followAgents??!1,this.#r=e.followWhile??(()=>!0),this.#i=e.session!==void 0,this.#e=this.#i?void 0:e.client??new Client({auth:e.auth,headers:e.headers,baseUrl:e.baseUrl??``}),this.#s=new ConversationClient(()=>this.#Z()),this.#S=(e.initialEvents??[]).filter(e=>this.#s.hydrate(e)),this.#c=new OptimisticMessageSubmissions(e=>this.#s.showSubmissions(e),e.optimistic??!0),this.#b=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex,inbox:e.initialSession.inbox})),this.#x=this.#q(),this.#C=this.#X()}get snapshot(){return this.#C}observe(){this.#p+=1,this.#M();let e=!1;return()=>{e||(e=!0,--this.#p,!this.#f&&this.#p===0&&this.#N())}}setCallbacks(e){this.#h=e}subscribe(e){return this.#a.add(e),()=>void this.#a.delete(e)}async prewarm(){if(this.#b!==void 0)return await this.#L(this.#b);let e=this.#g;try{await this.#I()}catch(t){throw e===this.#g&&!isAbortError(t)&&this.#l.size===0&&this.#J(t),t}e===this.#g&&this.#r(this.#s.conversation.view)&&this.#z()}async send(e){if(this.#y!==void 0)throw Error(`eve session is resuming.`);assertExclusiveTurnInput(e),assertAnswerable(e,this.#s.conversation);let t=this.#g,n=e.signal?AbortSignal.any([t.signal,e.signal]):t.signal,r=Promise.withResolvers();this.#l.add(r.promise),this.#x=void 0;let i=this.#c.submit(e,e.turnPolicy===`steer`?activeTurn(this.#s.view)?.turnId:void 0),a=this.#s.projectAnswers(e.answers);this.#Z();let o=!1;try{let s=this.#h.prepareSend===void 0?e:await waitWithSignal(Promise.resolve(this.#h.prepareSend(e)),n);throwIfAborted(n),assertExclusiveTurnInput(s),s!==e&&(i=this.#c.resubmit(i,s),a=this.#s.replaceAnswers(a,s),this.#Z()),o=!0,this.#E+=1;let c=await this.#R({...s,signal:n});throwIfAborted(n);let l=c.deliveryId;if(l===void 0)throw Error(`The server did not identify the accepted delivery.`);return a?.accept(l),a=void 0,t===this.#g&&(i!==void 0&&(this.#s.confirmSubmission(i,l),this.#c.correlate(i,l)),this.#H(l),this.#h.onSessionChange?.(this.#Y)),r.resolve(l),new StreamDelivery({sessionId:c.sessionId,deliveryId:l,createStream:e=>c.stream(e)})}catch(e){throw t===this.#g&&(a?.(),this.#c.fail(toError(e),i),isAbortError(e)||this.#J(e)),e}finally{r.resolve(void 0),t===this.#g&&(this.#l.delete(r.promise),o&&--this.#E,this.#Z(),this.#G())}}follow(e){if(this.#b===void 0)throw Error(`An eve session is required before following.`);if(e.sessionId!==this.#b.id)throw Error(`The delivery belongs to a different eve session.`);let t=this.#s.view,n=t.deliveries[e.deliveryId];t.session.status!==`ended`&&n?.status!==`settled`&&(this.#x=void 0,this.#H(e.deliveryId),this.#u.has(e.deliveryId)&&this.#z(),this.#Z())}resume(){if(this.#y!==void 0)return this.#y;if(this.#b===void 0)return Promise.reject(Error(`An eve session is required before resuming.`));if(this.#l.size>0)return Promise.reject(Error(`eve session has pending submissions.`));let e=this.#g;this.#x=void 0;let t=this.#z({startIndex:this.#s.view.position}).caughtUp.then(()=>{e===this.#g&&(this.#x??=this.#q())}).finally(()=>{e===this.#g&&(this.#y=void 0,this.#Z(),this.#G())});return this.#y=t,this.#Z(!0),t}async cancel(){let e=this.#g,t=activeTurn(this.#s.view)?.turnId??await this.#A(e.signal);return throwIfAborted(e.signal),this.#j(e=>e.cancel({turnId:t??null}))}async#A(e){let t=new Set(this.#u.keys()),n=[...this.#l],r=n.length,i=Promise.withResolvers(),check=()=>{let e=this.#s.view;if(e.session.status===`ended`)return i.resolve(void 0);for(let n of t){let r=e.deliveries[n],a=r?.turnId===void 0?void 0:e.turns[r.turnId];if(a?.status===`running`)return i.resolve(a.turnId);(r?.status===`settled`||a?.status===`settled`)&&t.delete(n)}r===0&&t.size===0?i.resolve(void 0):this.#x!==void 0&&i.reject(this.#x)};this.#o.add(check);for(let e of n)e.then(e=>{--r,e!==void 0&&t.add(e),check()});try{return check(),await waitWithSignal(i.promise,e)}finally{this.#o.delete(check)}}compact(){return this.#j(e=>e.compact())}clear(){return this.#j(e=>e.clear())}end(){return this.#j(e=>e.end())}async#j(e){let t=this.#g;this.#b===void 0&&this.#_!==void 0&&await waitWithSignal(this.#_.catch(()=>void 0),t.signal),throwIfAborted(t.signal);let n=this.#b;if(n===void 0)throw new SessionNotActiveError;this.#E+=1,this.#z(),this.#Z();try{let r=await e(n);return throwIfAborted(t.signal),this.#H(r.deliveryId),r}finally{t===this.#g&&(--this.#E,this.#Z(),this.#G())}}[attachStore](){this.#f=!0,this.#M()}#M(){if(this.#d)return;this.#d=!0,this.#B();let e=this.#m&&this.#r(this.#s.conversation.view);this.#m=!1,this.#b!==void 0&&(this.#W||e)&&this.#z(),this.#t&&this.#b===void 0&&this.prewarm().catch(()=>{})}[detachStore](){this.#f=!1,this.#p===0&&this.#N()}#N(){this.#d=!1,this.#m=this.#s.streaming,this.#P()}newSession(){this.#P(),this.#i||(this.#b=void 0),this.#u.clear(),this.#O.clear(),this.#S=[],this.#s.reset(),this.#c.reset(),this.#x=void 0,this.#d&&this.#B(),this.#h.onSessionChange?.(this.#Y),this.#Z(),this.#t&&this.#d&&this.prewarm().catch(()=>{})}#P(){this.#s.stop(),this.#g.abort(),this.#g=new AbortController,this.#_=void 0,this.#y=void 0,this.#l.clear(),this.#E=0,this.#D=0,this.#F()}#F(){this.#s.closeStream();let e=this.#S.length;for(;e>0&&this.#S[e-1].meta.endOfLine===!1;)--e;e<this.#S.length&&(this.#S=this.#S.slice(0,e)),this.#k=[],this.#T=!1}#I(e){if(this.#_!==void 0)return this.#_;let t=this.#e;if(t===void 0)return Promise.reject(Error(`This store cannot create a session.`));let n=this.#g,r=e?.signal??n.signal,i=(async()=>{let i,a;return e?.message===void 0?{session:i}=await t.sessions.create({signal:r}):{session:i,delivery:a}=await t.sessions.create({...e,message:e.message,signal:r}),throwIfAborted(n.signal),this.#b=i,this.#x=void 0,this.#h.onSessionChange?.(this.#Y),this.#B(),this.#Z(),a})();this.#_=i;let clear=()=>{this.#_===i&&(this.#_=void 0)};return i.then(clear,clear),i}#L(e){let t=this.#g;if(this.#v?.lifetime===t)return this.#v.promise;let n=e.prewarm({signal:t.signal}).then(()=>void 0),r={lifetime:t,promise:n};this.#v=r;let clear=()=>{this.#v===r&&(this.#v=void 0)};return n.then(clear,clear),n}async#R(e){if(this.#_!==void 0&&await waitWithSignal(this.#_.catch(()=>void 0),e.signal),throwIfAborted(e.signal),this.#b===void 0){if(e.message===void 0)throw Error(`Cannot answer before the session starts.`);let t=await this.#I(e);if(this.#z(e),t===void 0)throw Error(`The session was created without accepting a message.`);return t}return this.#z(e),e.answers===void 0?await this.#b.send(e.message,e):await this.#b.respond(e.answers,e)}#z(e={}){if(this.#b===void 0)throw Error(`A session is required before opening its stream.`);this.#B();let t=this.#g;return this.#s.stream(this.#b,{startIndex:this.#s.view.position,...e,onEvent:(e,n)=>{t===this.#g&&this.#V(e,n)},onError:e=>{t===this.#g&&(this.#F(),this.#J(e))}})}#B(){this.#n&&this.#b&&this.#s.follow(this.#b,this.#n)}#V(e,t){let n=this.#g;if(this.#T=e.meta.endOfLine===!1,!this.#s.observe(e,{notify:!1})||(this.#S=[...this.#S,e],this.#h.onEvent?.(e),n!==this.#g)||(e.type===`turn.started`&&!t&&(this.#x=void 0),(e.type===`turn.settled`||e.type===`session.ended`)&&this.#k.push({event:e,historical:t}),this.#T))return;let r=this.#s.view,i=new Set([...this.#u].map(e=>r.deliveries[e]?.turnId).filter(e=>e!==void 0));this.#U();for(let e of this.#k.splice(0)){if(e.event.type===`turn.settled`)e.historical?i.has(e.event.data.turnId)&&this.#l.size===0&&(this.#x??=this.#q(e.event.data.turnId)):this.#K(e.event.data.turnId);else if(e.event.data.outcome===`failed`){let t=Object.assign(Error(e.event.data.error?.message??`The session failed.`),{name:e.event.data.error?.code??`SESSION_FAILED`});e.historical?this.#l.size===0&&(this.#x??=t):this.#J(t)}if(n!==this.#g)return}for(let e of this.#o)e();this.#h.onSessionChange?.(this.#Y),n===this.#g&&(this.#Z(),n===this.#g&&(this.#s.reconcileFollowing(),n===this.#g&&this.#G()))}#H(e){this.#u.add(e),this.#U();let t=this.#s.view,n=t.deliveries[e]?.turnId;n!==void 0&&t.turns[n]?.status===`settled`&&(this.#x??=this.#q(n)),t.session.status===`ended`&&(this.#x??=this.#q())}#U(){let e=this.#s.view;e.session.status===`ended`&&this.#u.clear(),this.#c.reconcile(e);for(let t of this.#u)e.deliveries[t]?.status===`settled`&&this.#u.delete(t)}get#W(){return this.#y!==void 0||this.#E>0||this.#l.size>0||this.#u.size>0}#G(){this.#T||this.#W||this.#r(this.#s.conversation.view)||this.#s.closeStream()}#K(e){if(this.#O.has(e)||this.#s.view.turns[e]?.status!==`settled`)return;this.#O.add(e),this.#D+=1;let t=failure(this.#s.view,e);t!==void 0&&this.#J(Object.assign(Error(t.message),{name:t.code}))}#q(e=this.#s.view.session.latestTurnId){let t=this.#s.view,n=failure(t,e);return n===void 0?void 0:Object.assign(Error(n.message),{name:n.code})}#J(e){let t=this.#x!==void 0;this.#x=toError(e);for(let e of this.#o)e();t||this.#h.onError?.(this.#x),this.#Z()}get#Y(){if(this.#b===void 0)return this.#w=void 0;let e=this.#b.id,t=this.#s.view.position,{inbox:n}=this.#b.state;return(this.#w?.sessionId!==e||this.#w.streamIndex!==t||this.#w.inbox!==n)&&(this.#w={sessionId:e,streamIndex:t,inbox:n}),this.#w}#X(){this.#s.holdUnconfirmedMessages(this.#E>0&&this.#c.awaitingReceipt);let e=this.#s.conversation,{view:t}=e;return{...e,view:t,error:this.#x,events:this.#S,session:this.#Y,status:this.#y===void 0?this.#W||!idle(this.#s.view)?`busy`:`idle`:`resuming`}}#Z(e=!1){if(this.#y!==void 0&&!e)return;if(this.#T){if(this.#x===void 0&&!this.#W)return;this.#C={...this.#C,error:this.#x,status:this.#y===void 0?this.#W?`busy`:this.#C.status:`resuming`};for(let e of this.#a)e();return}this.#C=this.#X();let t=this.#D,n=this.#g;this.#D=0;for(let e of this.#a)e();for(let e=0;e<t&&n===this.#g;e+=1)this.#h.onFinish?.(this.#C)}};function detachSessionStore(e){e[detachStore]()}function attachSessionStore(e){e[attachStore]()}export{SessionStore,attachSessionStore,detachSessionStore};
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"moduleFingerprints": {
|
|
3
3
|
"@eve/catalog": "db73624902ce0b7d60bd87892bfc7c48c946eddf576ba079a8f3b58f0b0733f1",
|
|
4
4
|
"just-secrets": "1ce67d437d0bb06df02e4e99180a3c5f5edf0010314010226e97b96d462bba5d",
|
|
5
|
-
"@vercel/agent-runs": "
|
|
6
|
-
"@workflow/world-local": "
|
|
5
|
+
"@vercel/agent-runs": "f990af4ea53f9b9963c4626e86321357e0246a0d204ff6e5c538a24571d8304b",
|
|
6
|
+
"@workflow/world-local": "37afac934e42a46ce529bcfc2dd7a00cd24bc8340dda50940bcdc48357772f39"
|
|
7
7
|
},
|
|
8
8
|
"moduleVersions": {
|
|
9
9
|
"@agentclientprotocol/sdk": "1.3.0",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"@shadcn/registry": "0.1.3",
|
|
43
43
|
"@standard-schema/spec": "1.1.0",
|
|
44
44
|
"turndown": "7.2.4",
|
|
45
|
-
"@vercel/agent-runs": "1.0.0-rc.
|
|
45
|
+
"@vercel/agent-runs": "1.0.0-rc.3",
|
|
46
46
|
"@vercel/blob": "2.8.0",
|
|
47
47
|
"@vercel/connect": "2.7.0",
|
|
48
48
|
"@vercel/detect-agent": "1.2.3",
|
|
@@ -52,16 +52,16 @@
|
|
|
52
52
|
"@vercel/sandbox": "3.9.0",
|
|
53
53
|
"@vercel/sdk": "1.28.8",
|
|
54
54
|
"@vercel/schedules": "0.0.0-alpha.19",
|
|
55
|
-
"@workflow/core": "5.
|
|
55
|
+
"@workflow/core": "5.4.0",
|
|
56
56
|
"@workflow/errors": "5.1.0",
|
|
57
57
|
"@workflow/serde": "5.0.0",
|
|
58
58
|
"@workflow/world": "5.1.0",
|
|
59
|
-
"@workflow/world-local": "5.2.
|
|
60
|
-
"@workflow/world-vercel": "5.
|
|
59
|
+
"@workflow/world-local": "5.2.1",
|
|
60
|
+
"@workflow/world-vercel": "5.4.0",
|
|
61
61
|
"zod": "4.5.4",
|
|
62
62
|
"zod-validation-error": "5.0.0"
|
|
63
63
|
},
|
|
64
|
-
"scriptHash": "
|
|
64
|
+
"scriptHash": "7fe9eb3c4b6002d37747a8bbd80a3797f01396d992a01426efe2917db68025f8",
|
|
65
65
|
"toolVersions": {
|
|
66
66
|
"env-runner>crossws": "0.4.17",
|
|
67
67
|
"env-runner>srvx": "1.0.8",
|
|
@@ -17,6 +17,14 @@ export interface ResolvedContentOptions {
|
|
|
17
17
|
readonly recordInputs: boolean;
|
|
18
18
|
readonly recordOutputs: boolean;
|
|
19
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Re-applies the capture-policy attributes that a size-based content strip
|
|
22
|
+
* must not rewrite. Dropping content to fit a checkpoint budget is not the
|
|
23
|
+
* destination declining it, so `agent.trace.content.input` and
|
|
24
|
+
* `agent.trace.content.output` keep the record's real decision; otherwise a
|
|
25
|
+
* restored turn would report "omitted" although capture was on.
|
|
26
|
+
*/
|
|
27
|
+
export declare function preservingCapturePolicy(attributes: Readonly<Record<string, unknown>>, original: Readonly<Record<string, unknown>>): Record<string, unknown>;
|
|
20
28
|
/**
|
|
21
29
|
* The attributes with the declined content removed, or `undefined` when there
|
|
22
30
|
* was none to remove.
|
|
@@ -176,6 +176,20 @@ export interface ToolOptions {
|
|
|
176
176
|
readonly kind?: ToolKind;
|
|
177
177
|
readonly arguments?: unknown;
|
|
178
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* A wait on a person. Under a tool call it names that call; under a turn it has no call, such
|
|
181
|
+
* as a budget prompt or a sign-in the turn needs before it can run.
|
|
182
|
+
*/
|
|
183
|
+
export interface ApprovalOptions {
|
|
184
|
+
readonly requestId: string;
|
|
185
|
+
readonly request?: unknown;
|
|
186
|
+
/** What the person is asked, recorded as `agent.approval.kind`. Defaults to `tool-approval`. */
|
|
187
|
+
readonly kind?: string;
|
|
188
|
+
/** The connection a sign-in is for, recorded as `agent.connection.name`. */
|
|
189
|
+
readonly connectionName?: string;
|
|
190
|
+
readonly callId?: string;
|
|
191
|
+
readonly toolName?: string;
|
|
192
|
+
}
|
|
179
193
|
export type ScopeData = {
|
|
180
194
|
readonly type: "activation";
|
|
181
195
|
readonly options: TurnMetadata;
|
|
@@ -190,12 +204,7 @@ export type ScopeData = {
|
|
|
190
204
|
readonly options: ToolOptions;
|
|
191
205
|
} | {
|
|
192
206
|
readonly type: "approval";
|
|
193
|
-
readonly options:
|
|
194
|
-
requestId: string;
|
|
195
|
-
request?: unknown;
|
|
196
|
-
callId: string;
|
|
197
|
-
toolName: string;
|
|
198
|
-
};
|
|
207
|
+
readonly options: ApprovalOptions;
|
|
199
208
|
} | {
|
|
200
209
|
readonly type: "memory";
|
|
201
210
|
readonly options: {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { createAgentRun, type AgentRun, type AgentRunOptions, type AgentMemoryTracing, type TurnInput, type ResumeInput, } from "./agent-run.js";
|
|
2
2
|
export { otelTelemetry, type OtelTelemetryOptions } from "./adapters/otel.js";
|
|
3
3
|
export { AgentSpanIdGenerator } from "./adapters/otel-ids.js";
|
|
4
|
-
export type { Operation, TurnOperation, AttemptInput, AttemptOperation, ToolInput, ModelOperation, ToolOperation, ApprovalOperation, MemoryOperation, ModelCallReturn, ModelStreamReturn, } from "./operations.js";
|
|
4
|
+
export type { Operation, TurnOperation, AttemptInput, AttemptOperation, ToolInput, ModelOperation, ToolOperation, ApprovalInput, ApprovalOperation, MemoryOperation, ModelCallReturn, ModelStreamReturn, } from "./operations.js";
|
|
5
5
|
export type { ActiveOperation, AgentTelemetry, Attributes, CaptureDecision, ContentPart, ContentSerializer, ExecutionContext, MappingContext, OutputMapping, PreparedSpan, SpanWriter, TraceCheckpointer, TraceErrorContext, TraceErrorHandler, TraceLink, TraceReference, TraceSnapshot, Usage, } from "./core/types.js";
|
|
6
6
|
export { currentCapture } from "./capture.js";
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{b as e,f as t,g as n,i as r,l as i,m as a,n as o,o as s,r as c,s as l,t as u,u as d,v as f}from"../../_chunks/workflow/mcp-DyzJqSIB.js";import{n as p,t as m}from"../../_chunks/workflow/delegation-i2O_jNNn.js";import{createHash as h,randomBytes as g,randomUUID as _}from"node:crypto";var v=class{#e;#t;allocateSpanId(){return b(16)}deriveSpanId(e){return y(e)}deriveTraceId(e){let t=h(`sha256`).update(e).digest(`hex`).slice(0,32);return/^0+$/u.test(t)?`00000000000000000000000000000001`:t}generateSpanId(){let e=this.#e;return e===void 0?b(16):(this.#e=void 0,e)}generateTraceId(){let e=this.#t;return e===void 0?b(32):(this.#t=void 0,e)}withSpanId(e,t){this.#e=e;try{return t()}finally{this.#e=void 0}}withTraceId(e,t){this.#t=e;try{return t()}finally{this.#t=void 0}}};function y(e){let t=h(`sha256`).update(e).digest(`hex`).slice(0,16);return/^0+$/u.test(t)?`0000000000000001`:t}function b(e){let t;do{t=``;for(let n=0;n<e;n+=1)t+=`0123456789abcdef`[Math.trunc(Math.random()*16)]}while(!/[1-9a-f]/u.test(t));return t}function x(e,t,n,r){let i=!1;try{return e.run(t,()=>(i=!0,n()),r)}catch(t){if(i)throw t;if(e.suppressed!==void 0)try{return e.suppressed(()=>(i=!0,n()))}catch(e){if(i)throw e}return n()}}function S(e){function t(t,n=`complete`,r){try{return t()}catch(t){try{e.onError?.(t,{phase:n,reference:r})}catch{}return}}function r(r,i,a,o){let s=d(r.attributes,i)??r.attributes,c=i.emit?t(()=>e.telemetry.startSpan({...r,attributes:s},{reference:o,context:a}),`start`,o):void 0,l=c?.reference??{traceId:`0`.repeat(32),spanId:`0`.repeat(16),traceFlags:0},u=!1;return{reference:l,get capture(){return i},narrow(e){i=n(i,e)},get finished(){return u},setAttribute(e,n){let r=d({[e]:n},i);!u&&(r===void 0||e in r)&&t(()=>c?.setAttribute(e,r===void 0?n:r[e]))},addEvent(e,n,r){u||t(()=>c?.addEvent(e,n===void 0?void 0:d(n,i)??n,r))},fail(e,n){u||t(()=>c?.fail(i.recordOutputs?e:void 0,n??(e instanceof Error?e.name:void 0)))},setStatus(e){u||t(()=>c?.setStatus(e))},end(e){u||(u=!0,t(()=>c?.end(e)))},run(t){return u?t():x(e.telemetry,{type:r.type,reference:l,capture:i},t,a)}}}return{start:r,startReserved:(e,t,n,i)=>r(e,n,i,t)}}const C=32768,w=65536;function T(e,t){function n(t,n){return r(()=>Reflect.apply(e[t],e,n))}function r(e){try{let t=e();return t===void 0||new TextEncoder().encode(t).length>C?void 0:t}catch(e){try{t?.(e,{phase:`serialize`})}catch{}return}}return{json:e=>n(`json`,[e]),text:e=>n(`text`,[e]),inputMessages:t=>{let n=0,i=r(()=>{let r=e.inputMessages(t);return n=r?.omitted??0,r?.json});return i===void 0?void 0:{json:i,omitted:n}},instructions:e=>n(`instructions`,[e]),toolDefinitions:e=>n(`toolDefinitions`,[e]),outputMessages:(e,t)=>n(`outputMessages`,[e,t]),toolResults:e=>n(`toolResults`,[e])}}function E(e){return new TextEncoder().encode(JSON.stringify({...e,children:void 0})).length}function ee(e){return JSON.parse(JSON.stringify(e))}function D(e,t=w,n=0){try{if(n>16||typeof e!=`object`||!e)return!1;let r=e;if(r.children!==void 0&&(!Array.isArray(r.children)||r.children.length>1e4||!r.children.every(e=>D(e,t,n+1)))||r.version!==1||r.finished!==void 0&&typeof r.finished!=`boolean`||r.childSequence!==void 0&&(!Number.isSafeInteger(r.childSequence)||r.childSequence<0)||typeof r.key!=`string`||typeof r.startTimeMs!=`number`||!Number.isFinite(r.startTimeMs)||r.reference.traceFlags!==0&&r.reference.traceFlags!==1||r.reference.tracestate!==void 0&&(typeof r.reference.tracestate!=`string`||r.reference.tracestate.length>512)||r.parent!==void 0&&(!/^[a-f0-9]{32}$/u.test(r.parent.traceId)||!/^[a-f0-9]{16}$/u.test(r.parent.spanId))||![r.identity.conversationId,r.identity.runId,r.identity.turnId].every(e=>typeof e==`string`))return!1;let i=r.data.options;return!(!{activation:[],step:[],model:[`provider`,`modelId`],tool:[`callId`,`name`],approval:[`requestId`,`callId`,`toolName`],memory:[`operation`,`phase`,`slot`,`storeId`]}[r.data.type].every(e=>typeof i[e]==`string`)||r.data.type===`activation`&&!Number.isSafeInteger(i.sequence)||r.data.type===`step`&&!Number.isSafeInteger(i.index)||r.data.type===`memory`&&i.operation!==`search_memory`&&i.operation!==`upsert_memory`||!/^[a-f0-9]{32}$/u.test(r.reference.traceId)||!/^[a-f0-9]{16}$/u.test(r.reference.spanId)||typeof r.reference.traceFlags!=`number`||![r.capture.emit,r.capture.recordInputs,r.capture.recordOutputs].every(e=>typeof e==`boolean`)||![`activation`,`step`,`model`,`tool`,`approval`,`memory`].includes(r.data.type)||typeof r.data.options!=`object`||r.data.options===null||E(r)>t)}catch{return!1}}function O(e,t){let n=e.terminal;e={...e,children:e.children?.map(n=>O({...n,capture:{emit:n.capture.emit&&e.capture.emit,recordInputs:n.capture.recordInputs&&e.capture.recordInputs,recordOutputs:n.capture.recordOutputs&&e.capture.recordOutputs}},t))},e={...e,terminal:n===void 0||e.finished?void 0:{...n,errorCode:n.errorCode??(n.error instanceof Error?n.error.name:void 0),error:e.capture.recordOutputs?n.error instanceof Error?{name:n.error.name,message:t.text(n.error.message)}:n.error:void 0,output:e.capture.recordOutputs?n.output:void 0,response:e.capture.recordOutputs?n.response:void 0,records:e.capture.recordInputs?n.records:void 0,model:n.model===void 0?void 0:{...n.model,content:e.capture.recordOutputs?n.model.content:void 0}}},e={...e,attributes:d(e.attributes??{},e.capture)??e.attributes};let r=c(e.data,e.capture),i;try{i=t.json(r)}catch{}let a=()=>{let t=c(r,{emit:e.capture.emit,recordInputs:!1,recordOutputs:!1});return t.type===`step`&&(t={...t,options:{...t.options,runtimeContext:void 0}}),t.type===`model`&&(t={...t,options:{...t.options,runtimeContext:void 0}}),JSON.parse(JSON.stringify({...e,version:1,data:t,terminal:e.terminal===void 0?void 0:{outcome:e.terminal.outcome,failed:e.terminal.failed,errorCode:e.terminal.errorCode,usage:e.terminal.usage},attributes:d(e.attributes??{},{recordInputs:!1,recordOutputs:!1})??e.attributes}))};if(i===void 0||new TextEncoder().encode(i).length>C)return a();try{let t=JSON.parse(JSON.stringify({...e,version:1,data:JSON.parse(i)}));return E(t)<=w?t:a()}catch{return a()}}const k=1e4,A={emit:!1,recordInputs:!1,recordOutputs:!1},te=new Set([`activation`,`tool`,`approval`]),ne=new Set([`tool`,`approval`]);function j(e){return encodeURIComponent(String(e))}function re(e){switch(e.type){case`step`:return`step:${j(e.options.index)}:${j(e.options.attempt??0)}`;case`tool`:return`tool:${j(e.options.callId)}`;case`approval`:return`approval:${j(e.options.requestId)}`;default:return}}function ie(e){let t=e.failed||e.outcome===`failed`;return{...e,model:`result`in e?e.result:e.model,failed:t,errorCode:`errorType`in e?e.errorType:e.errorCode}}function M(t){let a=t.telemetry,f=T(t.serializer,t.onError),m=S({telemetry:a,onError:t.onError}),h=(e,n)=>{try{t.onError?.(e,n)}catch{}};function _(e){let t=f.json(e);try{return t===void 0?void 0:JSON.parse(t)}catch{return}}function v(e,n,r,i,o){let s=a.ids;if(t.durable&&s!==void 0&&e.type!==`model`&&e.type!==`memory`){if(e.type===`activation`&&r!==void 0)return{traceId:r.traceId,spanId:s.spanId(n),traceFlags:o.emit?r.traceFlags&1:0};if(e.type===`activation`){let e=s.traceId(n);return{traceId:e,spanId:s.spanId(n),traceFlags:o.emit&&(a.samples?.(e,i)??!0)?1:0}}return r===void 0?void 0:{...r,spanId:s.spanId(n),isRemote:!1}}}async function y(e,t,n,r,i,a,o){try{return await b(e,t,n,r,i,a,o)}catch(t){return h(t,{phase:`start`,operation:n.type,reference:a.reference}),b(e,A,c(n,A),r,i,{...a,sample:!1,reference:{traceId:a.reference?.traceId??r?.reference.traceId??a.parent?.traceId??g(16).toString(`hex`),spanId:a.reference?.spanId??g(8).toString(`hex`),traceFlags:0}},o)}}async function b(g,b,S,C,w,T,E){if(T.terminal?.error!==null&&typeof T.terminal?.error==`object`&&!(T.terminal.error instanceof Error)&&`message`in T.terminal.error&&typeof T.terminal.error.message==`string`){let e=Error(T.terminal.error.message);e.name=T.terminal.errorCode??`Error`,T={...T,terminal:{...T.terminal,error:e}}}let D=T.key,M=T.startTimeMs??Date.now(),N=T.parent??C?.reference;b.emit&&(b=n(b,a.active()?.capture));let P=b,F=c(S,P),I=l({identity:g,data:F,attempt:w,capture:P,key:D,parent:N,startTimeMs:M,links:T.links},f);I={...I,attributes:{...I.attributes,...T.attributes}},F=O({key:D,identity:g,data:F,capture:P,reference:T.reference??{traceId:`0`.repeat(32),spanId:`0`.repeat(16),traceFlags:0},startTimeMs:M},f).data;let L=T.deferred??(t.durable&&te.has(F.type)),R=T.executionContext,z=T.reference??v(S,D,N,I,P);T.sample===!0&&z!==void 0&&(z={...z,traceFlags:z.traceFlags&1&&P.emit&&(N!==void 0||(a.samples?.(z.traceId,I)??!0))?1:0});let B=L?void 0:m.start(I,P,R,z),V=z??B?.reference;if(V===void 0)throw Error(`A deferred trace scope requires a reserved reference.`);let H=!!(V.traceFlags&1);P={emit:P.emit&&H,recordInputs:P.emit&&H&&P.recordInputs,recordOutputs:P.emit&&H&&P.recordOutputs},F=c(F,P);let U=T.finished??!1,W=T.terminal,G=new Map,K=new Set,ae=T.childSequence??0,q=T.usage,J=new Set(T.usageKeys??[]),Y={},oe=F.type===`tool`?F.options.callId:void 0;function X(){E()}function Z(){return n(P,a.active()?.capture)}async function se(e,n,r={}){let i=G.get(n);if(t.durable&&i!==void 0&&!i.settled)return i.refine(e,r.startTimeMs),i;if(U)throw Error(`The operation is not permitted in this trace scope.`);for(let[e,t]of G)t.settled&&G.delete(e);let a=P;G.size>=k&&(h(Error(`Trace unfinished-child limit reached.`),{phase:`start`,operation:e.type,reference:V}),a=A),e.type===`model`&&B!==void 0&&o(B,{"agent.model.id":e.options.modelId});let s=await y(g,a,e,$,e.type===`step`?{index:e.options.index,attempt:e.options.attempt??0}:w,{key:n,executionContext:R,links:r.links,startTimeMs:r.startTimeMs},E);return(a.emit||G.size<k)&&G.set(n,s),await E(),s}async function Q(e,t){let n=F.type===`step`||F.type===`activation`;for(let r of G.values())!t&&n&&ne.has(r.type)||await r.release({failed:e.failed,error:e.error,outcome:`abandoned`})}async function ce(e){if(K.size>0&&await Promise.allSettled(K),U)return;let n=Z();n.recordOutputs||(e={...e,error:void 0}),W?.failed&&(e={...e,outcome:e.outcome===`completed`?`failed`:e.outcome,failed:!0,error:W.error,errorCode:e.errorCode??W.errorCode}),U=!0,W=e,await Q(e,e.failed===!0||!t.durable),B??=m.start(I,P,R,V);let i=F.type===`activation`&&e.usage===void 0?{...e,usage:q}:e;try{r(B,F,i,{...n,emit:P.emit},M,f)}catch(e){h(e,{phase:`complete`,operation:F.type,reference:V})}if(o(B,Y),F.type===`model`&&e.model!==void 0){await C?.usage(e.model.usage,D);let t=e.model.content;if(n.recordOutputs&&P.recordOutputs&&t!==void 0){let n=f.outputMessages(t,e.model.finishReason);n!==void 0&&C?.turnContent({output:n})}}B.end(e.endTimeMs),await E()}let $={waitUntil(e){K.add(e),C?.waitUntil(e),e.then(()=>K.delete(e),()=>K.delete(e))},snapshot:()=>ee($.record()),attributes:e=>$.update({attributes:e}),modelCall:(e,t)=>$.child({type:`model`,options:e},t),fail(e){return $.error(e),$.complete({outcome:`failed`,failed:!0})},update(e){if(U)return;let t=d(e.attributes??{},Z())??e.attributes;F.type===`activation`&&(F={...F,options:{...F.options,attributes:{...F.options.attributes,...t}}}),I={...I,attributes:{...I.attributes,...t},links:e.links??I.links},B!==void 0&&o(B,t),X()},useContext(e){R=e;for(let t of G.values())t.useContext(e)},refine(e,t){if(U||B!==void 0)return;if(t!==void 0&&t<M&&(M=t),e.type===`tool`&&F.type===`tool`){let t=F.options;F=c({type:`tool`,options:{...t,kind:t.kind??e.options.kind,arguments:t.arguments??(Z().recordInputs?_(e.options.arguments):void 0)}},P)}let n=l({identity:g,data:F,attempt:w,capture:P,key:D,parent:N,startTimeMs:M,links:I.links},f),r=Object.fromEntries(Object.entries(n.attributes).filter(([,e])=>e!==void 0));I={...I,name:n.name,kind:n.kind,startTimeMs:M,attributes:{...I.attributes,...r}},X()},narrow(e){P={...n(P,e),emit:P.emit},F=c(F,P);let t=d(I.attributes,P)??I.attributes;I={...I,attributes:F.type===`activation`?{...t,"agent.trace.content.input":P.recordInputs,"agent.trace.content.output":P.recordOutputs}:t};let r=d(Y,P)??Y;for(let e of Object.keys(Y))e in r||delete Y[e];!P.recordOutputs&&W?.error!==void 0&&(W={...W,error:void 0}),B?.narrow(P);for(let e of G.values())e.narrow(P);X()},async release(e){U?await Q(e,e.failed===!0||!t.durable):await ce(ie(e))},record(){return O({version:1,finished:U,terminal:W,usage:q,usageKeys:[...J],attributes:{...I.attributes,...Y},childSequence:ae,children:[...G.values()].filter(e=>!e.settled).map(e=>e.record()),key:D,identity:g,data:F,capture:P,reference:V,parent:N,startTimeMs:M,attempt:w,links:I.links},f)},get parent(){return N},get startTimeMs(){return M},child(e,n,r){if(!s(e).includes(F.type))throw Error(`The operation is not permitted in this trace scope.`);let i=n===void 0?(t.durable?re(e):void 0)??`${e.type}:${ae++}`:`${e.type}:${j(n)}`;return se(e,`${D}/${i}`,r)},find(e){let t=re(e),n=t===void 0?void 0:G.get(`${D}/${t}`);return n===void 0||n.settled?void 0:n},get children(){return[...G.values()].filter(e=>!e.settled)},type:F.type,reference:V,callId:oe,get capture(){return P},mcp:u({serializer:f,...P,write(e){let t=d(e,Z())??e;Object.assign(Y,t),B!==void 0&&o(B,t)},error(e,t){$.error(e,t)}}),get finished(){return U},get settled(){return U&&[...G.values()].every(e=>e.settled)},run(e,t){if(U)throw Error(`The trace scope has already finished.`);let r=n(n(P,t),a.active()?.capture),i=F.type===`tool`&&(F.options.kind===`subagent-call`||F.options.kind===`remote-agent-call`)?F.options:void 0,o=i===void 0?e:()=>p({caller:V,conversationId:g.conversationId,parentRunId:g.runId,parentCallId:i.callId,agentName:i.name,capture:r},e);return x(a,{type:$.type,reference:V,capture:r,mcp:$.mcp},o,R)},async complete(e=W??{}){U||await ce(ie(e))},async usage(e,t){t!==void 0&&J.has(t)||(t!==void 0&&J.add(t),B!==void 0&&o(B,i(e)),q={inputTokens:e.inputTokens===void 0?q?.inputTokens:(q?.inputTokens??0)+e.inputTokens,outputTokens:e.outputTokens===void 0?q?.outputTokens:(q?.outputTokens??0)+e.outputTokens,costUsd:e.costUsd===void 0?q?.costUsd:(q?.costUsd??0)+e.costUsd},await C?.usage(e,t))},turnContent(e){if(F.type!==`activation`)return C?.turnContent(e);if(U)return;let t={};e.input!==void 0&&I.attributes[`gen_ai.input.messages`]===void 0&&(t[`gen_ai.input.messages`]=e.input),e.output!==void 0&&(t[`gen_ai.output.messages`]=e.output),Object.keys(t).length>0&&$.update({attributes:t})},error(t,n){W={...W,failed:!0,error:Z().recordOutputs?t instanceof Error?e(t):_(t):void 0,errorCode:n??(t instanceof Error?t.name:void 0)},B!==void 0&&B.fail(W.error,W.errorCode),X()}};for(let e of T.children??[])G.set(e.key,await y(e.identity,n(e.capture,P),e.data,$,e.attempt,{...e,deferred:!0,executionContext:R},E));!U&&B!==void 0&&F.type===`step`&&B.addEvent(`step.started`,void 0,M);let le=I.attributes[`gen_ai.input.messages`];return!U&&F.type===`model`&&typeof le==`string`&&C?.turnContent({input:le}),$}return{start(e){return y(e.identity,e.capture,e.data,void 0,void 0,{key:e.key,parent:e.parent,reference:e.reference,sample:e.reference!==void 0&&e.data.type===`activation`,startTimeMs:e.startTimeMs,links:e.links,executionContext:e.context},e.onChange??(()=>Promise.resolve()))},async restore(e,t={}){if(!D(e))h(Error(`Invalid tracing checkpoint.`),{phase:`restore`});else return y(e.identity,n(e.capture,t.capture),e.data,void 0,e.attempt,{...e,deferred:!0,executionContext:t.context},t.onChange??(()=>Promise.resolve()))}}}function N(e,t,n){try{e?.(t,{phase:n})}catch{}}function P(e,t={outcome:`completed`},n){async function r(r,i){if(i===void 0)return e(r);let a=await e(r),o=t;try{let e=await a.run(()=>i(a));try{o=r.describe?.(e)??t}catch(e){N(n,e,`complete`)}return e}catch(e){throw o={outcome:`failed`,errorType:e instanceof Error?e.name:`_OTHER`,error:e},e}finally{try{await a.complete(o)}catch(e){N(n,e,`complete`)}}}return r}function F(e,t,n){let r=t=>Object.defineProperties(t,{finished:{get:()=>e.finished},capture:{get:()=>e.capture},parent:{get:()=>e.parent}}),i={type:e.type,reference:e.reference,get startTimeMs(){return e.startTimeMs},get parent(){return e.parent},get finished(){return e.finished},get capture(){return e.capture},run:(t,n)=>e.run(t,n),attributes:t=>e.attributes(t),complete:t=>e.complete(t),fail:t=>e.fail(t),recordError:(t,n)=>e.error(t,n)},a=async(t,r,i)=>F(await e.child(t,r,i),t,n),o=P(async({startTimeMs:e,...t})=>a({type:`tool`,options:t},void 0,{startTimeMs:e}),void 0,n),s=e=>e===void 0?void 0:F(e,e.record().data,n),c=P(async e=>a({type:`memory`,options:e}),void 0,n);if(t.type===`activation`)return r({...i,memory:c,links:t=>e.update({links:t}),findAttempt:t=>s(e.find({type:`step`,options:{index:t.stepIndex,attempt:t.attempt}})),findTool:t=>s(I(e,t)),attempt:P(async e=>a({type:`step`,options:{index:e.stepIndex,attempt:e.attempt,runtimeContext:e.runtimeContext,channel:e.channel}},void 0,{links:e.links}),void 0,n)});if(t.type===`step`){let t=e=>P(async t=>a({type:`tool`,options:{callId:t.callId,name:t.agentName,kind:e}}),void 0,n),s=(e,t)=>a({type:`model`,options:e},t);async function l(e,t){if(typeof t!=`function`)return s(e,t);let r=await s(e),i;try{i=await r.run(t)}catch(e){try{await r.fail(e)}catch(e){N(n,e,`complete`)}throw e}try{await r.complete({outcome:`completed`,result:i})}catch(e){N(n,e,`complete`)}return i.result}return r({...i,memory:c,tool:o,callSubAgent:t(`subagent-call`),callRemoteAgent:t(`remote-agent-call`),modelCall:l,async modelStream(t,r){let i=await s(t);try{let t=await i.run(r),a=Promise.resolve(t.completion).then(e=>i.complete({outcome:`completed`,result:e}),e=>i.fail(e)).catch(e=>N(n,e,`complete`));return e.waitUntil(a),t.result}catch(e){try{await i.fail(e)}catch(e){N(n,e,`complete`)}throw e}}})}return t.type===`tool`?r({...i,memory:c,tool:o,findApproval:n=>s(e.find({type:`approval`,options:{requestId:n,callId:t.options.callId,toolName:t.options.name}})),approval:P(async e=>a({type:`approval`,options:{...e,callId:t.options.callId,toolName:t.options.name}}),{outcome:`ignored`},n)}):i}function I(e,t){for(let n of e.children){if(n.type===`tool`&&n.callId===t)return n;if(n.type===`step`||n.type===`tool`){let e=I(n,t);if(e!==void 0)return e}}}const L={emit:!0,recordInputs:!1,recordOutputs:!1};function R(e){let r=e.telemetry??t(),i=e.checkpointer;if(i!==void 0&&r.ids===void 0)throw Error(`Durable agent tracing needs stable span IDs. Pass the AgentSpanIdGenerator installed on your tracer provider to otelTelemetry({ idGenerator }).`);let a=(t,n)=>{try{e.onError?.(t,n)}catch{}},o=M({telemetry:r,serializer:e.serializer??f,durable:i!==void 0,onError:e.onError}),s=new Map;function c(e){return i===void 0?`turn:${_()}`:[`turn`,e.runId,e.turnId].map(encodeURIComponent).join(`:`)}function l(e,t){let n=Promise.resolve();return()=>{let r=t();return i===void 0||r===void 0||r.retired||(r.writes++,n=n.then(async()=>{try{if(r.root.settled)s.delete(e),await i.delete(e);else{let t=_();await i.set(e,ee({...r.root.record(),revision:t})),r.revision=t,r.revisions.size<1e4&&r.revisions.add(t)}}catch(e){a(e,{phase:`checkpoint`,operation:`activation`})}finally{r.writes--}})),n}}async function u(e){try{return await i.get(e)}catch(e){a(e,{phase:`restore`,operation:`activation`});return}}async function d(e,t,r,a,s){let c=m()?.capture;s=s===void 0?c:n(s,c);let d=i===void 0?void 0:await u(e),f=d?.revision;if(t!==void 0&&(t.writes>0||f===t.revision||f!==void 0&&t.revisions.has(f)))return a!==void 0&&t.root.useContext(a),s!==void 0&&t.root.narrow(s),t;t!==void 0&&(t.retired=!0);let p,h=l(e,()=>p),g=d===void 0?void 0:await o.restore(d,{capture:s,context:a,onChange:h}),_=g??await r?.(h);if(_!==void 0)return p={root:_,revision:f,revisions:new Set(f===void 0?[]:[f]),retired:!1,writes:0},g===void 0&&await h(),p}function p(e,t){let n=s.get(e),r=(async()=>t(n===void 0?void 0:await n.catch(()=>void 0)))();return s.set(e,r),r.then(t=>{(t===void 0||t.root.settled)&&s.delete(e)},()=>s.delete(e)),s.size>1e3&&s.delete(s.keys().next().value),r}function h(e,t){return i=>{let a=m(),s=n(e.capture??L,a?.capture),c=a!==void 0&&e.sequence===0,l=e.parent??(c&&a?.remote!==!0?a?.caller:void 0),u=[...c&&a?.remote===!0?[{relationship:`agent.dispatch`,context:a.caller}]:[],...e.links??[]];return o.start({identity:{...e.identity,conversationId:a?.conversationId??e.identity.conversationId,agentName:e.agentName,framework:e.framework},key:t,capture:s,parent:l,reference:r.ids===void 0?void 0:e.reference,startTimeMs:e.startTimeMs,data:{type:`activation`,options:{sequence:e.sequence,attributes:e.attributes,channel:e.channel,subagent:a!==void 0||e.lineage!==void 0,subagentName:a?.agentName??e.lineage?.agentName,parentRunId:a?.parentRunId??e.lineage?.parentRunId,parentCallId:a?.parentCallId??e.lineage?.parentCallId}},links:u.length===0?void 0:u,context:e.context,onChange:i})}}function g(t){return F(t,{type:`activation`,options:{sequence:0}},e.onError)}async function v(e){let t=c(e.identity);return g((i===void 0?await d(t,void 0,h(e,t),e.context):await p(t,n=>d(t,n,h(e,t),e.context,e.capture))).root)}async function y(e){if(i===void 0)return;let t=c(e.identity),n=await p(t,n=>d(t,n,void 0,e.context));return n===void 0?void 0:g(n.root)}async function b(e){try{await e()}catch(e){a(e,{phase:`complete`})}}async function x(e,t,n){let i=r.active(),s=await o.start({identity:t.identity,key:`memory:${_()}`,capture:t.capture??i?.capture??L,parent:t.parent??i?.reference,context:t.context,data:{type:`memory`,options:{operation:e,phase:t.phase,slot:t.slot,storeId:t.storeId}}}),c;try{c=await s.run(n)}catch(e){throw await s.fail(e).catch(e=>a(e,{phase:`complete`})),e}return await s.complete({outcome:`completed`,...t.describe?.(c)}).catch(e=>a(e,{phase:`complete`})),c}return{turn:P(v,void 0,e.onError),resume:y,memory:{search:(e,t)=>x(`search_memory`,e,t),write:(e,t)=>x(`upsert_memory`,e,t)},forceFlush:()=>b(()=>r.forceFlush()),shutdown:()=>b(()=>r.shutdown())}}export{v as AgentSpanIdGenerator,R as createAgentRun,a as currentCapture,t as otelTelemetry};
|
|
1
|
+
import{_ as e,d as t,h as n,i as r,l as i,n as a,o,p as s,r as c,s as l,t as u,u as d,x as f,y as p}from"../../_chunks/workflow/mcp-LeXvhyIJ.js";import{n as m,t as h}from"../../_chunks/workflow/delegation-i2O_jNNn.js";import{createHash as g,randomBytes as _,randomUUID as v}from"node:crypto";var y=class{#e;#t;allocateSpanId(){return x(16)}deriveSpanId(e){return b(e)}deriveTraceId(e){let t=g(`sha256`).update(e).digest(`hex`).slice(0,32);return/^0+$/u.test(t)?`00000000000000000000000000000001`:t}generateSpanId(){let e=this.#e;return e===void 0?x(16):(this.#e=void 0,e)}generateTraceId(){let e=this.#t;return e===void 0?x(32):(this.#t=void 0,e)}withSpanId(e,t){this.#e=e;try{return t()}finally{this.#e=void 0}}withTraceId(e,t){this.#t=e;try{return t()}finally{this.#t=void 0}}};function b(e){let t=g(`sha256`).update(e).digest(`hex`).slice(0,16);return/^0+$/u.test(t)?`0000000000000001`:t}function x(e){let t;do{t=``;for(let n=0;n<e;n+=1)t+=`0123456789abcdef`[Math.trunc(Math.random()*16)]}while(!/[1-9a-f]/u.test(t));return t}function S(e,t,n,r){let i=!1;try{return e.run(t,()=>(i=!0,n()),r)}catch(t){if(i)throw t;if(e.suppressed!==void 0)try{return e.suppressed(()=>(i=!0,n()))}catch(e){if(i)throw e}return n()}}function C(n){function r(e,t=`complete`,r){try{return e()}catch(e){try{n.onError?.(e,{phase:t,reference:r})}catch{}return}}function i(i,a,o,s){let c=t(i.attributes,a)??i.attributes,l=a.emit?r(()=>n.telemetry.startSpan({...i,attributes:c},{reference:s,context:o}),`start`,s):void 0,u=l?.reference??{traceId:`0`.repeat(32),spanId:`0`.repeat(16),traceFlags:0},d=!1;return{reference:u,get capture(){return a},narrow(t){a=e(a,t)},get finished(){return d},setAttribute(e,n){let i=t({[e]:n},a);!d&&(i===void 0||e in i)&&r(()=>l?.setAttribute(e,i===void 0?n:i[e]))},addEvent(e,n,i){d||r(()=>l?.addEvent(e,n===void 0?void 0:t(n,a)??n,i))},fail(e,t){d||r(()=>l?.fail(a.recordOutputs?e:void 0,t??(e instanceof Error?e.name:void 0)))},setStatus(e){d||r(()=>l?.setStatus(e))},end(e){d||(d=!0,r(()=>l?.end(e)))},run(e){return d?e():S(n.telemetry,{type:i.type,reference:u,capture:a},e,o)}}}return{start:i,startReserved:(e,t,n,r)=>i(e,n,r,t)}}const w=262144,T=524288,E=[`gen_ai.input.messages`,`gen_ai.output.messages`],D=new TextEncoder;function O(e){return D.encode(e).length}function k(e){if(!Array.isArray(e))return``;let t=``;for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;e.type===`text`&&typeof e.content==`string`&&(t+=(t.length===0?``:`
|
|
2
|
+
`)+e.content)}return t}function A(e,t){if(t<=0)return;if(O(e)<=t)return e;let n;try{n=JSON.parse(e)}catch{return}if(!Array.isArray(n)||n.length===0)return;let r=n.at(-1);if(typeof r!=`object`||!r)return;let i=r;if(typeof i.role!=`string`)return;let a=k(i.parts),o=typeof i.kind==`string`?{kind:i.kind,role:i.role}:{role:i.role},s=e=>JSON.stringify([{...o,parts:[{content:`${a.slice(0,e)}… [truncated]`,type:`text`}]}]),c,l=1,u=a.length;for(;l<=u;){let e=Math.floor((l+u)/2),n=s(e);O(n)<=t?(c=n,l=e+1):u=e-1}if(c!==void 0)return c;let d=s(0);return O(d)<=t?d:void 0}function j(e,t,n){let r=e;for(let e of E){let i=t[e];if(typeof i!=`string`)continue;let a={...r};delete a[e];let o={...n,attributes:a},s=Math.min(w-O(JSON.stringify(o.data)),T-N(o));for(;s>0;){let t=A(i,s);if(t===void 0)break;let a={...r,[e]:t};if(N({...n,attributes:a})<=T){r=a;break}s=Math.floor(s/2)}}return r}function M(e,t){function n(t,n){return r(()=>Reflect.apply(e[t],e,n))}function r(e){try{let t=e();return t===void 0||new TextEncoder().encode(t).length>w?void 0:t}catch(e){try{t?.(e,{phase:`serialize`})}catch{}return}}return{json:e=>n(`json`,[e]),text:e=>n(`text`,[e]),inputMessages:t=>{let n=0,i=r(()=>{let r=e.inputMessages(t);return n=r?.omitted??0,r?.json});return i===void 0?void 0:{json:i,omitted:n}},instructions:e=>n(`instructions`,[e]),toolDefinitions:e=>n(`toolDefinitions`,[e]),outputMessages:(e,t)=>n(`outputMessages`,[e,t]),toolResults:e=>n(`toolResults`,[e])}}function N(e){return new TextEncoder().encode(JSON.stringify({...e,children:void 0})).length}function ee(e){return JSON.parse(JSON.stringify(e))}function P(e,t=T,n=0){try{if(n>16||typeof e!=`object`||!e)return!1;let r=e;if(r.children!==void 0&&(!Array.isArray(r.children)||r.children.length>1e4||!r.children.every(e=>P(e,t,n+1)))||r.version!==1||r.finished!==void 0&&typeof r.finished!=`boolean`||r.childSequence!==void 0&&(!Number.isSafeInteger(r.childSequence)||r.childSequence<0)||typeof r.key!=`string`||typeof r.startTimeMs!=`number`||!Number.isFinite(r.startTimeMs)||r.reference.traceFlags!==0&&r.reference.traceFlags!==1||r.reference.tracestate!==void 0&&(typeof r.reference.tracestate!=`string`||r.reference.tracestate.length>512)||r.parent!==void 0&&(!/^[a-f0-9]{32}$/u.test(r.parent.traceId)||!/^[a-f0-9]{16}$/u.test(r.parent.spanId))||![r.identity.conversationId,r.identity.runId,r.identity.turnId].every(e=>typeof e==`string`))return!1;let i=r.data.options;return!(!{activation:[],step:[],model:[`provider`,`modelId`],tool:[`callId`,`name`],approval:[`requestId`],memory:[`operation`,`phase`,`slot`,`storeId`]}[r.data.type].every(e=>typeof i[e]==`string`)||r.data.type===`approval`&&![`kind`,`connectionName`,`callId`,`toolName`].every(e=>i[e]===void 0||typeof i[e]==`string`)||r.data.type===`activation`&&!Number.isSafeInteger(i.sequence)||r.data.type===`step`&&!Number.isSafeInteger(i.index)||r.data.type===`memory`&&i.operation!==`search_memory`&&i.operation!==`upsert_memory`||!/^[a-f0-9]{32}$/u.test(r.reference.traceId)||!/^[a-f0-9]{16}$/u.test(r.reference.spanId)||typeof r.reference.traceFlags!=`number`||![r.capture.emit,r.capture.recordInputs,r.capture.recordOutputs].every(e=>typeof e==`boolean`)||![`activation`,`step`,`model`,`tool`,`approval`,`memory`].includes(r.data.type)||typeof r.data.options!=`object`||r.data.options===null||N(r)>t)}catch{return!1}}function F(e,n){let r=e.terminal;e={...e,children:e.children?.map(t=>F({...t,capture:{emit:t.capture.emit&&e.capture.emit,recordInputs:t.capture.recordInputs&&e.capture.recordInputs,recordOutputs:t.capture.recordOutputs&&e.capture.recordOutputs}},n))},e={...e,terminal:r===void 0||e.finished?void 0:{...r,errorCode:r.errorCode??(r.error instanceof Error?r.error.name:void 0),error:e.capture.recordOutputs?r.error instanceof Error?{name:r.error.name,message:n.text(r.error.message)}:r.error:void 0,output:e.capture.recordOutputs?r.output:void 0,response:e.capture.recordOutputs?r.response:void 0,records:e.capture.recordInputs?r.records:void 0,model:r.model===void 0?void 0:{...r.model,content:e.capture.recordOutputs?r.model.content:void 0}}},e={...e,attributes:t(e.attributes??{},e.capture)??e.attributes};let i=c(e.data,e.capture),a;try{a=n.json(i)}catch{}let o=()=>{let n={emit:e.capture.emit,recordInputs:!1,recordOutputs:!1},r=c(i,n);r.type===`step`&&(r={...r,options:{...r.options,runtimeContext:void 0}}),r.type===`model`&&(r={...r,options:{...r.options,runtimeContext:void 0}});let a=e.attributes??{},o=j(d(t(a,n)??{},a),a,{...e,version:1,data:r});return JSON.parse(JSON.stringify({...e,version:1,data:r,terminal:e.terminal===void 0?void 0:{outcome:e.terminal.outcome,failed:e.terminal.failed,errorCode:e.terminal.errorCode,usage:e.terminal.usage},attributes:o}))};if(a===void 0||new TextEncoder().encode(a).length>w)return o();try{let t=JSON.parse(JSON.stringify({...e,version:1,data:JSON.parse(a)}));return N(t)<=T?t:o()}catch{return o()}}const te=1e4,I={emit:!1,recordInputs:!1,recordOutputs:!1},ne=new Set([`activation`,`tool`,`approval`]),re=new Set([`tool`,`approval`]);function L(e){return encodeURIComponent(String(e))}function R(e){switch(e.type){case`step`:return`step:${L(e.options.index)}:${L(e.options.attempt??0)}`;case`tool`:return`tool:${L(e.options.callId)}`;case`approval`:return`approval:${L(e.options.requestId)}`;default:return}}function z(e){let t=e.failed||e.outcome===`failed`;return{...e,model:`result`in e?e.result:e.model,failed:t,errorCode:`errorType`in e?e.errorType:e.errorCode}}function B(n){let s=n.telemetry,d=M(n.serializer,n.onError),p=C({telemetry:s,onError:n.onError}),h=(e,t)=>{try{n.onError?.(e,t)}catch{}};function g(e){let t=d.json(e);try{return t===void 0?void 0:JSON.parse(t)}catch{return}}function v(e,t,r,i,a){let o=s.ids;if(n.durable&&o!==void 0&&e.type!==`model`&&e.type!==`memory`){if(e.type===`activation`&&r!==void 0)return{traceId:r.traceId,spanId:o.spanId(t),traceFlags:a.emit?r.traceFlags&1:0};if(e.type===`activation`){let e=o.traceId(t);return{traceId:e,spanId:o.spanId(t),traceFlags:a.emit&&(s.samples?.(e,i)??!0)?1:0}}return r===void 0?void 0:{...r,spanId:o.spanId(t),isRemote:!1}}}async function y(e,t,n,r,i,a,o){try{return await b(e,t,n,r,i,a,o)}catch(t){return h(t,{phase:`start`,operation:n.type,reference:a.reference}),b(e,I,c(n,I),r,i,{...a,sample:!1,reference:{traceId:a.reference?.traceId??r?.reference.traceId??a.parent?.traceId??_(16).toString(`hex`),spanId:a.reference?.spanId??_(8).toString(`hex`),traceFlags:0}},o)}}async function b(_,b,x,C,w,T,E){if(T.terminal?.error!==null&&typeof T.terminal?.error==`object`&&!(T.terminal.error instanceof Error)&&`message`in T.terminal.error&&typeof T.terminal.error.message==`string`){let e=Error(T.terminal.error.message);e.name=T.terminal.errorCode??`Error`,T={...T,terminal:{...T.terminal,error:e}}}let D=T.key,O=T.startTimeMs??Date.now(),k=T.parent??C?.reference;b.emit&&(b=e(b,s.active()?.capture));let A=b,j=c(x,A),M=l({identity:_,data:j,attempt:w,capture:A,key:D,parent:k,startTimeMs:O,links:T.links},d);M={...M,attributes:{...M.attributes,...T.attributes}},j=F({key:D,identity:_,data:j,capture:A,reference:T.reference??{traceId:`0`.repeat(32),spanId:`0`.repeat(16),traceFlags:0},startTimeMs:O},d).data;let N=T.deferred??(n.durable&&ne.has(j.type)),P=T.executionContext,B=T.reference??v(x,D,k,M,A);T.sample===!0&&B!==void 0&&(B={...B,traceFlags:B.traceFlags&1&&A.emit&&(k!==void 0||(s.samples?.(B.traceId,M)??!0))?1:0});let V=N?void 0:p.start(M,A,P,B),H=B??V?.reference;if(H===void 0)throw Error(`A deferred trace scope requires a reserved reference.`);let U=!!(H.traceFlags&1);A={emit:A.emit&&U,recordInputs:A.emit&&U&&A.recordInputs,recordOutputs:A.emit&&U&&A.recordOutputs},j=c(j,A);let W=T.finished??!1,G=T.terminal,K=new Map,q=new Set,ie=T.childSequence??0,J=T.usage,Y=new Set(T.usageKeys??[]),X={},ae=j.type===`tool`?j.options.callId:void 0;function Z(){E()}function Q(){return e(A,s.active()?.capture)}async function oe(e,t,r={}){let i=K.get(t);if(n.durable&&i!==void 0&&!i.settled)return i.refine(e,r.startTimeMs),i;if(W)throw Error(`The operation is not permitted in this trace scope.`);for(let[e,t]of K)t.settled&&K.delete(e);let o=A;K.size>=te&&(h(Error(`Trace unfinished-child limit reached.`),{phase:`start`,operation:e.type,reference:H}),o=I),e.type===`model`&&V!==void 0&&a(V,{"agent.model.id":e.options.modelId});let s=await y(_,o,e,$,e.type===`step`?{index:e.options.index,attempt:e.options.attempt??0}:w,{key:t,executionContext:P,links:r.links,startTimeMs:r.startTimeMs},E);return(o.emit||K.size<te)&&K.set(t,s),await E(),s}async function se(e,t){let n=j.type===`step`||j.type===`activation`;for(let r of K.values())!t&&n&&re.has(r.type)||await r.release({failed:e.failed,error:e.error,outcome:`abandoned`})}async function ce(e){if(q.size>0&&await Promise.allSettled(q),W)return;let t=Q();t.recordOutputs||(e={...e,error:void 0}),G?.failed&&(e={...e,outcome:e.outcome===`completed`?`failed`:e.outcome,failed:!0,error:G.error,errorCode:e.errorCode??G.errorCode}),W=!0,G=e,await se(e,e.failed===!0||!n.durable),V??=p.start(M,A,P,H);let i=j.type===`activation`&&e.usage===void 0?{...e,usage:J}:e;try{r(V,j,i,{...t,emit:A.emit},O,d)}catch(e){h(e,{phase:`complete`,operation:j.type,reference:H})}if(a(V,X),j.type===`model`&&e.model!==void 0){await C?.usage(e.model.usage,D);let n=e.model.content;if(t.recordOutputs&&A.recordOutputs&&n!==void 0){let t=d.outputMessages(n,e.model.finishReason);t!==void 0&&C?.turnContent({output:t})}}V.end(e.endTimeMs),await E()}let $={waitUntil(e){q.add(e),C?.waitUntil(e),e.then(()=>q.delete(e),()=>q.delete(e))},snapshot:()=>ee($.record()),attributes:e=>$.update({attributes:e}),modelCall:(e,t)=>$.child({type:`model`,options:e},t),fail(e){return $.error(e),$.complete({outcome:`failed`,failed:!0})},update(e){if(W)return;let n=t(e.attributes??{},Q())??e.attributes;M={...M,attributes:{...M.attributes,...n},links:e.links??M.links},V!==void 0&&a(V,n),Z()},useContext(e){P=e;for(let t of K.values())t.useContext(e)},refine(e,t){if(W||V!==void 0)return;if(t!==void 0&&t<O&&(O=t),e.type===`tool`&&j.type===`tool`){let t=j.options;j=c({type:`tool`,options:{...t,kind:t.kind??e.options.kind,arguments:t.arguments??(Q().recordInputs?g(e.options.arguments):void 0)}},A)}let n=l({identity:_,data:j,attempt:w,capture:A,key:D,parent:k,startTimeMs:O,links:M.links},d),r=Object.fromEntries(Object.entries(n.attributes).filter(([,e])=>e!==void 0));M={...M,name:n.name,kind:n.kind,startTimeMs:O,attributes:{...M.attributes,...r}},Z()},narrow(n){A={...e(A,n),emit:A.emit},j=c(j,A);let r=t(M.attributes,A)??M.attributes;M={...M,attributes:j.type===`activation`?{...r,"agent.trace.content.input":A.recordInputs,"agent.trace.content.output":A.recordOutputs}:r};let i=t(X,A)??X;for(let e of Object.keys(X))e in i||delete X[e];!A.recordOutputs&&G?.error!==void 0&&(G={...G,error:void 0}),V?.narrow(A);for(let e of K.values())e.narrow(A);Z()},async release(e){W?await se(e,e.failed===!0||!n.durable):await ce(z(e))},record(){return F({version:1,finished:W,terminal:G,usage:J,usageKeys:[...Y],attributes:{...M.attributes,...X},childSequence:ie,children:[...K.values()].filter(e=>!e.settled).map(e=>e.record()),key:D,identity:_,data:j,capture:A,reference:H,parent:k,startTimeMs:O,attempt:w,links:M.links},d)},get parent(){return k},get startTimeMs(){return O},child(e,t,r){if(!o(e).includes(j.type))throw Error(`The operation is not permitted in this trace scope.`);let i=t===void 0?(n.durable?R(e):void 0)??`${e.type}:${ie++}`:`${e.type}:${L(t)}`;return oe(e,`${D}/${i}`,r)},find(e){let t=R(e),n=t===void 0?void 0:K.get(`${D}/${t}`);return n===void 0||n.settled?void 0:n},get children(){return[...K.values()].filter(e=>!e.settled)},type:j.type,reference:H,callId:ae,get capture(){return A},mcp:u({serializer:d,...A,write(e){let n=t(e,Q())??e;Object.assign(X,n),V!==void 0&&a(V,n)},error(e,t){$.error(e,t)}}),get finished(){return W},get settled(){return W&&[...K.values()].every(e=>e.settled)},run(t,n){if(W)throw Error(`The trace scope has already finished.`);let r=e(e(A,n),s.active()?.capture),i=j.type===`tool`&&(j.options.kind===`subagent-call`||j.options.kind===`remote-agent-call`)?j.options:void 0,a=i===void 0?t:()=>m({caller:H,conversationId:_.conversationId,parentRunId:_.runId,parentCallId:i.callId,agentName:i.name,capture:r},t);return S(s,{type:$.type,reference:H,capture:r,mcp:$.mcp},a,P)},async complete(e=G??{}){W||await ce(z(e))},async usage(e,t){t!==void 0&&Y.has(t)||(t!==void 0&&Y.add(t),V!==void 0&&a(V,i(e)),J={inputTokens:e.inputTokens===void 0?J?.inputTokens:(J?.inputTokens??0)+e.inputTokens,outputTokens:e.outputTokens===void 0?J?.outputTokens:(J?.outputTokens??0)+e.outputTokens,costUsd:e.costUsd===void 0?J?.costUsd:(J?.costUsd??0)+e.costUsd},await C?.usage(e,t))},turnContent(e){if(j.type!==`activation`)return C?.turnContent(e);if(W)return;let t={};e.input!==void 0&&M.attributes[`gen_ai.input.messages`]===void 0&&(t[`gen_ai.input.messages`]=e.input),e.output!==void 0&&(t[`gen_ai.output.messages`]=e.output),Object.keys(t).length>0&&$.update({attributes:t})},error(e,t){G={...G,failed:!0,error:Q().recordOutputs?e instanceof Error?f(e):g(e):void 0,errorCode:t??(e instanceof Error?e.name:void 0)},V!==void 0&&V.fail(G.error,G.errorCode),Z()}};for(let t of T.children??[])K.set(t.key,await y(t.identity,e(t.capture,A),t.data,$,t.attempt,{...t,deferred:!0,executionContext:P},E));!W&&V!==void 0&&j.type===`step`&&V.addEvent(`step.started`,void 0,O);let le=M.attributes[`gen_ai.input.messages`];return!W&&j.type===`model`&&typeof le==`string`&&C?.turnContent({input:le}),$}return{start(e){return y(e.identity,e.capture,e.data,void 0,void 0,{key:e.key,parent:e.parent,reference:e.reference,sample:e.reference!==void 0&&e.data.type===`activation`,startTimeMs:e.startTimeMs,links:e.links,executionContext:e.context},e.onChange??(()=>Promise.resolve()))},async restore(t,n={}){if(!P(t))h(Error(`Invalid tracing checkpoint.`),{phase:`restore`});else return y(t.identity,e(t.capture,n.capture),t.data,void 0,t.attempt,{...t,deferred:!0,executionContext:n.context},n.onChange??(()=>Promise.resolve()))}}}function V(e,t,n){try{e?.(t,{phase:n})}catch{}}function H(e,t={outcome:`completed`},n){async function r(r,i){if(i===void 0)return e(r);let a=await e(r),o=t;try{let e=await a.run(()=>i(a));try{o=r.describe?.(e)??t}catch(e){V(n,e,`complete`)}return e}catch(e){throw o={outcome:`failed`,errorType:e instanceof Error?e.name:`_OTHER`,error:e},e}finally{try{await a.complete(o)}catch(e){V(n,e,`complete`)}}}return r}function U(e,t,n){let r=t=>Object.defineProperties(t,{finished:{get:()=>e.finished},capture:{get:()=>e.capture},parent:{get:()=>e.parent}}),i={type:e.type,reference:e.reference,get startTimeMs(){return e.startTimeMs},get parent(){return e.parent},get finished(){return e.finished},get capture(){return e.capture},run:(t,n)=>e.run(t,n),attributes:t=>e.attributes(t),complete:t=>e.complete(t),fail:t=>e.fail(t),recordError:(t,n)=>e.error(t,n)},a=async(t,r,i)=>U(await e.child(t,r,i),t,n),o=H(async({startTimeMs:e,...t})=>a({type:`tool`,options:t},void 0,{startTimeMs:e}),void 0,n),s=e=>e===void 0?void 0:U(e,e.record().data,n),c=H(async e=>a({type:`memory`,options:e}),void 0,n),l=t=>({findApproval:n=>s(e.find({type:`approval`,options:{requestId:n,...t}})),approval:H(async e=>a({type:`approval`,options:{...e,...t}}),{outcome:`ignored`},n)});if(t.type===`activation`)return r({...i,memory:c,...l(),links:t=>e.update({links:t}),findAttempt:t=>s(e.find({type:`step`,options:{index:t.stepIndex,attempt:t.attempt}})),findTool:t=>s(W(e,t)),attempt:H(async e=>a({type:`step`,options:{index:e.stepIndex,attempt:e.attempt,runtimeContext:e.runtimeContext,channel:e.channel}},void 0,{links:e.links}),void 0,n)});if(t.type===`step`){let t=e=>H(async t=>a({type:`tool`,options:{callId:t.callId,name:t.agentName,kind:e}}),void 0,n),s=(e,t)=>a({type:`model`,options:e},t);async function l(e,t){if(typeof t!=`function`)return s(e,t);let r=await s(e),i;try{i=await r.run(t)}catch(e){try{await r.fail(e)}catch(e){V(n,e,`complete`)}throw e}try{await r.complete({outcome:`completed`,result:i})}catch(e){V(n,e,`complete`)}return i.result}return r({...i,memory:c,tool:o,callSubAgent:t(`subagent-call`),callRemoteAgent:t(`remote-agent-call`),modelCall:l,async modelStream(t,r){let i=await s(t);try{let t=await i.run(r),a=Promise.resolve(t.completion).then(e=>i.complete({outcome:`completed`,result:e}),e=>i.fail(e)).catch(e=>V(n,e,`complete`));return e.waitUntil(a),t.result}catch(e){try{await i.fail(e)}catch(e){V(n,e,`complete`)}throw e}}})}return t.type===`tool`?r({...i,memory:c,tool:o,...l({callId:t.options.callId,toolName:t.options.name})}):i}function W(e,t){for(let n of e.children){if(n.type===`tool`&&n.callId===t)return n;if(n.type===`step`||n.type===`tool`){let e=W(n,t);if(e!==void 0)return e}}}const G={emit:!0,recordInputs:!1,recordOutputs:!1};function K(t){let n=t.telemetry??s(),r=t.checkpointer;if(r!==void 0&&n.ids===void 0)throw Error(`Durable agent tracing needs stable span IDs. Pass the AgentSpanIdGenerator installed on your tracer provider to otelTelemetry({ idGenerator }).`);let i=(e,n)=>{try{t.onError?.(e,n)}catch{}},a=B({telemetry:n,serializer:t.serializer??p,durable:r!==void 0,onError:t.onError}),o=new Map;function c(e){return r===void 0?`turn:${v()}`:[`turn`,e.runId,e.turnId].map(encodeURIComponent).join(`:`)}function l(e,t){let n=Promise.resolve();return()=>{let a=t();return r===void 0||a===void 0||a.retired||(a.writes++,n=n.then(async()=>{try{if(a.root.settled)o.delete(e),await r.delete(e);else{let t=v();await r.set(e,ee({...a.root.record(),revision:t})),a.revision=t,a.revisions.size<1e4&&a.revisions.add(t)}}catch(e){i(e,{phase:`checkpoint`,operation:`activation`})}finally{a.writes--}})),n}}async function u(e){try{return await r.get(e)}catch(e){i(e,{phase:`restore`,operation:`activation`});return}}async function d(t,n,i,o,s){let c=h()?.capture;s=s===void 0?c:e(s,c);let d=r===void 0?void 0:await u(t),f=d?.revision;if(n!==void 0&&(n.writes>0||f===n.revision||f!==void 0&&n.revisions.has(f)))return o!==void 0&&n.root.useContext(o),s!==void 0&&n.root.narrow(s),n;n!==void 0&&(n.retired=!0);let p,m=l(t,()=>p),g=d===void 0?void 0:await a.restore(d,{capture:s,context:o,onChange:m}),_=g??await i?.(m);if(_!==void 0)return p={root:_,revision:f,revisions:new Set(f===void 0?[]:[f]),retired:!1,writes:0},g===void 0&&await m(),p}function f(e,t){let n=o.get(e),r=(async()=>t(n===void 0?void 0:await n.catch(()=>void 0)))();return o.set(e,r),r.then(t=>{(t===void 0||t.root.settled)&&o.delete(e)},()=>o.delete(e)),o.size>1e3&&o.delete(o.keys().next().value),r}function m(t,r){return i=>{let o=h(),s=e(t.capture??G,o?.capture),c=o!==void 0&&t.sequence===0,l=t.parent??(c&&o?.remote!==!0?o?.caller:void 0),u=[...c&&o?.remote===!0?[{relationship:`agent.dispatch`,context:o.caller}]:[],...t.links??[]];return a.start({identity:{...t.identity,conversationId:o?.conversationId??t.identity.conversationId,agentName:t.agentName,framework:t.framework},key:r,capture:s,parent:l,reference:n.ids===void 0?void 0:t.reference,startTimeMs:t.startTimeMs,data:{type:`activation`,options:{sequence:t.sequence,attributes:t.attributes,channel:t.channel,subagent:o!==void 0||t.lineage!==void 0,subagentName:o?.agentName??t.lineage?.agentName,parentRunId:o?.parentRunId??t.lineage?.parentRunId,parentCallId:o?.parentCallId??t.lineage?.parentCallId}},links:u.length===0?void 0:u,context:t.context,onChange:i})}}function g(e){return U(e,{type:`activation`,options:{sequence:0}},t.onError)}async function _(e){let t=c(e.identity);return g((r===void 0?await d(t,void 0,m(e,t),e.context):await f(t,n=>d(t,n,m(e,t),e.context,e.capture))).root)}async function y(e){if(r===void 0)return;let t=c(e.identity),n=await f(t,n=>d(t,n,void 0,e.context));return n===void 0?void 0:g(n.root)}async function b(e){try{await e()}catch(e){i(e,{phase:`complete`})}}async function x(e,t,r){let o=n.active(),s=await a.start({identity:t.identity,key:`memory:${v()}`,capture:t.capture??o?.capture??G,parent:t.parent??o?.reference,context:t.context,data:{type:`memory`,options:{operation:e,phase:t.phase,slot:t.slot,storeId:t.storeId}}}),c;try{c=await s.run(r)}catch(e){throw await s.fail(e).catch(e=>i(e,{phase:`complete`})),e}return await s.complete({outcome:`completed`,...t.describe?.(c)}).catch(e=>i(e,{phase:`complete`})),c}return{turn:H(_,void 0,t.onError),resume:y,memory:{search:(e,t)=>x(`search_memory`,e,t),write:(e,t)=>x(`upsert_memory`,e,t)},forceFlush:()=>b(()=>n.forceFlush()),shutdown:()=>b(()=>n.shutdown())}}export{y as AgentSpanIdGenerator,K as createAgentRun,n as currentCapture,s as otelTelemetry};
|
|
@@ -46,6 +46,17 @@ export interface TurnOperation extends Operation {
|
|
|
46
46
|
/** Replaces the turn's links before its deferred span is exported. */
|
|
47
47
|
links(links: readonly TraceLink[]): void;
|
|
48
48
|
memory: WrappedOperation<MemoryInput, MemoryOperation>;
|
|
49
|
+
/** A wait on a person that no tool call owns, such as a budget prompt or a sign-in. */
|
|
50
|
+
approval: WrappedOperation<ApprovalInput, ApprovalOperation>;
|
|
51
|
+
/** Returns an open turn-level approval without starting one. Durable turns only. */
|
|
52
|
+
findApproval(requestId: string): ApprovalOperation | undefined;
|
|
53
|
+
}
|
|
54
|
+
/** What a person is asked. `kind` defaults to `tool-approval`. */
|
|
55
|
+
export interface ApprovalInput {
|
|
56
|
+
readonly requestId: string;
|
|
57
|
+
readonly request?: unknown;
|
|
58
|
+
readonly kind?: string;
|
|
59
|
+
readonly connectionName?: string;
|
|
49
60
|
}
|
|
50
61
|
/**
|
|
51
62
|
* One tool call. In a durable turn, calling `tool` again with the same `callId`
|
|
@@ -71,10 +82,7 @@ export interface AttemptOperation extends Operation {
|
|
|
71
82
|
memory: WrappedOperation<MemoryInput, MemoryOperation>;
|
|
72
83
|
}
|
|
73
84
|
export interface ToolOperation extends Operation {
|
|
74
|
-
approval: WrappedOperation<
|
|
75
|
-
requestId: string;
|
|
76
|
-
request?: unknown;
|
|
77
|
-
}, ApprovalOperation>;
|
|
85
|
+
approval: WrappedOperation<ApprovalInput, ApprovalOperation>;
|
|
78
86
|
/** Returns an open approval without starting one. Durable turns only. */
|
|
79
87
|
findApproval(requestId: string): ApprovalOperation | undefined;
|
|
80
88
|
/** A tool call made while this tool runs, such as a connector's nested call. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{v as CONTENT_ATTRIBUTE_LIMIT,c as USAGE_FIELDS,f as activeTraceOperation,b as boundedPrincipalId,S as contentAttribute,a as invocationName,t as mcpLifecycle,C as telemetryByteLength,w as truncateTelemetryText,g as withCapture,m as withErrorContent,d as withoutDeclinedContent}from"../../_chunks/workflow/mcp-LeXvhyIJ.js";
|
|
@@ -99,6 +99,21 @@ export interface Webhook<T extends Request> extends Hook<T> {
|
|
|
99
99
|
*/
|
|
100
100
|
url: string;
|
|
101
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Options accepted by the orchestrator's `createHook` for hooks the SDK
|
|
104
|
+
* itself creates (the `AbortController` signal hook, the child-run completion
|
|
105
|
+
* hook). Deliberately not part of the public {@link HookOptions}.
|
|
106
|
+
*
|
|
107
|
+
* A system hook is an ordinary hook (same tokens, conflicts, resumes and
|
|
108
|
+
* disposal) that is recorded with `isSystem: true`, so observability can
|
|
109
|
+
* label it and the runtime can treat it as written by another run: its
|
|
110
|
+
* resumes come from outside this run's replay.
|
|
111
|
+
*
|
|
112
|
+
* @internal
|
|
113
|
+
*/
|
|
114
|
+
export interface SystemHookOptions extends HookOptions {
|
|
115
|
+
isSystem?: boolean;
|
|
116
|
+
}
|
|
102
117
|
export interface HookOptions {
|
|
103
118
|
/**
|
|
104
119
|
* Unique token that is used to associate with the hook.
|
|
@@ -92,7 +92,7 @@ export interface EventsConsumerOptions {
|
|
|
92
92
|
isDeliveryIdle: () => boolean;
|
|
93
93
|
/**
|
|
94
94
|
* The run's start Hook id (`startHookId(runId)`), for a run started with
|
|
95
|
-
* `start(workflow, args, {
|
|
95
|
+
* `start(workflow, args, { experimental_hook })`. That Hook exists from the run's
|
|
96
96
|
* admission, so payloads can be resumed into it before the body calls
|
|
97
97
|
* `createHook` (even before `run_started`), and another run can force-claim
|
|
98
98
|
* it before then too.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,
|
|
2
|
-
`)}`)}return await
|
|
1
|
+
import{a as e,i as t,r as n,t as r}from"../../_chunks/workflow/attribute-changes-CZ1IbpSN.js";import{l as i,n as a}from"../../_chunks/workflow/resume-hook-ZanR4XtL.js";import{Di as o,Ei as s,Jr as c,Oi as l,Si as u,T as d,Ti as f,X as p,Z as m,bi as h,gi as g,i as _,pi as v,x as y,xi as b,yi as x}from"../../_chunks/workflow/serialization-BsJ0NayH.js";import{t as S}from"../../_chunks/workflow/sleep-C8DQfwTV.js";import{FatalError as C,FatalError as w,RetryableError as T}from"#compiled/@workflow/errors/index.js";function E(e){t(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,E)}function D(e){t(`createWebhook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-webhook`,D)}function O({schema:e}={}){function n(e){t(`defineHook().create()`,`https://workflow-sdk.dev/docs/api-reference/workflow/define-hook`,n)}return{create:n,async resume(t,n){if(!e?.[`~standard`])return await a(t,n);let r=e[`~standard`].validate(n);if(r instanceof Promise&&(r=await r),r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>String(typeof e==`object`&&e?e.key:e)).join(`.`);return t?` at "${t}": ${e.message}`:` ${e.message}`});throw Error(`Hook payload did not match the defined schema:\n${e.join(`
|
|
2
|
+
`)}`)}return await a(t,r.value)}}}async function k(e,t={}){let n=m.getStore(),a=n?.workflowMetadata?.workflowRunId;if(!a)throw new w(`setAttributes() must be called from a 'use workflow' or 'use step' function. Calling it from plain host code is not supported.`);let o={type:`step`,stepId:n.stepMetadata.stepId,attempt:n.stepMetadata.attempt},s=r(e,t,o);s.length!==0&&(n.runReadyBarrier&&await n.runReadyBarrier,await(await g()).events.create(a,{eventType:`attr_set`,specVersion:i(n.runSpecVersion),eventData:{changes:s,writer:o,...t.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{}}},{inBand:!1}))}function A(){let e=m.getStore();return e||n(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,A),e.stepMetadata}function j(){let t=m.getStore();return t||e(`getWorkflowMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-workflow-metadata`,j),t.workflowMetadata}function M(t={}){let n=m.getStore();n||e(`getWritable()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-writable`,M);let{namespace:r}=t,i=n.workflowMetadata.workflowRunId,a=p(i,r);n.writables??=new Map;let g=n.writables,S=g.get(a);if(S)return S.writable;let C=x();C.deferReleaseSettlement=n.streamStates!==void 0;let w=d(y(globalThis,n.ops,i,n.encryptionKey,!0,n.runReadyBarrier),n.encryptionKey),T=new _(i,a,n.runReadyBarrier);n.streamStates??=[],n.streamStates.push(C),n.ops.push(C.promise),h(w.readable,T,C).catch(()=>{});let E=u(w.writable,C);return b(E,C),Object.defineProperty(E,f,{value:a,writable:!1}),Object.defineProperty(E,l,{value:i,writable:!1}),n.workflowDeploymentId&&Object.defineProperty(E,s,{value:n.workflowDeploymentId,writable:!1}),c(n.encryptionKey)&&Object.defineProperty(E,o,{value:v(n.encryptionKey.keyPair.publicKey),writable:!1}),g.set(a,{writable:E,state:C}),E}export{C as FatalError,T as RetryableError,E as createHook,D as createWebhook,O as defineHook,A as getStepMetadata,j as getWorkflowMetadata,M as getWritable,k as setAttributes,S as sleep};
|