eve 0.90.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 +34 -23
- package/dist/src/channel/auth/http-basic.js +1 -1
- package/dist/src/channel/channel-operations.d.ts +1 -1
- package/dist/src/channel/types.d.ts +2 -0
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
- package/dist/src/client/session.d.ts +1 -1
- package/dist/src/compiled/.vendor-stamp.json +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/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/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/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/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/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/value-delta.d.ts +5 -4
- package/dist/src/shared/value-delta.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/docs/agent-config.md +199 -222
- package/docs/channels/chat-sdk.mdx +60 -64
- package/docs/channels/custom.mdx +264 -281
- package/docs/channels/discord.mdx +176 -123
- package/docs/channels/eve.mdx +136 -206
- 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 -198
- 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 +175 -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 +16 -19
- 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 +87 -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 +45 -43
- 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/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,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};
|
|
@@ -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__",
|
|
@@ -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";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function snapshotValue(e){return Array.isArray(e)?e.map(e=>snapshotValue(e)):isPlainObject(e)?
|
|
1
|
+
function snapshotValue(e){return Array.isArray(e)?e.map(e=>snapshotValue(e)):isPlainObject(e)?objectLike(e,Object.keys(e).map(t=>[t,snapshotValue(e[t])])):e}function diffValue(e,t){if(!Object.is(e,t))return Array.isArray(e)&&Array.isArray(t)?diffArray(e,t):isPlainObject(e)&&isPlainObject(t)&&isDictionary(e)===isDictionary(t)?diffObject(e,t):{kind:`value`,value:t}}function applyValueDelta(e,t){if(t===void 0)return e;switch(t.kind){case`value`:return t.value;case`array`:{if(!Array.isArray(e))throw deltaMismatch(`an array`);let n=e.slice(0,t.length);for(let[e,r]of Object.entries(t.set??{}))n[Number(e)]=r;for(let[r,i]of Object.entries(t.patch??{}))n[Number(r)]=applyValueDelta(e[Number(r)],i);return n}case`object`:{if(!isPlainObject(e))throw deltaMismatch(`an object`);let n=Object.keys(e),r=t.set??{},i=t.patch??{};return objectLike(e,(t.keys??impliedKeys(n,r)).map(t=>Object.hasOwn(r,t)?[t,r[t]]:Object.hasOwn(i,t)?[t,applyValueDelta(e[t],i[t])]:[t,e[t]]))}}}function diffArray(e,t){let n=[],r=[],i=0;for(let a=0;a<t.length;a++){if(!(a in t)||a<e.length&&!(a in e))return{kind:`value`,value:t};if(a>=e.length){n.push([String(a),t[a]]);continue}let o=diffValue(e[a],t[a]);o===void 0?i++:o.kind===`value`?n.push([String(a),o.value]):r.push([String(a),o])}if(n.length!==0||r.length!==0||t.length!==e.length)return i===0&&r.length===0?{kind:`value`,value:t}:{...entryChanges(n,r),kind:`array`,length:t.length}}function diffObject(e,t){let n=Object.keys(e),r=Object.keys(t),i=[],a=[],o=0;for(let n of r){if(!Object.hasOwn(e,n)){i.push([n,t[n]]);continue}let r=diffValue(e[n],t[n]);r===void 0?o++:r.kind===`value`?i.push([n,r.value]):a.push([n,r])}let s=entryChanges(i,a),c=!sameKeys(impliedKeys(n,s.set??{}),r);if(i.length!==0||a.length!==0||c)return o===0&&a.length===0?{kind:`value`,value:t}:c?{...s,keys:r,kind:`object`}:{...s,kind:`object`}}function entryChanges(e,t){let n={};return e.length>0&&(n.set=Object.fromEntries(e)),t.length>0&&(n.patch=Object.fromEntries(t)),n}function impliedKeys(e,t){let n=new Set(e),r=Object.keys(t).filter(e=>!n.has(e));return r.length===0?e:[...e,...r]}function sameKeys(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function isPlainObject(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function isDictionary(e){return Object.getPrototypeOf(e)===null}function objectLike(e,t){let n=Object.fromEntries(t);return isDictionary(e)?Object.assign(Object.create(null),n):n}function deltaMismatch(e){return Error(`Value delta does not match its base: expected ${e}.`)}export{applyValueDelta,diffValue,snapshotValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){switch(e.status){case`answered`:return{answer:e.optionId??e.text??``,status:`answered`};case`cancelled`:return{interrupted:!0};case`unavailable`:return{status:`unavailable`}}}executeAskQuestionTool.workflowId=`workflow//eve@0.
|
|
1
|
+
async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){switch(e.status){case`answered`:return{answer:e.optionId??e.text??``,status:`answered`};case`cancelled`:return{interrupted:!0};case`unavailable`:return{status:`unavailable`}}}executeAskQuestionTool.workflowId=`workflow//eve@0.91.0//executeAskQuestionTool`;export{executeAskQuestionTool,toAskQuestionOutput,toAskQuestionRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e,t){"use workflow";if(t.abortSignal.aborted)return{interrupted:!0};let n=new Promise(e=>t.abortSignal.addEventListener(`abort`,()=>e(`interrupted`),{once:!0})),r=sleep(Math.ceil(e.seconds*1e3)).then(()=>`elapsed`);return await Promise.race([r,n])===`elapsed`?{waitedSeconds:e.seconds}:{interrupted:!0}}executeSleepTool.workflowId=`workflow//eve@0.
|
|
1
|
+
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e,t){"use workflow";if(t.abortSignal.aborted)return{interrupted:!0};let n=new Promise(e=>t.abortSignal.addEventListener(`abort`,()=>e(`interrupted`),{once:!0})),r=sleep(Math.ceil(e.seconds*1e3)).then(()=>`elapsed`);return await Promise.race([r,n])===`elapsed`?{waitedSeconds:e.seconds}:{interrupted:!0}}executeSleepTool.workflowId=`workflow//eve@0.91.0//executeSleepTool`;export{executeSleepTool};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{frameworkTool}from"./framework-tool.js";import{defineJsonSchema}from"#tools/schema.js";import{defineTool}from"#tools/definition.js";import{toolLabel}from"#tools/tool-label.js";import{executeWebFetchTool}from"#execution/web-fetch/execute.js";const WEB_FETCH_INPUT_SCHEMA=defineJsonSchema({type:`object`,properties:{format:{type:`string`,enum:[`markdown`,`text`,`html`],description:`The format to return the content in (text, markdown, or html). HTML responses are automatically converted to the requested format. Defaults to "markdown".`},timeout:{type:`number`,description:`Optional timeout in seconds. Defaults to 30, max 120.`},url:{type:`string`,description:`The fully-formed URL to fetch content from. Must start with https://.`}},required:[`url`],additionalProperties:!1}),WEB_FETCH_OUTPUT_SCHEMA=defineJsonSchema({type:`object`,properties:{content:{type:`string`},contentType:{type:`string`},truncated:{type:`boolean`},url:{type:`string`}},required:[`content`,`contentType`,`truncated`,`url`],additionalProperties:!1}),webFetch=frameworkTool(defineTool({label:{start:e=>toolLabel(`Fetch`,e.url)},description:[`Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.`,``,`Usage notes:`,`- The URL must be a fully-formed valid URL starting with https://`,`- HTML responses are automatically converted to markdown or plain text based on the requested format`,`- Format options: "markdown" (default), "text", or "html"`,`- Default timeout is 30 seconds (max 120 seconds)`,`- Maximum response size is 5 MB; content is further capped at the shared tool-output budget (50 KB / 2000 lines)`,`- This tool is read-only and does not modify any files`].join(`
|
|
1
|
+
import{frameworkTool}from"./framework-tool.js";import{defineJsonSchema}from"#tools/schema.js";import{defineTool}from"#tools/definition.js";import{toolLabel}from"#tools/tool-label.js";import{executeWebFetchTool}from"#execution/web-fetch/execute.js";const WEB_FETCH_INPUT_SCHEMA=defineJsonSchema({type:`object`,properties:{format:{type:`string`,enum:[`markdown`,`text`,`html`],description:`The format to return the content in (text, markdown, or html). HTML responses are automatically converted to the requested format. Defaults to "markdown".`},timeout:{type:`number`,description:`Optional timeout in seconds, greater than 0. Defaults to 30, max 120.`},url:{type:`string`,description:`The fully-formed URL to fetch content from. Must start with https://.`}},required:[`url`],additionalProperties:!1},e=>e.timeout!==void 0&&!(e.timeout>0)?`timeout must be greater than 0 seconds.`:void 0),WEB_FETCH_OUTPUT_SCHEMA=defineJsonSchema({type:`object`,properties:{content:{type:`string`},contentType:{type:`string`},truncated:{type:`boolean`},url:{type:`string`}},required:[`content`,`contentType`,`truncated`,`url`],additionalProperties:!1}),webFetch=frameworkTool(defineTool({label:{start:e=>toolLabel(`Fetch`,e.url)},description:[`Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.`,``,`Usage notes:`,`- The URL must be a fully-formed valid URL starting with https://`,`- HTML responses are automatically converted to markdown or plain text based on the requested format`,`- Format options: "markdown" (default), "text", or "html"`,`- Default timeout is 30 seconds (max 120 seconds)`,`- Maximum response size is 5 MB; content is further capped at the shared tool-output budget (50 KB / 2000 lines)`,`- This tool is read-only and does not modify any files`].join(`
|
|
2
2
|
`),async execute(e,t){return await executeWebFetchTool(e,{abortSignal:t.abortSignal})},inputSchema:WEB_FETCH_INPUT_SCHEMA,outputSchema:WEB_FETCH_OUTPUT_SCHEMA}));export{WEB_FETCH_INPUT_SCHEMA,WEB_FETCH_OUTPUT_SCHEMA,webFetch as default,webFetch};
|