eve 0.71.1 → 0.71.3
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 +24 -0
- package/dist/src/channel/conversation-context.d.ts +4 -1
- package/dist/src/channel/invoke-tool.d.ts +41 -0
- package/dist/src/channel/invoke-tool.js +1 -0
- package/dist/src/channel/routes.d.ts +3 -0
- package/dist/src/cli/dev/tui/transcript.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +2 -2
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/caller-scope.d.ts +7 -0
- package/dist/src/context/caller-scope.js +1 -0
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.d.ts +2 -1
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/coordination-dispatch-step.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/invoke-tool.d.ts +35 -0
- package/dist/src/execution/invoke-tool.js +1 -0
- package/dist/src/execution/publish-session-events.d.ts +8 -4
- package/dist/src/execution/publish-session-events.js +1 -1
- package/dist/src/execution/sandbox/active-handles.d.ts +6 -0
- package/dist/src/execution/sandbox/active-handles.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/session/active-turn.js +1 -1
- package/dist/src/execution/session/answer-caller.d.ts +15 -0
- package/dist/src/execution/session/answer-caller.js +1 -0
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/terminal-session-completion-step.d.ts +3 -0
- package/dist/src/execution/terminal-session-completion-step.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/connection-tools.js +1 -1
- package/dist/src/execution/tools/workflow/authorization-completion.js +1 -1
- package/dist/src/execution/tools/workflow/step-execution.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/harness/approval-candidates.d.ts +4 -0
- package/dist/src/harness/approval-candidates.js +1 -1
- package/dist/src/harness/approved-call-callers.d.ts +11 -0
- package/dist/src/harness/approved-call-callers.js +1 -0
- package/dist/src/harness/coordination.d.ts +4 -0
- package/dist/src/harness/coordination.js +1 -1
- package/dist/src/harness/emission-state.d.ts +10 -0
- package/dist/src/harness/emission-state.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/input-requests.d.ts +6 -0
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/provider-tools.d.ts +5 -1
- package/dist/src/harness/provider-tools.js +1 -1
- package/dist/src/harness/session-limit-continuation.d.ts +3 -1
- package/dist/src/harness/session-limit-continuation.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-call-io.d.ts +25 -0
- package/dist/src/harness/tool-call-io.js +1 -0
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/tool-model-output.d.ts +1 -2
- package/dist/src/harness/tools.d.ts +1 -0
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/harness/workflow-dispatch.js +1 -1
- package/dist/src/instrumentation/lifecycle.d.ts +4 -0
- package/dist/src/instrumentation/native-events.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/gateway.d.ts +2 -0
- package/dist/src/internal/gateway.js +1 -1
- package/dist/src/internal/nitro/host/instrumentation-entry.js +2 -2
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/internal/nitro/routes/route-invoke-tool.d.ts +24 -0
- package/dist/src/internal/nitro/routes/route-invoke-tool.js +1 -0
- package/dist/src/internal/workflow/cancel-expired-development-run.js +1 -1
- package/dist/src/internal/workflow/development-world-client.js +1 -1
- package/dist/src/public/channels/discord/hitl.js +1 -1
- package/dist/src/public/channels/index.d.ts +1 -1
- package/dist/src/public/channels/slack/connections.d.ts +11 -11
- package/dist/src/public/channels/slack/connections.js +1 -1
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/public/channels/teams/defaults.js +1 -1
- package/dist/src/public/channels/twilio/defaults.d.ts +1 -1
- package/dist/src/public/channels/twilio/defaults.js +4 -2
- package/dist/src/public/definitions/channel.d.ts +1 -0
- package/dist/src/public/models/openai/chatgpt/model.js +1 -1
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +2 -2
- package/dist/src/setup/scaffold/create/web-template.js +25 -8
- 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/agent-action-instrumentation.d.ts +1 -0
- package/dist/src/tracing/agent-action-instrumentation.js +1 -1
- package/dist/src/tracing/agent-otel-provider.js +1 -1
- package/dist/src/tracing/agent-span-contract.d.ts +8 -0
- package/dist/src/tracing/agent-span-contract.js +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.d.ts +1 -0
- package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
- package/dist/src/tracing/agent-trace-context-codec.js +1 -1
- package/dist/src/tracing/agent-trace-span-processor.js +1 -1
- package/dist/src/tracing/agent-trace-state.d.ts +1 -0
- package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
- package/dist/src/tracing/invoke-tool-span.d.ts +61 -0
- package/dist/src/tracing/invoke-tool-span.js +1 -0
- package/docs/channels/custom.mdx +1 -0
- package/docs/reference/cli.md +2 -0
- package/docs/tools/human-in-the-loop.md +2 -0
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.71.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- a8262be: When someone other than the person who asked approves a tool call, only that call now runs as the approver. Before, the approver became the caller for the rest of the turn, so later tool calls and approvals in that turn also ran with the approver's identity and credentials.
|
|
8
|
+
- 8ecfd4f: Show the budget prompt again when someone sends a message after pressing Stop on it. The re-raised prompt reused the earlier prompt's request id, so `eve/client`, the Web Chat template, and the dev TUI treated it as already answered and left it unanswerable.
|
|
9
|
+
- 8df6c83: Typing "approve" on a session budget prompt now resumes the session when you had already sent another message while the prompt was open. Before, eve joined your queued message and the approval into a single message that matched neither option, so the agent stayed blocked. The queued message now runs after the approval.
|
|
10
|
+
- a2453a9: `chatgpt()` now sends `serviceTier: "fast"` to the Codex backend as `priority`, the value the Codex CLI uses for Fast mode, instead of failing with `400 Unsupported service_tier: fast`.
|
|
11
|
+
- dcb995c: Select web search backends using the resolved model provider so dynamic models from non-Gateway providers do not receive AI Gateway tools.
|
|
12
|
+
- 61e20b2: Return a not-found or transient error before opening an unavailable session stream, and close streams after terminal failures.
|
|
13
|
+
- 77c2d3e: Include a new message in the first model step after cancelling a turn that was waiting for tool approval, instead of first replying to the cancelled call alone.
|
|
14
|
+
- 1066932: `eve build` keeps the named exports of the Nitro preset entry. Builds with presets such as `NITRO_PRESET=node-middleware` export `middleware` and `handleUpgrade` again instead of only `default`.
|
|
15
|
+
- 55d4604: Channel route handlers now receive `invokeTool(name, input, { auth })`, which runs one of the agent's tools as the given caller outside any conversation, with a sandbox that lasts for the call. Tools whose approval policy asks a person resolve to `approval-required` without running.
|
|
16
|
+
- 61e20b2: Fix channel `session.completed` handlers throwing when a session expires, resets, or closes between turns. The handler's `ctx.session.turn` reports the session's last turn.
|
|
17
|
+
- dd36ab3: Fix nested connector actions appearing as unrelated model tool calls in traces: they now carry their parent call ID and nest beneath the calling action. Action spans also retain their request start time and cover tool execution when SDK telemetry arrives first.
|
|
18
|
+
- 3d78c3e: The Web Chat template now shows every question a tool call asks at once. Before, when a workflow called `ctx.ask` twice in parallel, the second question replaced the first, so the first question couldn't be answered and the tool stayed blocked.
|
|
19
|
+
|
|
20
|
+
## 0.71.2
|
|
21
|
+
|
|
22
|
+
### Patch Changes
|
|
23
|
+
|
|
24
|
+
- 76e9079: Return a not-found or transient error before opening an unavailable session stream, and close streams after terminal failures.
|
|
25
|
+
- 52ebf7d: Discord now posts session budget prompts instead of failing on a button ID over 100 characters. Slack sends its private sign-in prompt for sign-ins that only have instructions. Teams sign-in cards show the confirmation code and instructions, Twilio texts sign-ins and their outcome, and the dev TUI labels a sign-in with its display name. Discord buttons posted before this update stop working once it's deployed.
|
|
26
|
+
|
|
3
27
|
## 0.71.1
|
|
4
28
|
|
|
5
29
|
### Patch Changes
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { RunInput, SessionAuthContext } from "#channel/types.js";
|
|
2
2
|
import { type AudienceCaller, type ConversationContext, type ConversationEnvironment } from "#shared/conversation-context.js";
|
|
3
|
-
|
|
3
|
+
/** What a conversation context is built from: a run, or a direct tool call's channel and caller. */
|
|
4
|
+
type ConversationSource = RunInput | (Pick<RunInput, "adapter" | "auth"> & Partial<Pick<RunInput, "audienceAuth" | "channelName" | "inheritedConversation" | "parentTraceContext">>);
|
|
5
|
+
export declare function buildConversationContext(run: ConversationSource, environment: ConversationEnvironment): ConversationContext;
|
|
4
6
|
/** Projects route auth into the minimal identity audience classifiers need. */
|
|
5
7
|
export declare function toAudienceCaller(auth: SessionAuthContext | null | undefined): AudienceCaller;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
import type { ToolModelOutput } from "#tools/model-output.js";
|
|
3
|
+
/** Options for one {@link InvokeToolFn} call. */
|
|
4
|
+
export interface InvokeToolOptions {
|
|
5
|
+
/** The caller this request authenticated. Becomes `ctx.session.auth.current`. */
|
|
6
|
+
readonly auth: SessionAuthContext;
|
|
7
|
+
readonly signal?: AbortSignal;
|
|
8
|
+
}
|
|
9
|
+
/** Outcome of one {@link InvokeToolFn} call. */
|
|
10
|
+
export type InvokeToolResult = {
|
|
11
|
+
readonly status: "completed";
|
|
12
|
+
readonly output: unknown;
|
|
13
|
+
readonly modelOutput: ToolModelOutput;
|
|
14
|
+
} | {
|
|
15
|
+
readonly status: "failed";
|
|
16
|
+
readonly message: string;
|
|
17
|
+
readonly errorId?: string;
|
|
18
|
+
} | {
|
|
19
|
+
readonly status: "invalid-input";
|
|
20
|
+
readonly message: string;
|
|
21
|
+
} | {
|
|
22
|
+
readonly status: "denied";
|
|
23
|
+
readonly reason?: string;
|
|
24
|
+
}
|
|
25
|
+
/** The tool's approval policy asks a person. A call has no one to ask, so the tool did not run. */
|
|
26
|
+
| {
|
|
27
|
+
readonly status: "approval-required";
|
|
28
|
+
}
|
|
29
|
+
/** The tool needs a sign-in to these connections first. The tool stopped where it needed them. */
|
|
30
|
+
| {
|
|
31
|
+
readonly status: "authorization-required";
|
|
32
|
+
readonly connections: readonly string[];
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Runs one of the agent's tools outside a conversation. No model, turn, or
|
|
36
|
+
* workflow step is involved, and the call never parks. Each call gets its own
|
|
37
|
+
* session: `ctx.session.auth.current` is the caller, authored state starts from
|
|
38
|
+
* its initial value and is not kept, and a sandbox the tool opens is deleted
|
|
39
|
+
* when the call ends.
|
|
40
|
+
*/
|
|
41
|
+
export type InvokeToolFn = (name: string, input: unknown, options: InvokeToolOptions) => Promise<InvokeToolResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { UserContent } from "ai";
|
|
2
2
|
import type { CrossChannelToFn } from "#channel/cross-channel-receive.js";
|
|
3
3
|
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
|
|
4
|
+
import type { InvokeToolFn } from "#channel/invoke-tool.js";
|
|
4
5
|
import type { InputResponse } from "#shared/input.js";
|
|
5
6
|
import type { Session } from "#channel/session.js";
|
|
6
7
|
import type { JsonObject } from "#shared/json.js";
|
|
@@ -36,6 +37,8 @@ export interface RouteHandlerArgs<TState = undefined> {
|
|
|
36
37
|
* inspection detail of `GET /eve/v1/info`.
|
|
37
38
|
*/
|
|
38
39
|
describe(): Promise<AgentDescription>;
|
|
40
|
+
/** Runs one of the agent's tools as `auth`, outside any conversation. */
|
|
41
|
+
readonly invokeTool: InvokeToolFn;
|
|
39
42
|
}
|
|
40
43
|
export interface SendPayload {
|
|
41
44
|
readonly message?: string | UserContent;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FileContentCache}from"./file-content-cache.js";import{agentDisplayName,agentTaskLabel,isPanelRoutedTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{isTerminalToolCallPart}from"./terminal-tool-part.js";import{activeToolSteps,authorizationTerminalMessage,childToolCallIds,endLine,firstLine,followUpLine,formatAuthorization,isActive,isToolCallRow,nestedTaskRecord,startLine,subagentSteps,taskCallsById,taskNeedsApproval,toolBlock,toolState,userText,writeExistedFlag}from"./transcript-parts.js";import{signInLabel,waitingLabel}from"./task-activity.js";import{TaskRecords}from"./task-records.js";import{isTaskControlTool}from"#protocol/task-tools.js";import{stripTerminalControls}from"#cli/ui/terminal-text.js";import{agentCallTurns,agentToolSession,conversationAuthorizations,isAgentCallContentPending}from"#client/conversation-state.js";import{authorizationKey}from"#client/session-utils.js";const TASK_END_GRACE_MS=2e3;var ConversationTranscript=class{#e=new Map;#t=new FileContentCache;#n=new Map;#r=new Map;#i=new Set;#a=new TaskRecords;#o=new Map;#s=[];#c=new Set;#l=[];reset(){this.#e=new Map,this.#t.clear(),this.#n.clear(),this.#r=new Map,this.#i.clear(),this.#a.clear(),this.#o.clear(),this.#s=[],this.#c.clear(),this.#l=[]}get tasks(){return this.#l}get finishing(){return this.#l.some(e=>e.finishing===!0)}taskLabel(e,t){let n=e.tasks[t];if(n===void 0)return;let r=Object.values(n.calls),i=r.findLast(e=>e.status===`working`)??r.at(-1),a=i===void 0?void 0:this.#a.get(i.callId);return a===void 0?n.kind===`agent`?agentTaskLabel(agentDisplayName(stripTerminalControls(n.name))):stripTerminalControls(n.name):a.kind===`agent`?agentTaskLabel(a.name):a.name}stopWorking(e){let t=[];for(let n of this.#a.values())n.ended||(n.ended=!0,t.push(endLine(n,{status:`cancelled`},void 0,e.dot??`·`)));return this.#l=[],t}project(e,t){let{conversation:n,working:r}=e,i=Date.now(),a=[];this.#h(n.messages);let o=childToolCallIds(n),s=taskCallsById(n),c=new Set(e.data.withdrawnCallIds),l=e.data.toolLabels;for(let e of n.messages){if(e.role===`user`){let t=this.#g(e);t!==void 0&&a.push(t);continue}let u=e.parts.filter(e=>isToolCallRow(e)&&(e.state!==`input-streaming`||r)&&!isTaskControlTool(e.toolName)&&!c.has(e.toolCallId)&&e.toolMetadata?.eve?.inputRequest?.kind!==`session-limit`&&!s.has(e.toolCallId)&&!o.has(e.toolCallId)&&!isPanelRoutedTool(e.toolName)),d=new Map(u.map(e=>[e,toolState(e,n,r,!1)])),f=activeToolSteps(d);for(let[n,o]of e.parts.entries())if(o.type===`text`||o.type===`reasoning`){let i=this.#_(e,n,t,r);i!==void 0&&a.push(i)}else if(o.type===`authorization`)t.connectionAuth!==`hidden`&&a.push(this.#v(o));else if(o.type===`dynamic-tool`){let e=s.get(o.toolCallId);if(e!==void 0){let n=this.#d(o,e.task,l,t,i);n!==void 0&&a.push(n);continue}let n=d.get(o);if(n===void 0||t.tools===`hidden`)continue;let r=l[o.toolCallId];a.push(this.#y(o,n,f.has(o.stepIndex),r,t))}let p=e.metadata?.turnId;p!==void 0&&n.turns[p]?.status===`cancelled`&&a.push(this.#m(`cancelled:${p}`,[],()=>({kind:`notice`,body:`Cancelled.`,live:!1})))}for(let[n,r]of e.failures.entries())a.push(this.#b(n,r,t));let u=this.#u(a),d=this.#f(e,s,t,i);for(let e of d){let t=u.slice(-8).map(e=>e.id);this.#s.push({block:e,after:t}),this.#c.add(e.id),u.push(e)}return u}#u(e){let t=[...e];for(let{block:e,after:n}of this.#s){let r=t.length;for(let e=n.length-1;e>=0;--e){let i=t.findIndex(t=>t.id===n[e]);if(i!==-1){r=i+1;break}}t.splice(r,0,e)}return t}#d(e,t,n,r,i){if(!(t.kind===`agent`?r.subagents!==`hidden`:r.tools!==`hidden`))return;let a=n[e.toolCallId]?.start,o=this.#a.record(e,t,a,i);return o.callId===e.toolCallId?this.#m(`task:${o.callId}:start`,[o],()=>startLine(o)):this.#m(`task:${e.toolCallId}:message`,[o],()=>followUpLine(o,e,a))}#f(e,t,n,r){let{conversation:i,working:a}=e,o=Object.values(i.turns).at(-1),s=!a&&(e.data.sessionFailed||o?.status===`cancelled`||o?.status===`failed`),c=[],l=[],u={remaining:128};for(let e of this.#a.values()){if(e.ended)continue;let o=t.get(e.callId)?.task;if(o===void 0)continue;let d=e.callIds.flatMap(e=>{let n=t.get(e)?.call;return n===void 0?[]:[n]}),f=d.at(-1),p=this.#p(e,o,d,i,n,u);if(n.subagents===`full`)for(let e of p.rows)this.#c.has(e.id)||c.push(e);let m=d.every(e=>e.status!==`working`);m&&(e.settledAtMs??=r);let h=m&&p.pending&&a&&r-(e.settledAtMs??r)<2e3;if(m&&!h||!m&&s){e.ended=!0,c.push(endLine(e,m?f:{status:`cancelled`},p.tools,n.dot??`·`));continue}let g={callId:e.callId,kind:e.kind,name:e.name,toolName:e.toolName,input:e.input,label:e.label,purpose:e.purpose,children:p.children,omittedTasks:p.omittedTasks,omittedAttention:p.omittedAttention,startedAtMs:e.startedAtMs,childTools:new Map(p.tools.map(e=>[e.id,e]))};p.step!==void 0&&(g.step=p.step),h&&(g.finishing=!0),l.push(g)}return this.#l=l,c}#p(e,t,n,r,i,a,o=0){let s=t.kind===`agent`?agentToolSession(r,t):void 0,c=s===void 0||s.observation.status===`not-followed`?void 0:s.observation.conversation;if(s===void 0||c===void 0)return{tools:[],rows:[],pending:!1};let l=s.observation.status===`following`&&n.some(e=>isAgentCallContentPending(t,e,c)),u=agentCallTurns(t,c),d=new Set(n.flatMap(e=>u.get(e.callId)??[])),f=c.messages.filter(e=>e.role===`assistant`&&e.metadata?.turnId!==void 0&&d.has(e.metadata.turnId)),p=n.some(e=>e.status===`working`)||l,m=taskCallsById(c),h=[],g=[],_=[],v=new Set,y=0,b=!1,x=0;for(let t of f)for(let n of t.parts){if(x+=1,!isToolCallRow(n)||isTaskControlTool(n.toolName))continue;let t=m.get(n.toolCallId),r=toolState(n,c,p,t?.call.status===`working`),s=`subagent:${e.callId}:tool:${n.toolCallId}`,l=this.#m(s,[n,r.status,e.name],()=>{let a=this.#x(n.toolCallId,n,r,i,{isSubagent:t?.task.kind===`agent`});return{...toolBlock(n,r,a),kind:`subagent-tool`,subagentCallId:e.callId,agentName:e.name,depth:1,live:!1}}),u=t?.task.kind===`agent`?i.subagents!==`hidden`:i.tools!==`hidden`;if(t?.call.status===`working`&&u){if(v.has(t.task.taskId))continue;if(v.add(t.task.taskId),o>=8||a.remaining<=0){y+=1,b||=r.status===`approval`||taskNeedsApproval(c,t.task);continue}--a.remaining;let s=`${e.callId}/${n.toolCallId}`,u=this.#o.get(s);u===void 0&&(u=nestedTaskRecord(s,n,t.task,l),this.#o.set(s,u));let d=this.#p(u,t.task,Object.values(t.task.calls).filter(e=>e.status===`working`),c,i,a,o+1);_.push({...u,step:d.step,children:d.children,omittedTasks:d.omittedTasks,omittedAttention:d.omittedAttention,childTools:new Map(d.tools.map(e=>[e.id,e]))})}else g.push(l);h.push({order:x,block:l,settled:!isActive(r.status)})}let S=subagentSteps(f);for(let t of S){if(!t.finalized)continue;let n=`subagent:${e.callId}:step:${t.key}`,r=this.#m(n,[t.reasoning,t.message,e.name],()=>{let n={kind:`subagent-step`,subagentCallId:e.callId,agentName:e.name,depth:1,body:t.message,live:!1};return t.reasoning.length>0&&(n.reasoning=t.reasoning),n});h.push({order:t.order,block:r,settled:!0})}let C=h.filter(e=>e.settled).sort((e,t)=>e.order-t.order).map(e=>e.block),w=S.at(-1),T={tools:g,rows:C,children:_,omittedTasks:y,omittedAttention:b,pending:l};return w!==void 0&&(T.step=firstLine(w.message)??`Thinking`),T}#m(e,t,n){let r=this.#e.get(e);if(r!==void 0&&sameKey(r.key,t))return r.block;let i={...n(),id:e};return this.#e.set(e,{key:t,block:i}),i}#h(e){let t=new Map;for(let n of e)n.role===`user`&&n.metadata?.optimistic===!0&&t.set(n.id,userText(n));let n=[...this.#r].filter(([e])=>!t.has(e)),r=new Set(t.values());for(let t of e){if(t.role!==`user`||t.metadata?.optimistic===!0||this.#i.has(t.id))continue;let e=userText(t),i=n.findIndex(([,t])=>t===e);i===-1&&r.has(e)||(this.#i.add(t.id),i!==-1&&(this.#n.set(t.id,n[i][0]),n.splice(i,1)))}this.#r=t}#g(e){if(e.metadata?.optimistic!==!0&&!this.#i.has(e.id))return;let t=stripTerminalControls(userText(e));if(t.trim().length===0)return;let n=`user:${this.#n.get(e.id)??e.id}`;return this.#m(n,[t],()=>({kind:`user`,body:t,live:!1}))}#_(e,t,n,r){let i=e.parts[t];if(i?.type!==`text`&&i?.type!==`reasoning`||i.type===`reasoning`&&n.reasoning!==`full`)return;let a=stripTerminalControls(i.text).trim();if(a.length===0)return;let o=i.state===`streaming`&&r,s=`${i.type}:${i.id??`${e.id}:${t}`}`;return this.#m(s,[a,o],()=>i.type===`text`?{kind:`assistant`,body:a,live:o}:{kind:`reasoning`,body:a,collapsed:!1,live:o})}#v(e){return this.#m(`connection-auth:${authorizationKey(e)}`,[e],()=>{let t=e.state===`completed`?e.outcome:e.state,n=authorizationTerminalMessage(t);return{kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${t}`,body:formatAuthorization(e,n),preformatted:!0,live:n===void 0}})}#y(e,t,n,r,i){let a=n||isActive(t.status);return this.#m(`tool:${e.toolCallId}`,[e,t.status,a,i.tools,i.subagentNames,r],()=>{let n=this.#x(e.toolCallId,e,t,i,{label:r?.start,completeLabel:r?.complete});return{...toolBlock(e,t,n),kind:`tool`,live:a,expanded:i.tools===`full`}})}#b(e,t,n){let{message:r,hint:i,detail:a}=t;return this.#m(`failure:${e}`,[r,i,a],()=>{let e={kind:`error`,title:`Error`,body:stripTerminalControls(r),live:!1};return i!==void 0&&(e.hint=stripTerminalControls(i)),a!==void 0&&(e.detail=n.diagnosticsPath===void 0?stripTerminalControls(a):`details: ${n.diagnosticsPath}`),e})}#x(e,t,n,r,i={}){n.output!==void 0&&this.#t.observeRead(n.output);let a={};(i.isSubagent===!0||r.subagentNames?.includes(toolBaseName(t.toolName))===!0)&&(a.isSubagent=!0),i.label!==void 0&&(a.label=i.label),i.completeLabel!==void 0&&(a.completeLabel=i.completeLabel);let o=readWriteFileInput(t.toolName,t.input);if(o!==void 0){let t=this.#t.observeWrite({...o,callId:e});t!==void 0&&(a.previousContent=t);let r=writeExistedFlag(n.output);r!==void 0&&(a.existed=r)}return Object.keys(a).length>0?a:void 0}};function turnActivity(e,t){let{conversation:n}=e,r=n.activeTurnId===void 0?void 0:n.turns[n.activeTurnId],i=e.conversation.messages.findLast(e=>e.role===`assistant`),a=taskCallsById(n);if(i?.parts.some(e=>isTerminalToolCallPart(e)&&!isTaskControlTool(e.toolName)&&!a.has(e.toolCallId)&&(e.state===`input-available`||e.state===`approval-responded`))===!0)return`Running`;if(r===void 0||r.waiting===!0){let e=conversationAuthorizations(n).filter(e=>e.state===`required`&&e.awaitsCallback===!0);if(e.length>0)return signInLabel(e.map(e=>e.displayName))}if(r?.waiting===!0&&t.length>0)return waitingLabel(t);if(i===void 0)return`Thinking`;let o=i.parts.findLast(e=>e.type!==`step-start`);return o?.type===`text`&&o.state===`streaming`||o?.type===`dynamic-tool`&&o.state===`input-streaming`?`Generating`:`Thinking`}function sameKey(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{ConversationTranscript,TASK_END_GRACE_MS,turnActivity};
|
|
1
|
+
import{FileContentCache}from"./file-content-cache.js";import{agentDisplayName,agentTaskLabel,isPanelRoutedTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{isTerminalToolCallPart}from"./terminal-tool-part.js";import{activeToolSteps,authorizationTerminalMessage,childToolCallIds,endLine,firstLine,followUpLine,formatAuthorization,isActive,isToolCallRow,nestedTaskRecord,startLine,subagentSteps,taskCallsById,taskNeedsApproval,toolBlock,toolState,userText,writeExistedFlag}from"./transcript-parts.js";import{signInLabel,waitingLabel}from"./task-activity.js";import{TaskRecords}from"./task-records.js";import{isTaskControlTool}from"#protocol/task-tools.js";import{stripTerminalControls}from"#cli/ui/terminal-text.js";import{agentCallTurns,agentToolSession,conversationAuthorizations,isAgentCallContentPending}from"#client/conversation-state.js";import{authorizationKey}from"#client/session-utils.js";const TASK_END_GRACE_MS=2e3;var ConversationTranscript=class{#e=new Map;#t=new FileContentCache;#n=new Map;#r=new Map;#i=new Set;#a=new TaskRecords;#o=new Map;#s=[];#c=new Set;#l=[];reset(){this.#e=new Map,this.#t.clear(),this.#n.clear(),this.#r=new Map,this.#i.clear(),this.#a.clear(),this.#o.clear(),this.#s=[],this.#c.clear(),this.#l=[]}get tasks(){return this.#l}get finishing(){return this.#l.some(e=>e.finishing===!0)}taskLabel(e,t){let n=e.tasks[t];if(n===void 0)return;let r=Object.values(n.calls),i=r.findLast(e=>e.status===`working`)??r.at(-1),a=i===void 0?void 0:this.#a.get(i.callId);return a===void 0?n.kind===`agent`?agentTaskLabel(agentDisplayName(stripTerminalControls(n.name))):stripTerminalControls(n.name):a.kind===`agent`?agentTaskLabel(a.name):a.name}stopWorking(e){let t=[];for(let n of this.#a.values())n.ended||(n.ended=!0,t.push(endLine(n,{status:`cancelled`},void 0,e.dot??`·`)));return this.#l=[],t}project(e,t){let{conversation:n,working:r}=e,i=Date.now(),a=[];this.#h(n.messages);let o=childToolCallIds(n),s=taskCallsById(n),c=new Set(e.data.withdrawnCallIds),l=e.data.toolLabels;for(let e of n.messages){if(e.role===`user`){let t=this.#g(e);t!==void 0&&a.push(t);continue}let u=e.parts.filter(e=>isToolCallRow(e)&&(e.state!==`input-streaming`||r)&&!isTaskControlTool(e.toolName)&&!c.has(e.toolCallId)&&e.toolMetadata?.eve?.inputRequest?.kind!==`session-limit`&&!s.has(e.toolCallId)&&!o.has(e.toolCallId)&&!isPanelRoutedTool(e.toolName)),d=new Map(u.map(e=>[e,toolState(e,n,r,!1)])),f=activeToolSteps(d);for(let[n,o]of e.parts.entries())if(o.type===`text`||o.type===`reasoning`){let i=this.#_(e,n,t,r);i!==void 0&&a.push(i)}else if(o.type===`authorization`)t.connectionAuth!==`hidden`&&a.push(this.#v(o));else if(o.type===`dynamic-tool`){let e=s.get(o.toolCallId);if(e!==void 0){let n=this.#d(o,e.task,l,t,i);n!==void 0&&a.push(n);continue}let n=d.get(o);if(n===void 0||t.tools===`hidden`)continue;let r=l[o.toolCallId];a.push(this.#y(o,n,f.has(o.stepIndex),r,t))}let p=e.metadata?.turnId;p!==void 0&&n.turns[p]?.status===`cancelled`&&a.push(this.#m(`cancelled:${p}`,[],()=>({kind:`notice`,body:`Cancelled.`,live:!1})))}for(let[n,r]of e.failures.entries())a.push(this.#b(n,r,t));let u=this.#u(a),d=this.#f(e,s,t,i);for(let e of d){let t=u.slice(-8).map(e=>e.id);this.#s.push({block:e,after:t}),this.#c.add(e.id),u.push(e)}return u}#u(e){let t=[...e];for(let{block:e,after:n}of this.#s){let r=t.length;for(let e=n.length-1;e>=0;--e){let i=t.findIndex(t=>t.id===n[e]);if(i!==-1){r=i+1;break}}t.splice(r,0,e)}return t}#d(e,t,n,r,i){if(!(t.kind===`agent`?r.subagents!==`hidden`:r.tools!==`hidden`))return;let a=n[e.toolCallId]?.start,o=this.#a.record(e,t,a,i);return o.callId===e.toolCallId?this.#m(`task:${o.callId}:start`,[o],()=>startLine(o)):this.#m(`task:${e.toolCallId}:message`,[o],()=>followUpLine(o,e,a))}#f(e,t,n,r){let{conversation:i,working:a}=e,o=Object.values(i.turns).at(-1),s=!a&&(e.data.sessionFailed||o?.status===`cancelled`||o?.status===`failed`),c=[],l=[],u={remaining:128};for(let e of this.#a.values()){if(e.ended)continue;let o=t.get(e.callId)?.task;if(o===void 0)continue;let d=e.callIds.flatMap(e=>{let n=t.get(e)?.call;return n===void 0?[]:[n]}),f=d.at(-1),p=this.#p(e,o,d,i,n,u);if(n.subagents===`full`)for(let e of p.rows)this.#c.has(e.id)||c.push(e);let m=d.every(e=>e.status!==`working`);m&&(e.settledAtMs??=r);let h=m&&p.pending&&a&&r-(e.settledAtMs??r)<2e3;if(m&&!h||!m&&s){e.ended=!0,c.push(endLine(e,m?f:{status:`cancelled`},p.tools,n.dot??`·`));continue}let g={callId:e.callId,kind:e.kind,name:e.name,toolName:e.toolName,input:e.input,label:e.label,purpose:e.purpose,children:p.children,omittedTasks:p.omittedTasks,omittedAttention:p.omittedAttention,startedAtMs:e.startedAtMs,childTools:new Map(p.tools.map(e=>[e.id,e]))};p.step!==void 0&&(g.step=p.step),h&&(g.finishing=!0),l.push(g)}return this.#l=l,c}#p(e,t,n,r,i,a,o=0){let s=t.kind===`agent`?agentToolSession(r,t):void 0,c=s===void 0||s.observation.status===`not-followed`?void 0:s.observation.conversation;if(s===void 0||c===void 0)return{tools:[],rows:[],pending:!1};let l=s.observation.status===`following`&&n.some(e=>isAgentCallContentPending(t,e,c)),u=agentCallTurns(t,c),d=new Set(n.flatMap(e=>u.get(e.callId)??[])),f=c.messages.filter(e=>e.role===`assistant`&&e.metadata?.turnId!==void 0&&d.has(e.metadata.turnId)),p=n.some(e=>e.status===`working`)||l,m=taskCallsById(c),h=[],g=[],_=[],v=new Set,y=0,b=!1,x=0;for(let t of f)for(let n of t.parts){if(x+=1,!isToolCallRow(n)||isTaskControlTool(n.toolName))continue;let t=m.get(n.toolCallId),r=toolState(n,c,p,t?.call.status===`working`),s=`subagent:${e.callId}:tool:${n.toolCallId}`,l=this.#m(s,[n,r.status,e.name],()=>{let a=this.#x(n.toolCallId,n,r,i,{isSubagent:t?.task.kind===`agent`});return{...toolBlock(n,r,a),kind:`subagent-tool`,subagentCallId:e.callId,agentName:e.name,depth:1,live:!1}}),u=t?.task.kind===`agent`?i.subagents!==`hidden`:i.tools!==`hidden`;if(t?.call.status===`working`&&u){if(v.has(t.task.taskId))continue;if(v.add(t.task.taskId),o>=8||a.remaining<=0){y+=1,b||=r.status===`approval`||taskNeedsApproval(c,t.task);continue}--a.remaining;let s=`${e.callId}/${n.toolCallId}`,u=this.#o.get(s);u===void 0&&(u=nestedTaskRecord(s,n,t.task,l),this.#o.set(s,u));let d=this.#p(u,t.task,Object.values(t.task.calls).filter(e=>e.status===`working`),c,i,a,o+1);_.push({...u,step:d.step,children:d.children,omittedTasks:d.omittedTasks,omittedAttention:d.omittedAttention,childTools:new Map(d.tools.map(e=>[e.id,e]))})}else g.push(l);h.push({order:x,block:l,settled:!isActive(r.status)})}let S=subagentSteps(f);for(let t of S){if(!t.finalized)continue;let n=`subagent:${e.callId}:step:${t.key}`,r=this.#m(n,[t.reasoning,t.message,e.name],()=>{let n={kind:`subagent-step`,subagentCallId:e.callId,agentName:e.name,depth:1,body:t.message,live:!1};return t.reasoning.length>0&&(n.reasoning=t.reasoning),n});h.push({order:t.order,block:r,settled:!0})}let C=h.filter(e=>e.settled).sort((e,t)=>e.order-t.order).map(e=>e.block),w=S.at(-1),T={tools:g,rows:C,children:_,omittedTasks:y,omittedAttention:b,pending:l};return w!==void 0&&(T.step=firstLine(w.message)??`Thinking`),T}#m(e,t,n){let r=this.#e.get(e);if(r!==void 0&&sameKey(r.key,t))return r.block;let i={...n(),id:e};return this.#e.set(e,{key:t,block:i}),i}#h(e){let t=new Map;for(let n of e)n.role===`user`&&n.metadata?.optimistic===!0&&t.set(n.id,userText(n));let n=[...this.#r].filter(([e])=>!t.has(e)),r=new Set(t.values());for(let t of e){if(t.role!==`user`||t.metadata?.optimistic===!0||this.#i.has(t.id))continue;let e=userText(t),i=n.findIndex(([,t])=>t===e);i===-1&&r.has(e)||(this.#i.add(t.id),i!==-1&&(this.#n.set(t.id,n[i][0]),n.splice(i,1)))}this.#r=t}#g(e){if(e.metadata?.optimistic!==!0&&!this.#i.has(e.id))return;let t=stripTerminalControls(userText(e));if(t.trim().length===0)return;let n=`user:${this.#n.get(e.id)??e.id}`;return this.#m(n,[t],()=>({kind:`user`,body:t,live:!1}))}#_(e,t,n,r){let i=e.parts[t];if(i?.type!==`text`&&i?.type!==`reasoning`||i.type===`reasoning`&&n.reasoning!==`full`)return;let a=stripTerminalControls(i.text).trim();if(a.length===0)return;let o=i.state===`streaming`&&r,s=`${i.type}:${i.id??`${e.id}:${t}`}`;return this.#m(s,[a,o],()=>i.type===`text`?{kind:`assistant`,body:a,live:o}:{kind:`reasoning`,body:a,collapsed:!1,live:o})}#v(e){return this.#m(`connection-auth:${authorizationKey(e)}`,[e],()=>{let t=e.state===`completed`?e.outcome:e.state,n=authorizationTerminalMessage(t);return{kind:`connection-auth`,title:`${stripTerminalControls(e.displayName)} · authorization · ${t}`,body:formatAuthorization(e,n),preformatted:!0,live:n===void 0}})}#y(e,t,n,r,i){let a=n||isActive(t.status);return this.#m(`tool:${e.toolCallId}`,[e,t.status,a,i.tools,i.subagentNames,r],()=>{let n=this.#x(e.toolCallId,e,t,i,{label:r?.start,completeLabel:r?.complete});return{...toolBlock(e,t,n),kind:`tool`,live:a,expanded:i.tools===`full`}})}#b(e,t,n){let{message:r,hint:i,detail:a}=t;return this.#m(`failure:${e}`,[r,i,a],()=>{let e={kind:`error`,title:`Error`,body:stripTerminalControls(r),live:!1};return i!==void 0&&(e.hint=stripTerminalControls(i)),a!==void 0&&(e.detail=n.diagnosticsPath===void 0?stripTerminalControls(a):`details: ${n.diagnosticsPath}`),e})}#x(e,t,n,r,i={}){n.output!==void 0&&this.#t.observeRead(n.output);let a={};(i.isSubagent===!0||r.subagentNames?.includes(toolBaseName(t.toolName))===!0)&&(a.isSubagent=!0),i.label!==void 0&&(a.label=i.label),i.completeLabel!==void 0&&(a.completeLabel=i.completeLabel);let o=readWriteFileInput(t.toolName,t.input);if(o!==void 0){let t=this.#t.observeWrite({...o,callId:e});t!==void 0&&(a.previousContent=t);let r=writeExistedFlag(n.output);r!==void 0&&(a.existed=r)}return Object.keys(a).length>0?a:void 0}};function turnActivity(e,t){let{conversation:n}=e,r=n.activeTurnId===void 0?void 0:n.turns[n.activeTurnId],i=e.conversation.messages.findLast(e=>e.role===`assistant`),a=taskCallsById(n);if(i?.parts.some(e=>isTerminalToolCallPart(e)&&!isTaskControlTool(e.toolName)&&!a.has(e.toolCallId)&&(e.state===`input-available`||e.state===`approval-responded`))===!0)return`Running`;if(r===void 0||r.waiting===!0){let e=conversationAuthorizations(n).filter(e=>e.state===`required`&&e.awaitsCallback===!0);if(e.length>0)return signInLabel(e.map(e=>e.displayName))}if(r?.waiting===!0&&t.length>0)return waitingLabel(t);if(i===void 0)return`Thinking`;let o=i.parts.findLast(e=>e.type!==`step-start`);return o?.type===`text`&&o.state===`streaming`||o?.type===`dynamic-tool`&&o.state===`input-streaming`?`Generating`:`Thinking`}function sameKey(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{ConversationTranscript,TASK_END_GRACE_MS,turnActivity};
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"zod": "4.5.4",
|
|
58
58
|
"zod-validation-error": "5.0.0"
|
|
59
59
|
},
|
|
60
|
-
"scriptHash": "
|
|
60
|
+
"scriptHash": "635b143e3a7617f1eba75e922597c2ff0b0b034341a16d11b1367e5b119532e2",
|
|
61
61
|
"toolVersions": {
|
|
62
62
|
"rolldown": "1.2.9",
|
|
63
63
|
"typescript": "7.0.2"
|
|
@@ -97,8 +97,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
97
97
|
};
|
|
98
98
|
};
|
|
99
99
|
readonly channel: {
|
|
100
|
-
readonly current:
|
|
101
|
-
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46];
|
|
100
|
+
readonly current: 47;
|
|
101
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47];
|
|
102
102
|
readonly dropped: {
|
|
103
103
|
readonly 12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.";
|
|
104
104
|
readonly 19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=2,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:73,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,29,30,31,32,34,35,54,55,63,64,65,66,67,68,69,70,71,72,73],dropped:{14:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,15:`TaskExec replaces stageEffect with send`,16:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,17:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,18:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,19:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,20:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,21:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,22:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,28:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,33:`ctx.agent now accepts the subagent name as its first argument, derives invocation identity internally, and infers structured output types`,36:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,37:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,38:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,39:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,40:`runWorkflowProgram was made internal; use the workflow factory from eve/tools/workflow`,41:`workflow no longer accepts agents and its options argument is optional; use workflow() or workflow({ maxSubagents })`,42:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,43:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,44:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,45:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,46:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,47:`eve/experimental/evaluate was removed; import evaluate from eve/ai`,48:`eve/experimental/evaluate was removed; import evaluate from eve/ai`,49:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,50:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,51:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,52:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,53:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,56:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,57:`agentRouter() no longer accepts a model-facing outputSchema; structured subagent output is requested only through ctx.agent().`,58:`Workflow tools no longer accept execution or return background task receipts; every call blocks until it settles.`,59:`Workflow tools no longer accept execution or return background task receipts, and every call blocks until it settles. ctx.ask() no longer accepts dismissible and reports a withdrawn request as cancelled, workflow tool contexts carry interruptSignal, and ctx.agent(name) returns a session handle whose send() delivers a message and whose result() resolves the turn; ctx.agent(name, { message, agentId }) and AgentInput were removed. A ctx.ask() question parks the open turn with turn.waiting instead of ending it.`,60:`Workflow tools define exactly one of execute(input, ctx), task(input, ctx), or serve(receive, ctx): a task() call returns a receipt and runs as a task, a serve() call reaches a resumable task through receive() and its model input gains taskId, and stream events gained task.started and task.settled. Agent tools are serve() tools with taskId in place of agentId, and the subagent.* stream events were removed. ctx.interruptSignal and WorkflowTaskContext were removed: a steering message aborts the abortSignal of an execute call the turn waits on.`,61:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,62:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`}},dynamicTool:{current:70,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,22,31,32,33,52,54,60,61,62,63,64,65,66,67,68,69,70],dropped:{21:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,28:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,29:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,30:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,34:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,35:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,36:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,37:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,38:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,39:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,40:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,41:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,42:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,43:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,44:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,45:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,46:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,47:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,48:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,49:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,50:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,51:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,53:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,55:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,56:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,57:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,58:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,59:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`}},channel:{current:46,supported:[1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,29,31,36,37,38,39,40,41,42,43,44,45,46],dropped:{12:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,19:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,20:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,21:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,22:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,23:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,24:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,25:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,26:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,27:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,28:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,30:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,32:`Run mode and caller-supplied output schemas were removed from channel operations; sessions always park, and send options, audience inputs, and ConversationContext no longer carry mode, while from().send() and from().respond() no longer accept outputSchema.`,33:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text.`,34:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,35:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},schedule:{current:26,supported:[1,2,3,4,6,7,8,9,10,11,12,13,14,15,18,19,20,21,22,23,24,25,26],dropped:{5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,16:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,17:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},subagent:{current:29,supported:[3,4,6,7,8,9,10,11,12,13,14,15,16,19,23,24,25,26,27,28,29],dropped:{1:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,2:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,17:`Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.`,18:`Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.`,20:`Run mode was removed and agent definitions no longer declare outputSchema; sessions always park, ConversationContext no longer carries mode, and structured output is requested per turn.`,21:`Background task execution was removed: subagent results no longer carry backgroundTask, message.completed always carries text, and experimental.tasks is gone. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,22:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},connection:{current:38,supported:[1,2,3,4,5,6,7,8,11,12,13,14,15,16,17,18,19,20,21,22,24,26,32,33,34,35,36,37,38],dropped:{9:`Dynamic connection resolvers no longer receive conversation or channel continuation data`,10:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,25:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,27:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,28:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,29:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,30:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,31:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`}},hook:{current:37,supported:[20,21,22,23,25,27,31,32,33,34,35,36,37],dropped:{1:`Model identity moved from session.started runtime metadata to step.started call attribution.`,2:`Model identity moved from session.started runtime metadata to step.started call attribution.`,3:`Model identity moved from session.started runtime metadata to step.started call attribution.`,4:`Model identity moved from session.started runtime metadata to step.started call attribution.`,5:`Model identity moved from session.started runtime metadata to step.started call attribution.`,6:`Model identity moved from session.started runtime metadata to step.started call attribution.`,7:`Model identity moved from session.started runtime metadata to step.started call attribution.`,8:`Model identity moved from session.started runtime metadata to step.started call attribution.`,9:`Model identity moved from session.started runtime metadata to step.started call attribution.`,10:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,11:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,12:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,13:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,14:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,15:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,16:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,17:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,18:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,19:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,24:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,26:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,28:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text.`,29:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,30:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`}},skill:{current:2,supported:[1,2],dropped:{}},dynamicSkill:{current:31,supported:[1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,21,25,26,27,28,29,30,31],dropped:{13:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,22:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,23:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,24:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},instructions:{current:2,supported:[1,2],dropped:{}},dynamicInstructions:{current:32,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,26,27,28,29,30,31,32],dropped:{14:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,24:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,25:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},config:{current:1,supported:[1],dropped:{}},state:{current:9,supported:[1,2,3,4,5,7,9],dropped:{6:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,8:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestV1Schema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict(),extensionCompatibilityManifestV2Schema=extensionCompatibilityManifestV1Schema.extend({formatVersion:z.literal(2),build:z.object({externalDependencies:z.array(z.string().min(1)).readonly()}).strict().optional()}),extensionCompatibilityManifestSchema=z.union([extensionCompatibilityManifestV1Schema,extensionCompatibilityManifestV2Schema]);function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(e){return parseExtensionCompatibilityManifest(await readFile(e,`utf8`),e)}async function writeExtensionCompatibilityManifest(e,t){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(t),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
|
|
1
|
+
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=2,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:73,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,29,30,31,32,34,35,54,55,63,64,65,66,67,68,69,70,71,72,73],dropped:{14:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,15:`TaskExec replaces stageEffect with send`,16:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,17:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,18:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,19:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,20:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,21:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,22:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,28:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,33:`ctx.agent now accepts the subagent name as its first argument, derives invocation identity internally, and infers structured output types`,36:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,37:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,38:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,39:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,40:`runWorkflowProgram was made internal; use the workflow factory from eve/tools/workflow`,41:`workflow no longer accepts agents and its options argument is optional; use workflow() or workflow({ maxSubagents })`,42:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,43:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,44:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,45:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,46:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,47:`eve/experimental/evaluate was removed; import evaluate from eve/ai`,48:`eve/experimental/evaluate was removed; import evaluate from eve/ai`,49:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,50:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,51:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,52:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,53:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,56:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,57:`agentRouter() no longer accepts a model-facing outputSchema; structured subagent output is requested only through ctx.agent().`,58:`Workflow tools no longer accept execution or return background task receipts; every call blocks until it settles.`,59:`Workflow tools no longer accept execution or return background task receipts, and every call blocks until it settles. ctx.ask() no longer accepts dismissible and reports a withdrawn request as cancelled, workflow tool contexts carry interruptSignal, and ctx.agent(name) returns a session handle whose send() delivers a message and whose result() resolves the turn; ctx.agent(name, { message, agentId }) and AgentInput were removed. A ctx.ask() question parks the open turn with turn.waiting instead of ending it.`,60:`Workflow tools define exactly one of execute(input, ctx), task(input, ctx), or serve(receive, ctx): a task() call returns a receipt and runs as a task, a serve() call reaches a resumable task through receive() and its model input gains taskId, and stream events gained task.started and task.settled. Agent tools are serve() tools with taskId in place of agentId, and the subagent.* stream events were removed. ctx.interruptSignal and WorkflowTaskContext were removed: a steering message aborts the abortSignal of an execute call the turn waits on.`,61:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,62:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`}},dynamicTool:{current:70,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,22,31,32,33,52,54,60,61,62,63,64,65,66,67,68,69,70],dropped:{21:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,28:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,29:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,30:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,34:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,35:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,36:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,37:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,38:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,39:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,40:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,41:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,42:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,43:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,44:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,45:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,46:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,47:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,48:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,49:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,50:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,51:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,53:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,55:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,56:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,57:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,58:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,59:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`}},channel:{current:47,supported:[1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,29,31,36,37,38,39,40,41,42,43,44,45,46,47],dropped:{12:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,19:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,20:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,21:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,22:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,23:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,24:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,25:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,26:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,27:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,28:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,30:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,32:`Run mode and caller-supplied output schemas were removed from channel operations; sessions always park, and send options, audience inputs, and ConversationContext no longer carry mode, while from().send() and from().respond() no longer accept outputSchema.`,33:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text.`,34:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,35:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},schedule:{current:26,supported:[1,2,3,4,6,7,8,9,10,11,12,13,14,15,18,19,20,21,22,23,24,25,26],dropped:{5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,16:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,17:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},subagent:{current:29,supported:[3,4,6,7,8,9,10,11,12,13,14,15,16,19,23,24,25,26,27,28,29],dropped:{1:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,2:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,17:`Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.`,18:`Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.`,20:`Run mode was removed and agent definitions no longer declare outputSchema; sessions always park, ConversationContext no longer carries mode, and structured output is requested per turn.`,21:`Background task execution was removed: subagent results no longer carry backgroundTask, message.completed always carries text, and experimental.tasks is gone. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,22:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},connection:{current:38,supported:[1,2,3,4,5,6,7,8,11,12,13,14,15,16,17,18,19,20,21,22,24,26,32,33,34,35,36,37,38],dropped:{9:`Dynamic connection resolvers no longer receive conversation or channel continuation data`,10:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,25:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,27:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,28:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,29:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,30:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,31:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`}},hook:{current:37,supported:[20,21,22,23,25,27,31,32,33,34,35,36,37],dropped:{1:`Model identity moved from session.started runtime metadata to step.started call attribution.`,2:`Model identity moved from session.started runtime metadata to step.started call attribution.`,3:`Model identity moved from session.started runtime metadata to step.started call attribution.`,4:`Model identity moved from session.started runtime metadata to step.started call attribution.`,5:`Model identity moved from session.started runtime metadata to step.started call attribution.`,6:`Model identity moved from session.started runtime metadata to step.started call attribution.`,7:`Model identity moved from session.started runtime metadata to step.started call attribution.`,8:`Model identity moved from session.started runtime metadata to step.started call attribution.`,9:`Model identity moved from session.started runtime metadata to step.started call attribution.`,10:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,11:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,12:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,13:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,14:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,15:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,16:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,17:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,18:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,19:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,24:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,26:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,28:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text.`,29:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,30:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`}},skill:{current:2,supported:[1,2],dropped:{}},dynamicSkill:{current:31,supported:[1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,21,25,26,27,28,29,30,31],dropped:{13:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,22:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,23:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,24:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},instructions:{current:2,supported:[1,2],dropped:{}},dynamicInstructions:{current:32,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,26,27,28,29,30,31,32],dropped:{14:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,24:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,25:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},config:{current:1,supported:[1],dropped:{}},state:{current:9,supported:[1,2,3,4,5,7,9],dropped:{6:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,8:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestV1Schema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict(),extensionCompatibilityManifestV2Schema=extensionCompatibilityManifestV1Schema.extend({formatVersion:z.literal(2),build:z.object({externalDependencies:z.array(z.string().min(1)).readonly()}).strict().optional()}),extensionCompatibilityManifestSchema=z.union([extensionCompatibilityManifestV1Schema,extensionCompatibilityManifestV2Schema]);function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(e){return parseExtensionCompatibilityManifest(await readFile(e,`utf8`),e)}async function writeExtensionCompatibilityManifest(e,t){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(t),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Runs `fn` with `caller` as the session's current caller. Writes still reach
|
|
4
|
+
* the outer context; only reads of the caller change, so work running beside
|
|
5
|
+
* `fn` in the same step keeps the outer caller.
|
|
6
|
+
*/
|
|
7
|
+
export declare function runAsCaller<T>(caller: SessionAuthContext, fn: () => T): T;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{contextStorage}from"#context/container.js";import{AuthKey,SessionKey}from"#context/keys.js";function runAsCaller(e,t){let n=contextStorage.getStore();return n===void 0?t():contextStorage.run(new CallerScope(n,e),t)}var CallerScope=class{#e;#t;constructor(e,t){this.#t=e,this.#e=t}get localDevRequest(){return this.#t.localDevRequest}get(e){if(e.name===AuthKey.name)return this.#e;if(e.name===SessionKey.name){let e=this.#t.get(SessionKey);return e===void 0?void 0:{...e,auth:{...e.auth,current:this.#e}}}return this.#t.get(e)}require(e){if(!this.has(e))throw Error(`Context key "${e.name}" is not set.`);return this.get(e)}has(e){return e.name===AuthKey.name||this.#t.has(e)}set(e,t){return this.#t.set(e,t)}ensure(e,t){return this.#t.ensure(e,t)}delete(e){return this.#t.delete(e)}entries(){return this.#t.entries()}setVirtualContext(e,t){this.#t.setVirtualContext(e,t)}};export{runAsCaller};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,splitLegacyTaskFields}from"#execution/legacy-remote-agent/protocol.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{parseSessionCallback}from"#channel/session-callback.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion}from"#protocol/remote-agent-protocol.js";import{parseTurnPolicyField}from"#eve-channel/turn-policy-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){let t=splitLegacyTaskFields(e),{payload:n}=t;if(n.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let r=parseMessageField(n.message);if(r instanceof Response)return r;let i=parseClientContextField(n.clientContext);if(i instanceof Response)return i;let a=parseCallbackField(n.callback);if(a instanceof Response)return a;let o=a===void 0?void 0:parseProtocolVersionField(n.protocolVersion);if(o instanceof Response)return o;let s=parseCapabilitiesField(n.capabilities);if(s instanceof Response)return s;let c=parseOutputSchemaField(n.outputSchema);if(c instanceof Response)return c;let l=validateMessageFreeCreate({callback:a,hasClientContext:n.clientContext!==void 0,hasMessageField:`message`in n,message:r,outputSchema:c});if(l!==void 0)return l;let u=n.operationId;if(u!==void 0&&(typeof u!=`string`||!u))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let d={callback:a,capabilities:s,context:i,outputSchema:c};return r!==void 0&&(d.message=r),typeof u==`string`&&(d.operationId=u),o!==void 0&&(d.protocolVersion=o),o===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION&&(d.legacyRemoteAgentCaller=t.taskId===void 0?{}:{taskId:t.taskId}),d}function parseSessionMessageBody(e){let{payload:t}=splitLegacyTaskFields(e),n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=parseMessageField(t.message);if(r instanceof Response)return r;let i=parseCallbackField(t.callback);if(i instanceof Response)return i;let a=parseInputResponses$1(t.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(t.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(t.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(t.turnPolicy);return c instanceof Response?c:r===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):r!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:i,message:r,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400}):typeof r==`string`?{turnId:r}:{}}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseIncludeTailIndex(e);try{let i=r?await t.getStreamTailIndex():void 0,a=await t.getEventStream({startIndex:n}),o=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,s=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return i!==void 0&&s.set(EVE_STREAM_TAIL_INDEX_HEADER,String(i)),new Response(serializeAsNdjson(a,e.signal,streamEventLimit(n,i),o!==void 0),{headers:s})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseProtocolVersionField(e){if(e!==void 0&&typeof e!=`number`)return Response.json({error:`Expected 'protocolVersion' to be a number.`,ok:!1},{status:400});let t=readRemoteAgentProtocolVersion(e);return t===REMOTE_AGENT_PROTOCOL_VERSION||t===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION?t:Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:`This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(t)}. Upgrade both deployments to the same eve release.`,ok:!1,protocolVersion:REMOTE_AGENT_PROTOCOL_VERSION},{status:409})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
|
|
1
|
+
import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,splitLegacyTaskFields}from"#execution/legacy-remote-agent/protocol.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{parseSessionCallback}from"#channel/session-callback.js";import{isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion}from"#protocol/remote-agent-protocol.js";import{parseTurnPolicyField}from"#eve-channel/turn-policy-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){let t=splitLegacyTaskFields(e),{payload:n}=t;if(n.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let r=parseMessageField(n.message);if(r instanceof Response)return r;let i=parseClientContextField(n.clientContext);if(i instanceof Response)return i;let a=parseCallbackField(n.callback);if(a instanceof Response)return a;let o=a===void 0?void 0:parseProtocolVersionField(n.protocolVersion);if(o instanceof Response)return o;let s=parseCapabilitiesField(n.capabilities);if(s instanceof Response)return s;let c=parseOutputSchemaField(n.outputSchema);if(c instanceof Response)return c;let l=validateMessageFreeCreate({callback:a,hasClientContext:n.clientContext!==void 0,hasMessageField:`message`in n,message:r,outputSchema:c});if(l!==void 0)return l;let u=n.operationId;if(u!==void 0&&(typeof u!=`string`||!u))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let d={callback:a,capabilities:s,context:i,outputSchema:c};return r!==void 0&&(d.message=r),typeof u==`string`&&(d.operationId=u),o!==void 0&&(d.protocolVersion=o),o===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION&&(d.legacyRemoteAgentCaller=t.taskId===void 0?{}:{taskId:t.taskId}),d}function parseSessionMessageBody(e){let{payload:t}=splitLegacyTaskFields(e),n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=parseMessageField(t.message);if(r instanceof Response)return r;let i=parseCallbackField(t.callback);if(i instanceof Response)return i;let a=parseInputResponses$1(t.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(t.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(t.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(t.turnPolicy);return c instanceof Response?c:r===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):r!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:i,message:r,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400}):typeof r==`string`?{turnId:r}:{}}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseIncludeTailIndex(e);try{let i=await t.getStreamTailIndex(),a=await t.getEventStream({startIndex:n}),o=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,s=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return r&&s.set(EVE_STREAM_TAIL_INDEX_HEADER,String(i)),new Response(serializeAsNdjson(a,e.signal,r?streamEventLimit(n,i):void 0,o!==void 0),{headers:s})}catch(e){let t=isMissingWorkflowRunError(e);return Response.json({error:t?`Session not found.`:`Session stream unavailable.`,ok:!1},{status:t?404:503})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseProtocolVersionField(e){if(e!==void 0&&typeof e!=`number`)return Response.json({error:`Expected 'protocolVersion' to be a number.`,ok:!1},{status:400});let t=readRemoteAgentProtocolVersion(e);return t===REMOTE_AGENT_PROTOCOL_VERSION||t===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION?t:Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:`This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(t)}. Upgrade both deployments to the same eve release.`,ok:!1,protocolVersion:REMOTE_AGENT_PROTOCOL_VERSION},{status:409})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
|
|
2
2
|
${e}`}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function streamEventLimit(e,t){if(t===void 0)return;let n=e===void 0?0:e<0?Math.max(0,t+1+e):e;return Math.max(0,t-n+1)}function serializeAsNdjson(e,t,n,r=!1){let i=new TextEncoder,a=0,o,s,clearTimers=()=>{clearTimeout(o),clearTimeout(s),o=void 0,s=void 0},scheduleHeartbeat=e=>{clearTimeout(o),o=setTimeout(()=>{try{e.enqueue(i.encode(`
|
|
3
3
|
`)),scheduleHeartbeat(e)}catch{clearTimers()}},1e4)},startLease=e=>{scheduleHeartbeat(e),s=setTimeout(()=>{clearTimers();try{e.enqueue(i.encode(`${JSON.stringify(EVE_STREAM_LEASE_ENDED_CONTROL)}\n`)),e.terminate()}catch{}},6e4)},c=new TransformStream({start(e){e.enqueue(i.encode(`
|
|
4
4
|
`)),n===0?e.terminate():r&&startLease(e)},transform(e,t){t.enqueue(i.encode(`${JSON.stringify(e)}\n`)),a+=1,a===n?(clearTimers(),t.terminate()):r&&scheduleHeartbeat(t)},flush(){clearTimers()}});return e.pipeTo(c.writable,{signal:t}).catch(()=>{}).finally(clearTimers),c.readable}export{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
2
|
import { type ChannelAdapter, type ChannelAdapterContext } from "#channel/adapter.js";
|
|
3
3
|
import { type LocalDevRequestProvenance } from "#context/keys.js";
|
|
4
4
|
import { ContextContainer } from "#context/container.js";
|
|
@@ -61,6 +61,7 @@ export declare function prepareCoordinationDispatch(input: {
|
|
|
61
61
|
readonly sessionState: DurableSessionState;
|
|
62
62
|
}): Promise<PreparedCoordinationDispatch | undefined>;
|
|
63
63
|
interface DispatchBatch {
|
|
64
|
+
readonly approvers?: Readonly<Record<string, SessionAuthContext>>;
|
|
64
65
|
readonly event: {
|
|
65
66
|
readonly sequence: number;
|
|
66
67
|
readonly stepIndex: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ConversationContextKey}from"#shared/conversation-context.js";import"#channel/adapter.js";import"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey,LocalDevRequestKey,ParentSessionKey,TraceRootKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import"#subagents/tool.js";import{assertUniqueCoordinationCallIds,getPendingCoordinationBatch,setPendingCoordinationBatch}from"#harness/coordination.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resolveWorkflowAgentMetadata}from"#execution/agent-sessions/metadata.js";import{readDynamicSubagentSelections}from"#context/dynamic-subagent-lifecycle.js";async function prepareCoordinationDispatch(e){let t=readDurableSession(e.sessionState),n=getPendingCoordinationBatch(t.state);if(n===void 0)return;let r=n.tasks;if(r.length===0)return;let i=n.event.turnId||activeTurnId(e.sessionState.emissionState),a=n.event.turnId===i?n.event:{...n.event,turnId:i},o=await deserializeContext(e.serializedContext),s=await prepareActionDispatch({batch:{event:a,requests:r},ctx:o,durableSession:t,plan:()=>r,serializedContext:e.serializedContext});if(a===n.event)return{...s,sessionState:e.sessionState};let c=setPendingCoordinationBatch({...n,event:a,session:s.session});return{...s,session:c,sessionState:createDurableSessionState({session:c})}}async function prepareActionDispatch(e){let{batch:t,durableSession:n}=e;assertUniqueCoordinationCallIds(t.requests);let r=e.ctx,i=r.require(BundleKey),a=resolveEffectiveAgentRuntime(i,r),o=hydrateDurableSession({compactionOverrides:{thresholdPercent:a.thresholdPercent},durable:n,turnAgent:a.turnAgent}),s=r.require(ChannelKey),c=e.plan({bundle:i,ctx:r,requests:t.requests,session:o}),l=resolveActiveSandboxSessionId(s.state,o.sessionId);return{adapter:s,adapterCtx:buildAdapterContext(s,r),auth:r.get(AuthKey)??null,batch:t,bundle:i,capabilities:r.get(CapabilitiesKey),channelMetadata:r.get(ChannelInstrumentationKey),dynamicSubagentSelections:readDynamicSubagentSelections(r),inheritedConversation:r.get(ConversationContextKey),initiatorAuth:r.get(InitiatorAuthKey)??null,localDevRequest:r.get(LocalDevRequestKey),parentSession:r.get(ParentSessionKey),plan:c,sandboxSessionId:l,serializedContext:e.serializedContext,session:o,traceRoot:childTraceRoot(r,o.sessionId),workflowAgents:resolveWorkflowAgentMetadata(r)}}function childTraceRoot(e,t){if(e.get(TraceRootKey)!==void 0)return{kind:`inherited`,sessionId:resolveTraceRootSessionId(e,t)}}function resolveActiveSandboxSessionId(e,t){if(typeof e!=`object`||!e)return t;let n=e.sandboxSessionId;return typeof n==`string`&&n.length>0?n:t}export{prepareActionDispatch,prepareCoordinationDispatch};
|
|
1
|
+
import{ConversationContextKey}from"#shared/conversation-context.js";import"#channel/adapter.js";import"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey,LocalDevRequestKey,ParentSessionKey,TraceRootKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import"#subagents/tool.js";import{assertUniqueCoordinationCallIds,getPendingCoordinationBatch,setPendingCoordinationBatch}from"#harness/coordination.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resolveWorkflowAgentMetadata}from"#execution/agent-sessions/metadata.js";import{readDynamicSubagentSelections}from"#context/dynamic-subagent-lifecycle.js";async function prepareCoordinationDispatch(e){let t=readDurableSession(e.sessionState),n=getPendingCoordinationBatch(t.state);if(n===void 0)return;let r=n.tasks;if(r.length===0)return;let i=n.event.turnId||activeTurnId(e.sessionState.emissionState),a=n.event.turnId===i?n.event:{...n.event,turnId:i},o=await deserializeContext(e.serializedContext),s=await prepareActionDispatch({batch:{approvers:n.approvers,event:a,requests:r},ctx:o,durableSession:t,plan:()=>r,serializedContext:e.serializedContext});if(a===n.event)return{...s,sessionState:e.sessionState};let c=setPendingCoordinationBatch({...n,event:a,session:s.session});return{...s,session:c,sessionState:createDurableSessionState({session:c})}}async function prepareActionDispatch(e){let{batch:t,durableSession:n}=e;assertUniqueCoordinationCallIds(t.requests);let r=e.ctx,i=r.require(BundleKey),a=resolveEffectiveAgentRuntime(i,r),o=hydrateDurableSession({compactionOverrides:{thresholdPercent:a.thresholdPercent},durable:n,turnAgent:a.turnAgent}),s=r.require(ChannelKey),c=e.plan({bundle:i,ctx:r,requests:t.requests,session:o}),l=resolveActiveSandboxSessionId(s.state,o.sessionId);return{adapter:s,adapterCtx:buildAdapterContext(s,r),auth:r.get(AuthKey)??null,batch:t,bundle:i,capabilities:r.get(CapabilitiesKey),channelMetadata:r.get(ChannelInstrumentationKey),dynamicSubagentSelections:readDynamicSubagentSelections(r),inheritedConversation:r.get(ConversationContextKey),initiatorAuth:r.get(InitiatorAuthKey)??null,localDevRequest:r.get(LocalDevRequestKey),parentSession:r.get(ParentSessionKey),plan:c,sandboxSessionId:l,serializedContext:e.serializedContext,session:o,traceRoot:childTraceRoot(r,o.sessionId),workflowAgents:resolveWorkflowAgentMetadata(r)}}function childTraceRoot(e,t){if(e.get(TraceRootKey)!==void 0)return{kind:`inherited`,sessionId:resolveTraceRootSessionId(e,t)}}function resolveActiveSandboxSessionId(e,t){if(typeof e!=`object`||!e)return t;let n=e.sandboxSessionId;return typeof n==`string`&&n.length>0?n:t}export{prepareActionDispatch,prepareCoordinationDispatch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDurableSessionState}from"#execution/durable-session-store.js";import{prepareCoordinationDispatch}from"#execution/coordination-dispatch-shared.js";import{publishSessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{startWorkflowTask}from"#execution/tools/workflow/start.js";import{sendToTask,startTaskRun}from"#execution/tasks/start.js";import{captureAgentSessionContext,resolveStepAgentLimits}from"#execution/agent-sessions/context.js";async function dispatchCoordinationStep(e){"use step";return await withSessionStateDelta(e,dispatchCoordination)}async function dispatchCoordination(e){let t=await prepareCoordinationDispatch({serializedContext:e.serializedContext,sessionState:e.sessionState});if(t===void 0)return{results:[],serializedContext:e.serializedContext,sessionState:e.sessionState};let{batch:n,session:r}=t,i=r,a=[],o=[],s=resolveStepAgentLimits(t);for(let r of t.plan){let c=await dispatchWorkflowCall({agentContext:captureAgentSessionContext(t,r.callId,s),auth:{current:t.auth,initiator:t.initiatorAuth},batchEvent:n.event,owner:e.workflowToolRunOwner,parentSession:t.parentSession,session:i,task:r});i=c.session,c.result!==void 0&&a.push(c.result),c.started!==void 0&&o.push(c.started)}return{results:a,...await publishSessionEvents({serializedContext:e.serializedContext,sessionState:i===r?t.sessionState:createDurableSessionState({session:i}),sessionWritable:e.sessionWritable},o)}}async function dispatchWorkflowCall(e){let{entry:t}=e.task;switch(t.entryPoint){case`execute`:return await startWorkflowTask(e);case`task`:case`serve`:return await startTaskRun({...e,entry:t});case`receive`:return await sendToTask({...e,taskId:t.taskId})}}export{dispatchCoordinationStep};
|
|
1
|
+
import{createDurableSessionState}from"#execution/durable-session-store.js";import{prepareCoordinationDispatch}from"#execution/coordination-dispatch-shared.js";import{publishSessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{startWorkflowTask}from"#execution/tools/workflow/start.js";import{sendToTask,startTaskRun}from"#execution/tasks/start.js";import{captureAgentSessionContext,resolveStepAgentLimits}from"#execution/agent-sessions/context.js";async function dispatchCoordinationStep(e){"use step";return await withSessionStateDelta(e,dispatchCoordination)}async function dispatchCoordination(e){let t=await prepareCoordinationDispatch({serializedContext:e.serializedContext,sessionState:e.sessionState});if(t===void 0)return{results:[],serializedContext:e.serializedContext,sessionState:e.sessionState};let{batch:n,session:r}=t,i=r,a=[],o=[],s=resolveStepAgentLimits(t);for(let r of t.plan){let c=await dispatchWorkflowCall({agentContext:captureAgentSessionContext(t,r.callId,s),auth:{current:n.approvers?.[r.callId]??t.auth,initiator:t.initiatorAuth},batchEvent:n.event,owner:e.workflowToolRunOwner,parentSession:t.parentSession,session:i,task:r});i=c.session,c.result!==void 0&&a.push(c.result),c.started!==void 0&&o.push(c.started)}return{results:a,...await publishSessionEvents({serializedContext:e.serializedContext,sessionState:i===r?t.sessionState:createDurableSessionState({session:i}),sessionWritable:e.sessionWritable},o)}}async function dispatchWorkflowCall(e){let{entry:t}=e.task;switch(t.entryPoint){case`execute`:return await startWorkflowTask(e);case`task`:case`serve`:return await startTaskRun({...e,entry:t});case`receive`:return await sendToTask({...e,taskId:t.taskId})}}export{dispatchCoordinationStep};
|
|
@@ -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.71.
|
|
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.71.3//runWorkflowProgramTask`;export{runWorkflowProgramTask};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { InvokeToolOptions, InvokeToolResult } from "#channel/invoke-tool.js";
|
|
2
|
+
import { type CompiledToolBindings } from "#channel/tool-eligibility.js";
|
|
3
|
+
import type { CompiledToolDefinition } from "#compiler/manifest.js";
|
|
4
|
+
import type { HarnessToolMap } from "#harness/types.js";
|
|
5
|
+
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
|
|
6
|
+
import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
|
|
7
|
+
import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
|
|
8
|
+
import { type InvokeToolTraceOrigin } from "#tracing/invoke-tool-span.js";
|
|
9
|
+
/** What `invokeTool` needs from the agent: its static tools and sandbox. */
|
|
10
|
+
export interface InvokeToolRuntime {
|
|
11
|
+
/** Present in a deployed agent so framework helpers can reach the compiled graph. */
|
|
12
|
+
readonly bundle?: CompiledRuntimeAgentBundle;
|
|
13
|
+
/** Base URL for framework callbacks, such as the page a sign-in lands on. */
|
|
14
|
+
readonly callbackBaseUrl: string;
|
|
15
|
+
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
|
|
16
|
+
/** The root node's compiled tools and source bindings, which decide invocability. */
|
|
17
|
+
readonly manifest: InvokeToolManifest;
|
|
18
|
+
readonly nodeId: string;
|
|
19
|
+
/** The agent's name, for trace policy and `gen_ai.agent.name`. */
|
|
20
|
+
readonly agentName: string;
|
|
21
|
+
/** The channel the call arrived on, for trace policy and span attributes. */
|
|
22
|
+
readonly origin?: InvokeToolTraceOrigin;
|
|
23
|
+
readonly sandboxRegistry: RuntimeSandboxRegistry;
|
|
24
|
+
/** Static tools only: dynamic resolvers never run outside a turn. */
|
|
25
|
+
readonly tools: HarnessToolMap;
|
|
26
|
+
}
|
|
27
|
+
/** The part of a compiled manifest `invokeTool` reads to decide invocability. */
|
|
28
|
+
export interface InvokeToolManifest extends CompiledToolBindings {
|
|
29
|
+
readonly tools: readonly Pick<CompiledToolDefinition, "behavior" | "hasExecute" | "name" | "sourceId">[];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Runs one tool outside a turn; see `InvokeToolFn` for the contract. Each call
|
|
33
|
+
* gets a fresh session id, so nothing it opens is shared with another call.
|
|
34
|
+
*/
|
|
35
|
+
export declare function invokeTool(runtime: InvokeToolRuntime, name: string, input: unknown, options: InvokeToolOptions): Promise<InvokeToolResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{compiledToolOwner,isInvocableCompiledTool}from"#channel/tool-eligibility.js";import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SandboxKey,SessionIdKey,SessionKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{ensureSandboxAccess}from"#execution/sandbox/ensure.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{isConnectionAuthorizationFailedError}from"#connections/errors.js";import{AuthorizationHookKey,CallbackBaseUrlKey,isAuthorizationSignal,modelFacingAuthorizationOutput}from"#harness/authorization.js";import{checkToolCallInput,toolCallModelOutput}from"#harness/tool-call-io.js";import{normalizeToolJsonOutput}from"#harness/tool-model-output.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{createUlid}from"#shared/ulid.js";import{withInvokeToolSpan}from"#tracing/invoke-tool-span.js";const log=createLogger(`invoke-tool`);function ineligibility(e,t){if(!isInvocableCompiledTool(e,t))return compiledToolOwner(e,t).kind===`framework`?`it is a framework tool, which needs a conversation`:t.behavior?.handling===void 0?`it has no server-side execute`:`the harness or the model provider runs it, not its execute`}async function invokeTool(e,t,n,r){let i=e.manifest.tools.find(e=>e.name===t),a=e.tools.get(t);if(i===void 0||a===void 0)return failed(`The agent has no tool named "${t}".`);let o=ineligibility(e.manifest,i)??(a.execute===void 0?`it has no server-side execute`:void 0);if(o!==void 0)return failed(`Tool "${t}" cannot be invoked outside a conversation: ${o}.`);let s=`call_${createUlid()}`,c=`call_session_${createUlid()}`;return await withInvokeToolSpan({agentName:e.agentName,auth:r.auth,callId:s,origin:e.origin,sessionId:c,toolName:t},i=>runInvocation({callId:s,definition:a,input:n,name:t,observer:i,options:r,runtime:e,sessionId:c}))}async function runInvocation(e){let{callId:t,definition:n,name:r,observer:i,options:a,runtime:o,sessionId:s}=e,c=await checkToolCallInput(n,e.input,t);if(c.kind===`threw`)return i.failedWith(c.error),failedFromError(c.error,r,`input validation failed`);if(c.kind===`invalid`)return{message:c.message,status:`invalid-input`};let l=await callSandbox(o,s),u=createCallContext({auth:a.auth,callId:t,callbackBaseUrl:o.callbackBaseUrl,sessionId:s});u.setVirtualContext(SandboxKey,l.access),o.bundle!==void 0&&u.setVirtualContext(BundleKey,o.bundle);try{return await contextStorage.run(u,()=>runCall({callId:t,definition:n,input:c.value,observer:i,signal:a.signal}))}finally{await l.release().catch(e=>{logError(log,`failed to delete a call's sandbox`,e,{sessionId:s,toolName:r})})}}async function callSandbox(e,t){let n=await ensureSandboxAccess({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId,ownsSandbox:!0,registry:e.sandboxRegistry,sessionId:t,state:null}),r;return{access:{...n,get(){let e=n.get();return r=e,e}},async release(){r!==void 0&&await r.catch(()=>null)!==null&&await n.delete?.()}}}function createCallContext(e){let t=new ContextContainer;return t.set(AuthKey,e.auth),t.set(InitiatorAuthKey,e.auth),t.set(SessionIdKey,e.sessionId),t.setVirtualContext(SessionKey,{auth:{current:e.auth,initiator:e.auth},sessionId:e.sessionId,turn:{id:e.callId,sequence:0}}),t.set(CallbackBaseUrlKey,e.callbackBaseUrl.replace(/\/$/,``)),t.setVirtualContext(AuthorizationHookKey,`invoke-tool:${e.callId}`),t}async function runCall(e){let{callId:t,definition:n,observer:r}=e,i=e.signal??new AbortController().signal;if(n.approval!==void 0){let a;try{a=await resolveApprovalPolicy(n.approval)({...buildCallbackContext(),abortSignal:i,approvedTools:new Set,callId:t,toolInput:e.input,toolName:n.name})}catch(e){return r.failedWith(e),failedFromError(e,n.name,`approval policy failed`)}let o=decideApproval(a);if(o.kind===`denied`)return denied(o.reason);if(o.kind===`user-approval`)return{status:`approval-required`}}let a={abortSignal:i,messages:[],toolCallId:t};await r.executing(e.input);let o,s,c=!1,l=performance.now(),elapsed=()=>performance.now()-l,u;try{o=await n.execute(e.input,a),isAsyncIterable(o)&&(o=await lastIterated(o)),c=!0,isAuthorizationSignal(o)||(s=normalizeToolJsonOutput({boundary:`execute`,output:o,toolCallId:t,toolName:n.name})),u=elapsed()}catch(e){return await r.executed({durationMs:elapsed(),error:e,type:`error`}),r.failedWith(e),c?failedFromError(e,n.name,`tool output could not be serialized`):isConnectionAuthorizationFailedError(e)?failed(toErrorMessage(e)):failedFromError(e,n.name,`tool execution failed`)}if(isAuthorizationSignal(o))return await r.executed({durationMs:u,output:modelFacingAuthorizationOutput(o),type:`result`}),{connections:o.challenges.map(e=>e.name),status:`authorization-required`};await r.executed({durationMs:u,output:s,type:`result`});try{return{modelOutput:await toolCallModelOutput(n,s,t),output:s,status:`completed`}}catch(e){return r.failedWith(e),failedFromError(e,n.name,`tool output could not be serialized`)}}function decideApproval(e){if(e===!0||e===`user-approval`)return{kind:`user-approval`};if(e===`denied`)return{kind:`denied`};if(typeof e==`object`&&e){if(e.type===`user-approval`)return{kind:`user-approval`};if(e.type===`denied`)return{kind:`denied`,reason:e.reason}}return{kind:`run`}}async function lastIterated(e){let t;for await(let n of e)t=n;return t}function denied(e){return e===void 0?{status:`denied`}:{reason:e,status:`denied`}}function failed(e){return{message:e,status:`failed`}}function failedFromError(e,t,n){let r=context.with(trace.deleteSpan(context.active()),()=>logError(log,`invokeTool ${n}`,e,{toolName:t}));return{errorId:r,message:`Tool "${t}" failed: ${n}. The error is logged with id ${r}.`,status:`failed`}}export{invokeTool};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ChannelAdapterContext } from "#channel/adapter.js";
|
|
2
2
|
import { type ContextContainer } from "#context/container.js";
|
|
3
3
|
import { type DurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
|
|
4
|
+
import type { HarnessTurnRef } from "#harness/emission-state.js";
|
|
4
5
|
import { type HarnessModelMessage } from "#harness/messages.js";
|
|
5
6
|
import type { HandleEventFn, HarnessSession, HarnessSessionBase } from "#harness/types.js";
|
|
6
7
|
import { type MessageStreamEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
@@ -93,7 +94,7 @@ export declare function publishFromSessionStep<T, R = undefined>(step: RestoredS
|
|
|
93
94
|
* releases it. Events reach the stream through `SessionEventPublisher.emit`.
|
|
94
95
|
*/
|
|
95
96
|
export interface SessionEventWriter {
|
|
96
|
-
/** Closes the session stream; only a terminal `done
|
|
97
|
+
/** Closes the session stream; only a terminal event (`done`, completion, or failure) does this. */
|
|
97
98
|
close(): Promise<void>;
|
|
98
99
|
/** Releases the writer lock so the next step can acquire it. Safe after `close()`. */
|
|
99
100
|
release(): void;
|
|
@@ -133,17 +134,20 @@ type TerminalSessionEvent = Extract<UnstampedMessageStreamEvent, {
|
|
|
133
134
|
/**
|
|
134
135
|
* Publishes a terminal `session.completed` or `session.failed` from outside a
|
|
135
136
|
* turn as the session's own event, through its channel adapter and
|
|
136
|
-
* instrumentation
|
|
137
|
+
* instrumentation, then closes the session stream so readers following it
|
|
138
|
+
* reach EOF. Stream-event hooks do not run: the ending session may not
|
|
137
139
|
* restore, and no turn scope remains for authored code. Never throws.
|
|
138
140
|
*
|
|
139
|
-
* When the context cannot be restored, the event is only stamped
|
|
140
|
-
* the stream
|
|
141
|
+
* When the context cannot be restored, the event is only stamped, written, and
|
|
142
|
+
* the stream closed: the one degraded write of a session event.
|
|
141
143
|
*/
|
|
142
144
|
export declare function publishTerminalSessionEvent(input: {
|
|
143
145
|
readonly errorId?: string;
|
|
144
146
|
readonly event: TerminalSessionEvent;
|
|
145
147
|
readonly serializedContext: Record<string, unknown>;
|
|
146
148
|
readonly sessionWritable: WritableStream<Uint8Array>;
|
|
149
|
+
/** The session's last turn, for channel handlers' `ctx.session.turn`. */
|
|
150
|
+
readonly turn?: HarnessTurnRef;
|
|
147
151
|
/** The turn the event ends, for instrumentation. */
|
|
148
152
|
readonly turnId?: string;
|
|
149
153
|
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{ParentSessionKey,TurnDeliveryIdsKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{forwardSessionInput}from"#execution/forward-session-input.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";const log=createLogger(`execution.publish-session-events`);async function publishSessionEvents(e,t){return await publishEventsFromStep(e,`own`,t)}async function relaySessionEvents(e,t){return await publishEventsFromStep(e,`relayed`,t)}async function publishEventsFromStep(e,t,n){if(n.length===0)return{serializedContext:e.serializedContext,sessionState:e.sessionState};let{published:r}=await publishFromSessionStep(await restoreSessionStep(e),{origin:t,async publish(e){for(let t of n)await e(t)}});return r}async function restoreSessionStep(e){return{ctx:await deserializeContext(e.serializedContext),durableSession:readDurableSession(e.sessionState),sessionWritable:e.sessionWritable}}async function publishFromSessionStep(e,t){let{ctx:n}=e,r=await publishInSessionScope(e,t),i=t.updateSession?.(r.session,r.result)??{session:r.session},a=reconcileSessionContinuationToken(n,i.session);return{published:{serializedContext:serializeContext(n),sessionState:createDurableSessionState({session:a}),...`history`in a&&{history:a.history}},result:i.result}}async function publishInSessionScope(e,t){let{ctx:n}=e,r=resolveEffectiveAgentRuntime(n.require(BundleKey),n),i=hydrateDurableSession({compactionOverrides:{thresholdPercent:r.thresholdPercent},durable:e.durableSession,turnAgent:r.turnAgent}),a=e.history===void 0?i:{...i,history:validateHarnessModelMessages(e.history)},o=t.origin===`own`?bindSessionInstrumentation({agentName:r.turnAgent.id,ctx:n,rootSessionId:a.rootSessionId??a.sessionId,sessionId:a.sessionId}):void 0,s=openSessionEventPublisher({ctx:n,inputSource:t.inputSource,origin:t.origin,sessionWritable:e.sessionWritable});try{return await withContextScope(n,a,async n=>{let r=o?.createHandleEvent({handleEvent:s.publish,turnId:activeTurnId(getHarnessEmissionState(e.durableSession.state))})??s.publish;return{result:await t.publish(r,n),session:n}})}finally{await o?.flush(),s.writer.release()}}function openSessionEventPublisher(e){let{ctx:t,origin:n}=e,r=createSessionEventDispatcher(e),i=openSessionEventWriter({deliveryIds:()=>n===`own`?t.get(TurnDeliveryIdsKey):void 0,sessionWritable:e.sessionWritable}),emit=async e=>await i.write(await r.deliver(e));return{dispatcher:r,writer:i,emit,async publish(e){await r.runHooks(await emit(e))}}}function createSessionEventDispatcher(e){let{ctx:t,inputSource:n}=e,r=t.require(ChannelKey),i=buildAdapterContext(r,t);return{adapterCtx:i,async deliver(e){let a=await forwardSessionInput(t,e,n)?e:await callAdapterEventHandler(r,e,n===void 0?i:{...i,inputSource:n});return setChannelContext(t,{...r,state:{...i.state}}),a},async runHooks(e,n){await dispatchStreamEventHooks({cancelTurn:n,ctx:t,event:e,registry:t.require(BundleKey).hookRegistry})}}}function openSessionEventWriter(e){let t=e.sessionWritable.getWriter(),n=!1,release=()=>{n||(n=!0,t.releaseLock())};return{async write(n){let r=stampMessageStreamEvent(n,e.deliveryIds());return await t.write(encodeMessageStreamEvent(r)),r},close:async()=>{await t.close(),release()},release}}async function publishTerminalSessionEvent(e){let t=e.serializedContext[`eve.sessionId`]??``,n={errorId:e.errorId,sessionId:t},{type:r}=e.event,i,a;try{i=await deserializeContext(e.serializedContext),a=openSessionEventPublisher({ctx:i,origin:`own`,sessionWritable:e.sessionWritable})}catch(t){log.error(`failed to restore context for terminal ${r} event`,{...n,error:t}),await writeUnroutedSessionEvent(e.sessionWritable,e.event).catch(e=>log.error(`failed to write terminal ${r} event`,{...n,error:e}));return}let publish=async e=>{await a.emit(e)},
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,ParentSessionKey,SessionKey,TurnDeliveryIdsKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{forwardSessionInput}from"#execution/forward-session-input.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";const log=createLogger(`execution.publish-session-events`);async function publishSessionEvents(e,t){return await publishEventsFromStep(e,`own`,t)}async function relaySessionEvents(e,t){return await publishEventsFromStep(e,`relayed`,t)}async function publishEventsFromStep(e,t,n){if(n.length===0)return{serializedContext:e.serializedContext,sessionState:e.sessionState};let{published:r}=await publishFromSessionStep(await restoreSessionStep(e),{origin:t,async publish(e){for(let t of n)await e(t)}});return r}async function restoreSessionStep(e){return{ctx:await deserializeContext(e.serializedContext),durableSession:readDurableSession(e.sessionState),sessionWritable:e.sessionWritable}}async function publishFromSessionStep(e,t){let{ctx:n}=e,r=await publishInSessionScope(e,t),i=t.updateSession?.(r.session,r.result)??{session:r.session},a=reconcileSessionContinuationToken(n,i.session);return{published:{serializedContext:serializeContext(n),sessionState:createDurableSessionState({session:a}),...`history`in a&&{history:a.history}},result:i.result}}async function publishInSessionScope(e,t){let{ctx:n}=e,r=resolveEffectiveAgentRuntime(n.require(BundleKey),n),i=hydrateDurableSession({compactionOverrides:{thresholdPercent:r.thresholdPercent},durable:e.durableSession,turnAgent:r.turnAgent}),a=e.history===void 0?i:{...i,history:validateHarnessModelMessages(e.history)},o=t.origin===`own`?bindSessionInstrumentation({agentName:r.turnAgent.id,ctx:n,rootSessionId:a.rootSessionId??a.sessionId,sessionId:a.sessionId}):void 0,s=openSessionEventPublisher({ctx:n,inputSource:t.inputSource,origin:t.origin,sessionWritable:e.sessionWritable});try{return await withContextScope(n,a,async n=>{let r=o?.createHandleEvent({handleEvent:s.publish,turnId:activeTurnId(getHarnessEmissionState(e.durableSession.state))})??s.publish;return{result:await t.publish(r,n),session:n}})}finally{await o?.flush(),s.writer.release()}}function openSessionEventPublisher(e){let{ctx:t,origin:n}=e,r=createSessionEventDispatcher(e),i=openSessionEventWriter({deliveryIds:()=>n===`own`?t.get(TurnDeliveryIdsKey):void 0,sessionWritable:e.sessionWritable}),emit=async e=>await i.write(await r.deliver(e));return{dispatcher:r,writer:i,emit,async publish(e){await r.runHooks(await emit(e))}}}function createSessionEventDispatcher(e){let{ctx:t,inputSource:n}=e,r=t.require(ChannelKey),i=buildAdapterContext(r,t);return{adapterCtx:i,async deliver(e){let a=await forwardSessionInput(t,e,n)?e:await callAdapterEventHandler(r,e,n===void 0?i:{...i,inputSource:n});return setChannelContext(t,{...r,state:{...i.state}}),a},async runHooks(e,n){await dispatchStreamEventHooks({cancelTurn:n,ctx:t,event:e,registry:t.require(BundleKey).hookRegistry})}}}function openSessionEventWriter(e){let t=e.sessionWritable.getWriter(),n=!1,release=()=>{n||(n=!0,t.releaseLock())};return{async write(n){let r=stampMessageStreamEvent(n,e.deliveryIds());return await t.write(encodeMessageStreamEvent(r)),r},close:async()=>{await t.close(),release()},release}}async function publishTerminalSessionEvent(e){let t=e.serializedContext[`eve.sessionId`]??``,n={errorId:e.errorId,sessionId:t},{type:r}=e.event,i,a;try{i=await deserializeContext(e.serializedContext),a=openSessionEventPublisher({ctx:i,origin:`own`,sessionWritable:e.sessionWritable})}catch(t){log.error(`failed to restore context for terminal ${r} event`,{...n,error:t}),await writeUnroutedSessionEvent(e.sessionWritable,e.event).catch(e=>log.error(`failed to write terminal ${r} event`,{...n,error:e}));return}let o=i.get(AuthKey)??null;i.setVirtualContext(SessionKey,{auth:{current:o,initiator:i.get(InitiatorAuthKey)??o},parent:i.get(ParentSessionKey),sessionId:t,turn:e.turn??{id:`turn_0`,sequence:0}});let publish=async e=>{await a.emit(e),await a.writer.close()},s;try{s=bindSessionInstrumentation({agentName:i.require(BundleKey).turnAgent.id,ctx:i,rootSessionId:i.get(ParentSessionKey)?.rootSessionId??t,sessionId:t})}catch(e){log.error(`failed to bind instrumentation for terminal ${r} event`,{...n,error:e})}let c=s?.createHandleEvent({handleEvent:publish,turnId:e.turnId})??publish;try{await contextStorage.run(i,()=>c(e.event))}catch(e){log.error(`failed to publish terminal ${r} event`,{...n,error:e})}finally{a.writer.release();try{await s?.flush()}catch(e){log.error(`failed to flush instrumentation after terminal ${r} event`,{...n,error:e})}}}async function writeUnroutedSessionEvent(e,t){let n=openSessionEventWriter({deliveryIds:()=>void 0,sessionWritable:e});try{await n.write(t),await n.close()}finally{n.release()}}export{openSessionEventPublisher,publishFromSessionStep,publishSessionEvents,publishTerminalSessionEvent,relaySessionEvents,restoreSessionStep};
|
|
@@ -15,6 +15,12 @@ export declare function trackActiveSandboxHandle(input: {
|
|
|
15
15
|
readonly handle: ShutdownCapableSandboxHandle;
|
|
16
16
|
readonly sessionId: string;
|
|
17
17
|
}): void;
|
|
18
|
+
/** Drops a handle from shutdown tracking, unless a newer handle replaced it. */
|
|
19
|
+
export declare function untrackActiveSandboxHandle(input: {
|
|
20
|
+
readonly providerName: string;
|
|
21
|
+
readonly handle: ShutdownCapableSandboxHandle;
|
|
22
|
+
readonly sessionId: string;
|
|
23
|
+
}): void;
|
|
18
24
|
/**
|
|
19
25
|
* Stops every tracked sandbox by invoking its runtime-shutdown hook in
|
|
20
26
|
* parallel, then clears the registry. Failures are logged and never
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorMessage}from"#shared/errors.js";const activeSandboxHandles=new Map;function createActiveSandboxHandleKey(e,t){return`${e}\0${t}`}function trackActiveSandboxHandle(e){activeSandboxHandles.set(createActiveSandboxHandleKey(e.providerName,e.sessionId),e.handle)}async function shutdownActiveSandboxHandles(e){let t=[...activeSandboxHandles.entries()];activeSandboxHandles.clear();let n=await Promise.allSettled(t.map(([,e])=>e.onRuntimeShutdown()));for(let[r,i]of n.entries())if(i.status===`rejected`){let n=t[r];e?.log?.(`failed to shut down sandbox "${n?.[0]??`unknown`}": ${toErrorMessage(i.reason)}`)}}export{shutdownActiveSandboxHandles,trackActiveSandboxHandle};
|
|
1
|
+
import{toErrorMessage}from"#shared/errors.js";const activeSandboxHandles=new Map;function createActiveSandboxHandleKey(e,t){return`${e}\0${t}`}function trackActiveSandboxHandle(e){activeSandboxHandles.set(createActiveSandboxHandleKey(e.providerName,e.sessionId),e.handle)}function untrackActiveSandboxHandle(e){let t=createActiveSandboxHandleKey(e.providerName,e.sessionId);activeSandboxHandles.get(t)===e.handle&&activeSandboxHandles.delete(t)}async function shutdownActiveSandboxHandles(e){let t=[...activeSandboxHandles.entries()];activeSandboxHandles.clear();let n=await Promise.allSettled(t.map(([,e])=>e.onRuntimeShutdown()));for(let[r,i]of n.entries())if(i.status===`rejected`){let n=t[r];e?.log?.(`failed to shut down sandbox "${n?.[0]??`unknown`}": ${toErrorMessage(i.reason)}`)}}export{shutdownActiveSandboxHandles,trackActiveSandboxHandle,untrackActiveSandboxHandle};
|