eve 0.87.0 โ 0.88.1
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 +13 -61
- package/dist/src/channel/interaction-prompts.d.ts +0 -2
- package/dist/src/channel/interaction-prompts.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +3 -3
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/extensions/git/extension/extension.d.ts +5 -2
- package/dist/src/extensions/git/extension/extension.js +1 -1
- package/dist/src/extensions/git/extension/instructions/github.js +1 -1
- package/dist/src/extensions/git/extension/lib/connect-user-auth.d.ts +15 -0
- package/dist/src/extensions/git/extension/lib/connect-user-auth.js +1 -0
- package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +8 -1
- package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
- package/dist/src/extensions/git/extension/lib/github-guidance.d.ts +2 -1
- package/dist/src/extensions/git/extension/lib/github-guidance.js +14 -1
- package/dist/src/extensions/git/extension/lib/github-shell.d.ts +12 -4
- package/dist/src/extensions/git/extension/lib/github-shell.js +1 -1
- package/dist/src/instrumentation/content.js +1 -1
- package/dist/src/instrumentation/lifecycle.d.ts +5 -0
- package/dist/src/instrumentation/native-events.d.ts +4 -1
- package/dist/src/instrumentation/native-events.js +1 -1
- package/dist/src/instrumentation/principal-summary.d.ts +2 -0
- package/dist/src/instrumentation/principal-summary.js +1 -1
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/instrumentation/session-context.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/invocation/agent-invocation.d.ts +2 -0
- package/dist/src/internal/invocation/workflow-execution.js +1 -1
- package/dist/src/protocol/session-projection/reader.d.ts +3 -1
- package/dist/src/protocol/session-projection/reader.js +1 -1
- package/dist/src/public/channels/mcp.js +1 -1
- package/dist/src/public/channels/slack/app-manifest.d.ts +4 -0
- package/dist/src/public/channels/slack/app-manifest.js +1 -1
- package/dist/src/public/channels/slack/auth.d.ts +1 -0
- package/dist/src/public/channels/slack/auth.js +1 -1
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/public/channels/slack/inbound.d.ts +7 -0
- package/dist/src/public/channels/slack/index.d.ts +1 -0
- package/dist/src/public/channels/slack/model-context.d.ts +3 -2
- package/dist/src/public/channels/slack/model-context.js +3 -3
- package/dist/src/public/channels/slack/request-cards.js +2 -2
- package/dist/src/public/channels/slack/slackChannel.d.ts +26 -0
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/slack/user-info.d.ts +64 -0
- package/dist/src/public/channels/slack/user-info.js +1 -0
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/setup/scaffold/create/project.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/tracing/eve/agent-approval-instrumentation.js +1 -1
- package/dist/src/tracing/eve/session.js +1 -1
- package/docs/channels/mcp.mdx +1 -1
- package/docs/channels/slack.mdx +68 -1
- package/docs/code-extension.mdx +51 -12
- package/docs/guides/instrumentation/instrumentation.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +2 -0
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,67 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# eve 0.88.1
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Released 2026-10-29 ยท [Compare with 0.88.0](https://github.com/vercel/eve/compare/eve%400.88.0...eve%400.88.1)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## Features
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
- Approval spans now record who approved or denied the call as `agent.approval.responder.type` and `agent.approval.responder.id`, an approved call's tool span records its approver as `agent.tool.approver.type` and `agent.tool.approver.id`, and the `interaction.settled` instrumentation event carries the same `responder`.
|
|
8
|
+
An approved call runs as the requester, so until now traces showed only the requester and an audit had to read the session stream to find the approver. The responder's id follows the same rule as the turn's principal ids: it is recorded only when the trace policy records both inputs and outputs and the conversation is public or running in development. ([#5596](https://github.com/vercel/eve/pull/5596))
|
|
9
|
+
- The MCP channel's `agent_get` now returns an optional `statusMessage` while an invocation is `working`.
|
|
10
|
+
It names the tool call that is running, using the tool's activity label when it has one, so MCP clients can show progress instead of a bare `working`. ([#5314](https://github.com/vercel/eve/pull/5314))
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
## Bug Fixes
|
|
10
13
|
|
|
11
|
-
|
|
14
|
+
- Release notes now list breaking changes first and use plain headings, one paragraph per change, and a single compare link.
|
|
15
|
+
A `minor` changeset always appears under Breaking Changes, so breaking changes merged with an internal PR title are no longer left out. The 0.86.0 and 0.87.0 notes now include the two breaking changes they missed. ([#5588](https://github.com/vercel/eve/pull/5588))
|
|
16
|
+
- Upgrade `undici` to `8.12.3` for the security fixes published in `8.12.2`.
|
|
17
|
+
A TLS 1.2 server that renegotiates to a certificate for another host now fails the `web_fetch` request instead of crashing the process. Thanks @pedro757 for reporting this in #5589. ([#5591](https://github.com/vercel/eve/pull/5591))
|
|
12
18
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
Ending keeps the retired ID: use `newSession()` or `client.sessions.create()` for a fresh conversation, or `clear()` to clear context in place; remote-agent and session-history compatibility encodings remain unchanged.
|
|
16
|
-
|
|
17
|
-
- eve's authoring and configuration types no longer expose AI SDK, zod, OpenTelemetry, or channel-adapter types, so import eve's own types where you named the third-party ones. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
18
|
-
|
|
19
|
-
Agent `model` fields accept `EveLanguageModel`, `DecisionModel` requires specification `v4`, memory providers return `MemoryToolSet` instead of the removed `MemoryToolDefinition`, `TokenUsage` is exported from `eve`, and `eve/instrumentation/otel`, `eve/channels/linq`, and `eve/channels/photon` export eve-owned span processor/exporter, `LinqWebhookVerifier`, and `PhotonIMessageWebhookVerifier`/`PhotonProjectCredentials` types. Any AI SDK language model or OpenTelemetry processor still type-checks wherever eve accepts one.
|
|
20
|
-
|
|
21
|
-
- Import durable primitives from `eve/workflow` and run/hook operations from `eve/workflow/api`, because bare `workflow` imports now fail in authored modules. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
22
|
-
|
|
23
|
-
Both entries declare eve-owned types: `start(workflow, args?)` takes no options, runs expose only `runId`, `status`, `returnValue`, and `cancel()`, and `getHookByToken` is removed, so pass a deterministic `token` to `createHook` and call `resumeHook(token, payload)`. Ambient Workflow types are no longer needed, though existing `eve/workflow-modules` tsconfig entries can stay through 1.x.
|
|
24
|
-
|
|
25
|
-
- The just-bash escape hatches and the Discord Gateway relay move to experimental entries, so update their imports. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
26
|
-
|
|
27
|
-
Pass `customCommands` and `filesystem` as `JustBashSandbox.environment({ experimental: { customCommands, filesystem } })` and import their types, such as `JustBashCommand` and `JustBashFilesystem`, from `eve/experimental/sandbox/just-bash`. Import `runDiscordGatewayRelay` (formerly `experimental_runDiscordGatewayRelay`) from `eve/experimental/channels/discord/gateway` instead of `eve/channels/discord/gateway`.
|
|
28
|
-
|
|
29
|
-
- Import `defineWorkspaceAgent`, `WorkspaceAgentDefinition`, and `WorkspaceAgentTransport` from `eve/experimental/workspace` instead of `eve`. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
30
|
-
|
|
31
|
-
The helper is experimental; workspace layout and `eve/vercel` remain stable.
|
|
32
|
-
|
|
33
|
-
- Builds now reject agent and connection definitions that don't come from eve's helpers. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
34
|
-
|
|
35
|
-
Export `defineAgent({...})` from every local `agent.ts` (and return it from dynamic subagents), wrap static connections in `defineMcpClientConnection` or `defineOpenAPIConnection` (plain objects no longer default to MCP), and create sentinels only with `defineDynamic()`, `disableTool()`, and `disableRoute()`. Move an `agent/sandbox.ts` that sits beside `agent/sandbox/` to `agent/sandbox/sandbox.ts`.
|
|
36
|
-
|
|
37
|
-
- Remove the undocumented public exports `isDisabledToolSentinel`, `isDisabledRouteSentinel`, `isInstrumentationDisabled`, `answerFromText`, `failureOf`, and Linear's `defaultOnAgentSession`. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
38
|
-
|
|
39
|
-
Use `failure(view, turnId)` from `eve/events` on a folded view, or check raw `turn.settled` and `session.ended` events for `outcome === "failed"`. Omit `onAgentSession` to keep Linear's default handler.
|
|
40
|
-
|
|
41
|
-
- Flatten client stream retry settings into `reconnect?: false | ReconnectOptions`. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
42
|
-
|
|
43
|
-
Replace `streamReconnectPolicy: { reconnect: false }` with `reconnect: false`, move `streamOpenReconnectPolicy` fields under `reconnect`, and rename `retryableErrorStatuses` to `retryableStatuses`. The `StreamReconnectPolicy` and `StreamReconnectRetryPolicy` types are removed in favor of `ReconnectOptions`.
|
|
44
|
-
|
|
45
|
-
- Rename `compaction.thresholdPercent` to `compaction.threshold`, which takes a 0โ1 fraction. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
46
|
-
|
|
47
|
-
The old key now fails with migration guidance. Set `limits.sessionUsage: false` to disable usage limits, including limits inherited from a parent agent.
|
|
48
|
-
|
|
49
|
-
- Built-in channel state types no longer publish the default handlers' bookkeeping, so keep custom handler data in your own state keys. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
50
|
-
|
|
51
|
-
Hidden fields include Slack `taskCards`, `threadStatus`, and the code-channel reply fields `replyThreadTs` and `pendingReplyThreadTs`, Chat SDK streaming fields, `pendingSignIns`, prompt-card fields, and Discord's `interactionToken` (read it from the Discord handle), and `TelegramHitlState` is no longer exported. `SendTurnPayload` is now exported from `eve/client`.
|
|
52
|
-
|
|
53
|
-
- Slack `initialMessage` now accepts Markdown, text, raw blocks, or a card, with optional files uploaded into the root message's thread. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
54
|
-
|
|
55
|
-
Remove unsupported `Modal*`, `ExternalSelect*`, `TextInput*`, `CardJSXElement`, `CardJSXProps`, `isCardElement`, and `cardChildToFallbackText` exports, plus the card builders' JSX-props overloads and their `*Props`, `ContainerProps`, and `ChatElement` types. Call builders with their data forms such as `Button({ id, label })`, use `CardText` for labels, native Slack view data for modals, and `cardToFallbackText` for whole cards (see [Slack cards](https://eve.dev/docs/channels/slack#cards)).
|
|
56
|
-
|
|
57
|
-
- Clarify that Next.js `servicePrefix` supports manually configured Vercel services and production proxying; it is not a legacy option. [#5479](https://github.com/vercel/eve/pull/5479)
|
|
58
|
-
|
|
59
|
-
## Other Changes
|
|
60
|
-
|
|
61
|
-
See the [full list of changes](https://github.com/vercel/eve/commits/eve%400.87.0).
|
|
62
|
-
|
|
63
|
-
## Contributors
|
|
64
|
-
|
|
65
|
-
- [@OwenKephart](https://github.com/OwenKephart)
|
|
66
|
-
|
|
67
|
-
For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%400.87.0/packages/eve/CHANGELOG.md).
|
|
19
|
+
For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%400.88.1/packages/eve/CHANGELOG.md).
|
|
@@ -46,8 +46,6 @@ export declare function firstOpenRequest(view: SessionView): Interaction | undef
|
|
|
46
46
|
export declare function requestSettlementOf(view: SessionView, data: InteractionSettledData): RequestSettlement | undefined;
|
|
47
47
|
/** An answer a check or policy refused, from its `response.settled`. */
|
|
48
48
|
export declare function refusedAnswerOf(view: SessionView, data: ResponseSettledData): RefusedAnswer | undefined;
|
|
49
|
-
/** Who gave an answer: the principal of the delivery it arrived in. */
|
|
50
|
-
export declare function responderOf(view: SessionView, responseId: string): Principal | undefined;
|
|
51
49
|
/** An option's style a channel can render: a style a newer eve added reads as none. */
|
|
52
50
|
export declare function optionStyle(option: {
|
|
53
51
|
readonly style?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decidingAnswer,interaction,interaction as interaction$1,promptQueueHead,signInEnding}from"#protocol/session-projection/reader.js";import{interactionBatches,interactionOwner}from"#protocol/session-projection/selectors.js";function requestBatchOf(e,t){let n=e.interactions[t.interactionId],r=interactionBatches(e).find(e=>e[0]===n);if(n===void 0||r===void 0)return;let i=r.flatMap(t=>interaction$1(e,t.interactionId)??[]);if(i.length===0)return;let a=interactionOwner(e,n),o={requests:i,turnId:a.turnId??``};return a.taskId!==void 0&&(o.taskId=a.taskId),(n.origin!==void 0||n.request.kind===`question`)&&`callId`in n.subject&&(o.callId=n.subject.callId),o}function firstOpenRequest(e){let t=promptQueueHead(e);return t===void 0?void 0:interaction$1(e,t.interactionId)}function requestSettlementOf(e,t){let n=e.interactions[t.interactionId];if(n===void 0||n.request.kind===`sign-in`)return;let r={interactionId:n.interactionId,kind:n.request.kind,outcome:t.outcome},i=decidingAnswer({...n,response:t.response});i!==void 0&&(r.answer=i),t.reason!==void 0&&(r.reason=t.reason);let a=t.cause!==void 0&&`responseId`in t.cause?responderOf(e,t.cause.responseId):void 0;return a!==void 0&&(r.responder=a),r}function refusedAnswerOf(e,t){if(t.outcome!==`refused`&&t.outcome!==`failed`)return;let n=e.responses[t.responseId];if(n===void 0)return;let r={interactionId:n.interactionId,outcome:t.outcome};t.reason!==void 0&&(r.reason=t.reason);let i=responderOf(e,t.responseId);return i!==void 0&&(r.responder=i),r}function
|
|
1
|
+
import{decidingAnswer,interaction,interaction as interaction$1,promptQueueHead,responderOf,signInEnding}from"#protocol/session-projection/reader.js";import{interactionBatches,interactionOwner}from"#protocol/session-projection/selectors.js";function requestBatchOf(e,t){let n=e.interactions[t.interactionId],r=interactionBatches(e).find(e=>e[0]===n);if(n===void 0||r===void 0)return;let i=r.flatMap(t=>interaction$1(e,t.interactionId)??[]);if(i.length===0)return;let a=interactionOwner(e,n),o={requests:i,turnId:a.turnId??``};return a.taskId!==void 0&&(o.taskId=a.taskId),(n.origin!==void 0||n.request.kind===`question`)&&`callId`in n.subject&&(o.callId=n.subject.callId),o}function firstOpenRequest(e){let t=promptQueueHead(e);return t===void 0?void 0:interaction$1(e,t.interactionId)}function requestSettlementOf(e,t){let n=e.interactions[t.interactionId];if(n===void 0||n.request.kind===`sign-in`)return;let r={interactionId:n.interactionId,kind:n.request.kind,outcome:t.outcome},i=decidingAnswer({...n,response:t.response});i!==void 0&&(r.answer=i),t.reason!==void 0&&(r.reason=t.reason);let a=t.cause!==void 0&&`responseId`in t.cause?responderOf(e,t.cause.responseId):void 0;return a!==void 0&&(r.responder=a),r}function refusedAnswerOf(e,t){if(t.outcome!==`refused`&&t.outcome!==`failed`)return;let n=e.responses[t.responseId];if(n===void 0)return;let r={interactionId:n.interactionId,outcome:t.outcome};t.reason!==void 0&&(r.reason=t.reason);let i=responderOf(e,t.responseId);return i!==void 0&&(r.responder=i),r}function optionStyle(e){let{style:t}=e;return t===`primary`||t===`danger`||t==="default"?t:void 0}export{firstOpenRequest,interaction,optionStyle,refusedAnswerOf,requestBatchOf,requestSettlementOf,signInEnding};
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"moduleFingerprints": {
|
|
3
3
|
"@eve/catalog": "29b7529f6044427c750e4c27fe91da792014c60c660db31b7ca1fff0afe7f603",
|
|
4
4
|
"just-secrets": "1ce67d437d0bb06df02e4e99180a3c5f5edf0010314010226e97b96d462bba5d",
|
|
5
|
-
"@vercel/agent-runs": "
|
|
5
|
+
"@vercel/agent-runs": "8a64c66bdfa39999f05321865b37e84aba509ff993db76e7fe988e8630d756b0",
|
|
6
6
|
"@workflow/world-local": "a10e78551f65fc607cf75261a569d852c40bc9cfac13a7fb6e15c88bf1ccf429"
|
|
7
7
|
},
|
|
8
8
|
"moduleVersions": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"@shadcn/registry": "0.1.3",
|
|
43
43
|
"@standard-schema/spec": "1.1.0",
|
|
44
44
|
"turndown": "7.2.4",
|
|
45
|
-
"@vercel/agent-runs": "0.0.
|
|
45
|
+
"@vercel/agent-runs": "0.0.4",
|
|
46
46
|
"@vercel/blob": "2.8.0",
|
|
47
47
|
"@vercel/connect": "2.5.2",
|
|
48
48
|
"@vercel/detect-agent": "1.2.3",
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"zod": "4.5.4",
|
|
62
62
|
"zod-validation-error": "5.0.0"
|
|
63
63
|
},
|
|
64
|
-
"scriptHash": "
|
|
64
|
+
"scriptHash": "8d606c6729fcbfca8be615a4186723cebba6b9e35208bf6c160be584417b2928",
|
|
65
65
|
"toolVersions": {
|
|
66
66
|
"rolldown": "1.2.9",
|
|
67
67
|
"typescript": "7.0.2"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.
|
|
1
|
+
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.88.1//runWorkflowProgramTask`;export{runWorkflowProgramTask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{reply:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({signal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.
|
|
1
|
+
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{reply:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({signal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.88.1//runAgentRouterTask`;export{runAgentRouterTask};
|
|
@@ -8,10 +8,13 @@ export type { GitHubAttribution } from "./lib/github-shell.ts";
|
|
|
8
8
|
declare const _default: import("eve/extension").ExtensionHandle<z.ZodObject<{
|
|
9
9
|
github: z.ZodOptional<z.ZodObject<{
|
|
10
10
|
connector: z.ZodString;
|
|
11
|
-
org: z.ZodString;
|
|
12
11
|
broker: z.ZodCustom<(sandbox: import("../../../shared/sandbox-session.ts").SandboxSession, rules: Readonly<Record<string, readonly import("./lib/github-shell.ts").GitHubLeaseRule[]>> | null) => Promise<void>, (sandbox: import("../../../shared/sandbox-session.ts").SandboxSession, rules: Readonly<Record<string, readonly import("./lib/github-shell.ts").GitHubLeaseRule[]>> | null) => Promise<void>>;
|
|
13
12
|
attribution: z.ZodOptional<z.ZodCustom<GitHubAttribution, GitHubAttribution>>;
|
|
14
|
-
authorize: z.
|
|
13
|
+
authorize: z.ZodCustom<GitHubAuthorize, GitHubAuthorize>;
|
|
14
|
+
principalType: z.ZodOptional<z.ZodEnum<{
|
|
15
|
+
app: "app";
|
|
16
|
+
user: "user";
|
|
17
|
+
}>>;
|
|
15
18
|
}, z.core.$strip>>;
|
|
16
19
|
}, z.core.$strip>>;
|
|
17
20
|
export default _default;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{defineExtension}from"eve/extension";const fn=()=>z.custom(e=>typeof e==`function`);var extension_default=defineExtension({config:z.object({github:z.object({connector:z.string().min(1),
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{defineExtension}from"eve/extension";const fn=()=>z.custom(e=>typeof e==`function`);var extension_default=defineExtension({config:z.object({github:z.object({connector:z.string().min(1),broker:fn(),attribution:fn().optional(),authorize:fn(),principalType:z.enum([`app`,`user`]).optional()}).optional()})});export{extension_default as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import extension_default from"../extension.js";import{githubInstructions}from"../lib/github-guidance.js";import{defineDynamic,defineInstructions}from"eve/instructions";var github_default=defineDynamic(()=>defineInstructions({content:githubInstructions(extension_default.config.github!==void 0)}));export{github_default as default};
|
|
1
|
+
import extension_default from"../extension.js";import{githubInstructions}from"../lib/github-guidance.js";import{defineDynamic,defineInstructions}from"eve/instructions";var github_default=defineDynamic(()=>defineInstructions({content:githubInstructions(extension_default.config.github!==void 0,extension_default.config.github?.principalType===`user`)}));export{github_default as default};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { deleteTokenCacheEntry, getTokenResponse, startAuthorization } from "@vercel/connect";
|
|
2
|
+
import { type InteractiveAuthorizationDefinition } from "eve/connections";
|
|
3
|
+
/** The Connect calls the sign-in uses; injectable for tests. */
|
|
4
|
+
export interface ConnectUserClient {
|
|
5
|
+
readonly getTokenResponse: typeof getTokenResponse;
|
|
6
|
+
readonly startAuthorization: typeof startAuthorization;
|
|
7
|
+
readonly deleteTokenCacheEntry: typeof deleteTokenCacheEntry;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Connect-backed sign-in for user-scoped `gh` tokens. It mirrors
|
|
11
|
+
* `connect({ connector, principalType: "user" })` from `@vercel/connect/eve`,
|
|
12
|
+
* which eve cannot bundle because it imports `eve` itself. Requests carry no
|
|
13
|
+
* authorization details, so one grant serves every repository.
|
|
14
|
+
*/
|
|
15
|
+
export declare function connectUserAuthorization(connector: string, client?: ConnectUserClient): InteractiveAuthorizationDefinition;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ConnectorInstallationRequiredError,NoValidTokenError,UserAuthorizationRequiredError,deleteTokenCacheEntry,getTokenResponse,startAuthorization}from"#compiled/@vercel/connect/index.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError}from"eve/connections";const CONNECT={getTokenResponse,startAuthorization,deleteTokenCacheEntry};function connectUserAuthorization(e,t=CONNECT){let params=e=>{if(e.type!==`user`)throw new ConnectionAuthorizationFailedError(`connect`,{message:`User-scoped GitHub access requires a signed-in caller.`,reason:`principal_required`,retryable:!1});return{subject:{type:`user`,id:e.id,issuer:e.issuer}}},token=async(n,r)=>{try{let r=await t.getTokenResponse(e,params(n));return{token:r.token,expiresAt:r.expiresAt}}catch(e){throw translate(e,r)}};return{principalType:`user`,vercelConnect:{connector:e},getToken:({principal:e})=>token(e,`getToken`),async startAuthorization({principal:n,callbackUrl:r}){try{let i=await t.startAuthorization(e,params(n),{callbackUrl:r,deviceCode:!0}),a=i.connector?.serviceName??i.connector?.name;return{challenge:{url:i.url,...i.deviceCode?{userCode:i.deviceCode}:null,...i.expiresAt?{expiresAt:new Date(i.expiresAt).toISOString()}:null,...a?{displayName:a}:null}}}catch(e){throw translate(e,`startAuthorization`)}},completeAuthorization:({principal:e})=>token(e,`completeAuthorization`),evict({principal:n}){try{t.deleteTokenCacheEntry(e,params(n))}catch{}}}}function translate(e,t){return e instanceof UserAuthorizationRequiredError||e instanceof NoValidTokenError?t===`completeAuthorization`?new ConnectionAuthorizationFailedError(`connect`,{message:`Authorization did not complete. Vercel Connect still reports the user as unauthorized.`}):new ConnectionAuthorizationRequiredError(`connect`,{message:e.message}):e instanceof ConnectorInstallationRequiredError?new ConnectionAuthorizationFailedError(`connect`,{message:e.message,reason:`connector_installation_required`,retryable:!1}):e instanceof Error?e:Error(String(e))}export{connectUserAuthorization};
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { type GitHubConfig } from "./github-shell.ts";
|
|
2
|
-
|
|
2
|
+
declare const GH_TOOL_SCOPE: {
|
|
3
|
+
readonly repository: "Connect mints the real token for only that repository, and the sandbox process receives only a placeholder GH_TOKEN that the firewall exchanges on matching GitHub requests. GitHub rejects access outside the token's server-side repository scope; commands that explicitly name another repository with -R, --repo, --repo=, or a repository argument to gh repo clone, view, or fork are denied before minting.";
|
|
4
|
+
readonly caller: "Connect resolves the caller's own GitHub token for that command, and the sandbox process receives only a placeholder GH_TOKEN that the firewall exchanges on matching GitHub requests. The token carries the caller's GitHub permissions, so GitHub allows whatever the caller can access; commands that explicitly name another repository with -R, --repo, --repo=, or a repository argument to gh repo clone, view, or fork are denied before the token is resolved.";
|
|
5
|
+
};
|
|
6
|
+
/** Describes the `gh` tool for app-installation (`repository`) or user-scoped (`caller`) tokens. */
|
|
7
|
+
export declare function ghToolDescription(scope: keyof typeof GH_TOOL_SCOPE): string;
|
|
8
|
+
export declare const GH_TOOL_DESCRIPTION: string;
|
|
3
9
|
/** The Connect-brokered `gh` tool, rebuilt by the dynamic resolver with its current config. */
|
|
4
10
|
export declare function defineGhTool(github: () => GitHubConfig | undefined, description?: string): import("eve/tools").ToolDefinition<{
|
|
5
11
|
command: string;
|
|
@@ -27,3 +33,4 @@ export declare function defineGhTool(github: () => GitHubConfig | undefined, des
|
|
|
27
33
|
workingDirectory?: string | undefined;
|
|
28
34
|
}, ctx: import("eve/tools").ToolContext): Promise<import("./github-shell.ts").GitHubShellOutput>;
|
|
29
35
|
};
|
|
36
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{executeGitHubShell,githubShellApproval}from"./github-shell.js";import{githubShellInputSchema}from"./github-shell-schema.js";import{z}from"#compiled/zod/index.js";import{defineTool}from"eve/tools";const
|
|
1
|
+
import{executeGitHubShell,githubShellApproval}from"./github-shell.js";import{githubShellInputSchema}from"./github-shell-schema.js";import{z}from"#compiled/zod/index.js";import{defineTool}from"eve/tools";const GH_TOOL_SCOPE={repository:`Connect mints the real token for only that repository, and the sandbox process receives only a placeholder GH_TOKEN that the firewall exchanges on matching GitHub requests. GitHub rejects access outside the token's server-side repository scope; commands that explicitly name another repository with -R, --repo, --repo=, or a repository argument to gh repo clone, view, or fork are denied before minting.`,caller:`Connect resolves the caller's own GitHub token for that command, and the sandbox process receives only a placeholder GH_TOKEN that the firewall exchanges on matching GitHub requests. The token carries the caller's GitHub permissions, so GitHub allows whatever the caller can access; commands that explicitly name another repository with -R, --repo, --repo=, or a repository argument to gh repo clone, view, or fork are denied before the token is resolved.`};function ghToolDescription(e){return`Run one authenticated GitHub command in the sandbox. The full gh CLI surface is available. Commands run without an approval prompt; description records the GitHub-side result the command intends to produce. Declare exactly one owner/name repository; the agent's access policy decides which repositories commands may use. ${GH_TOOL_SCOPE[e]} Use simple argv quoting only, never environment assignments, pipes, redirects, substitutions, or other shell syntax. gh alias and extension commands may execute local code, but remain sandboxed. Use git here only for authenticated fetch, pull, push, or ls-remote against a strictly validated origin, and use gh-signed-commit only with --repo. Use ordinary bash for local git status, diff, add, commit, and rebase.`}const GH_TOOL_DESCRIPTION=ghToolDescription(`repository`),ghOutputSchema=z.object({exitCode:z.number().int(),stderr:z.string(),stdout:z.string(),truncated:z.boolean()});function defineGhTool(e,t=ghToolDescription(e()?.principalType===`user`?`caller`:`repository`)){return defineTool({description:t,approval:({toolInput:e})=>githubShellApproval(e),inputSchema:githubShellInputSchema,outputSchema:ghOutputSchema,execute(t,n){return executeGitHubShell(t,e(),{context:n,auth:n.session.auth.current,getToken:(e,t)=>n.getToken(e,t),requireAuth:(e,t)=>n.requireAuth(e,t),getSandbox:()=>n.getSandbox(),sessionId:n.session.id})}})}export{GH_TOOL_DESCRIPTION,defineGhTool,ghToolDescription};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
/** `callerScoped` describes user tokens (`principalType: "user"`) instead of repository-scoped app tokens. */
|
|
2
|
+
export declare function githubInstructions(github: boolean, callerScoped?: boolean): string;
|
|
2
3
|
export declare function prSkillDescription(github: boolean): string;
|
|
3
4
|
export declare function prSkillMarkdown(github: boolean): string;
|
|
@@ -1,4 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
const TOKEN_SCOPE={repository:{token:"Connect mints the real token for only the declared repository. The sandbox process receives only a placeholder `GH_TOKEN`, and the firewall exchanges it on matching GitHub requests. GitHub rejects access outside the token's server-side repository scope.",context:"Commands without an explicit repository may use normal `gh` context, but their token remains scoped to the declared repository."},caller:{token:"Connect resolves the caller's own GitHub token for each command. The sandbox process receives only a placeholder `GH_TOKEN`, and the firewall exchanges it on matching GitHub requests. The token carries the caller's GitHub permissions, so access is limited to what the caller can reach on GitHub.",context:"Commands without an explicit repository may use normal `gh` context."}},connectInstructions=e=>`# GitHub
|
|
2
|
+
|
|
3
|
+
GitHub credentials are not available to ordinary \`bash\`. Use the \`gh\` tool for every authenticated GitHub operation. The full \`gh\` CLI surface is available. Declare exactly one \`owner/name\` repository with write-capable access; the agent's access policy decides which repositories commands may use. Authenticated commands run without an approval prompt; describe the intended GitHub-side result accurately in \`description\`. ${e.token} Never put credentials in URLs or commands. If access is denied, report it plainly and stop.
|
|
4
|
+
|
|
5
|
+
Pass commands as simple argv with ordinary quoting. Do not use environment assignments, pipes, redirects, substitutions, or other shell syntax. ${e.context} An explicit \`-R\`, \`--repo\`, \`--repo=\`, or repository argument to \`gh repo clone\`, \`view\`, or \`fork\` must match the declaration.
|
|
6
|
+
|
|
7
|
+
Determine the repositories needed to complete the task through source discovery and investigation, even when the requester does not name them. Do not ask the requester to enumerate repositories that can be discovered, and never default to the current agent's repository. The agent may select additional repositories as the work reveals them. Each authenticated command declares exactly one target repository and mints a credential lease for that repository at the moment it is needed, so cross-repository work uses separate scoped commands and leases.
|
|
8
|
+
|
|
9
|
+
Clone with \`gh repo clone owner/name\`. Use authenticated \`git fetch\`, \`git pull\`, \`git push\`, and \`git ls-remote\` through the \`gh\` tool too. Local \`git status\`, \`diff\`, \`add\`, \`commit\`, and \`rebase\` remain ordinary \`bash\` commands because they need no GitHub credential.
|
|
10
|
+
|
|
11
|
+
Use GitHub CLI commands through the \`gh\` tool for issues, pull requests, reviews, Actions, CI, authentication status, configuration, aliases, extensions, and API requests. Common commands include \`gh pr create --draft\`, \`gh pr checks\`, \`gh run rerun --failed\`, and \`gh pr review\`, but they are not restrictions.
|
|
12
|
+
|
|
13
|
+
Repositories that require verified signatures reject ordinary sandbox commits. Stage the intended changes explicitly, run \`gh-signed-commit --repo owner/name --branch <branch> -m <headline>\` through the \`gh\` tool, then create the draft pull request through the same tool.
|
|
14
|
+
`;function githubInstructions(e,t=!1){return`${e?connectInstructions(TOKEN_SCOPE[t?`caller`:`repository`]):"# GitHub\n\nUse the `gh` and `git` CLIs in `bash` for GitHub operations: cloning, fetching, pushing, issues, pull requests, reviews, and CI. They authenticate with the credentials already configured in the shell. Never put credentials in URLs or commands. If access is denied, report it plainly and stop.\n"}\nLoad the pr skill before publishing. Create one pull request per request unless the requester asks otherwise.\n`}function prSkillDescription(e){return e?`Prepare and publish a draft pull request with a signed commit, motivation-led description, testable hypothesis, and validation evidence.`:`Prepare and publish a draft pull request with a motivation-led description, testable hypothesis, and validation evidence.`}function prSkillMarkdown(e){return`# Publish a proposal
|
|
2
15
|
|
|
3
16
|
Fetch the current base immediately before publication. Rebase onto it, or replay only the intended diff onto a clean checkout when local commits are unavailable. Stop on conflicts, stale refs, unexpected paths, or unrelated reversions.
|
|
4
17
|
|
|
@@ -31,18 +31,23 @@ export interface GitHubConfig {
|
|
|
31
31
|
* requester's linked accounts.
|
|
32
32
|
*/
|
|
33
33
|
readonly attribution?: GitHubAttribution;
|
|
34
|
-
|
|
34
|
+
/** The only repository access control: commands run only when it returns `true`. */
|
|
35
|
+
readonly authorize: GitHubAuthorize;
|
|
35
36
|
readonly broker: (sandbox: SandboxSession, rules: Readonly<Record<string, readonly GitHubLeaseRule[]>> | null) => Promise<void>;
|
|
36
37
|
readonly connector: string;
|
|
37
|
-
|
|
38
|
+
/**
|
|
39
|
+
* `"app"` (default) mints GitHub App installation tokens. `"user"` resolves
|
|
40
|
+
* the caller's own token through `ctx.getToken`, signing them in when needed.
|
|
41
|
+
*/
|
|
42
|
+
readonly principalType?: "app" | "user";
|
|
38
43
|
}
|
|
39
44
|
/** What an `authorize` callback sees before a `gh` command runs. */
|
|
40
45
|
export interface GitHubAuthorizeRequest {
|
|
41
46
|
/** The session's current caller, or `null` when the session has none. */
|
|
42
47
|
readonly auth: SessionAuthContext | null;
|
|
43
|
-
/** The `owner/name` repository the command declared. */
|
|
48
|
+
/** The `owner/name` repository the command declared, which every explicit command target matches. */
|
|
44
49
|
readonly repository: string;
|
|
45
|
-
/** The
|
|
50
|
+
/** The token Connect minted for this command, for API lookups. It reaches the command only after `authorize` returns `true`. */
|
|
46
51
|
readonly token: string;
|
|
47
52
|
}
|
|
48
53
|
/** Decides whether the session's caller may run a `gh` command against one repository. */
|
|
@@ -77,6 +82,9 @@ interface GitHubShellDependencies {
|
|
|
77
82
|
type: "app";
|
|
78
83
|
};
|
|
79
84
|
}) => Promise<string>;
|
|
85
|
+
/** Resolves and re-authorizes user-scoped providers; the tool's `ctx.getToken` and `ctx.requireAuth`. */
|
|
86
|
+
readonly getToken?: ToolContext["getToken"];
|
|
87
|
+
readonly requireAuth?: ToolContext["requireAuth"];
|
|
80
88
|
readonly getSandbox: () => Promise<SandboxSession>;
|
|
81
89
|
/** Serializes credential leases per eve session; every `ctx.getSandbox()` call returns a new handle. */
|
|
82
90
|
readonly sessionId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{attributeCommand,coAuthorTrailer,isAttributable}from"./attribution.js";import{shellQuote}from"./shell.js";import{validateRepositoryRoot}from"./repository-root.js";import{GITHUB_TOOLING_PATHS}from"./tooling.js";import{posix}from"node:path";import{getToken}from"#compiled/@vercel/connect/index.js";const MAX_OUTPUT_BYTES=1e5,leaseQueues=new Map,ALLOWED_GIT_REMOTE_COMMANDS=new Set([`fetch`,`ls-remote`,`pull`,`push`]);function githubShellApproval(e){if(!e)return`not-applicable`;try{return validateGitHubShellInput(e),`not-applicable`}catch(e){return{type:`denied`,reason:e instanceof Error?e.message:`Invalid GitHub command.`}}}async function executeGitHubShell(e,t,n){if(!t)throw Error(`GitHub command access is not configured for this agent.`);let r=validateGitHubShellInput(e),i=await n.getSandbox(),a=resolveWorkingDirectory(i,e.workingDirectory);(r[0]===`git`||r[0]===`gh-signed-commit`)&&(a=await validateRepositoryRoot(i,a));let o=e.permissions[0].repositories,s=await assertCommandTargets(r,o,a,i),c=crypto.randomUUID(),l=`/tmp/eve-git-body-${c}.md`,u=
|
|
1
|
+
import{attributeCommand,coAuthorTrailer,isAttributable}from"./attribution.js";import{connectUserAuthorization}from"./connect-user-auth.js";import{shellQuote}from"./shell.js";import{validateRepositoryRoot}from"./repository-root.js";import{GITHUB_TOOLING_PATHS}from"./tooling.js";import{posix}from"node:path";import{getToken}from"#compiled/@vercel/connect/index.js";const MAX_OUTPUT_BYTES=1e5,leaseQueues=new Map,ALLOWED_GIT_REMOTE_COMMANDS=new Set([`fetch`,`ls-remote`,`pull`,`push`]),GITHUB_UNAUTHORIZED=/HTTP 401\b|Bad credentials|Authentication failed for|failed: 401\b/u;function githubShellApproval(e){if(!e)return`not-applicable`;try{return validateGitHubShellInput(e),`not-applicable`}catch(e){return{type:`denied`,reason:e instanceof Error?e.message:`Invalid GitHub command.`}}}async function executeGitHubShell(e,t,n){if(!t)throw Error(`GitHub command access is not configured for this agent.`);let r=validateGitHubShellInput(e),i=await n.getSandbox(),a=resolveWorkingDirectory(i,e.workingDirectory);(r[0]===`git`||r[0]===`gh-signed-commit`)&&(a=await validateRepositoryRoot(i,a));let o=e.permissions[0].repositories,s=await assertCommandTargets(r,o,a,i),c=crypto.randomUUID(),l=`/tmp/eve-git-body-${c}.md`,{repository:u,owner:d,name:f}=declaredRepository(o),p=n.auth??null,m,h;if(t.principalType===`user`){if(!n.getToken||!n.requireAuth)throw Error(`User-scoped GitHub access requires ctx.getToken and ctx.requireAuth.`);m=connectUserAuthorization(t.connector),{token:h}=await n.getToken(m)}else h=await(n.getConnectToken??getToken)(t.connector,{authorizationDetails:[{type:`github_app_installation`,org:d,repositories:[f]}],subject:{type:`app`}});if(!h)throw Error(`Connect returned an empty token for ${JSON.stringify(t.connector)}.`);if(!await t.authorize({auth:p,repository:u,token:h}))throw Error(`The current caller is not authorized to access ${u}.`);let g=t.attribution&&n.context&&isAttributable(r)?await t.attribution(n.context):null,_=g?await attributeCommand(r,coAuthorTrailer(g),i,a,l):r,v=executablePath(_[0]),y=s?[`-c`,`protocol.allow=never`,`-c`,`protocol.https.allow=always`,_[1],`https://github.com/${s}.git`,..._.slice(3)]:_.slice(1),b=`cd ${shellQuote(a)} && exec ${shellQuote(v)} ${y.map(shellQuote).join(` `)}`,x=`Basic ${Buffer.from(`x-access-token:${h}`).toString(`base64`)}`,S=`eve-github-${c}`,C=`/tmp/eve-code-gh-${c}`,w=`Basic ${Buffer.from(`x-access-token:${S}`).toString(`base64`)}`,T;try{T=await withGitHubCredentialLease(i,n.sessionId,{authorization:x,placeholder:S,placeholderAuthorization:w,token:h},()=>{let e={GH_CONFIG_DIR:C,GH_PROMPT_DISABLED:`1`};return r[0]!==`git`&&(e.GH_TOKEN=S),e.GIT_CONFIG_COUNT=`2`,e.GIT_CONFIG_KEY_0=`http.https://github.com/.extraheader`,e.GIT_CONFIG_VALUE_0=`Authorization: ${w}`,e.GIT_CONFIG_KEY_1=`core.hooksPath`,e.GIT_CONFIG_VALUE_1=`/dev/null`,e.GIT_TERMINAL_PROMPT=`0`,e.PATH=`/usr/local/bin:/usr/bin:/bin`,i.run({command:b,env:e})},t.broker)}finally{await i.removePath({path:C,recursive:!0,force:!0}),await i.removePath({path:l,force:!0})}m&&T.exitCode!==0&&GITHUB_UNAUTHORIZED.test(T.stderr)&&n.requireAuth(m);let E=sanitizeOutput(T.stdout,h,x),D=sanitizeOutput(T.stderr,h,x);return{exitCode:T.exitCode,stdout:E.value,stderr:D.value,truncated:E.truncated||D.truncated}}async function withGitHubCredentialLease(e,t,n,r,i){let a=leaseQueues.get(t)??Promise.resolve(),o,s=new Promise(e=>{o=e}),c=a.then(()=>s);leaseQueues.set(t,c),await a;try{return await i(e,{"api.github.com":[{match:{headers:[{key:{exact:`authorization`},value:{regex:`^(?:token|Bearer) ${n.placeholder}$`}}]},transform:[{headers:{authorization:`Bearer ${n.token}`}}]}],"github.com":[{match:{headers:[{key:{exact:`authorization`},value:{exact:n.placeholderAuthorization}}]},transform:[{headers:{authorization:n.authorization}}]}]}),await r()}finally{try{await i(e,null)}finally{o(),leaseQueues.get(t)===c&&leaseQueues.delete(t)}}}function parseCommand(e){let t=e.trim();if(!t)throw Error(`GitHub command must not be empty.`);let n=[],r=``,i=null,a=!1,o=!1;for(let e of t){if(a){r+=e,a=!1,o=!0;continue}if(e===`\\`&&i!==`single`){a=!0,o=!0;continue}if(i===`single`){e===`'`?i=null:r+=e;continue}if(i===`double`){if(e===`"`)i=null;else if(e===`$`||e==="`")throw unsupportedSyntax();else r+=e;continue}if(e===`'`)i=`single`,o=!0;else if(e===`"`)i=`double`,o=!0;else if(/\s/u.test(e))o&&=(n.push(r),r=``,!1);else if(";&|<>$`(){}".includes(e))throw unsupportedSyntax();else r+=e,o=!0}if(a||i)throw Error(`GitHub command contains an unfinished quote or escape.`);if(o&&n.push(r),n.length===0)throw Error(`GitHub command must not be empty.`);return n}function validateGitHubShellInput(e){let t=parseCommand(e.command),n=e.permissions[0];if(e.permissions.length!==1||n?.provider!==`github`)throw Error(`Exactly one GitHub permission is required.`);if(n.access!==`write`)throw Error(`GitHub App commands require explicit write-capable access.`);if(!e.description.trim())throw Error(`description must describe the intended result.`);let[r,i]=t;if(r===`gh`){if(!i)throw Error(`A gh subcommand is required.`)}else if(r===`git`){if(!i||!ALLOWED_GIT_REMOTE_COMMANDS.has(i))throw Error(`Authenticated git supports only fetch, ls-remote, pull, and push; clone with gh repo clone.`)}else if(r!==`gh-signed-commit`)throw Error(`GitHub commands must use gh, an authenticated git remote command, or gh-signed-commit.`);return t}async function assertCommandTargets(e,t,n,r){let i=new Set(t.map(e=>e.toLowerCase())),a,o;if(e[0]===`git`){if(e[2]!==`origin`)throw Error(`Authenticated git commands must use the validated origin remote.`);let t=e[1]===`push`,i=await r.run({command:`cd ${shellQuote(n)} && git remote get-url ${t?`--push `:``}origin`,env:{GIT_TERMINAL_PROMPT:`0`,PATH:`/usr/bin:/bin`}});if(i.exitCode!==0)throw Error(`Could not resolve the origin GitHub repository.`);a=repositoryFromRemote(i.stdout.trim()),o=[a]}else if(e[0]===`gh-signed-commit`){if(o=repoFlagTargets(e.slice(1)),o.length===0)throw Error(`gh-signed-commit requires an explicit --repo owner/repository target.`)}else o=repoFlagTargets(e.slice(1)),e[1]===`repo`&&(e[2]===`clone`||e[2]===`view`||e[2]===`fork`)&&e[3]&&!e[3].startsWith(`-`)&&o.push(canonicalRepository(e[3]));for(let e of o)if(!i.has(e.toLowerCase()))throw Error(`Command target ${JSON.stringify(e)} is not in the declared repositories.`);return a}function repoFlagTargets(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`--repo`||r===`-R`){let i=e[n+1];if(!i)throw Error(`${r} requires an owner/repository value.`);t.push(canonicalRepository(i)),n+=1}else r?.startsWith(`--repo=`)&&t.push(canonicalRepository(r.slice(7)))}return t}function repositoryFromRemote(e){let t=/^https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/iu.exec(e);if(t?.[1])return canonicalRepository(t[1]);let n=/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/iu.exec(e);if(n?.[1])return canonicalRepository(n[1]);throw Error(`The origin remote is not a canonical GitHub repository URL.`)}function canonicalRepository(e){let t=e.replace(/\.git$/iu,``);if(!/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u.test(t))throw Error(`Invalid GitHub repository ${JSON.stringify(e)}.`);return t}function declaredRepository(e){if(e.length!==1)throw Error(`Exactly one GitHub repository is required.`);let t=e[0],n=/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)$/u.exec(t);if(!n)throw Error(`Invalid GitHub repository ${JSON.stringify(t)}.`);return{repository:t,owner:n[1],name:n[2]}}function executablePath(e){return e===`gh`?GITHUB_TOOLING_PATHS.ghReal:e===`gh-signed-commit`?GITHUB_TOOLING_PATHS.trustedSignedCommit:`git`}function resolveWorkingDirectory(e,t){let n=posix.resolve(`/`,e.resolvePath(``)),r=posix.resolve(`/`,e.resolvePath(t?.trim()||``));if(r!==n&&!r.startsWith(`${n}/`))throw Error(`GitHub command workingDirectory must stay inside the sandbox workspace.`);return r}function sanitizeOutput(e,t,n){let r=e.replaceAll(t,`[redacted]`).replaceAll(n,`[redacted]`);return Buffer.byteLength(r)<=MAX_OUTPUT_BYTES?{value:r,truncated:!1}:{value:`[output truncated: showing final ${MAX_OUTPUT_BYTES} bytes]\n${Buffer.from(r).subarray(-1e5).toString()}`,truncated:!0}}function unsupportedSyntax(){return Error(`GitHub commands support argv syntax only, not pipes, redirects, substitutions, or shell operators.`)}export{executeGitHubShell,githubShellApproval,parseCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readGatewayRouting}from"#shared/gateway-routing.js";function withoutInstrumentationContent(e){return withInstrumentationDecision(e,{action:`record`,recordInputs:!1,recordOutputs:!1})}function withInstrumentationDecision(e,t){switch(e.type){case`session.started`:return t.recordInputs?e:Object.freeze({...e,title:void 0});case`call.requested`:return t.recordInputs?e:Object.freeze({...e,input:void 0,capability:Object.freeze({...e.capability,label:void 0})});case`delivery.consumed`:case`model.call.started`:return t.recordInputs?e:Object.freeze({...e,input:void 0});case`interaction.opened`:return t.recordOutputs?e:Object.freeze({...e,request:void 0});case`interaction.settled`:return Object.freeze({...e,error:t.recordOutputs?e.error:void 0,answer:t.recordInputs?e.answer:void 0});case`call.settled`:return t.recordOutputs?e:Object.freeze({...e,error:void 0,output:void 0});case`model.call.settled`:return e.outcome===`failed`?t.recordOutputs?e:Object.freeze({...e,error:void 0}):t.recordOutputs?e:Object.freeze({...e,content:void 0,providerMetadata:e.providerMetadata===void 0?void 0:structuralProviderMetadata(e.providerMetadata)});case`memory.operation.settled`:return e.outcome===`failed`?t.recordOutputs?e:Object.freeze({...e,error:void 0}):t.recordInputs?e:Object.freeze({...e,outputRecords:void 0});case`model.retried`:case`model.settled`:case`session.ended`:case`turn.settled`:return t.recordOutputs?e:Object.freeze({...e,error:void 0});default:return e}}function structuralProviderMetadata(e){let t=e.gateway;if(typeof t!=`object`||!t||Array.isArray(t))return Object.freeze({});let n=t,r={};for(let e of[`cost`,`generationId`]){let t=n[e];(typeof t==`string`||typeof t==`number`)&&(r[e]=t)}let i=readGatewayRouting(n.routing);return i!==void 0&&(r.routing=i),Object.freeze(Object.keys(r).length===0?{}:{gateway:Object.freeze(r)})}export{structuralProviderMetadata,withInstrumentationDecision,withoutInstrumentationContent};
|
|
1
|
+
import{applyPrincipalTraceDecision}from"#instrumentation/principal-summary.js";import{readGatewayRouting}from"#shared/gateway-routing.js";function withoutInstrumentationContent(e){return withInstrumentationDecision(e,{action:`record`,recordInputs:!1,recordOutputs:!1})}function withInstrumentationDecision(e,t){switch(e.type){case`session.started`:return t.recordInputs?e:Object.freeze({...e,title:void 0});case`call.requested`:return t.recordInputs?e:Object.freeze({...e,input:void 0,capability:Object.freeze({...e.capability,label:void 0})});case`delivery.consumed`:case`model.call.started`:return t.recordInputs?e:Object.freeze({...e,input:void 0});case`interaction.opened`:return t.recordOutputs?e:Object.freeze({...e,request:void 0});case`interaction.settled`:return Object.freeze({...e,error:t.recordOutputs?e.error:void 0,answer:t.recordInputs?e.answer:void 0,responder:applyPrincipalTraceDecision(e.responder,t)});case`call.settled`:return t.recordOutputs?e:Object.freeze({...e,error:void 0,output:void 0});case`model.call.settled`:return e.outcome===`failed`?t.recordOutputs?e:Object.freeze({...e,error:void 0}):t.recordOutputs?e:Object.freeze({...e,content:void 0,providerMetadata:e.providerMetadata===void 0?void 0:structuralProviderMetadata(e.providerMetadata)});case`memory.operation.settled`:return e.outcome===`failed`?t.recordOutputs?e:Object.freeze({...e,error:void 0}):t.recordInputs?e:Object.freeze({...e,outputRecords:void 0});case`model.retried`:case`model.settled`:case`session.ended`:case`turn.settled`:return t.recordOutputs?e:Object.freeze({...e,error:void 0});default:return e}}function structuralProviderMetadata(e){let t=e.gateway;if(typeof t!=`object`||!t||Array.isArray(t))return Object.freeze({});let n=t,r={};for(let e of[`cost`,`generationId`]){let t=n[e];(typeof t==`string`||typeof t==`number`)&&(r[e]=t)}let i=readGatewayRouting(n.routing);return i!==void 0&&(r.routing=i),Object.freeze(Object.keys(r).length===0?{}:{gateway:Object.freeze(r)})}export{structuralProviderMetadata,withInstrumentationDecision,withoutInstrumentationContent};
|
|
@@ -169,6 +169,11 @@ export interface InstrumentationInteractionSettledEvent {
|
|
|
169
169
|
readonly outcome: InstrumentationInteractionOutcome;
|
|
170
170
|
/** Content. Absent unless this provider's trace policy records this direction. */
|
|
171
171
|
readonly answer?: InstrumentationAnswer;
|
|
172
|
+
/**
|
|
173
|
+
* Who decided the request, as their response's delivery was admitted. Absent when no response
|
|
174
|
+
* decided it. Its `id` is absent unless this provider's trace policy records both directions.
|
|
175
|
+
*/
|
|
176
|
+
readonly responder?: InstrumentationPrincipalSummary;
|
|
172
177
|
readonly scope: InstrumentationScope;
|
|
173
178
|
}
|
|
174
179
|
/** Runtime action call IDs are durable and unique within one session. */
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { DeliverHookPayload } from "#channel/types.js";
|
|
2
2
|
import type { InstrumentationScope, InstrumentationHooks, InstrumentationParentLineage, InstrumentationTraceContext } from "#instrumentation/lifecycle.js";
|
|
3
3
|
import type { HandleEventFn } from "#harness/types.js";
|
|
4
|
-
import type
|
|
4
|
+
import { type ChannelAudience } from "#shared/channel-audience.js";
|
|
5
|
+
import type { ConversationEnvironment } from "#shared/conversation-context.js";
|
|
5
6
|
export interface CreateInstrumentationHandleEventInput {
|
|
6
7
|
readonly deliveryInput?: DeliverHookPayload;
|
|
7
8
|
readonly isFrameworkTool?: (name: string) => boolean;
|
|
@@ -10,6 +11,8 @@ export interface CreateInstrumentationHandleEventInput {
|
|
|
10
11
|
readonly agentName?: string;
|
|
11
12
|
readonly channelKind?: string;
|
|
12
13
|
readonly channelAudience?: ChannelAudience;
|
|
14
|
+
/** With `channelAudience`, whether principal ids may be recorded; absent counts as production. */
|
|
15
|
+
readonly environment?: ConversationEnvironment;
|
|
13
16
|
readonly handleEvent?: HandleEventFn;
|
|
14
17
|
readonly hooks?: InstrumentationHooks;
|
|
15
18
|
readonly parentLineage?: InstrumentationParentLineage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isTerminalType}from"#protocol/session-events/catalog.js";import{copyView,foldReceivedEvent}from"#protocol/session-projection/fold.js";import{askedCall,decidingAnswer}from"#protocol/session-projection/reader.js";import{callRun,runTurn}from"#protocol/session-projection/selectors.js";import{contextStorage}from"#context/container.js";import{currentView,enteredView}from"#harness/session-machine/current.js";import{cascade}from"#harness/session-machine/cascade.js";import{eventsOf}from"#harness/publication.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{actionIdempotencyKey,attemptIdempotencyKey,inputIdempotencyKey,sessionIdempotencyKey,turnIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentationScope}from"#instrumentation/scope.js";import{deliveryEvent}from"#instrumentation/channel-delivery.js";function attemptScopeOf(e,{runId:t,attempt:n,stepIndex:r,turnId:i}){return instrumentationScope({runId:t,attempt:n,channelAudience:e.channelAudience,functionId:e.functionId,rootSessionId:e.rootSessionId,sessionId:e.sessionId,traceSessionId:e.traceSessionId,turnId:i},r)}function createInstrumentationHandleEvent(e){if(e.hooks===void 0)return e.handleEvent;if(e.handleEvent===void 0)return;let{handleEvent:t,hooks:n}=e;return async(r,i)=>{let a=Date.now(),o=contextStorage.getStore(),s=o===void 0?void 0:enteredView(o),c;try{await t(r,i)}catch(e){if(!isTurnCancellation(e)||s===void 0||o===void 0||currentView(o).position<=s.position)throw e;c={error:e}}let l=eventsOf(r),u=s!==void 0&&l.some(e=>isTerminalType(e.type))?cascade(s,l):l,d=s===void 0?void 0:copyView(s);if(d!==void 0)for(let e of u)foldReceivedEvent(d,{...e,meta:{endOfLine:!1}});let f=
|
|
1
|
+
import{isTerminalType}from"#protocol/session-events/catalog.js";import{copyView,foldReceivedEvent}from"#protocol/session-projection/fold.js";import{askedCall,decidingAnswer,responderOf}from"#protocol/session-projection/reader.js";import{callRun,runTurn}from"#protocol/session-projection/selectors.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{currentView,enteredView}from"#harness/session-machine/current.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{cascade}from"#harness/session-machine/cascade.js";import{eventsOf}from"#harness/publication.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{actionIdempotencyKey,attemptIdempotencyKey,inputIdempotencyKey,sessionIdempotencyKey,turnIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentationPrincipal}from"#instrumentation/principal-summary.js";import{instrumentationScope}from"#instrumentation/scope.js";import{deliveryEvent}from"#instrumentation/channel-delivery.js";function attemptScopeOf(e,{runId:t,attempt:n,stepIndex:r,turnId:i}){return instrumentationScope({runId:t,attempt:n,channelAudience:e.channelAudience,functionId:e.functionId,rootSessionId:e.rootSessionId,sessionId:e.sessionId,traceSessionId:e.traceSessionId,turnId:i},r)}function createInstrumentationHandleEvent(e){if(e.hooks===void 0)return e.handleEvent;if(e.handleEvent===void 0)return;let{handleEvent:t,hooks:n}=e;return async(r,i)=>{let a=Date.now(),o=contextStorage.getStore(),s=o===void 0?void 0:enteredView(o),c;try{await t(r,i)}catch(e){if(!isTurnCancellation(e)||s===void 0||o===void 0||currentView(o).position<=s.position)throw e;c={error:e}}let l=eventsOf(r),u=s!==void 0&&l.some(e=>isTerminalType(e.type))?cascade(s,l):l,d=s===void 0?void 0:copyView(s);if(d!==void 0)for(let e of u)foldReceivedEvent(d,{...e,meta:{endOfLine:!1}});let f=n.capturesInputs??n.capturesContent??!1,p=n.capturesOutputs??n.capturesContent??!1,m={attemptScope:t=>attemptScopeOf(e,t),capturesInputs:f,capturesOutputs:p,capturesPrincipalIds:f&&p&&shouldCaptureInstrumentationContent({audience:normalizeChannelAudience(e.channelAudience),environment:e.environment??`production`}),settledAtMs:o?.get(RuntimeActionSettlementTimesKey),startedAtMs:a,view:d??(o===void 0?void 0:currentView(o))};for(let t of u){let r=deliveryEvent(t,o,e);r!==void 0&&await n.publish(Object.freeze(r));for(let r of instrumentationEventsOf(t,m,e))await n.publish(Object.freeze(r))}if(c!==void 0)throw c.error}}function instrumentationEventsOf(e,t,n){let{sessionId:r}=n,i=sessionIdempotencyKey(r);switch(e.type){case`session.started`:return[{agentName:n.agentName,channelAudience:n.channelAudience,channelKind:n.channelKind,idempotencyKey:i,parentLineage:n.parentLineage,parentTraceContext:n.parentTraceContext,rootSessionId:n.rootSessionId??r,traceSessionId:n.traceSessionId,scheduleId:n.scheduleId,sessionId:r,title:n.title,type:`session.started`}];case`session.ended`:{let{cause:n}=e.data,a=n!==void 0&&`turnId`in n?n.turnId:latestTurnId(t.view),{outcome:o}=e.data;return[{error:o===`failed`?Error(e.data.error?.message??`The session failed.`):void 0,idempotencyKey:i,outcome:o,sessionId:r,turnId:a,type:`session.ended`}]}case`turn.started`:return[{idempotencyKey:turnIdempotencyKey(r,e.data.turnId),parentLineage:n.parentLineage,parentTraceContext:n.parentTraceContext,rootSessionId:n.rootSessionId??r,traceSessionId:n.traceSessionId,sequence:turnSequence(e.data.turnId),sessionId:r,turnId:e.data.turnId,type:`turn.started`}];case`turn.settled`:{let{outcome:t,turnId:n}=e.data;return[{error:t===`failed`?Error(e.data.error?.message??`The turn failed.`):void 0,idempotencyKey:turnIdempotencyKey(r,n),outcome:t,sessionId:r,turnId:n,type:`turn.settled`}]}case`model.retried`:{let n=runAttempt(t,e.data.runId);return n===void 0?[]:[{error:Error(e.data.error.message),idempotencyKey:attemptIdempotencyKey(n),scope:n,type:`model.retried`}]}case`model.settled`:{let n=runAttempt(t,e.data.runId);if(n===void 0)return[];let{error:r,outcome:i}=e.data,a=attemptIdempotencyKey(n),o=i===`interrupted`&&n.turnId!==void 0&&t.view?.turns[n.turnId]?.outcome===`cancelled`;return[{error:r===void 0?void 0:Error(r.message),idempotencyKey:a,scope:n,outcome:o?`cancelled`:i,type:`model.settled`}]}case`call.requested`:{let i=t.view?.calls[e.data.callId],a=i===void 0?void 0:runAttempt(t,callRun(t.view,i));if(a===void 0)return[];let{callId:o,capability:s}=e.data,c=s.name;return[{callId:o,frameworkTool:s.kind===`skill`||n.isFrameworkTool?.(c)===!0,idempotencyKey:actionIdempotencyKey(r,a.turnId,o),input:t.capturesInputs?e.data.input:void 0,capability:s,scope:a,startedAtMs:t.startedAtMs,toolName:c,type:`call.requested`}]}case`call.settled`:{let{callId:n,outcome:i}=e.data,a=t.view?.calls[n],o=a===void 0?void 0:runAttempt(t,callRun(t.view,a));if(o===void 0)return[];let s=actionIdempotencyKey(r,o.turnId,n),c=i===`completed`?e.data.output:void 0,l=i===`completed`?void 0:e.data.error===void 0?e.data.output:Object.assign(Error(e.data.error.message),{code:e.data.error.code,name:e.data.error.name??`Error`});return[{acceptedAtMs:t.settledAtMs?.[n],cause:e.data.cause,error:t.capturesOutputs?l:void 0,errorCode:e.data.error?.code,idempotencyKey:s,outcome:i,reason:e.data.reason,output:t.capturesOutputs?c:void 0,scope:o,type:`call.settled`,usage:a?.usage}]}case`interaction.opened`:{let n=t.view?.interactions[e.data.interactionId],i=n===void 0?void 0:interactionAttempt(t,n);if(n===void 0||i===void 0)return[];let{request:a}=n,o=askedCall(t.view,n);return[{call:o===void 0?void 0:{callId:o.callId,name:o.name},idempotencyKey:inputIdempotencyKey(r,i.turnId,n.interactionId),interactionId:n.interactionId,kind:a.kind,request:t.capturesOutputs?{allowFreeform:a.allowFreeform,display:a.display,options:a.options,prompt:a.prompt,title:a.title}:void 0,scope:i,type:`interaction.opened`}]}case`interaction.settled`:{let n=t.view?.interactions[e.data.interactionId],i=n===void 0?void 0:interactionAttempt(t,n);if(n===void 0||i===void 0)return[];let a=decidingAnswer(n);return[{answer:!t.capturesInputs||a===void 0?void 0:{optionId:a.optionId,text:a.text},idempotencyKey:inputIdempotencyKey(r,i.turnId,n.interactionId),interactionId:n.interactionId,kind:n.request.kind,outcome:e.data.outcome,responder:responderSummary(t.view,e.data.cause,t.capturesPrincipalIds),scope:i,type:`interaction.settled`}]}default:return[]}}function responderSummary(e,t,n){if(t===void 0||!(`responseId`in t))return;let r=responderOf(e,t.responseId);return r===void 0?void 0:instrumentationPrincipal(r.type,n?r.id:void 0)}function runAttempt(e,t){let n=t===void 0?void 0:e.view?.runs[t];if(n?.attempt===void 0)return;let r=runTurn(e.view,n.runId);return e.attemptScope({runId:n.runId,attempt:n.attempt,stepIndex:n.step,turnId:r})}function interactionAttempt(e,t){let n=e.view;if(t.request.kind===`sign-in`)return;let{subject:r}=t;if(`callId`in r){let t=n.calls[r.callId];return t===void 0?void 0:runAttempt(e,callRun(n,t))}if(`taskId`in r){let t=n.tasks[r.taskId],i=t===void 0?void 0:n.calls[t.startedBy.callId];return i===void 0?void 0:runAttempt(e,callRun(n,i))}return`turnId`in r?runAttempt(e,Object.values(n.runs).filter(e=>e.attempt!==void 0&&runTurn(n,e.runId)===r.turnId).at(-1)?.runId):void 0}function latestTurnId(e){return(e===void 0?[]:Object.keys(e.turns)).at(-1)}function turnSequence(e){let t=/^turn_(\d+)$/.exec(e);return t===null?0:Number(t[1])}export{attemptScopeOf,createInstrumentationHandleEvent};
|
|
@@ -4,6 +4,8 @@ import { type InstrumentationPrincipalSummary } from "#instrumentation/lifecycle
|
|
|
4
4
|
import { type InstrumentationContentContext } from "#shared/instrumentation-content.js";
|
|
5
5
|
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
|
|
6
6
|
export declare function summarizeInstrumentationPrincipal(principal: SessionAuthContext | null | undefined, content: InstrumentationContentContext): InstrumentationPrincipalSummary | undefined;
|
|
7
|
+
/** A principal as instrumentation records it: a known type, plus its id when given and bounded. */
|
|
8
|
+
export declare function instrumentationPrincipal(principalType: string, principalId: string | undefined): InstrumentationPrincipalSummary;
|
|
7
9
|
export declare function applyPrincipalTraceDecision(principal: InstrumentationPrincipalSummary | undefined, decision: InstrumentationDecision | undefined): InstrumentationPrincipalSummary | undefined;
|
|
8
10
|
export declare function readInstrumentationPrincipals(context: ContextReader, content: InstrumentationContentContext, decision?: InstrumentationDecision): {
|
|
9
11
|
readonly currentPrincipal?: InstrumentationPrincipalSummary;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AuthKey,InitiatorAuthKey}from"#context/keys.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{resolveTracePolicyDecision}from"#shared/trace-policy.js";import{isInstrumentationPrincipalType}from"#instrumentation/lifecycle.js";import{boundedPrincipalId}from"#compiled/@vercel/agent-runs/otel.js";function summarizeInstrumentationPrincipal(e,t){if(e
|
|
1
|
+
import{AuthKey,InitiatorAuthKey}from"#context/keys.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{resolveTracePolicyDecision}from"#shared/trace-policy.js";import{isInstrumentationPrincipalType}from"#instrumentation/lifecycle.js";import{boundedPrincipalId}from"#compiled/@vercel/agent-runs/otel.js";function summarizeInstrumentationPrincipal(e,t){if(e!==void 0)return e===null?{type:`none`}:instrumentationPrincipal(e.principalType,shouldCaptureInstrumentationContent(t)?e.principalId:void 0)}function instrumentationPrincipal(e,t){let n=isInstrumentationPrincipalType(e)&&e!==`none`?e:`other`,r=boundedPrincipalId(t);return r===void 0?{type:n}:{id:r,type:n}}function applyPrincipalTraceDecision(e,t){if(e!==void 0)return e.type!==`none`&&t?.action===`record`&&t.recordInputs&&t.recordOutputs?e:{type:e.type}}function readInstrumentationPrincipals(e,t,n=resolveTracePolicyDecision(!0,t)){return{currentPrincipal:applyPrincipalTraceDecision(summarizeInstrumentationPrincipal(e.get(AuthKey),t),n),initiatorPrincipal:applyPrincipalTraceDecision(summarizeInstrumentationPrincipal(e.get(InitiatorAuthKey),t),n)}}export{applyPrincipalTraceDecision,instrumentationPrincipal,readInstrumentationPrincipals,summarizeInstrumentationPrincipal};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ensureAiSdkWarningLogger}from"#instrumentation/ai-sdk-warnings.js";import{recordErrorOnSpan}from"#internal/logging.js";import{applyLiveDeliveryAudienceCeiling}from"#shared/forwarded-trace-policy.js";import{contextStorage}from"#context/container.js";import{ConversationIdKey,ParentSessionKey}from"#context/keys.js";import{readConversationId}from"#shared/conversation-identity.js";import{readSessionTraceDecision}from"#tracing/eve/agent-trace-context-store.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#shared/trace-policy.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{withCapture}from"#compiled/@vercel/agent-runs/otel.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{attemptScopeOf,createInstrumentationHandleEvent}from"#instrumentation/native-events.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import"#compiled/@vercel/agent-runs/index.js";import{createMemoryInstrumentation}from"#instrumentation/memory.js";import{readInstrumentationSessionContext}from"#instrumentation/session-context.js";import{readInstrumentationDecision}from"#shared/instrumentation-decision.js";import{getInstrumentationRuntime,registerInstrumentationRuntime}from"#instrumentation/runtime-global.js";import{initializeSessionInstrumentation}from"#instrumentation/session-init.js";import{createGatewayTraceContextHeaders}from"#tracing/eve/gateway.js";const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function bindInstrumentationRuntime(e,t,n){let r={...n,traceSessionId:resolveTraceRootSessionId(t,n.sessionId)};if(readConversationId(t.get(ConversationIdKey))===void 0&&t.set(ConversationIdKey,t.get(ParentSessionKey)?.rootSessionId??r.rootSessionId),e===void 0)return;let i,a=e.hooks,o=r.traceSessionId,readSessionContext=()=>{let e=readInstrumentationSessionContext(contextStorage.getStore()??t);return{...e,rootSessionId:e.parent?.rootSessionId??r.rootSessionId,traceSessionId:o}},bindHooks=e=>a.forTrace?.({agentName:r.agentName,...e.conversation})??a,captureExecutionRuntime=()=>{let t=e.otelSettings,n=e.ownsAgentSpans===!0;return t!==void 0&&!n&&ensureOtelIntegration(),{ownsAgentSpans:n,otelSettings:t,runtimeContextResolvers:e.runtimeContextResolvers,tracer:t===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(t,n)=>prepareTurnTraceContext({...t,instrumentation:e,principals:n.principals,session:{agentName:r.agentName,channelAudience:n.conversation.audience,channelKind:n.conversation.channel.kind,channelType:n.instrumentation?.channelType,parentLineage:n.parentLineage,parentTraceContext:n.parentTraceContext,rootSessionId:n.rootSessionId,traceSessionId:n.traceSessionId,scheduleId:n.scheduleId,sessionId:r.sessionId,title:n.title,traceSeed:n.traceSeed}}),s=e.memoryOperations===!0?createMemoryInstrumentation({resolveContext:()=>{let e=readSessionContext();return{hooks:bindHooks(e),rootSessionId:e.rootSessionId,traceSessionId:e.traceSessionId}},runInContext:e.runInContext,sessionId:r.sessionId}):void 0;return{prepareDelivery:e=>{i=e},createHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:r.agentName,channelAudience:t.conversation.audience,channelKind:t.conversation.channel.kind,functionId:captureExecutionRuntime().otelSettings?.functionId??r.agentName,handleEvent:e.handleEvent,deliveryInput:i,hooks:bindHooks(t),rootSessionId:t.rootSessionId,traceSessionId:t.traceSessionId,parentLineage:t.parentLineage,parentTraceContext:t.parentTraceContext,scheduleId:t.scheduleId,sessionId:r.sessionId,title:t.title})},flush:e.forceFlush,memory:s,prepareExecution:()=>{let t=captureExecutionRuntime();return{installAiSdkWarningLogger:ensureAiSdkWarningLogger,runStep:async(n,a)=>{let o=readSessionContext(),s=bindHooks(o),c=t.otelSettings,l=resolveStepInstrumentationDecision(c,r.agentName,o.conversation,o.traceSeed,readSessionTraceDecision(o.context,r.sessionId)),u=t.tracer,d={"eve.environment":n.environment,"eve.session.id":n.session.sessionId,"eve.version":n.eveVersion},f=c?.functionId??r.agentName;f&&(d[`ai.telemetry.functionId`]=f);let p=u!==void 0&&!t.ownsAgentSpans&&l?.action!==`drop`&&n.hasInput?u.startSpan(`ai.eve.turn`,{attributes:d}):void 0,m=p?.spanContext(),h=m===void 0?n.session:{...n.session,state:{...n.session.state,[TURN_TRACE_STATE_KEY]:{spanId:m.spanId,traceFlags:m.traceFlags,traceId:m.traceId}}},g=p===void 0?void 0:trace.setSpan(context.active(),p);if(g===void 0&&u!==void 0){let e=n.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(g=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let _=readSessionContext(),v=snapshotInstrumentationRuntimeContext(_.context),y=_.conversation,b=y.audience,x=shouldCaptureInstrumentationContent(y),S=l===void 0?l:applyLiveDeliveryAudienceCeiling(l,b,_.forwardedTracePolicy,y.environment),C=S===void 0?x:S.action===`record`&&S.recordInputs,w=l?.action===`drop`,T={recordInputs:!w&&(S?.action===`record`?S.recordInputs:x)&&(c?.recordInputs??!1),recordOutputs:!w&&(S?.action===`record`?S.recordOutputs:x)&&(c?.recordOutputs??!1)},telemetry=e=>{if(c===void 0&&e.bridgeIntegration===void 0)return;let n={};for(let t of Object.keys(e.runtimeContext??{}))n[t]=!0;let i=c!==void 0&&!(T.recordInputs&&T.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({...t.ownsAgentSpans?{excludeEveOtelIntegration:!0}:void 0,sanitizeEveOtelErrors:i});return{functionId:c?.functionId??r.agentName,includeRuntimeContext:n,integrations:e.bridgeIntegration===void 0?i?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:T.recordInputs,recordOutputs:T.recordOutputs}},E={channelAudience:b,functionId:c?.functionId??r.agentName,rootSessionId:_.rootSessionId,sessionId:r.sessionId,traceSessionId:_.traceSessionId},run=()=>a({gatewayTraceContextHeaders:createGatewayTraceContextHeaders,createHandleEvent:e=>createInstrumentationHandleEvent({...e,...E,deliveryInput:i,agentName:r.agentName,channelKind:y.channel.kind,hooks:s,parentLineage:_.parentLineage,parentTraceContext:_.parentTraceContext,scheduleId:_.scheduleId,title:_.title}),prepareAttempt:t=>{let n=attemptScopeOf(E,t),r=createAiSdkHookBridge(n,s,e.runInContext,t.runtimeContext,t.isFrameworkTool);return{scope:n,telemetry:telemetry({bridgeIntegration:r,runtimeContext:t.runtimeContext})}},preparePreamble:e=>preparePreamble(e,_),recordError:e=>{p!==void 0&&recordErrorOnSpan(p,e)},resolveRuntimeContext:e=>buildTelemetryRuntimeContext({...e,capturesContent:C,context:v,providerResolvers:t.runtimeContextResolvers}),session:h,setTurnId:e=>p?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:m===void 0||!isValidSpanContext(m)?void 0:{spanId:m.spanId,traceFlags:m.traceFlags,traceId:m.traceId}});try{return await context.with(withCapture(g??context.active(),{emit:!0,recordInputs:T.recordInputs,recordOutputs:T.recordOutputs}),run)}finally{p?.end(),p=void 0}}}},preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){let t={agentName:e.agentName,rootSessionId:e.rootSessionId,traceSessionId:resolveTraceRootSessionId(e.ctx,e.sessionId),sessionId:e.sessionId};return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,t)}function resolveStepInstrumentationDecision(e,t,n,r,i){if(e!==void 0)return r?.decision===void 0?i===void 0?r===void 0?resolveTracePolicy(e.tracePolicy,{agentName:t,...n}):resolveTracePolicyDecision(isSampledTrace(r),n):i:readInstrumentationDecision(r.decision)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
|
|
1
|
+
import{ensureAiSdkWarningLogger}from"#instrumentation/ai-sdk-warnings.js";import{recordErrorOnSpan}from"#internal/logging.js";import{applyLiveDeliveryAudienceCeiling}from"#shared/forwarded-trace-policy.js";import{contextStorage}from"#context/container.js";import{ConversationIdKey,ParentSessionKey}from"#context/keys.js";import{readConversationId}from"#shared/conversation-identity.js";import{readSessionTraceDecision}from"#tracing/eve/agent-trace-context-store.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#shared/trace-policy.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{withCapture}from"#compiled/@vercel/agent-runs/otel.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{attemptScopeOf,createInstrumentationHandleEvent}from"#instrumentation/native-events.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import"#compiled/@vercel/agent-runs/index.js";import{createMemoryInstrumentation}from"#instrumentation/memory.js";import{readInstrumentationSessionContext}from"#instrumentation/session-context.js";import{readInstrumentationDecision}from"#shared/instrumentation-decision.js";import{getInstrumentationRuntime,registerInstrumentationRuntime}from"#instrumentation/runtime-global.js";import{initializeSessionInstrumentation}from"#instrumentation/session-init.js";import{createGatewayTraceContextHeaders}from"#tracing/eve/gateway.js";const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function bindInstrumentationRuntime(e,t,n){let r={...n,traceSessionId:resolveTraceRootSessionId(t,n.sessionId)};if(readConversationId(t.get(ConversationIdKey))===void 0&&t.set(ConversationIdKey,t.get(ParentSessionKey)?.rootSessionId??r.rootSessionId),e===void 0)return;let i,a=e.hooks,o=r.traceSessionId,readSessionContext=()=>{let e=readInstrumentationSessionContext(contextStorage.getStore()??t);return{...e,rootSessionId:e.parent?.rootSessionId??r.rootSessionId,traceSessionId:o}},bindHooks=e=>a.forTrace?.({agentName:r.agentName,...e.conversation})??a,captureExecutionRuntime=()=>{let t=e.otelSettings,n=e.ownsAgentSpans===!0;return t!==void 0&&!n&&ensureOtelIntegration(),{ownsAgentSpans:n,otelSettings:t,runtimeContextResolvers:e.runtimeContextResolvers,tracer:t===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(t,n)=>prepareTurnTraceContext({...t,instrumentation:e,principals:n.principals,session:{agentName:r.agentName,channelAudience:n.conversation.audience,channelKind:n.conversation.channel.kind,channelType:n.instrumentation?.channelType,parentLineage:n.parentLineage,parentTraceContext:n.parentTraceContext,rootSessionId:n.rootSessionId,traceSessionId:n.traceSessionId,scheduleId:n.scheduleId,sessionId:r.sessionId,title:n.title,traceSeed:n.traceSeed}}),s=e.memoryOperations===!0?createMemoryInstrumentation({resolveContext:()=>{let e=readSessionContext();return{hooks:bindHooks(e),rootSessionId:e.rootSessionId,traceSessionId:e.traceSessionId}},runInContext:e.runInContext,sessionId:r.sessionId}):void 0;return{prepareDelivery:e=>{i=e},createHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:r.agentName,channelAudience:t.conversation.audience,channelKind:t.conversation.channel.kind,environment:t.conversation.environment,functionId:captureExecutionRuntime().otelSettings?.functionId??r.agentName,handleEvent:e.handleEvent,deliveryInput:i,hooks:bindHooks(t),rootSessionId:t.rootSessionId,traceSessionId:t.traceSessionId,parentLineage:t.parentLineage,parentTraceContext:t.parentTraceContext,scheduleId:t.scheduleId,sessionId:r.sessionId,title:t.title})},flush:e.forceFlush,memory:s,prepareExecution:()=>{let t=captureExecutionRuntime();return{installAiSdkWarningLogger:ensureAiSdkWarningLogger,runStep:async(n,a)=>{let o=readSessionContext(),s=bindHooks(o),c=t.otelSettings,l=resolveStepInstrumentationDecision(c,r.agentName,o.conversation,o.traceSeed,readSessionTraceDecision(o.context,r.sessionId)),u=t.tracer,d={"eve.environment":n.environment,"eve.session.id":n.session.sessionId,"eve.version":n.eveVersion},f=c?.functionId??r.agentName;f&&(d[`ai.telemetry.functionId`]=f);let p=u!==void 0&&!t.ownsAgentSpans&&l?.action!==`drop`&&n.hasInput?u.startSpan(`ai.eve.turn`,{attributes:d}):void 0,m=p?.spanContext(),h=m===void 0?n.session:{...n.session,state:{...n.session.state,[TURN_TRACE_STATE_KEY]:{spanId:m.spanId,traceFlags:m.traceFlags,traceId:m.traceId}}},g=p===void 0?void 0:trace.setSpan(context.active(),p);if(g===void 0&&u!==void 0){let e=n.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(g=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let _=readSessionContext(),v=snapshotInstrumentationRuntimeContext(_.context),y=_.conversation,b=y.audience,x=shouldCaptureInstrumentationContent(y),S=l===void 0?l:applyLiveDeliveryAudienceCeiling(l,b,_.forwardedTracePolicy,y.environment),C=S===void 0?x:S.action===`record`&&S.recordInputs,w=l?.action===`drop`,T={recordInputs:!w&&(S?.action===`record`?S.recordInputs:x)&&(c?.recordInputs??!1),recordOutputs:!w&&(S?.action===`record`?S.recordOutputs:x)&&(c?.recordOutputs??!1)},telemetry=e=>{if(c===void 0&&e.bridgeIntegration===void 0)return;let n={};for(let t of Object.keys(e.runtimeContext??{}))n[t]=!0;let i=c!==void 0&&!(T.recordInputs&&T.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({...t.ownsAgentSpans?{excludeEveOtelIntegration:!0}:void 0,sanitizeEveOtelErrors:i});return{functionId:c?.functionId??r.agentName,includeRuntimeContext:n,integrations:e.bridgeIntegration===void 0?i?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:T.recordInputs,recordOutputs:T.recordOutputs}},E={channelAudience:b,functionId:c?.functionId??r.agentName,rootSessionId:_.rootSessionId,sessionId:r.sessionId,traceSessionId:_.traceSessionId},run=()=>a({gatewayTraceContextHeaders:createGatewayTraceContextHeaders,createHandleEvent:e=>createInstrumentationHandleEvent({...e,...E,deliveryInput:i,agentName:r.agentName,channelKind:y.channel.kind,environment:y.environment,hooks:s,parentLineage:_.parentLineage,parentTraceContext:_.parentTraceContext,scheduleId:_.scheduleId,title:_.title}),prepareAttempt:t=>{let n=attemptScopeOf(E,t),r=createAiSdkHookBridge(n,s,e.runInContext,t.runtimeContext,t.isFrameworkTool);return{scope:n,telemetry:telemetry({bridgeIntegration:r,runtimeContext:t.runtimeContext})}},preparePreamble:e=>preparePreamble(e,_),recordError:e=>{p!==void 0&&recordErrorOnSpan(p,e)},resolveRuntimeContext:e=>buildTelemetryRuntimeContext({...e,capturesContent:C,context:v,providerResolvers:t.runtimeContextResolvers}),session:h,setTurnId:e=>p?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:m===void 0||!isValidSpanContext(m)?void 0:{spanId:m.spanId,traceFlags:m.traceFlags,traceId:m.traceId}});try{return await context.with(withCapture(g??context.active(),{emit:!0,recordInputs:T.recordInputs,recordOutputs:T.recordOutputs}),run)}finally{p?.end(),p=void 0}}}},preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){let t={agentName:e.agentName,rootSessionId:e.rootSessionId,traceSessionId:resolveTraceRootSessionId(e.ctx,e.sessionId),sessionId:e.sessionId};return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,t)}function resolveStepInstrumentationDecision(e,t,n,r,i){if(e!==void 0)return r?.decision===void 0?i===void 0?r===void 0?resolveTracePolicy(e.tracePolicy,{agentName:t,...n}):resolveTracePolicyDecision(isSampledTrace(r),n):i:readInstrumentationDecision(r.decision)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveInstrumentationEnvironment}from"#internal/application/dev-environment.js";import{ConversationContextKey,resolveConversationContext}from"#shared/conversation-context.js";import{readForwardedTraceAssertion,resolveForwardedTraceSeed}from"#shared/forwarded-trace-policy.js";import{AuthKey,ChannelInstrumentationKey,ParentSessionKey,ParentTraceContextKey,ScheduleIdKey,SessionCallbackKey,SessionTitleKey,SessionTraceSeedKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{
|
|
1
|
+
import{resolveInstrumentationEnvironment}from"#internal/application/dev-environment.js";import{ConversationContextKey,resolveConversationContext}from"#shared/conversation-context.js";import{readForwardedTraceAssertion,resolveForwardedTraceSeed}from"#shared/forwarded-trace-policy.js";import{AuthKey,ChannelInstrumentationKey,ParentSessionKey,ParentTraceContextKey,ScheduleIdKey,SessionCallbackKey,SessionTitleKey,SessionTraceSeedKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{readInstrumentationPrincipals}from"#instrumentation/principal-summary.js";import{resolveParentLineage}from"#instrumentation/parent-lineage.js";function readInstrumentationSessionContext(e){let t=e.get(SessionTraceSeedKey),n=resolveForwardedTraceSeed(t),r=t===void 0||n===void 0?void 0:{...t,...n},i=e.get(ParentSessionKey),a=e.get(ChannelKey),o=e.get(ChannelInstrumentationKey),s=readForwardedTraceAssertion(r?.forwardedTracePolicy),c=resolveConversationContext(e.get(ConversationContextKey),{channelKind:o?.kind,environment:resolveInstrumentationEnvironment(),forwardedTracePolicy:s,principalType:e.get(AuthKey)?.principalType});return{audience:c.audience,channel:a,conversation:c,context:e,forwardedTracePolicy:s,instrumentation:o,parent:i,parentLineage:resolveParentLineage(i,a,e.get(SessionCallbackKey)),parentTraceContext:e.get(ParentTraceContextKey),principals:readInstrumentationPrincipals(e,c,r?.decision),scheduleId:e.get(ScheduleIdKey),title:e.get(SessionTitleKey),traceSeed:r}}export{readInstrumentationSessionContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const STAMPED_PACKAGE_VERSION=`0.
|
|
1
|
+
const STAMPED_PACKAGE_VERSION=`0.88.1`;function readStampedPackageVersion(){return STAMPED_PACKAGE_VERSION.startsWith(`__`)?void 0:STAMPED_PACKAGE_VERSION}export{readStampedPackageVersion};
|
|
@@ -19,6 +19,8 @@ export type AgentInvocation = (AgentInvocationBase & {
|
|
|
19
19
|
readonly status: "working";
|
|
20
20
|
readonly pollAfterMs: number;
|
|
21
21
|
readonly result?: JsonValue;
|
|
22
|
+
/** What the agent is doing right now, such as the label of a running tool call. */
|
|
23
|
+
readonly statusMessage?: string;
|
|
22
24
|
}) | (AgentInvocationBase & {
|
|
23
25
|
readonly status: "awaiting-input";
|
|
24
26
|
readonly interactions: AgentInvocationInteractions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{emptySessionView,foldReceivedEvent}from"#protocol/session-projection/fold.js";import{interaction,openRequests,openSignIns}from"#protocol/session-projection/reader.js";import{failure,interactionBatches,reply,replyText}from"#protocol/session-projection/selectors.js";import{parseAnswers}from"#shared/input.js";import{createEventReader}from"#protocol/session-lines.js";import{isV26Line}from"#protocol/v26-lines.js";import{getWorld}from"#internal/workflow/runtime.js";import{streamSessionLines}from"#execution/session-event-stream.js";import{RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{INVOCATION_OWNER_ATTRIBUTE,INVOCATION_TOKEN_ATTRIBUTE,invocationOwnerKey}from"#internal/invocation/metadata.js";import{interactionJson}from"#protocol/interaction-json.js";var WorkflowAgentInvocationExecution=class{#e;#t;constructor(e){this.#e=e.createSession,this.#t=e.from}async create(e){let t=`invocation:${crypto.randomUUID()}`,n=await this.#e({auth:e.auth,capabilities:{requestInput:!0},continuationToken:t,externalInvocation:{continuationToken:t,ownerKey:invocationOwnerKey(e.auth)},input:{message:e.message}}),r=await this.#r(n.sessionId,e.auth);if(r===void 0)throw Error(`Invocation run was unavailable after durable creation.`);return workingInvocation(n.sessionId,r.createdAt.toISOString(),r.expiredAt?.toISOString())}async read(e){return(await this.#n(e))?.invocation}async update(e){let t=await this.#n(e);if(t===void 0)return{type:`not_found`};let{invocation:n,stream:r,token:i}=t,a=r?.pending;if(n.status!==`awaiting-input`||a===void 0)return r!==void 0&&replaysSettledBatch(r,e.responses)?{invocation:n,type:`success`}:conflict(`Invocation is not waiting for input.`);let o=new Set,s=[];for(let t of e.responses){if(a.get(t.interactionId)===void 0)return conflict(`Unknown input request: ${t.interactionId}`);o.add(t.interactionId),s.push(t)}if(o.size!==e.responses.length||o.size!==a.size)return conflict(`Responses must answer the complete pending input batch exactly once.`);if(i===void 0)return{type:`not_found`};try{await this.#t(i).respond(parseAnswers(s),{auth:e.auth})}catch(e){if(RunExpiredError.is(e))return{type:`not_found`};throw e}return{invocation:workingInvocation(e.invocationId,n.createdAt,n.expiresAt),type:`success`}}async cancel(e){let t=await this.#n(e);if(t!==void 0){if(isTerminal(t.invocation.status))return t.invocation;if(t.token!==void 0){try{await this.#t(t.token).cancel({auth:e.auth})}catch(e){if(WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))return;throw e}return await this.read(e)}}}async#n(e){let t=await this.#r(e.invocationId,e.auth);if(t===void 0)return;let n={createdAt:t.createdAt.toISOString(),expiresAt:t.expiredAt?.toISOString(),invocationId:t.runId};if(t.status===`cancelled`)return{invocation:{...n,sessionEnded:!0,status:`cancelled`}};let r=await readInvocationStream(e.invocationId);return{invocation:projectInvocation(n,t.status,r),stream:r,token:t.attributes[INVOCATION_TOKEN_ATTRIBUTE]}}async#r(e,t){let n=await getWorld();try{let r=await n.runs.get(e);return r.attributes[INVOCATION_TOKEN_ATTRIBUTE]===void 0?void 0:r.attributes[INVOCATION_OWNER_ATTRIBUTE]===invocationOwnerKey(t)?r:void 0}catch(e){if(WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))return;throw e}}};async function readInvocationStream(e){let t=emptySessionView(),n=createEventReader();for await(let{line:r,position:i,record:a}of streamSessionLines(e,{follow:!1})){if(r===void 0){if(i===0&&isV26Line(a))return startedOnEarlierEve(t);continue}for(let e of n.read(r,i))foldReceivedEvent(t,e)}let r=interactionBatches(t).map(e=>new Map(e.flatMap(e=>{let n=interaction(t,e.interactionId);return n===void 0?[]:[[e.interactionId,n]]}))),i=new Set(openRequests(t).map(e=>e.interactionId));return{batches:r,pending:r.map(e=>new Map([...e].filter(([e])=>i.has(e)))).findLast(e=>e.size>0),result:latestResult(t),settled:howItSettled(t),signIns:openSignIns(t),view:t}}function startedOnEarlierEve(e){return{batches:[],pending:void 0,result:void 0,settled:{error:{code:`session_version_unsupported`,hint:`Start a new invocation.`,message:`This invocation was started on an earlier eve version, and this deployment can't read it.`},terminal:!0},signIns:[],view:e}}function howItSettled(e){let{session:t}=e,n=t.outcome===`failed`?failure(e):void 0;if(n!==void 0)return{error:n,terminal:!0};let r=t.latestTurnId===void 0?void 0:e.turns[t.latestTurnId],i=r?.closedAt??1/0,a=t.status!==`ended`&&Object.values(e.interactions).some(e=>(e.closedAt??-1)>i);if(r?.status===`settled`&&!a){let t=r.outcome===`failed`?failure(e,r.turnId):void 0;return t===void 0?r.outcome===`cancelled`?`cancelled`:`completed`:{error:t,terminal:!1}}return t.status===`ended`?`completed`:void 0}function latestResult(e){let t=e.session.latestTurnId;if(t===void 0||e.turns[t]?.status!==`settled`)return;let n=reply(e,t).find(e=>e.kind===`result`);return n===void 0?replyText(e,t):n.value}function invocationInteractions(e){let t={};for(let[n,r]of e)r!==void 0&&(t[n]=interactionJson(r));return t}function replaysSettledBatch(e,t){let n=e.batches.at(-1);if(n===void 0||t.length!==n.size)return!1;let r=new Set;for(let i of t){let{interactionId:t}=i;if(!n.has(t)||r.has(t))return!1;r.add(t);let a=interaction(e.view,t);if(a?.status!==`settled`||a.answer===void 0||a.answer.optionId!==i.optionId||a.answer.text!==i.text)return!1}return!0}function projectInvocation(e,t,n){let{result:r,settled:i}=n,a={...e,sessionEnded:n.view.session.status===`ended`||t===`completed`||t===`failed`},o=typeof i==`object`?i:void 0,failed=()=>({...a,error:publicInvocationFailure(e.invocationId,o?.error),status:`failed`});if(t===`failed`||o?.terminal===!0)return failed();if(a.sessionEnded)return o===void 0?{...a,result:r,status:i===`cancelled`?`cancelled`:`completed`}:failed();if(n.pending!==void 0||n.signIns.length>0){let e=invocationInteractions([...n.pending??[],...n.signIns.map(e=>[e.interactionId,interaction(n.view,e.interactionId)])]);return{...a,interactions:e,pollAfterMs:1e3,result:r,status:`awaiting-input`}}return o===void 0?i===`cancelled`?{...a,status:`cancelled`}:i===`completed`?{...a,result:r,status:`completed`}:{...a,pollAfterMs:1e3,result:r,status:`working
|
|
1
|
+
import{emptySessionView,foldReceivedEvent}from"#protocol/session-projection/fold.js";import{interaction,openRequests,openSignIns}from"#protocol/session-projection/reader.js";import{activity,failure,interactionBatches,reply,replyText}from"#protocol/session-projection/selectors.js";import{parseAnswers}from"#shared/input.js";import{createEventReader}from"#protocol/session-lines.js";import{isV26Line}from"#protocol/v26-lines.js";import{getWorld}from"#internal/workflow/runtime.js";import{streamSessionLines}from"#execution/session-event-stream.js";import{RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{INVOCATION_OWNER_ATTRIBUTE,INVOCATION_TOKEN_ATTRIBUTE,invocationOwnerKey}from"#internal/invocation/metadata.js";import{interactionJson}from"#protocol/interaction-json.js";var WorkflowAgentInvocationExecution=class{#e;#t;constructor(e){this.#e=e.createSession,this.#t=e.from}async create(e){let t=`invocation:${crypto.randomUUID()}`,n=await this.#e({auth:e.auth,capabilities:{requestInput:!0},continuationToken:t,externalInvocation:{continuationToken:t,ownerKey:invocationOwnerKey(e.auth)},input:{message:e.message}}),r=await this.#r(n.sessionId,e.auth);if(r===void 0)throw Error(`Invocation run was unavailable after durable creation.`);return workingInvocation(n.sessionId,r.createdAt.toISOString(),r.expiredAt?.toISOString())}async read(e){return(await this.#n(e))?.invocation}async update(e){let t=await this.#n(e);if(t===void 0)return{type:`not_found`};let{invocation:n,stream:r,token:i}=t,a=r?.pending;if(n.status!==`awaiting-input`||a===void 0)return r!==void 0&&replaysSettledBatch(r,e.responses)?{invocation:n,type:`success`}:conflict(`Invocation is not waiting for input.`);let o=new Set,s=[];for(let t of e.responses){if(a.get(t.interactionId)===void 0)return conflict(`Unknown input request: ${t.interactionId}`);o.add(t.interactionId),s.push(t)}if(o.size!==e.responses.length||o.size!==a.size)return conflict(`Responses must answer the complete pending input batch exactly once.`);if(i===void 0)return{type:`not_found`};try{await this.#t(i).respond(parseAnswers(s),{auth:e.auth})}catch(e){if(RunExpiredError.is(e))return{type:`not_found`};throw e}return{invocation:workingInvocation(e.invocationId,n.createdAt,n.expiresAt),type:`success`}}async cancel(e){let t=await this.#n(e);if(t!==void 0){if(isTerminal(t.invocation.status))return t.invocation;if(t.token!==void 0){try{await this.#t(t.token).cancel({auth:e.auth})}catch(e){if(WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))return;throw e}return await this.read(e)}}}async#n(e){let t=await this.#r(e.invocationId,e.auth);if(t===void 0)return;let n={createdAt:t.createdAt.toISOString(),expiresAt:t.expiredAt?.toISOString(),invocationId:t.runId};if(t.status===`cancelled`)return{invocation:{...n,sessionEnded:!0,status:`cancelled`}};let r=await readInvocationStream(e.invocationId);return{invocation:projectInvocation(n,t.status,r),stream:r,token:t.attributes[INVOCATION_TOKEN_ATTRIBUTE]}}async#r(e,t){let n=await getWorld();try{let r=await n.runs.get(e);return r.attributes[INVOCATION_TOKEN_ATTRIBUTE]===void 0?void 0:r.attributes[INVOCATION_OWNER_ATTRIBUTE]===invocationOwnerKey(t)?r:void 0}catch(e){if(WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))return;throw e}}};async function readInvocationStream(e){let t=emptySessionView(),n=createEventReader();for await(let{line:r,position:i,record:a}of streamSessionLines(e,{follow:!1})){if(r===void 0){if(i===0&&isV26Line(a))return startedOnEarlierEve(t);continue}for(let e of n.read(r,i))foldReceivedEvent(t,e)}let r=interactionBatches(t).map(e=>new Map(e.flatMap(e=>{let n=interaction(t,e.interactionId);return n===void 0?[]:[[e.interactionId,n]]}))),i=new Set(openRequests(t).map(e=>e.interactionId));return{batches:r,pending:r.map(e=>new Map([...e].filter(([e])=>i.has(e)))).findLast(e=>e.size>0),result:latestResult(t),settled:howItSettled(t),signIns:openSignIns(t),view:t}}function startedOnEarlierEve(e){return{batches:[],pending:void 0,result:void 0,settled:{error:{code:`session_version_unsupported`,hint:`Start a new invocation.`,message:`This invocation was started on an earlier eve version, and this deployment can't read it.`},terminal:!0},signIns:[],view:e}}function howItSettled(e){let{session:t}=e,n=t.outcome===`failed`?failure(e):void 0;if(n!==void 0)return{error:n,terminal:!0};let r=t.latestTurnId===void 0?void 0:e.turns[t.latestTurnId],i=r?.closedAt??1/0,a=t.status!==`ended`&&Object.values(e.interactions).some(e=>(e.closedAt??-1)>i);if(r?.status===`settled`&&!a){let t=r.outcome===`failed`?failure(e,r.turnId):void 0;return t===void 0?r.outcome===`cancelled`?`cancelled`:`completed`:{error:t,terminal:!1}}return t.status===`ended`?`completed`:void 0}function latestResult(e){let t=e.session.latestTurnId;if(t===void 0||e.turns[t]?.status!==`settled`)return;let n=reply(e,t).find(e=>e.kind===`result`);return n===void 0?replyText(e,t):n.value}function invocationInteractions(e){let t={};for(let[n,r]of e)r!==void 0&&(t[n]=interactionJson(r));return t}function replaysSettledBatch(e,t){let n=e.batches.at(-1);if(n===void 0||t.length!==n.size)return!1;let r=new Set;for(let i of t){let{interactionId:t}=i;if(!n.has(t)||r.has(t))return!1;r.add(t);let a=interaction(e.view,t);if(a?.status!==`settled`||a.answer===void 0||a.answer.optionId!==i.optionId||a.answer.text!==i.text)return!1}return!0}function projectInvocation(e,t,n){let{result:r,settled:i}=n,a={...e,sessionEnded:n.view.session.status===`ended`||t===`completed`||t===`failed`},o=typeof i==`object`?i:void 0,failed=()=>({...a,error:publicInvocationFailure(e.invocationId,o?.error),status:`failed`});if(t===`failed`||o?.terminal===!0)return failed();if(a.sessionEnded)return o===void 0?{...a,result:r,status:i===`cancelled`?`cancelled`:`completed`}:failed();if(n.pending!==void 0||n.signIns.length>0){let e=invocationInteractions([...n.pending??[],...n.signIns.map(e=>[e.interactionId,interaction(n.view,e.interactionId)])]);return{...a,interactions:e,pollAfterMs:1e3,result:r,status:`awaiting-input`}}return o===void 0?i===`cancelled`?{...a,status:`cancelled`}:i===`completed`?{...a,result:r,status:`completed`}:{...a,pollAfterMs:1e3,result:r,status:`working`,statusMessage:statusMessage(activity(n.view))}:failed()}function statusMessage(e){let t=e.kind===`calling`?e.names:e.kind===`waiting-on-tasks`?e.tasks.map(e=>e.name):[],n=t.at(-1);if(n!==void 0)return t.length===1?n:`${n} (+${String(t.length-1)} more)`}function workingInvocation(e,t,n){return{createdAt:t,expiresAt:n,invocationId:e,sessionEnded:!1,pollAfterMs:1e3,status:`working`}}function publicInvocationFailure(e,t){let n={runId:e},r=vercelDeploymentId();return r!==void 0&&(n.vercelDeploymentId=r),t!==void 0&&(n.eveCode=t.code,t.id!==void 0&&(n.errorId=t.id),t.hint!==void 0&&(n.hint=t.hint)),{code:-32603,data:n,message:t?.message??`Invocation failed.`}}function vercelDeploymentId(){if(process.env.VERCEL!==`1`)return;let e=process.env.VERCEL_DEPLOYMENT_ID?.trim();return e&&e.length>0?e:void 0}function conflict(e){return{message:e,type:`conflict`}}function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}export{WorkflowAgentInvocationExecution};
|