eve 0.89.0 → 0.91.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -9
- package/dist/src/channel/adapter.d.ts +12 -3
- package/dist/src/channel/adapter.js +1 -1
- package/dist/src/channel/auth/definitions.d.ts +7 -20
- package/dist/src/channel/auth/definitions.js +1 -1
- package/dist/src/channel/auth/http-basic.js +1 -1
- package/dist/src/channel/auth/jwt-ecdsa.js +1 -1
- package/dist/src/channel/auth/jwt-hmac.js +1 -1
- package/dist/src/channel/auth/oidc.js +1 -1
- package/dist/src/channel/auth/result.d.ts +2 -3
- package/dist/src/channel/auth/result.js +1 -1
- package/dist/src/channel/channel-address.d.ts +1 -1
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/channel-operations.d.ts +1 -1
- package/dist/src/channel/schedule.js +1 -1
- package/dist/src/channel/types.d.ts +2 -0
- package/dist/src/chunks/{use-eve-agent-Bbl4H5aA.js → use-eve-agent-Bwloorf8.js} +77 -63
- package/dist/src/chunks/{use-eve-agent-CNpxgKEH.js → use-eve-agent-XCB0-tLX.js} +77 -63
- package/dist/src/cli/dev/environment.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
- package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
- package/dist/src/cli/dev/tui/remote-connection-types.d.ts +1 -0
- package/dist/src/cli/dev/tui/runner.js +2 -2
- package/dist/src/cli/dev/tui/status-line.d.ts +2 -2
- package/dist/src/cli/dev/tui/status-line.js +1 -1
- package/dist/src/client/agent-info-schema.d.ts +341 -326
- package/dist/src/client/agent-info-schema.js +1 -1
- package/dist/src/client/agent-info-types.d.ts +13 -10
- package/dist/src/client/client-error.d.ts +1 -1
- package/dist/src/client/client.d.ts +5 -3
- package/dist/src/client/client.js +1 -1
- package/dist/src/client/session.d.ts +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/evals/target.js +1 -1
- package/dist/src/eve-channel/auth.d.ts +19 -0
- package/dist/src/eve-channel/auth.js +1 -0
- package/dist/src/eve-channel/index.d.ts +1 -0
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/types.d.ts +23 -4
- package/dist/src/execution/catalog/connection-entry.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/proxied-deliver-step.js +1 -1
- package/dist/src/execution/sandbox/bash.js +2 -2
- package/dist/src/execution/session/active-turn.js +1 -1
- package/dist/src/execution/session/admission.d.ts +6 -0
- package/dist/src/execution/session/admission.js +1 -1
- package/dist/src/execution/session/delivery-facts.js +1 -1
- package/dist/src/execution/session/next-input.d.ts +2 -2
- package/dist/src/execution/session/next-input.js +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session-inbox/inbox.d.ts +2 -2
- package/dist/src/execution/session-inbox/inbox.js +1 -1
- package/dist/src/execution/session-inbox/protocol.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/harness/compaction/engine.js +2 -2
- package/dist/src/harness/current-messages.js +1 -1
- package/dist/src/harness/emission.d.ts +3 -0
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/facts.d.ts +5 -2
- package/dist/src/harness/facts.js +1 -1
- package/dist/src/harness/model-call/call.d.ts +7 -1
- package/dist/src/harness/model-call/call.js +3 -1
- package/dist/src/harness/provider-tool-history.d.ts +8 -0
- package/dist/src/harness/provider-tool-history.js +1 -1
- package/dist/src/harness/session-machine/transitions.d.ts +3 -2
- package/dist/src/harness/step/after-model.js +1 -1
- package/dist/src/harness/step/context.js +1 -1
- package/dist/src/harness/step/intake.js +1 -1
- package/dist/src/harness/step/prompt.js +1 -1
- package/dist/src/harness/tool-history-repair.d.ts +2 -0
- package/dist/src/harness/tool-history-repair.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-module-graph.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +2 -2
- package/dist/src/protocol/routes.d.ts +7 -1
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/protocol/session-events/families/delivery.d.ts +5 -3
- package/dist/src/protocol/session-events/families/delivery.js +1 -1
- package/dist/src/protocol/session-projection/fold.js +1 -1
- package/dist/src/public/channels/discord/hitl.js +1 -1
- package/dist/src/public/channels/github/githubChannel.js +1 -1
- package/dist/src/public/channels/github/state.d.ts +7 -0
- package/dist/src/public/channels/github/state.js +1 -1
- package/dist/src/public/channels/mcp.js +1 -1
- package/dist/src/public/channels/slack/hitl.d.ts +2 -1
- package/dist/src/public/channels/slack/hitl.js +3 -3
- package/dist/src/public/channels/slack/interaction-cards.js +1 -1
- package/dist/src/public/channels/slack/request-card-render.js +1 -1
- package/dist/src/public/channels/teams/hitl.js +1 -1
- package/dist/src/public/channels/teams/verify.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/connections/index.d.ts +1 -1
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/connections/tool-call.d.ts +2 -2
- package/dist/src/public/definitions/hook.d.ts +90 -7
- package/dist/src/public/definitions/hook.js +1 -1
- package/dist/src/public/hooks/index.d.ts +3 -2
- package/dist/src/reactions/continuation.d.ts +19 -0
- package/dist/src/reactions/continuation.js +1 -0
- package/dist/src/reactions/frame.js +1 -1
- package/dist/src/reactions/intents.d.ts +10 -4
- package/dist/src/reactions/intents.js +1 -1
- package/dist/src/reactions/kinds/hook.js +1 -1
- package/dist/src/reactions/runner.js +1 -1
- package/dist/src/reactions/state.d.ts +15 -2
- package/dist/src/reactions/state.js +1 -1
- package/dist/src/runtime/channels/registry.d.ts +2 -2
- package/dist/src/runtime/channels/registry.js +1 -1
- package/dist/src/runtime/connections/approval-scope.d.ts +9 -0
- package/dist/src/runtime/connections/approval-scope.js +1 -0
- package/dist/src/runtime/connections/mcp-client.d.ts +1 -1
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/provided-arguments.js +1 -1
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/setup/primitives/open-url.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/agent-info-access.d.ts +5 -0
- package/dist/src/shared/agent-info-access.js +1 -0
- package/dist/src/shared/connection-types.d.ts +21 -4
- package/dist/src/shared/value-delta.d.ts +5 -4
- package/dist/src/shared/value-delta.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/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tools/provided/web-fetch.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +199 -222
- package/docs/channels/chat-sdk.mdx +60 -64
- package/docs/channels/custom.mdx +265 -280
- package/docs/channels/discord.mdx +176 -123
- package/docs/channels/eve.mdx +136 -204
- package/docs/channels/github.mdx +24 -22
- package/docs/channels/linear.mdx +30 -30
- package/docs/channels/linq.mdx +25 -13
- package/docs/channels/mcp.mdx +154 -116
- package/docs/channels/overview.mdx +31 -32
- package/docs/channels/photon.mdx +32 -56
- package/docs/channels/slack.mdx +538 -375
- package/docs/channels/teams.mdx +40 -26
- package/docs/channels/telegram.mdx +13 -13
- package/docs/channels/twilio.mdx +11 -11
- package/docs/code-extension.mdx +40 -42
- package/docs/concepts/built-in-tools.md +89 -57
- package/docs/concepts/context-control.md +20 -20
- package/docs/concepts/default-harness.md +20 -36
- package/docs/concepts/execution-model-and-durability.mdx +96 -160
- package/docs/concepts/project-structure.mdx +21 -14
- package/docs/concepts/security-model.md +27 -27
- package/docs/concepts/sessions-runs-and-streaming.md +184 -194
- package/docs/concepts/state.md +7 -15
- package/docs/connections/mcp.mdx +109 -93
- package/docs/connections/openapi.mdx +57 -59
- package/docs/connections/overview.mdx +205 -170
- package/docs/evals/assertions.mdx +36 -29
- package/docs/evals/cases.mdx +38 -42
- package/docs/evals/judge.mdx +21 -29
- package/docs/evals/overview.mdx +42 -38
- package/docs/evals/reporters.mdx +54 -27
- package/docs/evals/running.mdx +15 -8
- package/docs/evals/targets.mdx +17 -18
- package/docs/evals/tool-stubs.mdx +111 -97
- package/docs/experimental/dynamic-schedules.mdx +118 -63
- package/docs/extensions.md +58 -65
- package/docs/getting-started.mdx +4 -6
- package/docs/guides/auth-and-route-protection.md +100 -70
- package/docs/guides/client/continuations.mdx +23 -26
- package/docs/guides/client/messages.mdx +47 -66
- package/docs/guides/client/output-schema.mdx +8 -8
- package/docs/guides/client/overview.mdx +47 -41
- package/docs/guides/client/streaming.mdx +62 -71
- package/docs/guides/decide.md +24 -79
- package/docs/guides/deployment/meta.json +1 -1
- package/docs/guides/deployment/overview.md +27 -18
- package/docs/guides/deployment/self-hosted-operations.md +99 -0
- package/docs/guides/deployment/self-hosting.md +63 -80
- package/docs/guides/deployment/vercel.mdx +31 -27
- package/docs/guides/deployment/workflow-worlds.md +100 -0
- package/docs/guides/dev-tui.md +48 -41
- package/docs/guides/dynamic-capabilities.md +49 -50
- package/docs/guides/frontend/nextjs.mdx +2 -2
- package/docs/guides/frontend/nuxt.mdx +11 -11
- package/docs/guides/frontend/overview.mdx +1 -1
- package/docs/guides/frontend/sveltekit.mdx +11 -11
- package/docs/guides/frontend/tanstack.mdx +16 -16
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +21 -21
- package/docs/guides/frontend/use-eve-agent-vue.mdx +22 -22
- package/docs/guides/frontend/use-eve-agent.mdx +25 -25
- package/docs/guides/hooks.md +152 -106
- package/docs/guides/instrumentation/agent-runs.mdx +26 -30
- package/docs/guides/instrumentation/instrumentation.mdx +49 -76
- package/docs/guides/instrumentation/meta.json +1 -1
- package/docs/guides/instrumentation/otel.mdx +113 -179
- package/docs/guides/prepare-for-1-0.md +23 -1
- package/docs/guides/remote-agents.md +125 -187
- package/docs/guides/self-modification.md +18 -18
- package/docs/guides/session-context.md +16 -16
- package/docs/install-integrations.mdx +26 -24
- package/docs/instructions.mdx +37 -42
- package/docs/memory/custom-provider.md +35 -41
- package/docs/memory/file.md +93 -76
- package/docs/memory/overview.mdx +145 -156
- package/docs/patterns/durable-cross-channel-notifications.md +15 -19
- package/docs/patterns/dynamic-scheduling.md +19 -23
- package/docs/patterns/multi-tenant-approvals.md +17 -22
- package/docs/patterns/multi-tenant-auth.md +43 -42
- package/docs/patterns/multi-tenant-memory.md +39 -36
- package/docs/patterns/voice-notes.md +3 -3
- package/docs/protocols/acp.md +13 -13
- package/docs/protocols/ucp.mdx +7 -7
- package/docs/reference/agent-files.md +6 -6
- package/docs/reference/cli.md +99 -98
- package/docs/reference/telemetry.md +1 -1
- package/docs/reference/typescript-api.md +52 -53
- package/docs/responsible-use.md +2 -2
- package/docs/sandbox/custom-providers.mdx +60 -56
- package/docs/sandbox/default.mdx +23 -24
- package/docs/sandbox/docker.mdx +16 -10
- package/docs/sandbox/index.mdx +93 -61
- package/docs/sandbox/just-bash.mdx +17 -11
- package/docs/sandbox/troubleshooting.mdx +29 -23
- package/docs/sandbox/vercel.mdx +45 -52
- package/docs/schedules.mdx +65 -54
- package/docs/skills.mdx +74 -49
- package/docs/subagents/index.mdx +97 -136
- package/docs/tools/human-in-the-loop.md +160 -90
- package/docs/tools/meta.json +1 -1
- package/docs/tools/overview.mdx +229 -237
- package/docs/tools/tasks.md +118 -117
- package/docs/tools/workflows.mdx +447 -543
- package/docs/tutorial/connect-a-warehouse.mdx +11 -13
- package/docs/tutorial/first-agent.mdx +14 -16
- package/docs/tutorial/guard-the-spend.mdx +6 -8
- package/docs/tutorial/how-it-runs.mdx +8 -8
- package/docs/tutorial/query-sample-data.mdx +8 -8
- package/docs/tutorial/remember-definitions.mdx +4 -4
- package/docs/tutorial/run-analysis.mdx +20 -22
- package/docs/tutorial/ship-it.mdx +19 -19
- package/docs/tutorial/team-playbooks.mdx +9 -9
- package/docs/use-cases.mdx +13 -11
- package/package.json +1 -1
- package/docs/guides/instrumentation/migration.md +0 -96
- package/docs/tools/tasks-upgrade.md +0 -218
|
@@ -2,6 +2,8 @@ import type { AuthoringEventType } from "#protocol/session-events/authoring.js";
|
|
|
2
2
|
import type { SessionEvent } from "../../protocol/session-event.js";
|
|
3
3
|
import type { FactPosition } from "../../protocol/session-events/envelope.js";
|
|
4
4
|
import type { Memo, Occurrence, SessionFrame } from "../../dynamic/definition.js";
|
|
5
|
+
import type { SessionSendOptions } from "#channel/session.js";
|
|
6
|
+
import type { MessageContent } from "#shared/message-content.js";
|
|
5
7
|
import type { SessionContext } from "./callback-context.js";
|
|
6
8
|
import type { ExactDefinition } from "./exact.js";
|
|
7
9
|
type ProtocolEvent<TType extends SessionEvent["type"]> = Extract<SessionEvent, {
|
|
@@ -23,11 +25,78 @@ export type HookEventType = keyof HookEventMap;
|
|
|
23
25
|
export type HookEventKey = HookEventType | "*";
|
|
24
26
|
/** Event received by a handler for one authored hook event key. */
|
|
25
27
|
export type HookEvent<TKey extends HookEventKey = HookEventType> = TKey extends HookEventType ? HookEventMap[TKey] : HookEventMap[HookEventType];
|
|
28
|
+
/**
|
|
29
|
+
* Which handlers may continue a turn with `ctx.continue()`, by event key. Total over every
|
|
30
|
+
* key, so a new hook event doesn't compile until it chooses.
|
|
31
|
+
*/
|
|
32
|
+
export declare const HOOK_CONTINUE_KEYS: {
|
|
33
|
+
readonly "*": true;
|
|
34
|
+
readonly "call.input": false;
|
|
35
|
+
readonly "call.progress": false;
|
|
36
|
+
readonly "call.requested": false;
|
|
37
|
+
readonly "call.settled": false;
|
|
38
|
+
readonly "call.started": false;
|
|
39
|
+
readonly "child.opened": false;
|
|
40
|
+
readonly "content.completed": false;
|
|
41
|
+
readonly "content.delta": false;
|
|
42
|
+
readonly "context.settled": false;
|
|
43
|
+
readonly "context.started": false;
|
|
44
|
+
readonly "delivery.admitted": false;
|
|
45
|
+
readonly "delivery.consumed": false;
|
|
46
|
+
readonly "delivery.settled": false;
|
|
47
|
+
readonly "interaction.opened": false;
|
|
48
|
+
readonly "interaction.settled": false;
|
|
49
|
+
readonly "model.requested": false;
|
|
50
|
+
readonly "model.retried": false;
|
|
51
|
+
readonly "model.settled": false;
|
|
52
|
+
readonly "model.started": false;
|
|
53
|
+
readonly "response.admitted": false;
|
|
54
|
+
readonly "response.settled": false;
|
|
55
|
+
readonly "response.submitted": false;
|
|
56
|
+
readonly "session.ended": false;
|
|
57
|
+
readonly "session.started": false;
|
|
58
|
+
readonly "task.ended": false;
|
|
59
|
+
readonly "task.started": false;
|
|
60
|
+
readonly "turn.paused": false;
|
|
61
|
+
readonly "turn.settled": true;
|
|
62
|
+
readonly "turn.started": false;
|
|
63
|
+
readonly "usage.recorded": false;
|
|
64
|
+
};
|
|
65
|
+
/** Event keys whose handlers receive `ctx.continue()`: `turn.settled`, and `*`. */
|
|
66
|
+
export type HookContinueEventKey = {
|
|
67
|
+
[K in HookEventKey]: (typeof HOOK_CONTINUE_KEYS)[K] extends true ? K : never;
|
|
68
|
+
}[HookEventKey];
|
|
69
|
+
/**
|
|
70
|
+
* Options for `ctx.continue()`: the shared send options' `context`, and `auth`, optional. Omitted,
|
|
71
|
+
* `auth` names no sender, and the turn runs as the session's current identity. A principal makes
|
|
72
|
+
* the turn act for them, and `null` runs it with no caller, as with `session.send()`. There's no
|
|
73
|
+
* `idempotencyKey`: a turn has one continuation, which eve records with the step and admits once.
|
|
74
|
+
*/
|
|
75
|
+
export type HookContinueOptions = Pick<SessionSendOptions, "context"> & Partial<Pick<SessionSendOptions, "auth">>;
|
|
76
|
+
/**
|
|
77
|
+
* What `ctx.continue()` did, decided when it's called. `queued` means eve recorded the message;
|
|
78
|
+
* another turn that starts first, a cancel, a clear, or a reset still drops it.
|
|
79
|
+
*/
|
|
80
|
+
export type HookContinueResult = {
|
|
81
|
+
readonly queued: true;
|
|
82
|
+
} | {
|
|
83
|
+
readonly queued: false;
|
|
84
|
+
/**
|
|
85
|
+
* `not-settled`: a `*` handler ran for an event other than `turn.settled`.
|
|
86
|
+
* `not-completed`: the turn failed, or something other than this hook cancelled it.
|
|
87
|
+
* `already-queued`: this hook already continued this turn.
|
|
88
|
+
* `auth-conflict`: another hook's continuation of this turn acts for a different principal.
|
|
89
|
+
*/
|
|
90
|
+
readonly reason: "not-settled" | "not-completed" | "already-queued" | "auth-conflict";
|
|
91
|
+
};
|
|
26
92
|
/**
|
|
27
93
|
* Every hook handler receives this context: the session as of the commit the event is in, the
|
|
28
|
-
* handler's occurrence, and the ways a hook acts.
|
|
94
|
+
* handler's occurrence, and the ways a hook acts. Handlers for {@link HookContinueEventKey} also
|
|
95
|
+
* receive {@link HookContinue.continue}.
|
|
29
96
|
*/
|
|
30
|
-
export
|
|
97
|
+
export type HookContext<TKey extends HookEventKey = HookEventKey> = HookBaseContext & ([TKey] extends [HookContinueEventKey] ? HookContinue : unknown);
|
|
98
|
+
/** What every hook handler receives. */
|
|
99
|
+
export interface HookBaseContext extends SessionContext, Omit<SessionFrame, "session"> {
|
|
31
100
|
readonly session: SessionContext["session"] & SessionFrame["session"];
|
|
32
101
|
readonly agent: {
|
|
33
102
|
readonly name: string;
|
|
@@ -53,18 +122,32 @@ export interface HookContext extends SessionContext, Omit<SessionFrame, "session
|
|
|
53
122
|
*/
|
|
54
123
|
cancel(reason?: string): void;
|
|
55
124
|
}
|
|
125
|
+
/** What `turn.settled` and `*` handlers receive besides {@link HookBaseContext}. */
|
|
126
|
+
export interface HookContinue {
|
|
127
|
+
/**
|
|
128
|
+
* Starts the session's next turn with `message` after a turn completes, or after a turn this
|
|
129
|
+
* hook cancelled, to redirect it. The message is recorded now and admitted once the session is
|
|
130
|
+
* idle, as a delivery whose source names this hook and the channel, and the model is told no
|
|
131
|
+
* person wrote it. Hooks that continue the same turn share one next turn, each message its own
|
|
132
|
+
* payload, in hook order. It yields: any other turn that starts first, a `session.cancel()`, a
|
|
133
|
+
* clear, or a reset drops it, so a person's input always wins. Unlike `session.send()`, it returns synchronously and there's no
|
|
134
|
+
* receipt: the delivery doesn't exist until the session admits it. Like other hook effects, it's
|
|
135
|
+
* lost if the step is interrupted before it's saved. Throws after the handler has settled.
|
|
136
|
+
*/
|
|
137
|
+
continue(message: MessageContent, options?: HookContinueOptions): HookContinueResult;
|
|
138
|
+
}
|
|
56
139
|
/**
|
|
57
140
|
* Handler for one accepted session event. `TEvent` is one variant of {@link HookEvent}, which
|
|
58
141
|
* {@link StreamEventHooks} infers from the event key.
|
|
59
142
|
*/
|
|
60
|
-
export type StreamEventHook<TEvent> = (event: TEvent, ctx: HookContext) => void | Promise<void>;
|
|
143
|
+
export type StreamEventHook<TEvent, TKey extends HookEventKey = HookEventKey> = (event: TEvent, ctx: HookContext<TKey>) => void | Promise<void>;
|
|
61
144
|
/**
|
|
62
145
|
* Map of event handlers an authored hook file may declare. `*` runs for every fact the session
|
|
63
146
|
* commits, after the typed handler for that event (if any). Progress (streamed deltas and partial
|
|
64
147
|
* results) reaches a hook only through its own key, such as `content.delta`.
|
|
65
148
|
*/
|
|
66
149
|
export type StreamEventHooks<TKey extends HookEventKey = HookEventKey> = {
|
|
67
|
-
readonly [TKey_ in TKey]?: StreamEventHook<HookEvent<TKey_
|
|
150
|
+
readonly [TKey_ in TKey]?: StreamEventHook<HookEvent<TKey_>, TKey_>;
|
|
68
151
|
};
|
|
69
152
|
/**
|
|
70
153
|
* Public hook definition authored in `agent/hooks/*.ts`: a map of event handlers, each called
|
|
@@ -76,9 +159,9 @@ export interface HookDefinition<TKey extends HookEventKey = HookEventKey> {
|
|
|
76
159
|
type DefinedHookEventKeys<TDefinition extends HookDefinition> = Extract<keyof TDefinition["events"], HookEventKey>;
|
|
77
160
|
/**
|
|
78
161
|
* Defines a hook. Each handler runs once for each matching fact a commit carries, before the next
|
|
79
|
-
* model call. A handler can call `ctx.cancel` or an external
|
|
80
|
-
* `ctx.occurrence.idempotencyKey` to services that support idempotency. A retry
|
|
81
|
-
* handlers again for facts already published. A handler that throws during a turn fails the turn;
|
|
162
|
+
* model call. A handler can call `ctx.cancel`, `ctx.continue` from `turn.settled`, or an external
|
|
163
|
+
* service. Pass `ctx.occurrence.idempotencyKey` to services that support idempotency. A retry
|
|
164
|
+
* does not run handlers again for facts already published. A handler that throws during a turn fails the turn;
|
|
82
165
|
* catch optional errors.
|
|
83
166
|
*
|
|
84
167
|
* ```ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function defineHook(e){return assertHookForm(e,`defineHook()`),e}function assertHookForm(e,t){if(typeof e!=`object`||!e)throw Error(`${t} takes an object with events handlers.`);let{events:n,...r}=e,i=Object.keys(r).filter(e=>e!==`kind`);if(i.length>0)throw Error(`${t} takes only events handlers; unknown key(s): ${i.join(`, `)}. A hook acts on a condition from a handler, such as "*", with ctx.cancel.`);if(typeof n!=`object`||!n)throw Error(`${t} requires events: an object of handlers keyed by event type.`)}export{assertHookForm,defineHook};
|
|
1
|
+
const HOOK_CONTINUE_KEYS={"*":!0,"call.input":!1,"call.progress":!1,"call.requested":!1,"call.settled":!1,"call.started":!1,"child.opened":!1,"content.completed":!1,"content.delta":!1,"context.settled":!1,"context.started":!1,"delivery.admitted":!1,"delivery.consumed":!1,"delivery.settled":!1,"interaction.opened":!1,"interaction.settled":!1,"model.requested":!1,"model.retried":!1,"model.settled":!1,"model.started":!1,"response.admitted":!1,"response.settled":!1,"response.submitted":!1,"session.ended":!1,"session.started":!1,"task.ended":!1,"task.started":!1,"turn.paused":!1,"turn.settled":!0,"turn.started":!1,"usage.recorded":!1};function defineHook(e){return assertHookForm(e,`defineHook()`),e}function assertHookForm(e,t){if(typeof e!=`object`||!e)throw Error(`${t} takes an object with events handlers.`);let{events:n,...r}=e,i=Object.keys(r).filter(e=>e!==`kind`);if(i.length>0)throw Error(`${t} takes only events handlers; unknown key(s): ${i.join(`, `)}. A hook acts on a condition from a handler, such as "*", with ctx.cancel.`);if(typeof n!=`object`||!n)throw Error(`${t} requires events: an object of handlers keyed by event type.`)}export{HOOK_CONTINUE_KEYS,assertHookForm,defineHook};
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* Hook authoring helpers for `agent/hooks/*.ts` files.
|
|
3
3
|
*
|
|
4
4
|
* A hook is a map of event handlers: each runs once for each matching fact a commit carries. A
|
|
5
|
-
* handler can cancel the running turn with `ctx.cancel
|
|
5
|
+
* handler can cancel the running turn with `ctx.cancel`, or start the session's next turn
|
|
6
|
+
* with `ctx.continue` once a turn settles. External effects use
|
|
6
7
|
* `ctx.occurrence.idempotencyKey` for services that support idempotency.
|
|
7
8
|
*/
|
|
8
|
-
export { type HookContext, type HookDefinition, type HookEvent, type HookEventKey, type HookEventMap, type HookEventType, type StreamEventHook, type StreamEventHooks, defineHook, } from "#public/definitions/hook.js";
|
|
9
|
+
export { type HookContext, type HookDefinition, type HookEvent, type HookEventKey, type HookEventMap, type HookEventType, type HookContinueEventKey, type HookContinueOptions, type HookContinueResult, type StreamEventHook, type StreamEventHooks, defineHook, } from "#public/definitions/hook.js";
|
|
9
10
|
export type { DynamicKey, DynamicTurn, Memo, Occurrence, SessionFrame, } from "#dynamic/definition.js";
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { DeliverHookPayload } from "#channel/types.js";
|
|
2
|
+
export declare const REACTIONS_STATE_KEY = "eve.reactions";
|
|
3
|
+
/**
|
|
4
|
+
* The session's continuation of a settled turn: one delivery that starts its next turn, with a
|
|
5
|
+
* payload for each hook that called `ctx.continue()`. Any other turn that starts first discards it,
|
|
6
|
+
* as do a cancel, a clear, and a reset.
|
|
7
|
+
*/
|
|
8
|
+
export interface Continuation {
|
|
9
|
+
/** The settled turn it continues. */
|
|
10
|
+
readonly turnId: string;
|
|
11
|
+
readonly delivery: DeliverHookPayload;
|
|
12
|
+
}
|
|
13
|
+
/** The idempotency key of a turn's continuation: one delivery per settled turn. */
|
|
14
|
+
export declare function continuationKey(sessionId: string, turnId: string): string;
|
|
15
|
+
/**
|
|
16
|
+
* The continuation hooks queued after `latestTurnId` settled, while no other turn has started
|
|
17
|
+
* since. The session admits it only when nothing else waits.
|
|
18
|
+
*/
|
|
19
|
+
export declare function pendingContinuation(serializedContext: Readonly<Record<string, unknown>>, latestTurnId: string | undefined): DeliverHookPayload | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const REACTIONS_STATE_KEY=`eve.reactions`;function continuationKey(e,t){return`${e}:continue:${t}`}function pendingContinuation(e,t){let n=e[REACTIONS_STATE_KEY];return t!==void 0&&n?.continuation?.turnId===t?n.continuation.delivery:void 0}export{REACTIONS_STATE_KEY,continuationKey,pendingContinuation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readReactionsState,sessionIdOf}from"./state.js";import{latestTurn}from"./turn.js";import{
|
|
1
|
+
import{readReactionsState,sessionIdOf}from"./state.js";import{latestTurn}from"./turn.js";import{getAdapterKind}from"#channel/adapter.js";import{normalizeInstrumentationChannelKind}from"#shared/instrumentation-channel-kind.js";import{ConversationContextKey}from"#shared/conversation-context.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,ParentSessionKey,SessionPredecessorKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{currentView}from"#harness/session-machine/current.js";function channelOf(e){let t=e.get(ChannelKey),n=e.get(ChannelInstrumentationKey);return{continuationToken:e.get(ContinuationTokenKey),kind:normalizeInstrumentationChannelKind(n?.kind??(t===void 0?void 0:getAdapterKind(t))),metadata:n?.metadata??{}}}function sessionFrameOf(e,t={}){let n=e.get(ConversationContextKey),r=e.get(ParentSessionKey),i=t.view??currentView(e),a=t.at??readReactionsState(e).at??i.session.startedAt;return{channel:channelOf(e),...n!==void 0&&{conversation:n},now:new Date(a??0),session:{auth:{current:e.get(AuthKey)??null,initiator:e.get(InitiatorAuthKey)??null},id:sessionIdOf(e),...r!==void 0&&{parent:r},predecessor:e.get(SessionPredecessorKey),schedule:readSessionSchedule(e)},turn:latestTurn(i),view:snapshotOf(i)}}export{channelOf,sessionFrameOf};
|
|
@@ -1,15 +1,21 @@
|
|
|
1
|
+
import type { DeliverHookPayload } from "#channel/types.js";
|
|
1
2
|
import type { ContextContainer } from "#context/container.js";
|
|
2
3
|
import type { Reaction } from "./reaction.js";
|
|
3
4
|
import { type PendingIntent } from "./state.js";
|
|
4
5
|
/** A command a hook asked for, before it's queued. */
|
|
5
|
-
export
|
|
6
|
+
export type Command = {
|
|
6
7
|
readonly type: "cancel";
|
|
7
8
|
readonly reason?: string;
|
|
8
|
-
}
|
|
9
|
+
} | {
|
|
10
|
+
readonly type: "continue";
|
|
11
|
+
readonly turnId: string;
|
|
12
|
+
readonly delivery: DeliverHookPayload;
|
|
13
|
+
};
|
|
9
14
|
/**
|
|
10
|
-
* Adds
|
|
15
|
+
* Adds a hook's commands to the session's queue. Cancels between turns are dropped; each hook's
|
|
16
|
+
* continuation joins the turn's one continuation delivery.
|
|
11
17
|
*/
|
|
12
|
-
export declare function queueCommands(ctx: ContextContainer,
|
|
18
|
+
export declare function queueCommands(ctx: ContextContainer, reaction: Pick<Reaction, "id" | "label">, occurrence: string, commands: readonly Command[]): void;
|
|
13
19
|
/** Removes and returns the waiting intents that match, because the session acted on them. */
|
|
14
20
|
export declare function takeIntents(ctx: ContextContainer, matches: (intent: PendingIntent) => boolean): readonly PendingIntent[];
|
|
15
21
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readReactionsState,writeReactionsState}from"./state.js";import{createLogger}from"#internal/logging.js";import{toErrorMessage}from"#shared/errors.js";import{currentProjection}from"#harness/session-machine/current.js";import{activeTurnIdOf}from"#protocol/session-projection.js";const log=createLogger(`hooks`);function queueCommands(e,t,n,r){if(r.length===0)return;let i=readReactionsState(e),a=[...i.intents??[]],o=activeTurnIdOf(currentProjection(e)),
|
|
1
|
+
import{readReactionsState,writeReactionsState}from"./state.js";import{createLogger}from"#internal/logging.js";import{toErrorMessage}from"#shared/errors.js";import{currentProjection}from"#harness/session-machine/current.js";import{coalesceDeliveries}from"#harness/messages.js";import{activeTurnIdOf}from"#protocol/session-projection.js";const log=createLogger(`hooks`);function queueCommands(e,t,n,r){if(r.length===0)return;let i=readReactionsState(e),a=[...i.intents??[]],{continuation:o}=i,s=activeTurnIdOf(currentProjection(e)),c=!1;for(let e of r){if(e.type===`continue`){let t=o?.turnId===e.turnId?o:void 0;o={delivery:t===void 0?e.delivery:coalesceDeliveries([t.delivery,e.delivery]),turnId:e.turnId},c=!0;continue}s!==void 0&&i.cancelledTurnId!==s&&(a.some(e=>e.type===`cancel`&&e.turnId===s)||(a.push({occurrence:n,reactionId:t.id,type:e.type,...e.reason!==void 0&&{reason:e.reason},turnId:s}),c=!0))}c&&writeReactionsState(e,{...i,intents:a,...o!==void 0&&{continuation:o}})}function takeIntents(e,t){let n=readReactionsState(e),r=(n.intents??[]).filter(t);if(r.length===0)return r;let i=(n.intents??[]).filter(e=>!t(e));return writeReactionsState(e,{...n,intents:i}),r}function reportReactionFailure(e,t,n,r){let i=activeTurnIdOf(currentProjection(e)),a=toErrorMessage(n),o=`${t.kind===`memory`?`Memory`:`Hook`} "${t.label}"`;if(log.error(`${o} failed.`,{error:a,occurrence:r,turnId:i}),i===void 0)return;let s=readReactionsState(e),c=s.intents??[];c.some(e=>e.type===`fail`&&e.turnId===i)||writeReactionsState(e,{...s,intents:[...c,{occurrence:r??`fail:${i}`,reactionId:t.id,reason:`${o} failed: ${a}`,turnId:i,type:`fail`}]})}function takeTurnFailure(e){if(e===void 0)return;let t=activeTurnIdOf(currentProjection(e));if(t===void 0)return;let[n]=takeIntents(e,e=>e.type===`fail`&&e.turnId===t);return n?.reason}export{queueCommands,reportReactionFailure,takeIntents,takeTurnFailure};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{discardedByDeployment,keepMemos,mergeMemos,readReactionsState}from"../state.js";import{queueCommands,reportReactionFailure}from"../intents.js";import{sessionFrameOf}from"../frame.js";import{openMemos}from"../records.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{currentProjection}from"#harness/session-machine/current.js";import{activeTurnIdOf}from"#protocol/session-projection.js";function hookReaction(e){let t={id:`hook:${e.slug}`,kind:`hook`,label:e.logicalPath};return{...t,onCommit:async n=>{for(let{event:r,position:i,progress:a,view:o}of n.written){let{meta:s,...c}=r;for(let r of a?[c.type]:[c.type,`*`]){let a=e.events[r];a!==void 0&&await runHandler({at:s?.at,event:c,handler:a,input:n,key:r,occurrence:`${i.line}.${i.index}`,position:i,reaction:t,view:o})}}},timing:`commit`}}async function runHandler(e){let{ctx:t,abortSignal:n}=e.input,{id:r,label:i}=e.reaction,a=buildCallbackContext(),o=sessionFrameOf(t,{at:e.at,view:e.view}),s=a.session.id,c=`${s}:${r}:${e.occurrence}:${e.key}`,l=`${r}#${e.key}`,u=!1,d=openMemos({abortSignal:n,afterDeployment:discardedByDeployment(t,l),kept:readReactionsState(t).memos?.[l],label:i,scope:l,sessionId:s}),f=[],
|
|
1
|
+
import{continuationKey}from"../continuation.js";import{discardedByDeployment,keepMemos,mergeMemos,readReactionsState,writeReactionsState}from"../state.js";import{queueCommands,reportReactionFailure}from"../intents.js";import{sessionFrameOf}from"../frame.js";import{openMemos}from"../records.js";import{getAdapterKind}from"#channel/adapter.js";import{serializeFilePartsInMessage}from"#channel/send-input.js";import{AuthKey,ChannelDeliveryKey,ChannelInstrumentationKey}from"#context/keys.js";import{HOOK_CONTINUE_KEYS}from"#public/definitions/hook.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{currentProjection}from"#harness/session-machine/current.js";import{normalizeMessage}from"#harness/messages.js";import{activeTurnIdOf}from"#protocol/session-projection.js";import{principalOf}from"#execution/session/principal.js";function hookReaction(e){let t={id:`hook:${e.slug}`,kind:`hook`,label:e.logicalPath};return{...t,onCommit:async n=>{for(let{event:r,position:i,progress:a,view:o}of n.written){let{meta:s,...c}=r;for(let r of a?[c.type]:[c.type,`*`]){let a=e.events[r];a!==void 0&&await runHandler({at:s?.at,event:c,handler:a,input:n,key:r,occurrence:`${i.line}.${i.index}`,position:i,reaction:t,slug:e.slug,view:o})}}},timing:`commit`}}async function runHandler(e){let{ctx:t,abortSignal:n}=e.input,{id:r,label:i}=e.reaction,a=buildCallbackContext(),o=sessionFrameOf(t,{at:e.at,view:e.view}),s=a.session.id,c=`${s}:${r}:${e.occurrence}:${e.key}`,l=`${r}#${e.key}`,u=!1,d=openMemos({abortSignal:n,afterDeployment:discardedByDeployment(t,l),kept:readReactionsState(t).memos?.[l],label:i,scope:l,sessionId:s}),f=[],assertOpen=e=>{if(u)throw Error(`Hook "${i}" called ctx.${e}() after its handler settled. Await the work that calls it before the handler returns.`)},cancel=e=>{assertOpen(`cancel`),f.push(e===void 0?{type:`cancel`}:{reason:e,type:`cancel`})},continueTurn=(n,a={})=>{if(assertOpen(`continue`),normalizeMessage(n)===void 0)throw TypeError(`Hook "${i}" called ctx.continue() without a message.`);if(e.event.type!==`turn.settled`)return{queued:!1,reason:`not-settled`};let o=e.event.data,c=readReactionsState(t),l=o.outcome===`cancelled`&&c.cancelledTurnId===o.turnId&&c.cancelledBy===r;if(o.outcome!==`completed`&&!l)return{queued:!1,reason:`not-completed`};let{turnId:u}=o,d=[...f.flatMap(e=>e.type===`continue`&&e.turnId===u?[e.delivery]:[]),...c.continuation?.turnId===u?[c.continuation.delivery]:[]];return d.some(({deliveryMetadata:t})=>t?.some(t=>t.hook===e.slug))?{queued:!1,reason:`already-queued`}:d.length>0&&actsFor(t,d[0].auth)!==actsFor(t,a.auth)?{queued:!1,reason:`auth-conflict`}:(f.push({delivery:hookDelivery(t,{...a,idempotencyKey:continuationKey(s,u),message:n,slug:e.slug}),turnId:u,type:`continue`}),{queued:!0})},p={...a,...o,agent:agentOf(t),cancel,memo:d.memo,occurrence:{abortSignal:n,idempotencyKey:c},position:e.position,session:{...a.session,...o.session},...HOOK_CONTINUE_KEYS[e.key]===!0&&{continue:continueTurn}};try{await e.handler(e.event,p),keepMemos(t,l,d.used()),u=!0;let n=e.event.type===`delivery.admitted`&&activeTurnIdOf(currentProjection(t))===void 0?e.input.cancelBeforeTurn:void 0;if(n===void 0)queueCommands(t,e.reaction,c,f);else for(let a of f)if(a.type===`cancel`){let o=e.input.facts.flatMap(e=>e.type===`delivery.admitted`?[e.data.deliveryId]:[]);writeReactionsState(t,{...readReactionsState(t),cancelledOpening:{by:r,deliveryIds:o}}),n({hook:i,...a.reason!==void 0&&{reason:a.reason}})}}catch(n){mergeMemos(t,l,d.used()),reportReactionFailure(t,e.reaction,n,c)}finally{u=!0,d.close()}}function actsFor(e,t){return principalOf(t===void 0?e.get(AuthKey):t)}function agentOf(e){let t=e.require(BundleKey);return{name:t.turnAgent.id,nodeId:t.nodeId}}function hookDelivery(e,t){let n=e.get(ChannelDeliveryKey),r=n?.channelKind??e.get(ChannelInstrumentationKey)?.kind??getAdapterKind(e.require(ChannelKey));return{...t.auth!==void 0&&{auth:t.auth},deliveryMetadata:[{channelKind:r,channelName:n?.channelName??r,deliveryId:crypto.randomUUID(),hook:t.slug,payloadIndex:0}],idempotencyKey:t.idempotencyKey,kind:`deliver`,payloads:[{...t.context!==void 0&&{context:t.context},message:serializeFilePartsInMessage(t.message)}],turnPolicy:`queue`}}export{hookReaction};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{requireHistory}from"./reaction.js";import{clearLive,digestOf,discardedByDeployment,forgetSessionLive,keepMemos,mergeMemos,readLive,readReactionsState,readSlot,sessionIdOf,writeLive,writeReactionsState}from"./state.js";import{reportReactionFailure,takeIntents}from"./intents.js";import{sessionFrameOf}from"./frame.js";import{openMemos}from"./records.js";import{effectiveModelId}from"./kinds/model.js";import{bundleReactions}from"./bundle.js";import{createLogger}from"#internal/logging.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{SessionIdKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonValue}from"#shared/json.js";import{currentProjection}from"#harness/session-machine/current.js";import{activeTurnIdOf}from"#protocol/session-projection.js";const log=createLogger(`reactions`),neverAborted=new AbortController().signal;async function runReactions(e,t){let{reactions:n}=await bundleReactions(e);writeReactionsState(e,withLatest(readReactionsState(e),t.written));let r=n.filter(e=>e.timing===`commit`);if(r.length===0||t.written.length===0)return;let cancelBeforeTurn,i=t.cancelBeforeTurn,a={cancelBeforeTurn:i===void 0?void 0:e=>{cancelBeforeTurn??=()=>i(e)},abortSignal:t.abortSignal??neverAborted,ctx:e,facts:t.written.map(({event:e})=>e),history:t.conversation,written:t.written};for(let n of r)if(!(n.kind!==`hook`&&t.written.every(({progress:e})=>e)))try{await n.onCommit(a)}catch(t){reportReactionFailure(e,n,t)}actOnCancels(e,n,t.cancelTurn),cancelBeforeTurn?.()}var ReactionFailedError=class extends Error{name=`ReactionFailedError`;reaction;constructor(e,t){super(toErrorMessage(t),{cause:t}),this.reaction=e}};function isReactionFailedError(e){return e instanceof ReactionFailedError}async function evaluateValues(e,t){let{reactions:n,effects:r}=await bundleReactions(e),i=new Set;for(let r of values(n)){let n=Date.now(),a;try{a=await evaluate(e,r,{...t,mode:`evaluate`})}catch(e){throw failed(r,e)}a.changed&&i.add(r.kind),log.debug(`Evaluated a dynamic value`,{changed:a.changed,durationMs:Date.now()-n,reaction:r.label})}for(let t of i)await r[t]?.(e)}function failed(e,t){return log.error(`Dynamic value "${e.label}" failed; the turn fails.`,{error:toErrorMessage(t),kind:e.kind}),new ReactionFailedError(e.label,t)}async function restoreReactions(e,t={}){let n=readReactionsState(e);if(t.revision!==void 0&&t.revision!==n.revision){let r=n.revision!==void 0&&n.memos!==void 0;r&&log.info(`The session moved to another deployment; its memos run again.`);let{memos:i,...a}=n;writeReactionsState(e,{...r?{...a,discarded:Object.keys(i??{})}:n,revision:t.revision})}if(process.env.NODE_ENV!==`production`&&process.env.EVE_REACTIONS_COLD===`1`){let t=e.get(SessionIdKey);t!==void 0&&forgetSessionLive(t)}let{reactions:r}=await bundleReactions(e);dropRemovedSlots(e,r);for(let n of values(r)){let r=readSlot(e,n.id);if(r?.live===!0&&readLive(e,n.id,r)===void 0)try{await evaluate(e,n,{...t,mode:`restore`})}catch(e){log.warn(`Dynamic value "${n.label}" didn't evaluate for this step.`,{error:toErrorMessage(e)})}}}function dropRemovedSlots(e,t){let n=readReactionsState(e),r=new Set(t.map(({id:e})=>e)),i=Object.keys(n.slots).filter(e=>!r.has(e)),a=Object.keys(n.memos??{}).filter(e=>!r.has(e.split(`#`)[0]));if(i.length===0&&a.length===0)return;let o={...n.slots};for(let t of i)delete o[t],clearLive(e,t);let s={...n.memos};for(let e of a)delete s[e];writeReactionsState(e,{...n,memos:s,slots:o})}async function applyReactionEffects(e){let{effects:t}=await bundleReactions(e);for(let n of Object.values(t))await n(e)}function values(e){return e.filter(e=>e.timing!==`commit`)}function writeSlot(e,t,n){let r=readReactionsState(e);writeReactionsState(e,{...r,slots:{...r.slots,[t]:n}})}async function evaluate(e,t,n){let r=n.abortSignal??neverAborted,i=sessionIdOf(e),a=readReactionsState(e).memos?.[t.id],o=openMemos({abortSignal:r,kept:a,label:t.label,scope:t.id,sessionId:i,afterDeployment:discardedByDeployment(e,t.id)}),s;try{let i=internalContext(e,t,{...n,abortSignal:r,memo:o.memo});s=await t.contribute(await t.evaluate(i),i)}catch(n){throw mergeMemos(e,t.id,o.used()),n}finally{o.close()}let c=o.used();keepMemos(e,t.id,c);let l=parseJsonValue(s.value??null),u=digestOf(l);isEveDevEnvironment()&&n.mode===`evaluate`&&await checkStable(e,t,{...n,abortSignal:r,digest:u,used:c});let d=readSlot(e,t.id),f=d?.digest===u;!f&&d!==void 0&&n.mode===`restore`&&log.warn(`Dynamic value "${t.label}" offers something other than what the session was offered after a restart: code outside its memos answered differently. eve offers the new value from the next model call.`);let p=readReactionsState(e).latest[`*`]??0,m={digest:u,since:f?d.since:p,value:l,...s.live!==void 0&&{live:!0}};return writeSlot(e,t.id,m),s.live===void 0?clearLive(e,t.id):writeLive(e,t.id,m,s.live),{changed:!f||s.live!==void 0}}async function checkStable(e,t,n){let r=openMemos({abortSignal:n.abortSignal,kept:n.used,label:t.label,restoring:`a second evaluation used a memo key the first didn't`,scope:t.id,sessionId:sessionIdOf(e)});try{let i=internalContext(e,t,{...n,memo:r.memo}),a=await t.contribute(await t.evaluate(i),i);if(digestOf(parseJsonValue(a.value??null))===n.digest)return;log.warn(`Dynamic value "${t.label}" returned something different when evaluated again with the same memos. Code outside a memo, such as Math.random() or Date.now() in a name or description, makes eve rebuild it before every model call; move it into a memo, or use ctx.now.`)}catch(e){log.warn(`Dynamic value "${t.label}" failed when evaluated again with the same memos.`,{error:toErrorMessage(e)})}finally{r.close()}}function internalContext(e,t,n){let r=sessionFrameOf(e),i=n.conversation;return Object.defineProperties({...r,abortSignal:n.abortSignal,ctx:e,history:i,memo:n.memo,messages:async()=>requireHistory({history:i},t.label)},{model:{enumerable:!0,get(){if(t.kind===`model`)throw Error(`"${t.label}" read ctx.model while choosing the model. The model field's function runs before the model is chosen.`);let n=effectiveModelId(e);if(n===void 0)throw Error(`"${t.label}" read ctx.model before the session chose one.`);return{id:n}}}})}function actOnCancels(e,t,n){let r=activeTurnIdOf(currentProjection(e));takeIntents(e,e=>(e.type===`cancel`||e.type===`fail`)&&e.turnId!==r);let[i]=(readReactionsState(e).intents??[]).filter(e=>e.type===`cancel`);if(i===void 0||n===void 0)return;let a=t.find(({id:e})=>e===i.reactionId)?.label??i.reactionId;takeIntents(e,e=>e.type===`cancel`),writeReactionsState(e,{...readReactionsState(e),cancelledTurnId:i.turnId}),n({hook:a,...i.reason!==void 0&&{reason:i.reason}})}function withLatest(e,t){if(t.length===0)return e;let n={...e.latest},r=e.at;for(let{event:e,position:i,progress:a}of t)n[e.type]=i.line,!a&&(n[`*`]=i.line,r=e.meta?.at??r,(e.type===`context.started`||e.type===`context.settled`)&&(n[`${e.type}:${e.data.kind??``}`]=i.line));return{...e,latest:n,...r!==void 0&&{at:r}}}export{ReactionFailedError,applyReactionEffects,evaluateValues,isReactionFailedError,restoreReactions,runReactions};
|
|
1
|
+
import{requireHistory}from"./reaction.js";import{clearLive,digestOf,discardedByDeployment,forgetSessionLive,keepMemos,mergeMemos,readLive,readReactionsState,readSlot,sessionIdOf,writeLive,writeReactionsState}from"./state.js";import{reportReactionFailure,takeIntents}from"./intents.js";import{sessionFrameOf}from"./frame.js";import{openMemos}from"./records.js";import{effectiveModelId}from"./kinds/model.js";import{bundleReactions}from"./bundle.js";import{createLogger}from"#internal/logging.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{SessionIdKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonValue}from"#shared/json.js";import{currentProjection}from"#harness/session-machine/current.js";import{activeTurnIdOf,latestTurnIdOf}from"#protocol/session-projection.js";const log=createLogger(`reactions`),neverAborted=new AbortController().signal;async function runReactions(e,t){let{reactions:n}=await bundleReactions(e);writeReactionsState(e,bindOpeningCancel(withLatest(readReactionsState(e),t.written),t.written));let r=n.filter(e=>e.timing===`commit`);if(r.length===0||t.written.length===0)return;let cancelBeforeTurn,i=t.cancelBeforeTurn,a={cancelBeforeTurn:i===void 0?void 0:e=>{cancelBeforeTurn??=()=>i(e)},abortSignal:t.abortSignal??neverAborted,ctx:e,facts:t.written.map(({event:e})=>e),history:t.conversation,written:t.written};for(let n of r)if(!(n.kind!==`hook`&&t.written.every(({progress:e})=>e)))try{await n.onCommit(a)}catch(t){reportReactionFailure(e,n,t)}actOnCancels(e,n,t.cancelTurn),dropYieldedContinuations(e,t.written),cancelBeforeTurn?.()}var ReactionFailedError=class extends Error{name=`ReactionFailedError`;reaction;constructor(e,t){super(toErrorMessage(t),{cause:t}),this.reaction=e}};function isReactionFailedError(e){return e instanceof ReactionFailedError}async function evaluateValues(e,t){let{reactions:n,effects:r}=await bundleReactions(e),i=new Set;for(let r of values(n)){let n=Date.now(),a;try{a=await evaluate(e,r,{...t,mode:`evaluate`})}catch(e){throw failed(r,e)}a.changed&&i.add(r.kind),log.debug(`Evaluated a dynamic value`,{changed:a.changed,durationMs:Date.now()-n,reaction:r.label})}for(let t of i)await r[t]?.(e)}function failed(e,t){return log.error(`Dynamic value "${e.label}" failed; the turn fails.`,{error:toErrorMessage(t),kind:e.kind}),new ReactionFailedError(e.label,t)}async function restoreReactions(e,t={}){let n=readReactionsState(e);if(t.revision!==void 0&&t.revision!==n.revision){let r=n.revision!==void 0&&n.memos!==void 0;r&&log.info(`The session moved to another deployment; its memos run again.`);let{memos:i,...a}=n;writeReactionsState(e,{...r?{...a,discarded:Object.keys(i??{})}:n,revision:t.revision})}if(process.env.NODE_ENV!==`production`&&process.env.EVE_REACTIONS_COLD===`1`){let t=e.get(SessionIdKey);t!==void 0&&forgetSessionLive(t)}let{reactions:r}=await bundleReactions(e);dropRemovedSlots(e,r);for(let n of values(r)){let r=readSlot(e,n.id);if(r?.live===!0&&readLive(e,n.id,r)===void 0)try{await evaluate(e,n,{...t,mode:`restore`})}catch(e){log.warn(`Dynamic value "${n.label}" didn't evaluate for this step.`,{error:toErrorMessage(e)})}}}function dropRemovedSlots(e,t){let n=readReactionsState(e),r=new Set(t.map(({id:e})=>e)),i=Object.keys(n.slots).filter(e=>!r.has(e)),a=Object.keys(n.memos??{}).filter(e=>!r.has(e.split(`#`)[0]));if(i.length===0&&a.length===0)return;let o={...n.slots};for(let t of i)delete o[t],clearLive(e,t);let s={...n.memos};for(let e of a)delete s[e];writeReactionsState(e,{...n,memos:s,slots:o})}async function applyReactionEffects(e){let{effects:t}=await bundleReactions(e);for(let n of Object.values(t))await n(e)}function values(e){return e.filter(e=>e.timing!==`commit`)}function writeSlot(e,t,n){let r=readReactionsState(e);writeReactionsState(e,{...r,slots:{...r.slots,[t]:n}})}async function evaluate(e,t,n){let r=n.abortSignal??neverAborted,i=sessionIdOf(e),a=readReactionsState(e).memos?.[t.id],o=openMemos({abortSignal:r,kept:a,label:t.label,scope:t.id,sessionId:i,afterDeployment:discardedByDeployment(e,t.id)}),s;try{let i=internalContext(e,t,{...n,abortSignal:r,memo:o.memo});s=await t.contribute(await t.evaluate(i),i)}catch(n){throw mergeMemos(e,t.id,o.used()),n}finally{o.close()}let c=o.used();keepMemos(e,t.id,c);let l=parseJsonValue(s.value??null),u=digestOf(l);isEveDevEnvironment()&&n.mode===`evaluate`&&await checkStable(e,t,{...n,abortSignal:r,digest:u,used:c});let d=readSlot(e,t.id),f=d?.digest===u;!f&&d!==void 0&&n.mode===`restore`&&log.warn(`Dynamic value "${t.label}" offers something other than what the session was offered after a restart: code outside its memos answered differently. eve offers the new value from the next model call.`);let p=readReactionsState(e).latest[`*`]??0,m={digest:u,since:f?d.since:p,value:l,...s.live!==void 0&&{live:!0}};return writeSlot(e,t.id,m),s.live===void 0?clearLive(e,t.id):writeLive(e,t.id,m,s.live),{changed:!f||s.live!==void 0}}async function checkStable(e,t,n){let r=openMemos({abortSignal:n.abortSignal,kept:n.used,label:t.label,restoring:`a second evaluation used a memo key the first didn't`,scope:t.id,sessionId:sessionIdOf(e)});try{let i=internalContext(e,t,{...n,memo:r.memo}),a=await t.contribute(await t.evaluate(i),i);if(digestOf(parseJsonValue(a.value??null))===n.digest)return;log.warn(`Dynamic value "${t.label}" returned something different when evaluated again with the same memos. Code outside a memo, such as Math.random() or Date.now() in a name or description, makes eve rebuild it before every model call; move it into a memo, or use ctx.now.`)}catch(e){log.warn(`Dynamic value "${t.label}" failed when evaluated again with the same memos.`,{error:toErrorMessage(e)})}finally{r.close()}}function internalContext(e,t,n){let r=sessionFrameOf(e),i=n.conversation;return Object.defineProperties({...r,abortSignal:n.abortSignal,ctx:e,history:i,memo:n.memo,messages:async()=>requireHistory({history:i},t.label)},{model:{enumerable:!0,get(){if(t.kind===`model`)throw Error(`"${t.label}" read ctx.model while choosing the model. The model field's function runs before the model is chosen.`);let n=effectiveModelId(e);if(n===void 0)throw Error(`"${t.label}" read ctx.model before the session chose one.`);return{id:n}}}})}function actOnCancels(e,t,n){let r=activeTurnIdOf(currentProjection(e));takeIntents(e,e=>(e.type===`cancel`||e.type===`fail`)&&e.turnId!==r);let[i]=(readReactionsState(e).intents??[]).filter(e=>e.type===`cancel`);if(i===void 0||n===void 0)return;let a=t.find(({id:e})=>e===i.reactionId)?.label??i.reactionId;takeIntents(e,e=>e.type===`cancel`),writeReactionsState(e,{...readReactionsState(e),cancelledBy:i.reactionId,cancelledTurnId:i.turnId}),n({hook:a,...i.reason!==void 0&&{reason:i.reason}})}function dropYieldedContinuations(e,t){let{continuation:n,...r}=readReactionsState(e);if(n===void 0)return;let i=latestTurnIdOf(currentProjection(e));(n.turnId!==i||t.some(({event:e})=>stopsContinuations(e)))&&writeReactionsState(e,r)}function stopsContinuations(e){if(e.type===`context.settled`)return e.data.kind===`clear`&&e.data.outcome===`completed`;if(e.type!==`delivery.admitted`)return!1;let{source:t}=e.data;return t!==void 0&&`control`in t&&(t.control===`cancel`||t.control===`reset`)}function bindOpeningCancel(e,t){let{cancelledOpening:n,...r}=e;if(n===void 0)return e;let i=t.find(({event:e})=>e.type===`turn.started`)?.event;if(i?.type!==`turn.started`)return e;let{cause:a,turnId:o}=i.data;return`deliveryId`in a&&n.deliveryIds.includes(a.deliveryId)?{...r,cancelledBy:n.by,cancelledTurnId:o}:r}function withLatest(e,t){if(t.length===0)return e;let n={...e.latest},r=e.at;for(let{event:e,position:i,progress:a}of t)n[e.type]=i.line,!a&&(n[`*`]=i.line,r=e.meta?.at??r,(e.type===`context.started`||e.type===`context.settled`)&&(n[`${e.type}:${e.data.kind??``}`]=i.line));return{...e,latest:n,...r!==void 0&&{at:r}}}export{ReactionFailedError,applyReactionEffects,evaluateValues,isReactionFailedError,restoreReactions,runReactions};
|
|
@@ -2,6 +2,7 @@ import type { ContextReader } from "#context/key.js";
|
|
|
2
2
|
import { ContextKey } from "#context/key.js";
|
|
3
3
|
import type { AlsContext } from "#context/container.js";
|
|
4
4
|
import type { JsonValue } from "#shared/json.js";
|
|
5
|
+
import { type Continuation } from "./continuation.js";
|
|
5
6
|
/** One dynamic value as installed. */
|
|
6
7
|
export interface Slot {
|
|
7
8
|
/** The value's JSON form: what readers of data kinds read. */
|
|
@@ -30,12 +31,24 @@ export interface ReactionsState {
|
|
|
30
31
|
readonly at?: string;
|
|
31
32
|
/** The runtime revision the latest step ran; memos made under another are discarded. */
|
|
32
33
|
readonly revision?: string;
|
|
33
|
-
/** Commands hooks queued that the session hasn't acted on yet. */
|
|
34
|
+
/** Commands hooks queued for the running turn that the session hasn't acted on yet. */
|
|
34
35
|
readonly intents?: readonly PendingIntent[];
|
|
36
|
+
/** The continuation hooks queued for the turn that settled, until the session admits or drops it. */
|
|
37
|
+
readonly continuation?: Continuation;
|
|
35
38
|
/** The turn a hook's cancel stopped: a cancel acts once on its turn. */
|
|
36
39
|
readonly cancelledTurnId?: string;
|
|
40
|
+
/** The hook whose cancel stopped `cancelledTurnId`, which may continue the turn. */
|
|
41
|
+
readonly cancelledBy?: string;
|
|
42
|
+
/**
|
|
43
|
+
* A hook that cancelled input before its turn opened, with the deliveries that commit admitted,
|
|
44
|
+
* until the next turn starts: that turn is the one it cancelled only if one of them caused it.
|
|
45
|
+
*/
|
|
46
|
+
readonly cancelledOpening?: {
|
|
47
|
+
readonly by: string;
|
|
48
|
+
readonly deliveryIds: readonly string[];
|
|
49
|
+
};
|
|
37
50
|
}
|
|
38
|
-
/** A command a hook queued, waiting for the session to act on it. */
|
|
51
|
+
/** A command a hook queued for the running turn, waiting for the session to act on it. */
|
|
39
52
|
export interface PendingIntent {
|
|
40
53
|
/** The hook that queued it. */
|
|
41
54
|
readonly reactionId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{isNonEmptyString}from"#shared/guards.js";import{SessionIdKey}from"#context/keys.js";import{ContextKey}from"#context/key.js";const ReactionsStateKey=new ContextKey(
|
|
1
|
+
import{REACTIONS_STATE_KEY}from"./continuation.js";import{createHash}from"node:crypto";import{isNonEmptyString}from"#shared/guards.js";import{SessionIdKey}from"#context/keys.js";import{ContextKey}from"#context/key.js";const ReactionsStateKey=new ContextKey(REACTIONS_STATE_KEY),EMPTY_STATE={latest:{},slots:{}};function readReactionsState(e){return e?.get(ReactionsStateKey)??EMPTY_STATE}function writeReactionsState(e,t){e.set(ReactionsStateKey,t)}function updateReactionsState(e,t){writeReactionsState(e,t(readReactionsState(e)))}const MEMOS_CAP=4194304;function memoBytes(e){return Buffer.byteLength(JSON.stringify(e))}function keepMemos(e,t,n){let r=readReactionsState(e),i=r.memos?.[t],a=r.discarded?.filter(e=>e!==t),o=withDiscarded(r,a);if(i===void 0&&Object.keys(n).length===0){a?.length!==r.discarded?.length&&writeReactionsState(e,o);return}let s={...r.memos};Object.keys(n).length===0?delete s[t]:s[t]=n,writeReactionsState(e,{...o,memos:s})}function withDiscarded(e,t){let{discarded:n,...r}=e;return t===void 0||t.length===0?r:{...r,discarded:t}}function discardedByDeployment(e,t){return readReactionsState(e).discarded?.includes(t)===!0}function mergeMemos(e,t,n){if(Object.keys(n).length===0)return;let r=readReactionsState(e),i={...r.memos?.[t],...n};memoBytes(i)>4194304||writeReactionsState(e,{...r,memos:{...r.memos,[t]:i}})}function slotValueOf(e){return e}function digestOf(e){return createHash(`sha256`).update(canonicalJson(e)).digest(`base64url`).slice(0,22)}function canonicalJson(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(canonicalJson).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${canonicalJson(t[e])}`).join(`,`)}}`}const LIVE_GLOBAL_KEY=Symbol.for(`eve.reactions.live`),liveSessions=globalThis[LIVE_GLOBAL_KEY]??=new Map;function sessionIdOf(e){let t=e.get(SessionIdKey);if(!isNonEmptyString(t))throw Error(`Reaction state requires a session ID.`);return t}function sessionLive(e){let t=sessionIdOf(e),n=liveSessions.get(t);return n===void 0?(n=new Map,liveSessions.set(t,n),liveSessions.size>1024&&liveSessions.delete(liveSessions.keys().next().value)):(liveSessions.delete(t),liveSessions.set(t,n)),n}function readLive(e,t,n){let r=sessionLive(e).get(t);if(r!==void 0&&r.digest===n.digest)return{live:r.live}}function writeLive(e,t,n,r){sessionLive(e).set(t,{digest:n.digest,live:r})}function clearLive(e,t){sessionLive(e).delete(t)}function forgetSessionLive(e){liveSessions.delete(e)}function slotsOf(e,t){if(e===void 0)return[];let n=`${t}:`;return Object.entries(readReactionsState(e).slots).filter(([e])=>e.startsWith(n)).map(([t,n])=>{let r=n.live===!0?readLive(e,t,n):void 0;return r===void 0?{id:t,slot:n}:{id:t,live:r.live,slot:n}})}function entryVersions(e,t){let n=digestOf(readReactionsState(e).memos?.[t]??{});return e=>digestOf({memos:n,offered:e})}function readSlot(e,t){return readReactionsState(e).slots[t]}export{MEMOS_CAP,ReactionsStateKey,canonicalJson,clearLive,digestOf,discardedByDeployment,entryVersions,forgetSessionLive,keepMemos,memoBytes,mergeMemos,readLive,readReactionsState,readSlot,sessionIdOf,slotValueOf,slotsOf,updateReactionsState,writeLive,writeReactionsState};
|
|
@@ -21,7 +21,7 @@ export declare function createRuntimeAdapterRegistry(input: {
|
|
|
21
21
|
* Rehydrates one serialized adapter from the runtime-owned registry.
|
|
22
22
|
*
|
|
23
23
|
* Looks up the adapter config by `kind`, then merges the serialized state
|
|
24
|
-
* onto
|
|
25
|
-
* restored state.
|
|
24
|
+
* onto a copy of its seed state. The result is a full adapter with behavior
|
|
25
|
+
* functions and restored state.
|
|
26
26
|
*/
|
|
27
27
|
export declare function deserializeRuntimeAdapter(registry: RuntimeAdapterRegistry, data: unknown): ChannelAdapter;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getAdapterKind}from"#channel/adapter.js";import{SCHEDULE_ADAPTER}from"#channel/schedule.js";import{HTTP_ADAPTER}from"#channel/http.js";import{SUBAGENT_ADAPTER}from"#subagents/adapter.js";import{RuntimeRegistryError}from"#internal/runtime-registry.js";const FRAMEWORK_ADAPTERS=[HTTP_ADAPTER,SUBAGENT_ADAPTER,SCHEDULE_ADAPTER],ADAPTER_NON_EVENT_FIELDS=new Set([`kind`,`state`,`deliver`,`createAdapterContext`,`fetchFile`,`instrumentation`,`uploadPolicy`]);function createRuntimeAdapterRegistry(e){let t=new Map,n=new Set;for(let e of FRAMEWORK_ADAPTERS){let r=requireAdapterKind(e);n.add(r),t.set(r,e)}for(let r of e.channels){if(r.adapter===void 0)continue;let e={logicalPath:r.logicalPath,sourceId:r.sourceId},i=r.adapter,a=requireAdapterKind(i,e);if(n.has(a)){if(carriesAdapterBehavior(i))throw new RuntimeRegistryError(`adapter`,`Channel adapter kind "${a}" is reserved by the framework. A route-declared adapter may share a framework kind only as a pass-through with no \`deliver\` hook, event handlers, \`attachments\` resolver, or \`createAdapterContext\` factory. Use a custom \`kind\` to add channel-specific behavior.`,{...e,entryName:a});continue}t.set(a,i)}return{adaptersByKind:t}}function deserializeRuntimeAdapter(e,t){let n=t,r=e.adaptersByKind.get(n.kind);if(r===void 0)throw Error(`Unknown adapter kind: "${n.kind}". Declare the adapter on the route that starts this session so the runtime can rehydrate it.`);return{...r,state:n.state}}function requireAdapterKind(e,t){let n=getAdapterKind(e);if(typeof n!=`string`||n.length===0)throw new RuntimeRegistryError(`adapter`,"Adapters must declare a non-empty `kind` field.",{entryName:`unknown`,logicalPath:t?.logicalPath,sourceId:t?.sourceId});return n}function carriesAdapterBehavior(e){if(e.deliver!==void 0||e.fetchFile!==void 0||e.uploadPolicy!==void 0||e.createAdapterContext!==void 0)return!0;for(let[t,n]of Object.entries(e))if(!ADAPTER_NON_EVENT_FIELDS.has(t)&&typeof n==`function`)return!0;return!1}export{createRuntimeAdapterRegistry,deserializeRuntimeAdapter};
|
|
1
|
+
import{getAdapterKind,seedChannelState}from"#channel/adapter.js";import{SCHEDULE_ADAPTER}from"#channel/schedule.js";import{HTTP_ADAPTER}from"#channel/http.js";import{SUBAGENT_ADAPTER}from"#subagents/adapter.js";import{RuntimeRegistryError}from"#internal/runtime-registry.js";const FRAMEWORK_ADAPTERS=[HTTP_ADAPTER,SUBAGENT_ADAPTER,SCHEDULE_ADAPTER],ADAPTER_NON_EVENT_FIELDS=new Set([`kind`,`state`,`deliver`,`createAdapterContext`,`fetchFile`,`instrumentation`,`uploadPolicy`]);function createRuntimeAdapterRegistry(e){let t=new Map,n=new Set;for(let e of FRAMEWORK_ADAPTERS){let r=requireAdapterKind(e);n.add(r),t.set(r,e)}for(let r of e.channels){if(r.adapter===void 0)continue;let e={logicalPath:r.logicalPath,sourceId:r.sourceId},i=r.adapter,a=requireAdapterKind(i,e);if(n.has(a)){if(carriesAdapterBehavior(i))throw new RuntimeRegistryError(`adapter`,`Channel adapter kind "${a}" is reserved by the framework. A route-declared adapter may share a framework kind only as a pass-through with no \`deliver\` hook, event handlers, \`attachments\` resolver, or \`createAdapterContext\` factory. Use a custom \`kind\` to add channel-specific behavior.`,{...e,entryName:a});continue}t.set(a,i)}return{adaptersByKind:t}}function deserializeRuntimeAdapter(e,t){let n=t,r=e.adaptersByKind.get(n.kind);if(r===void 0)throw Error(`Unknown adapter kind: "${n.kind}". Declare the adapter on the route that starts this session so the runtime can rehydrate it.`);return{...r,state:seedChannelState(r.state,n.state)}}function requireAdapterKind(e,t){let n=getAdapterKind(e);if(typeof n!=`string`||n.length===0)throw new RuntimeRegistryError(`adapter`,"Adapters must declare a non-empty `kind` field.",{entryName:`unknown`,logicalPath:t?.logicalPath,sourceId:t?.sourceId});return n}function carriesAdapterBehavior(e){if(e.deliver!==void 0||e.fetchFile!==void 0||e.uploadPolicy!==void 0||e.createAdapterContext!==void 0)return!0;for(let[t,n]of Object.entries(e))if(!ADAPTER_NON_EVENT_FIELDS.has(t)&&typeof n==`function`)return!0;return!1}export{createRuntimeAdapterRegistry,deserializeRuntimeAdapter};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
import type { ConnectionCallbackContext } from "#shared/connection-types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Runs one connection tool call so its `headers` and provided arguments see who approved it.
|
|
5
|
+
* One authorization context serves the whole call, so its inline providers share one scope.
|
|
6
|
+
*/
|
|
7
|
+
export declare function withConnectionApproval<T>(connectionName: string, responder: SessionAuthContext | undefined, fn: () => T): T;
|
|
8
|
+
/** The session context a connection's `headers` and provided-argument callbacks receive. */
|
|
9
|
+
export declare function buildConnectionCallbackContext(): ConnectionCallbackContext;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{contextScopeValue,withContextScopeValue}from"#context/container.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";const APPROVAL=Symbol(`eve.connectionApproval`);function withConnectionApproval(e,t,n){if(t===void 0)return n();let r=createAuthorizationContext({scope:e}),i={responder:{...t,getToken:(e,n)=>r.getResponderToken(t,e,n)}};return withContextScopeValue(APPROVAL,i,n)}function buildConnectionCallbackContext(){let e=contextScopeValue(APPROVAL);return{...buildCallbackContext(),...e!==void 0&&{approval:e}}}export{buildConnectionCallbackContext,withConnectionApproval};
|
|
@@ -80,7 +80,7 @@ export declare function passesToolFilter(names: readonly string[], filter: Reado
|
|
|
80
80
|
* flat `Record<string, string>` for the transport layer.
|
|
81
81
|
*
|
|
82
82
|
* Resolves dynamic `auth` and `headers` callbacks with the active
|
|
83
|
-
*
|
|
83
|
+
* session context, then resolves the {@link ConnectionPrincipal}
|
|
84
84
|
* and invokes `authorization.getToken({ principal })` to produce the bearer.
|
|
85
85
|
* `getToken` may throw {@link ConnectionAuthorizationRequiredError};
|
|
86
86
|
* callers catch it and it propagates as-is from here.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{evictScopedToken,resolveScopedToken}from"#runtime/connections/scoped-authorization.js";import{buildConnectionCallbackContext}from"#runtime/connections/approval-scope.js";import{FORWARDED_PRINCIPAL_HEADER,encodeForwardedPrincipalHeader}from"#internal/mcp/forwarded-principal-header.js";import{createMcpTraceFetch,withMcpToolCallSpan,withMcpToolsListSpan}from"#runtime/connections/mcp-tracing.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{ConnectionEventActions,isEventAction}from"#runtime/connections/events/actions.js";import{readTurnPrincipals}from"#context/turn-principals.js";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";var McpUnauthorizedError=class extends Error{statusCode=401;anonymous;constructor(e){super(`MCP HTTP request failed (HTTP 401).`),this.anonymous=e}};async function checkAuthorizationResponse(e,t){if(e.status===401)throw await e.body?.cancel(),new McpUnauthorizedError(t);return e}var McpConnectionClient=class{#e;#t;#n;#r;#i;eventActions;constructor(e){if(this.#i=e,e.experimental_events!==void 0){let t=new ConnectionEventActions(e,e.experimental_events,()=>resolveHeaders(e),this.#s());this.eventActions={ownsName:isEventAction,recoveryMetadata:()=>t.recoveryMetadata(),metadata:async()=>{try{return await t.metadata()}catch(e){return await this.#d(e)}},execute:async(e,n,r)=>{try{return await t.execute(e,n,r)}catch(e){return await this.#d(e)}}}}}async connect(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#a();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#a(){let{headers:e}=await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0}),t=this.#i.url,n=createMcpTraceFetch({connectionName:this.#i.connectionName,fetcher:this.#o(Object.keys(e)),getProtocolVersion:()=>this.#t?.initializeResult?.protocolVersion});try{return await createMCPClient({protocolVersionDiscovery:this.#i.protocolVersionDiscovery,transport:{fetch:n,headers:e,type:`http`,url:t}})}catch(r){if(!isMcpHttpFallbackRetryableError(r))throw r;return await createMCPClient({protocolVersionDiscovery:this.#i.protocolVersionDiscovery,transport:{fetch:n,headers:e,type:`sse`,url:t}})}}#o(e){let t=this.#s()??globalThis.fetch;return async(n,r)=>{let resolve=()=>resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0}),send=async i=>{let a=new Headers(r?.headers);for(let t of e)a.delete(t);for(let[e,t]of Object.entries(i.headers))a.set(e,t);return await t(n,{...r,headers:a})},i=await resolve(),a=await send(i);if(a.status!==401||i.anonymous||this.#i.authorization===void 0||r?.signal?.aborted)return await checkAuthorizationResponse(a,i.anonymous);await this.#p();let o=await resolve();return o.anonymous?await checkAuthorizationResponse(a,!0):(await a.body?.cancel(),await checkAuthorizationResponse(await send(o),o.anonymous))}}#s(){if(this.#i.forwardPrincipal!==!0)return;let e=this.#i.connectionName;return async(t,n)=>{let r=readTurnPrincipals();if(r===void 0)return await globalThis.fetch(t,n);let i=new Headers(n?.headers);return i.set(FORWARDED_PRINCIPAL_HEADER,encodeForwardedPrincipalHeader(r,e)),await globalThis.fetch(t,{...n,headers:i,redirect:`error`})}}async getToolMetadata(){return(await this.#c()).metadata}async executeTool(e,t,n){let r;try{let{tools:i}=await this.#c(),a=i[e];if(a?.execute===void 0)throw Error(`Tool "${e}" not found in connection "${this.#i.connectionName}".`);let o=a.execute,s=await resolveProvidedArguments({args:t,callId:n.callId,connection:this.#i,toolName:e});r=await withMcpToolCallSpan({arguments:t,connectionName:this.#i.connectionName,execute:async()=>await o(s,{abortSignal:n.abortSignal}),protocolVersion:this.#t?.initializeResult?.protocolVersion,toolName:e})}catch(e){return await this.#d(e)}return isMcpAuthChallengeResult(r)?await this.#f(`the server asked for sign-in to call "${e}"`):r}async#c(){if(this.#r!==void 0)return this.#r;if(this.#n!==void 0)return this.#n;this.#n=this.#l();try{return this.#r=await this.#n,this.#r}catch(e){throw this.#n=void 0,e}}async#l(){try{return await this.#u()}catch(e){return await this.#d(e)}}async#u(){let e=await this.connect(),t=await withMcpToolsListSpan({connectionName:this.#i.connectionName,execute:()=>e.listTools(),protocolVersion:e.initializeResult?.protocolVersion}),n=Object.keys(this.#i.toolCall?.providedArguments??{}),r=t.tools.map(e=>({...e,inputSchema:omitProvidedArgumentsFromSchema(e.inputSchema,n)})),i=e.toolsFromDefinitions({tools:r});return{metadata:r.map(e=>({annotations:e.annotations,description:e.description??``,inputSchema:e.inputSchema??{},name:e.name,outputSchema:`outputSchema`in e&&e.outputSchema!==void 0?e.outputSchema:void 0})),tools:i}}async close(){this.#t!==void 0&&(await this.#t.close(),this.#t=void 0),this.#e=void 0,this.#n=void 0,this.#r=void 0}async#d(e){if(!isMcpAuthRequiredError(e))throw e;let t=[...walkErrorChain(e)].find(e=>e instanceof McpUnauthorizedError)?.anonymous??(await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0})).anonymous;return await this.#f(t?`the server requires sign-in`:`the server rejected the token`,t)}async#f(e,t){throw t??=(await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0})).anonymous,t||await this.#p(),await this.close(),new ConnectionAuthorizationRequiredError(this.#i.connectionName,{message:`Connection "${this.#i.connectionName}" requires authorization (${e}).`})}async#p(){let e=await resolveConnectionAuthorization(this.#i);e!==void 0&&await evictScopedToken({authorization:e,connection:{url:this.#i.url},instanceId:this.#i.instanceId,scope:this.#i.connectionName})}};function isMcpAuthRequiredError(e){return readHttpStatus(e)===401}const MCP_WWW_AUTHENTICATE_META_KEY=`mcp/www_authenticate`;function isMcpAuthChallengeResult(e){if(!isObject(e)||e.isError!==!0||!isObject(e._meta))return!1;let t=e._meta[MCP_WWW_AUTHENTICATE_META_KEY];return(typeof t==`string`||Array.isArray(t))&&t.length>0}function isMcpHttpFallbackRetryableError(e){let t=readHttpStatus(e);return t===400||t===404||t===405}function readHttpStatus(e){for(let t of walkErrorChain(e)){if(!isObject(t))continue;let e=readStatusField(t);if(e!==void 0)return e;let n=t.response;if(isObject(n)){let e=readStatusField(n);if(e!==void 0)return e}if(typeof t.message==`string`){let e=/\bHTTP\s+(\d{3})\b/u.exec(t.message);if(e?.[1]!==void 0)return Number(e[1])}}}function readStatusField(e){if(typeof e.status==`number`)return e.status;if(typeof e.statusCode==`number`)return e.statusCode}function*walkErrorChain(e){let t=e,n=new Set;for(;t!=null&&!n.has(t);){if(n.add(t),yield t,!isObject(t)||!(`cause`in t))return;t=t.cause}}function passesToolFilter(e,t){return t===void 0?!0:`allow`in t?e.some(e=>t.allow.includes(e)):!e.some(e=>t.block.includes(e))}async function resolveHeaders(e){let{headers:t}=await resolveConnectionHeaders(e,{anonymousWhenAuthorizationRequired:!1});return t}async function resolveConnectionHeaders(e,t){let n={},r=!1,i=await resolveConnectionAuthorization(e);if(i!==void 0)try{n.Authorization=`Bearer ${(await resolveToken(e,i)).token}`}catch(e){if(!t.anonymousWhenAuthorizationRequired||!isConnectionAuthorizationRequiredError(e))throw e;r=!0}if(e.headers!==void 0){let t,r=await resolveHeadersDefinition(e.headers,()=>t??=buildConnectionCallbackContext());for(let[t,a]of Object.entries(r)){if(i!==void 0&&t.toLowerCase()===`authorization`)throw Error(`Connection "${e.connectionName}" headers must not include an "Authorization" key when "authorization" is also provided.`);n[t]=a}}return{anonymous:r,headers:n}}async function resolveToken(e,t){return await resolveScopedToken({authorization:t,connection:{url:e.url},instanceId:e.instanceId,scope:e.connectionName})}async function resolveHeadersDefinition(e,t){if(typeof e==`function`)return{...await e(t())};let n={},r=Object.entries(e);for(let[e,i]of r)n[e]=await resolveHeaderValue(i,t);return n}async function resolveHeaderValue(e,t){return typeof e==`function`?await e(t()):await e}export{MCP_WWW_AUTHENTICATE_META_KEY,McpConnectionClient,isMcpAuthChallengeResult,isMcpAuthRequiredError,passesToolFilter,readHttpStatus,resolveHeaders};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{parseJsonValue}from"#shared/json.js";import{
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{parseJsonValue}from"#shared/json.js";import{buildConnectionCallbackContext}from"#runtime/connections/approval-scope.js";async function resolveProvidedArguments(e){if(!isObject(e.args))throw Error(`Tool "${e.toolName}" in connection "${e.connection.connectionName}" expected object arguments.`);let t=e.connection.toolCall?.providedArguments;if(t===void 0||Object.keys(t).length===0)return e.args;let n,getContext=()=>n??={...buildConnectionCallbackContext(),callId:e.callId,toolName:e.toolName},r={};for(let[n,i]of Object.entries(t)){let t=typeof i==`function`?await i(getContext()):await i;try{r[n]=parseJsonValue(t)}catch{throw Error(`Connection "${e.connection.connectionName}" provided argument "${n}" must resolve to a JSON-serializable value.`)}}return{...e.args,...r}}function omitProvidedArgumentsFromSchema(e,t){if(t.length===0)return e;let n=new Set(t),r={...e};return isObject(e.properties)&&(r.properties=Object.fromEntries(Object.entries(e.properties).filter(([e])=>!n.has(e)))),Array.isArray(e.required)&&(r.required=e.required.filter(e=>typeof e!=`string`||!n.has(e))),r}export{omitProvidedArgumentsFromSchema,resolveProvidedArguments};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition}from"#internal/authored-definition/connection.js";import{readStampedConnectionProtocol}from"#public/definitions/connections/protocol.js";import{connectionDefinitionKey,registerDefinitionSource}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{createConnectionInstanceId}from"#runtime/connections/instance-identity.js";async function resolveConnectionDefinition(e,t,n){try{let r=await loadResolvedModuleExport({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),i=expectObjectRecord(r,`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);registerDefinitionSource(i,{kind:`connection`,logicalPath:e.logicalPath,name:e.connectionName},connectionDefinitionKey(e.url,e.description));let a=i.auth!==void 0,o=i.headers!==void 0,s=e.protocol===`openapi`?i.operations:i.tools,c={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,instanceId:createConnectionInstanceId({connectionName:e.connectionName,instanceKey:typeof i.instanceKey==`string`?i.instanceKey:void 0,protocol:e.protocol,sourceId:e.sourceId,url:e.url}),protocol:e.protocol,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(a){if(typeof i.auth==`function`)c.authorization=i.auth;else try{c.authorization=normalizeAuthorizationSpec(i.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new ResolveAgentError(toErrorMessage(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}}if(e.protocol===`mcp`&&i.protocolVersionDiscovery!==void 0){if(typeof i.protocolVersionDiscovery!=`boolean`)throw Error(`"protocolVersionDiscovery" must be a boolean.`);c.protocolVersionDiscovery=i.protocolVersionDiscovery}if(e.protocol===`mcp`&&i.forwardPrincipal!==void 0){if(typeof i.forwardPrincipal!=`boolean`)throw Error(`"forwardPrincipal" must be a boolean.`);c.forwardPrincipal=i.forwardPrincipal}if(e.experimental_events===!0){let t=normalizeMcpClientConnectionDefinition(i,`Connection "${e.connectionName}":`).experimental?.events,n=typeof c.authorization==`object`?c.authorization:void 0;if(t===void 0||n?.vercelConnect?.experimental_events===void 0)throw new ResolveAgentError(`Connection "${e.connectionName}": experimental.events requires a static Connect auth provider with the events bridge.`,{logicalPath:e.logicalPath,sourceId:e.sourceId});c.experimental_events={callbacks:t,authorization:n,connector:n.vercelConnect.connector,backend:n.vercelConnect.experimental_events}}return o&&(c.headers=i.headers),i.toolCall!==void 0&&(c.toolCall=i.toolCall),s!==void 0&&(c.tools=s),e.protocol===`openapi`&&i.spec!==void 0&&(c.spec=i.spec),
|
|
1
|
+
import{expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition}from"#internal/authored-definition/connection.js";import{readStampedConnectionProtocol}from"#public/definitions/connections/protocol.js";import{connectionDefinitionKey,registerDefinitionSource}from"#internal/authored-definition/source-identity.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{createConnectionInstanceId}from"#runtime/connections/instance-identity.js";async function resolveConnectionDefinition(e,t,n){try{let r=await loadResolvedModuleExport({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),i=expectObjectRecord(r,`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);registerDefinitionSource(i,{kind:`connection`,logicalPath:e.logicalPath,name:e.connectionName},connectionDefinitionKey(e.url,e.description));let a=i.auth!==void 0,o=i.headers!==void 0,s=e.protocol===`openapi`?i.operations:i.tools,c={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,instanceId:createConnectionInstanceId({connectionName:e.connectionName,instanceKey:typeof i.instanceKey==`string`?i.instanceKey:void 0,protocol:e.protocol,sourceId:e.sourceId,url:e.url}),protocol:e.protocol,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(a){if(typeof i.auth==`function`)c.authorization=i.auth;else try{c.authorization=normalizeAuthorizationSpec(i.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new ResolveAgentError(toErrorMessage(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}}if(e.protocol===`mcp`&&i.protocolVersionDiscovery!==void 0){if(typeof i.protocolVersionDiscovery!=`boolean`)throw Error(`"protocolVersionDiscovery" must be a boolean.`);c.protocolVersionDiscovery=i.protocolVersionDiscovery}if(e.protocol===`mcp`&&i.forwardPrincipal!==void 0){if(typeof i.forwardPrincipal!=`boolean`)throw Error(`"forwardPrincipal" must be a boolean.`);c.forwardPrincipal=i.forwardPrincipal}if(e.experimental_events===!0){let t=normalizeMcpClientConnectionDefinition(i,`Connection "${e.connectionName}":`).experimental?.events,n=typeof c.authorization==`object`?c.authorization:void 0;if(t===void 0||n?.vercelConnect?.experimental_events===void 0)throw new ResolveAgentError(`Connection "${e.connectionName}": experimental.events requires a static Connect auth provider with the events bridge.`,{logicalPath:e.logicalPath,sourceId:e.sourceId});c.experimental_events={callbacks:t,authorization:n,connector:n.vercelConnect.connector,backend:n.vercelConnect.experimental_events}}return o&&(c.headers=i.headers),i.toolCall!==void 0&&(c.toolCall=i.toolCall),s!==void 0&&(c.tools=s),e.protocol===`openapi`&&i.spec!==void 0&&(c.spec=i.spec),i.approval!==void 0&&(c.approval=normalizeApproval(i.approval,`"approval" must be a policy function or { request, response?, prompt? }.`)),c}catch(t){throw t instanceof ResolveAgentError?t:new ResolveAgentError(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${toErrorMessage(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function resolveDynamicConnectionValue(e,t){let n=readStampedConnectionProtocol(e),r=`Dynamic connection "${t.connectionName}" from "${t.logicalPath}" must be created by defineMcpClientConnection() or defineOpenAPIConnection().`;if(n===void 0)throw Error(r);if(registerDefinitionSource(e,{kind:`connection`,logicalPath:t.logicalPath,name:t.connectionName}),n===`openapi`){let i=normalizeOpenApiConnectionDefinition(e,r);return assertAuthenticatedDynamicInstanceKey(i.auth,i.instanceKey,r),omitUndefined({approval:i.approval,authorization:i.auth,connectionName:t.connectionName,description:i.description,exportName:t.exportName,headers:i.headers,instanceId:createConnectionInstanceId({connectionName:t.connectionName,instanceKey:i.instanceKey,protocol:n,sourceId:t.sourceId,url:i.baseUrl??``}),logicalPath:t.logicalPath,protocol:n,sourceId:t.sourceId,sourceKind:`module`,spec:i.spec,toolCall:i.toolCall,tools:i.operations,url:i.baseUrl??``})}let i=normalizeMcpClientConnectionDefinition(e,r);if(i.experimental?.events!==void 0)throw Error(`${r} experimental_events requires a statically authored connection so eve can mount its receiver at build time.`);return assertAuthenticatedDynamicInstanceKey(i.auth,i.instanceKey,r),omitUndefined({approval:i.approval,authorization:i.auth,connectionName:t.connectionName,description:i.description,exportName:t.exportName,headers:i.headers,instanceId:createConnectionInstanceId({connectionName:t.connectionName,instanceKey:i.instanceKey,protocol:n,sourceId:t.sourceId,url:i.url}),logicalPath:t.logicalPath,protocol:n,sourceId:t.sourceId,sourceKind:`module`,toolCall:i.toolCall,protocolVersionDiscovery:i.protocolVersionDiscovery,forwardPrincipal:i.forwardPrincipal,tools:i.tools,url:i.url})}function assertAuthenticatedDynamicInstanceKey(e,t,n){if(e!==void 0&&t===void 0)throw Error(`${n} Authenticated dynamic connections must set "instanceKey" to a stable, non-secret account or tenant identifier.`)}function omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}export{resolveConnectionDefinition,resolveDynamicConnectionValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
async function agentToolServeWorkflow(e,t){"use workflow";let n=t.agent(t.toolName),r=sendToAgent(n,await e()),i=e();for(;;){let a=await nextCallOrResult(i,r);if(a.kind===`call`){r=await forwardCall(n,r,a.call),i=e();continue}if(!r.signal.aborted){if(a.result.status===`failed`)throw Error(`The agent's turn failed: ${a.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let o=e();if(o!==i){r=sendToAgent(n,await i),i=o;continue}t.reply(a.result.reply??``)}r=sendToAgent(n,await i),i=e()}}async function agentWithModelServeWorkflow(e,t){"use workflow";let n=await e(),r=n.input.model.trim();if(r===``)throw TypeError(`agent model must not be empty.`);let i=t.agent(`agent`,{model:r}),a=sendToModelAgent(i,n,r),o=e();for(;;){let n=await nextModelCallOrResult(o,a);if(n.kind===`call`){a=await forwardModelCall(i,a,n.call,r),o=e();continue}if(!a.signal.aborted){if(n.result.status===`failed`)throw Error(`The agent's turn failed: ${n.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let s=e();if(s!==o){a=sendToModelAgent(i,await o,r),o=s;continue}t.reply(n.result.reply??``)}a=sendToModelAgent(i,await o,r),o=e()}}function sendToAgent(e,t){return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}function sendToModelAgent(e,t,n){if(t.input.model!==n)throw Error(`An agent task keeps the model it started with. This task has ended; start a new task to use another model.`);return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}async function nextCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function nextModelCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function forwardCall(e,t,n){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToAgent(e,n)}async function forwardModelCall(e,t,n,r){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToModelAgent(e,n,r)}agentToolServeWorkflow.workflowId=`workflow//eve//agentToolServeWorkflow`,agentWithModelServeWorkflow.workflowId=`workflow//eve@0.
|
|
1
|
+
async function agentToolServeWorkflow(e,t){"use workflow";let n=t.agent(t.toolName),r=sendToAgent(n,await e()),i=e();for(;;){let a=await nextCallOrResult(i,r);if(a.kind===`call`){r=await forwardCall(n,r,a.call),i=e();continue}if(!r.signal.aborted){if(a.result.status===`failed`)throw Error(`The agent's turn failed: ${a.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let o=e();if(o!==i){r=sendToAgent(n,await i),i=o;continue}t.reply(a.result.reply??``)}r=sendToAgent(n,await i),i=e()}}async function agentWithModelServeWorkflow(e,t){"use workflow";let n=await e(),r=n.input.model.trim();if(r===``)throw TypeError(`agent model must not be empty.`);let i=t.agent(`agent`,{model:r}),a=sendToModelAgent(i,n,r),o=e();for(;;){let n=await nextModelCallOrResult(o,a);if(n.kind===`call`){a=await forwardModelCall(i,a,n.call,r),o=e();continue}if(!a.signal.aborted){if(n.result.status===`failed`)throw Error(`The agent's turn failed: ${n.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let s=e();if(s!==o){a=sendToModelAgent(i,await o,r),o=s;continue}t.reply(n.result.reply??``)}a=sendToModelAgent(i,await o,r),o=e()}}function sendToAgent(e,t){return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}function sendToModelAgent(e,t,n){if(t.input.model!==n)throw Error(`An agent task keeps the model it started with. This task has ended; start a new task to use another model.`);return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}async function nextCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function nextModelCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function forwardCall(e,t,n){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToAgent(e,n)}async function forwardModelCall(e,t,n,r){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToModelAgent(e,n,r)}agentToolServeWorkflow.workflowId=`workflow//eve//agentToolServeWorkflow`,agentWithModelServeWorkflow.workflowId=`workflow//eve@0.91.0//agentWithModelServeWorkflow`;export{agentToolServeWorkflow,agentWithModelServeWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn}from"node:child_process";function osOpenCommand(e){switch(process.platform){case`darwin`:return{command:`open`,args:[e]};case`win32`:return{command:`
|
|
1
|
+
import{spawn}from"node:child_process";function osOpenCommand(e){switch(process.platform){case`darwin`:return{command:`open`,args:[e]};case`win32`:return{command:`rundll32`,args:[`url.dll,FileProtocolHandler`,e]};default:return{command:`xdg-open`,args:[e]}}}function parseWebUrl(e){let t=URL.parse(e.trim());if(t&&(t.protocol===`http:`||t.protocol===`https:`))return t.href}function openUrl(e){let t=parseWebUrl(e);if(t===void 0)return;let{command:n,args:r}=osOpenCommand(t);try{let e=spawn(n,r,{stdio:`ignore`,detached:!0});e.on(`error`,()=>{}),e.unref()}catch{}}export{openUrl,parseWebUrl};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{DEFAULT_CONNECT_PACKAGE_VERSION,resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_CHANNEL_TEMPLATES}from"./web-template.js";import{AGENT_INSTRUCTIONS_TEMPLATE}from"./instructions-template.js";import{SCAFFOLDED_AGENT_PATHS}from"./agent-paths.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.137`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.
|
|
1
|
+
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{DEFAULT_CONNECT_PACKAGE_VERSION,resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_CHANNEL_TEMPLATES}from"./web-template.js";import{AGENT_INSTRUCTIONS_TEMPLATE}from"./instructions-template.js";import{SCAFFOLDED_AGENT_PATHS}from"./agent-paths.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.137`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.91.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{[SCAFFOLDED_AGENT_PATHS.config]:renderAgentTemplate(e,t),[SCAFFOLDED_AGENT_PATHS.channel]:WEB_CHANNEL_TEMPLATES.default,[SCAFFOLDED_AGENT_PATHS.instructions]:AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,t){let n=parseChatGptModelSelection(e);return n===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(n)}),\n${reasoningTemplateLine(t)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(t.model)!==void 0?renderAgentTemplate(t.model,t.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
|
|
2
2
|
|
|
3
3
|
export default defineAgent({
|
|
4
4
|
model: "__EVE_INIT_MODEL__",
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { ClientError } from "#client/client-error.js";
|
|
2
|
+
/** Whether a client error is the info route refusing the caller's credential. */
|
|
3
|
+
export declare function isAgentInfoForbidden(error: unknown): error is ClientError;
|
|
4
|
+
/** Says which credential `GET /eve/v1/info` accepts, for callers it refused. */
|
|
5
|
+
export declare function formatAgentInfoForbiddenMessage(target: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AGENT_INFO_FORBIDDEN_CODE,AGENT_INFO_FORBIDDEN_MESSAGE}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";function isAgentInfoForbidden(e){return e instanceof ClientError&&e.status===403&&e.code===AGENT_INFO_FORBIDDEN_CODE}function formatAgentInfoForbiddenMessage(e){return`${e} refused GET /eve/v1/info. ${AGENT_INFO_FORBIDDEN_MESSAGE}`}export{formatAgentInfoForbiddenMessage,isAgentInfoForbidden};
|
|
@@ -7,6 +7,7 @@ import type { ConnectionEventsBackend } from "#shared/connection-events.js";
|
|
|
7
7
|
*/
|
|
8
8
|
import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";
|
|
9
9
|
import type { SessionContext } from "#context/session-context.js";
|
|
10
|
+
import type { ApprovedCall } from "#tools/definition.js";
|
|
10
11
|
import type { JsonValue } from "#shared/json.js";
|
|
11
12
|
/**
|
|
12
13
|
* Credential returned by a connection's `getToken` or
|
|
@@ -37,18 +38,34 @@ export interface TokenResult {
|
|
|
37
38
|
* client implementation. Never authored directly.
|
|
38
39
|
*/
|
|
39
40
|
export type ConnectionProtocol = "mcp" | "openapi";
|
|
41
|
+
/**
|
|
42
|
+
* Context passed to a connection's `headers` and `toolCall.providedArguments`
|
|
43
|
+
* callbacks.
|
|
44
|
+
*/
|
|
45
|
+
export interface ConnectionCallbackContext extends SessionContext {
|
|
46
|
+
/**
|
|
47
|
+
* Who approved the tool call these values are for. Present only while a
|
|
48
|
+
* connection tool call runs after a person approved it. The call still runs
|
|
49
|
+
* as the requester, `session.auth.current`, and its `auth` token is still
|
|
50
|
+
* the requester's. `approval.responder.getToken(provider)` resolves the
|
|
51
|
+
* approver's token as it does in a `defineTool` tool, so a callback can send
|
|
52
|
+
* the approver's credentials where the server should act for them.
|
|
53
|
+
*/
|
|
54
|
+
readonly approval?: ApprovedCall;
|
|
55
|
+
}
|
|
40
56
|
/** A single header value, supporting static strings and per-caller resolution. */
|
|
41
|
-
export type HeaderValue = string | Promise<string> | ((ctx:
|
|
57
|
+
export type HeaderValue = string | Promise<string> | ((ctx: ConnectionCallbackContext) => string | Promise<string>);
|
|
42
58
|
/**
|
|
43
59
|
* Arbitrary HTTP headers sent with every request to a connection server.
|
|
44
60
|
*
|
|
45
61
|
* Static form: key-value pairs where each value may be a string, Promise,
|
|
46
62
|
* or callback. Function form: a callback returning the full headers map,
|
|
47
63
|
* useful when multiple headers must be resolved together. Header callbacks
|
|
48
|
-
* receive the active {@link
|
|
49
|
-
* metadata can be selected from the current caller
|
|
64
|
+
* receive the active {@link ConnectionCallbackContext}, so credentials and
|
|
65
|
+
* routing metadata can be selected from the current caller, or from the
|
|
66
|
+
* approver of an approved tool call.
|
|
50
67
|
*/
|
|
51
|
-
export type HeadersDefinition = Readonly<Record<string, HeaderValue>> | ((ctx:
|
|
68
|
+
export type HeadersDefinition = Readonly<Record<string, HeaderValue>> | ((ctx: ConnectionCallbackContext) => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>);
|
|
52
69
|
/**
|
|
53
70
|
* Client-side tool filter applied after `listTools()`.
|
|
54
71
|
*
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
*
|
|
4
4
|
* `applyValueDelta(base, diffValue(base, next))` rebuilds `next` as a
|
|
5
5
|
* serializer sees it: the same entries, in the same key order, including
|
|
6
|
-
* entries whose value is `undefined`. Plain objects
|
|
7
|
-
* entry, so the result shares every
|
|
8
|
-
* value is compared by identity and
|
|
9
|
-
* values must be replaced rather than
|
|
6
|
+
* entries whose value is `undefined`. Plain objects, null-prototype ones
|
|
7
|
+
* included, and arrays change entry by entry, so the result shares every
|
|
8
|
+
* unchanged entry with `base`. Any other value is compared by identity and
|
|
9
|
+
* carried whole when it differs, so such values must be replaced rather than
|
|
10
|
+
* edited in place.
|
|
10
11
|
*/
|
|
11
12
|
export type ValueDelta = {
|
|
12
13
|
readonly kind: "value";
|