eve 0.60.0 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/src/chunks/{use-eve-agent-Dmc6sX4d.js → use-eve-agent-C5-yqRuq.js} +177 -85
- package/dist/src/chunks/{use-eve-agent-jSR8P4nK.js → use-eve-agent-CVWk5KKy.js} +177 -85
- package/dist/src/cli/agent-command.js +1 -1
- package/dist/src/cli/dev/local-server-child.js +1 -1
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/client/client.d.ts +3 -1
- package/dist/src/client/client.js +1 -1
- package/dist/src/client/eve-agent-projection.d.ts +1 -0
- package/dist/src/client/eve-agent-projection.js +1 -1
- package/dist/src/client/eve-agent-store-helpers.js +1 -1
- package/dist/src/client/eve-agent-store-state.d.ts +4 -1
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/message-response.d.ts +5 -0
- package/dist/src/client/message-response.js +1 -1
- package/dist/src/client/optimistic-message-submissions.d.ts +22 -0
- package/dist/src/client/optimistic-message-submissions.js +1 -0
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +6 -6
- package/dist/src/compiled/@workflow/core/index.js +1 -1
- package/dist/src/compiled/@workflow/core/log-format.d.ts +4 -0
- package/dist/src/compiled/@workflow/core/runtime/helpers.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime.js +5 -3
- package/dist/src/compiled/@workflow/core/serialization.js +1 -1
- package/dist/src/compiled/@workflow/core/types.d.ts +22 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/world/runs.d.ts +12 -1
- package/dist/src/compiled/@workflow/world-local/index.js +3 -3
- package/dist/src/compiled/@workflow/world-vercel/index.js +7 -7
- package/dist/src/compiled/_chunks/workflow/{attribute-changes-3SKHZsSX.js → attribute-changes-A6HfMNG3.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{dist-DearXsdS.js → dist-D38gP7YF.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/frames-QcJfYHmh.js +3 -0
- package/dist/src/compiled/_chunks/workflow/helpers-6kObVbfS.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{logger-CxBCNokg.js → logger-NN5YHpYy.js} +6 -5
- package/dist/src/compiled/_chunks/workflow/{resume-hook-B7_MC7FC.js → resume-hook-CAqlhwic.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{run-jGFog1uQ.js → run-DJevv8zz.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{serialization-VRHEKI6l.js → serialization-C5KgPESk.js} +3 -3
- package/dist/src/compiled/_chunks/workflow/sleep-CbUwdv6O.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{wait-until-DDJySKt-.js → wait-until-BMY_tOr-.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{ws-transport-CEFNBXPC.js → ws-transport-DSDcKH08.js} +1 -1
- package/dist/src/compiler/default-tool-policy.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +18 -18
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +5 -2
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-tool.js +1 -1
- package/dist/src/compiler/project-sources.js +1 -1
- package/dist/src/compiler/validate-artifact.js +1 -1
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/dynamic-tool-metadata.d.ts +1 -0
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.d.ts +2 -0
- 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/node-step.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.d.ts +5 -0
- package/dist/src/execution/tools/agent-router-workflow.js +1 -0
- package/dist/src/execution/tools/agent-router.d.ts +9 -0
- package/dist/src/execution/tools/agent-router.js +1 -0
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/metadata.d.ts +4 -0
- package/dist/src/execution/tools/subagent/metadata.js +1 -0
- package/dist/src/execution/tools/workflow/body.d.ts +3 -0
- package/dist/src/execution/tools/workflow/body.js +1 -1
- package/dist/src/execution/tools/workflow/start.d.ts +1 -0
- package/dist/src/execution/tools/workflow/start.js +1 -1
- package/dist/src/execution/tools/workflow/types.d.ts +2 -0
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +1 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/authored-runtime-modules.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +1 -0
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/development-generation.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/extension-distribution.js +1 -1
- package/dist/src/internal/nitro/host.js +1 -1
- package/dist/src/internal/node-esm-compat-banner.js +3 -3
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.d.ts +1 -0
- package/dist/src/internal/workflow-bundle/builder-support.js +1 -1
- package/dist/src/internal/workflow-bundle/builder.js +1 -1
- package/dist/src/internal/workflow-bundle/nitro-step-entry.d.ts +1 -0
- package/dist/src/internal/workflow-bundle/nitro-step-entry.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-directive-ast.d.ts +1 -0
- package/dist/src/internal/workflow-bundle/workflow-directive-ast.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +1 -1
- package/dist/src/protocol/message.d.ts +4 -0
- package/dist/src/protocol/message.js +1 -1
- package/dist/src/public/tools/agent-router.d.ts +1 -0
- package/dist/src/public/tools/agent-router.js +1 -0
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/tools/registry.js +1 -1
- package/dist/src/services/dev-client/agent-info-probe.d.ts +1 -0
- package/dist/src/services/dev-client/agent-info-probe.js +1 -1
- package/dist/src/setup/primitives/pm/pnpm.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/map-concurrent.d.ts +2 -0
- package/dist/src/shared/map-concurrent.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/definition.d.ts +2 -0
- package/dist/src/tools/dynamic.d.ts +1 -0
- package/dist/src/tools/provided/agent-router.d.ts +7 -0
- package/dist/src/tools/provided/agent-router.js +1 -0
- package/dist/src/tools/workflow-definition.d.ts +6 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +32 -32
- package/docs/guides/client/overview.mdx +2 -0
- package/docs/guides/evaluate.md +1 -1
- package/docs/guides/frontend/overview.mdx +7 -3
- package/docs/reference/typescript-api.md +3 -1
- package/docs/subagents/index.mdx +3 -3
- package/docs/tools/overview.mdx +17 -0
- package/docs/tools/workflows.mdx +99 -5
- package/package.json +12 -7
- package/dist/src/compiled/_chunks/workflow/frames-Bm_yZi8X.js +0 -3
- package/dist/src/compiled/_chunks/workflow/helpers-K7otPd_U.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-60eDbac6.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toError}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";import{Client}from"#client/client.js";import{consumeMessageResponse}from"#client/message-response.js";import{SessionEventStream}from"#client/session-event-stream.js";import{EveAgentProjection}from"#client/eve-agent-projection.js";import{assertExclusiveTurnInput,createAbortSignal,createActiveTurn,createSubmissionId,followSteeredTurns,isAbortError,isSettledSessionTail,summarizeUserContent,toTerminalStreamFailureError,waitWithSignal}from"#client/eve-agent-store-helpers.js";const detachStore=Symbol(`detachEveAgentStore`),attachStore=Symbol(`attachEveAgentStore`);var EveAgentStore=class{#e;#t;#n=!1;#r;#i=new Set;#a;#o;#s;#c=new Set;#l=createEventDeduper();#u;#d={};#f;#p;#m=[];#h=0;#g;#_;#v;#y;#b;#x=`ready`;constructor(e){this.#t=e.prewarm??!1,this.#a=e.session!==void 0,this.#e=this.#a?void 0:new Client({auth:e.auth,headers:e.headers,host:e.host??``});let t=[];for(let n of e.initialEvents??[])this.#l.admit(n)&&t.push(n),updatePendingAuthorizations(this.#i,n);this.#p=t,this.#s=new EveAgentProjection(e.reducer,this.#p),this.#o=e.optimistic??!0,this.#y=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#b=this.#I()}get snapshot(){return this.#b}setCallbacks(e){this.#d=e}subscribe(e){return this.#c.add(e),()=>{this.#c.delete(e)}}prewarm(){if(this.#g!==void 0)return this.#g;if(this.#y!==void 0||this.#a)return Promise.resolve();if(this.#u!==void 0)return this.#u.response.then(e=>{if(e===void 0)throw this.#f??new DOMException(`Session creation was aborted.`,`AbortError`)});let e=this.#e;if(e===void 0)return Promise.reject(Error(`This eve agent store does not own a session client.`));let t=this.#h,n=new AbortController;this.#_=n;let r=(async()=>{try{let r=await e.sessions.create({signal:n.signal});if(t!==this.#h)return;this.#y=r.session,this.#f=void 0,this.#x===`error`&&(this.#x=`ready`),this.#d.onSessionChange?.(r.session.state),this.#L(),this.#E()}catch(e){throw t===this.#h&&this.#u===void 0&&this.#f===void 0&&(this.#f=toError(e),this.#x=`error`,this.#d.onError?.(this.#f),this.#L()),e}})();this.#g=r;let clear=()=>{this.#g===r&&(this.#g=void 0,this.#_=void 0)};return r.then(clear,clear),r}async send(e){return await this.#S(e,this.#d.prepareSend)}async#S(e,t){if(this.#u!==void 0){if(this.#x===`resuming`)throw Error(`eve session is resuming.`);return await this.#w(this.#u,e,t)}let n=createActiveTurn(e=>e.acceptedFollowUps>0&&this.#y!==void 0?this.#y.cancel():e.response.then(e=>e===void 0?{status:`no_active_turn`}:e.cancel()));this.#u=n,this.#f=void 0,this.#x=`submitted`,this.#L();let r;try{let i=await(t===void 0?e:waitWithSignal(Promise.resolve(t(e)),createAbortSignal(e.signal,n.abortController.signal)));if(assertExclusiveTurnInput(i),!this.#k(n))return;this.#A(i),this.#j(i),this.#L();let a={...i,signal:createAbortSignal(i.signal,n.abortController.signal)},o=await this.#T(a),s=o.response;if(r=o.reader,!this.#k(n))return;n.resolveResponse(s);for await(let e of consumeMessageResponse(s,r)){if(!this.#k(n))return;n.receivedFollowUpEvents.delete(e)&&(n.receivedFollowUps+=1)}if(!this.#k(n)||(await followSteeredTurns(n,r,()=>this.#k(n)),!this.#k(n)))return;this.#x=this.#f===void 0?`ready`:`error`}catch(e){if(!this.#k(n))return;if(isAbortError(e))this.#x=`ready`,this.#F(toError(e));else{let t=this.#f!==void 0;this.#f??=toError(e),this.#x=`error`,this.#F(this.#f),t||this.#d.onError?.(this.#f)}}finally{r?.[Symbol.dispose](),this.#O(n)}}resume(){if(this.#v!==void 0)return this.#v;let e=this.#C();this.#v=e;let clear=()=>{this.#v===e&&(this.#v=void 0)};return e.then(clear,clear),e}async#C(){if(this.#x===`resuming`||this.#x===`streaming`||this.#x===`submitted`)throw Error(`eve session is already processing a turn.`);if(this.#y===void 0)throw Error(`An eve session is required before resuming.`);let e=this.#y,t=createActiveTurn(()=>e.cancel());this.#u=t,t.resolveResponse(void 0),this.#f=void 0,this.#x=`resuming`,this.#L();try{let n=this.#E({catchUp:!0,startIndex:this.#p.length===e.state.streamIndex?e.state.streamIndex:0});using r=n.subscribe(t.abortController.signal);if(await n.caughtUp,!this.#k(t))return;r.discard();let i=this.#p.at(-1);if(i!==void 0&&this.#P(i),i!==void 0&&this.#f===void 0&&!isSettledSessionTail(this.#p)){this.#x=`streaming`,this.#L();for await(let e of r){if(!this.#k(t))return;if(t.receivedFollowUpEvents.delete(e)&&(t.receivedFollowUps+=1),isCurrentTurnBoundaryEvent(e)&&this.#i.size===0)break}}await followSteeredTurns(t,r,()=>this.#k(t)),this.#k(t)&&(this.#x=this.#f===void 0?`ready`:`error`)}catch(e){if(!this.#k(t))return;isAbortError(e)?this.#x=`ready`:(this.#f=toError(e),this.#x=`error`,this.#d.onError?.(this.#f))}finally{this.#O(t)}}cancel(){let e=this.#u;return e===void 0?this.#x===`streaming`&&this.#y!==void 0?this.#y.cancel():Promise.resolve({status:`no_active_turn`}):e.cancel()}[attachStore](){this.#n=!0,this.#t&&this.#y===void 0&&this.prewarm().catch(()=>{})}[detachStore](){this.#n=!1,this.#r?.close(),this.#r=void 0,this.#u?.abortController.abort(),this.#D(),this.#v=void 0}reset(){this.#r?.close(),this.#r=void 0,this.#i.clear();let e=this.#u;this.#u=void 0,e?.resolveResponse(void 0),e?.resolveCompletion(),e?.abortController.abort(),this.#D(),this.#v=void 0,this.#a||(this.#y=void 0),this.#p=[],this.#l=createEventDeduper(),this.#m=[],this.#s.reset(),this.#f=void 0,this.#x=`ready`,this.#d.onSessionChange?.(this.#y?.state),this.#L(),this.#t&&this.#n&&this.prewarm().catch(()=>{})}async#w(e,t,n){if(t.message===void 0||t.turnPolicy!==`steer`)throw Error(`eve session is already processing a turn. Send a message with turnPolicy: "steer" to guide it at the next boundary.`);let r=this.#h,i=createAbortSignal(t.signal,e.abortController.signal),a=await waitWithSignal(Promise.resolve(n?.(t)),i)??t;if(r!==this.#h)return;if(assertExclusiveTurnInput(a),a.message===void 0||a.turnPolicy!==`steer`)throw Error(`An in-flight follow-up requires a message with turnPolicy: "steer".`);if(!this.#k(e))return await this.#S(a);let o=this.#A(a);o!==void 0&&e.followUpSubmissionIds.add(o),this.#L(),this.#E({headers:a.headers,streamReconnectPolicy:a.streamReconnectPolicy});let s;s=(async()=>{try{let t=createAbortSignal(a.signal,e.abortController.signal);if(await waitWithSignal(e.response,t),!this.#k(e)||this.#y===void 0)throw Error(`The active eve turn ended before the follow-up could be sent.`);let{message:n,...r}=a;await this.#y.send(n,{...r,signal:t}),e.acceptedFollowUps+=1}catch(t){throw this.#k(e)&&(this.#F(toError(t),o),this.#L()),t}finally{e.followUpDispatches.delete(s)}})(),e.followUpDispatches.add(s),await s,await e.completion}async#T(e){let t={headers:e.headers,streamReconnectPolicy:e.streamReconnectPolicy};if(this.#g!==void 0&&(await waitWithSignal(this.#g.catch(e=>{if(this.#y!==void 0)throw e}),e.signal),e.signal?.throwIfAborted()),this.#y===void 0){if(this.#e===void 0)throw Error(`An external eve session is required before sending.`);if(e.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let n=await this.#e.sessions.create({...e,message:e.message});return e.signal?.throwIfAborted(),this.#y=n.session,this.#d.onSessionChange?.(n.session.state),this.#L(),{response:n.response,reader:this.#E(t).subscribe(e.signal)}}let n=this.#E(t).subscribe(e.signal);try{if(e.inputResponses===void 0){let{message:t,...r}=e;return{response:await this.#y.send(t,r),reader:n}}let{inputResponses:t,...r}=e;return{response:await this.#y.respond(t,r),reader:n}}catch(e){throw n[Symbol.dispose](),e}}#E(e={}){if(this.#r!==void 0&&!this.#r.ended)return this.#r.setOptions(e),this.#r;if(this.#y===void 0)throw Error(`A session is required before opening its stream.`);let t=this.#y,n=this.#h;return this.#r=new SessionEventStream(t,{...e,onEvent:e=>{n===this.#h&&this.#M(e)},onError:e=>{n===this.#h&&(this.#r=void 0,this.#u===void 0&&(this.#f=toError(e),this.#x=`error`,this.#d.onError?.(this.#f),this.#L()))}}),this.#r}#D(){this.#h+=1,this.#_?.abort(),this.#_=void 0,this.#g=void 0}#O(e){if(this.#k(e)){e.resolveResponse(void 0),this.#u=void 0;try{this.#d.onSessionChange?.(this.#y?.state),this.#L(),this.#d.onFinish?.(this.#b)}finally{e.resolveCompletion()}}}#k(e){return this.#u===e}#A(e){if(e.message===void 0)return;let t=createSubmissionId(),n={createdAt:Date.now(),id:t,message:summarizeUserContent(e.message)};return this.#m=[...this.#m,n],this.#o&&this.#s.append({data:{createdAt:n.createdAt,message:n.message,submissionId:n.id},type:`client.message.submitted`}),t}#j(e){e.inputResponses!==void 0&&e.inputResponses.length!==0&&this.#s.append({data:{createdAt:Date.now(),responses:e.inputResponses},type:`client.input.responded`})}#M(e){if(!this.#l.admit(e))return;let t=this.#x===`streaming`;updatePendingAuthorizations(this.#i,e),this.#p=[...this.#p,e],this.#N(e),this.#d.onEvent?.(e),this.#P(e);let n=isCurrentTurnBoundaryEvent(e)&&this.#i.size===0;this.#x!==`resuming`&&this.#f===void 0&&(`data`in e&&`turnId`in e.data&&(this.#x=`streaming`),this.#u===void 0&&n&&(this.#x=`ready`)),this.#d.onSessionChange?.(this.#y?.state),this.#L(),this.#u===void 0&&t&&n&&this.#d.onFinish?.(this.#b)}#N(e){let t=this.#m[0];if(e.type===`message.received`&&t!==void 0){let n=t.id;this.#u?.followUpSubmissionIds.delete(n)&&this.#u.receivedFollowUpEvents.add(e),this.#m=this.#m.slice(1),this.#s.replace(e=>e.type===`client.message.submitted`&&e.data.submissionId===n,e);return}this.#s.append(e)}#P(e){let t=toTerminalStreamFailureError(e);t!==void 0&&(this.#x=`error`,this.#F(t),this.#f===void 0&&(this.#f=t,this.#d.onError?.(t)))}#F(e,t){let n=t===void 0?this.#m[0]:this.#m.find(e=>e.id===t);n!==void 0&&(this.#m=this.#m.filter(e=>e.id!==n.id),this.#s.replace(e=>e.type===`client.message.submitted`&&e.data.submissionId===n.id,{data:{createdAt:n.createdAt,error:{message:e.message},message:n.message,submissionId:n.id},type:`client.message.failed`}))}#I(){return{data:this.#s.data,error:this.#f,events:this.#p,session:this.#y?.state,status:this.#x}}#L(){this.#b=this.#I();for(let e of this.#c)e()}};function detachEveAgentStore(e){e[detachStore]()}function attachEveAgentStore(e){e[attachStore]()}export{EveAgentStore,attachEveAgentStore,detachEveAgentStore};
|
|
1
|
+
import{toError}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";import{Client}from"#client/client.js";import{consumeMessageResponse,getMessageResponseDeliveryId}from"#client/message-response.js";import{SessionEventStream}from"#client/session-event-stream.js";import{EveAgentProjection}from"#client/eve-agent-projection.js";import{OptimisticMessageSubmissions}from"#client/optimistic-message-submissions.js";import{assertExclusiveTurnInput,createAbortSignal,createActiveTurn,followSteeredTurns,isAbortError,isSettledSessionTail,toTerminalStreamFailureError,waitWithSignal}from"#client/eve-agent-store-helpers.js";const detachStore=Symbol(`detachEveAgentStore`),attachStore=Symbol(`attachEveAgentStore`);var EveAgentStore=class{#e;#t;#n=!1;#r;#i=new Set;#a;#o;#s;#c=new Set;#l=createEventDeduper();#u;#d={};#f;#p;#m;#h=0;#g;#_;#v;#y;#b;#x=`ready`;constructor(e){this.#t=e.prewarm??!1,this.#a=e.session!==void 0,this.#e=this.#a?void 0:new Client({auth:e.auth,headers:e.headers,host:e.host??``});let t=[];for(let n of e.initialEvents??[])this.#l.admit(n)&&t.push(n),updatePendingAuthorizations(this.#i,n);this.#p=t,this.#s=new EveAgentProjection(e.reducer,this.#p),this.#o=e.optimistic??!0,this.#m=new OptimisticMessageSubmissions(this.#s,this.#o),this.#y=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#b=this.#P()}get snapshot(){return this.#b}setCallbacks(e){this.#d=e}subscribe(e){return this.#c.add(e),()=>{this.#c.delete(e)}}prewarm(){if(this.#g!==void 0)return this.#g;if(this.#y!==void 0||this.#a)return Promise.resolve();if(this.#u!==void 0)return this.#u.response.then(e=>{if(e===void 0)throw this.#f??new DOMException(`Session creation was aborted.`,`AbortError`)});let e=this.#e;if(e===void 0)return Promise.reject(Error(`This eve agent store does not own a session client.`));let t=this.#h,n=new AbortController;this.#_=n;let r=(async()=>{try{let r=await e.sessions.create({signal:n.signal});if(t!==this.#h)return;this.#y=r.session,this.#f=void 0,this.#x===`error`&&(this.#x=`ready`),this.#d.onSessionChange?.(r.session.state),this.#F(),this.#E()}catch(e){throw t===this.#h&&this.#u===void 0&&this.#f===void 0&&(this.#f=toError(e),this.#x=`error`,this.#d.onError?.(this.#f),this.#F()),e}})();this.#g=r;let clear=()=>{this.#g===r&&(this.#g=void 0,this.#_=void 0)};return r.then(clear,clear),r}async send(e){return await this.#S(e,this.#d.prepareSend)}async#S(e,t){if(this.#u!==void 0){if(this.#x===`resuming`)throw Error(`eve session is resuming.`);return await this.#w(this.#u,e,t)}let n=createActiveTurn(e=>e.acceptedFollowUps>0&&this.#y!==void 0?this.#y.cancel():e.response.then(e=>e===void 0?{status:`no_active_turn`}:e.cancel()));this.#u=n,this.#f=void 0,this.#x=`submitted`,this.#F();let r;try{let i=await(t===void 0?e:waitWithSignal(Promise.resolve(t(e)),createAbortSignal(e.signal,n.abortController.signal)));if(assertExclusiveTurnInput(i),!this.#k(n))return;let a=this.#m.submit(i,this.#p.length);this.#A(i),this.#F();let o={...i,signal:createAbortSignal(i.signal,n.abortController.signal)},s=await this.#T(o),c=s.response;if(r=s.reader,!this.#k(n))return;n.resolveResponse(c),this.#M(this.#m.correlate(a,getMessageResponseDeliveryId(c),this.#p))&&this.#F();for await(let e of consumeMessageResponse(c,r)){if(!this.#k(n))return;n.receivedFollowUps+=n.receivedFollowUpEvents.get(e)??0,n.receivedFollowUpEvents.delete(e)}if(!this.#k(n)||(await followSteeredTurns(n,r,()=>this.#k(n)),!this.#k(n)))return;this.#x=this.#f===void 0?`ready`:`error`}catch(e){if(!this.#k(n))return;if(isAbortError(e))this.#x=`ready`,this.#m.fail(toError(e));else{let t=this.#f!==void 0;this.#f??=toError(e),this.#x=`error`,this.#m.fail(this.#f),t||this.#d.onError?.(this.#f)}}finally{r?.[Symbol.dispose](),this.#O(n)}}resume(){if(this.#v!==void 0)return this.#v;let e=this.#C();this.#v=e;let clear=()=>{this.#v===e&&(this.#v=void 0)};return e.then(clear,clear),e}async#C(){if(this.#x===`resuming`||this.#x===`streaming`||this.#x===`submitted`)throw Error(`eve session is already processing a turn.`);if(this.#y===void 0)throw Error(`An eve session is required before resuming.`);let e=this.#y,t=createActiveTurn(()=>e.cancel());this.#u=t,t.resolveResponse(void 0),this.#f=void 0,this.#x=`resuming`,this.#F();try{let n=this.#E({catchUp:!0,startIndex:this.#p.length===e.state.streamIndex?e.state.streamIndex:0});using r=n.subscribe(t.abortController.signal);if(await n.caughtUp,!this.#k(t))return;r.discard();let i=this.#p.at(-1);if(i!==void 0&&this.#N(i),i!==void 0&&this.#f===void 0&&!isSettledSessionTail(this.#p)){this.#x=`streaming`,this.#F();for await(let e of r){if(!this.#k(t))return;if(t.receivedFollowUps+=t.receivedFollowUpEvents.get(e)??0,t.receivedFollowUpEvents.delete(e),isCurrentTurnBoundaryEvent(e)&&this.#i.size===0)break}}await followSteeredTurns(t,r,()=>this.#k(t)),this.#k(t)&&(this.#x=this.#f===void 0?`ready`:`error`)}catch(e){if(!this.#k(t))return;isAbortError(e)?this.#x=`ready`:(this.#f=toError(e),this.#x=`error`,this.#d.onError?.(this.#f))}finally{this.#O(t)}}cancel(){let e=this.#u;return e===void 0?this.#x===`streaming`&&this.#y!==void 0?this.#y.cancel():Promise.resolve({status:`no_active_turn`}):e.cancel()}[attachStore](){this.#n=!0,this.#t&&this.#y===void 0&&this.prewarm().catch(()=>{})}[detachStore](){this.#n=!1,this.#r?.close(),this.#r=void 0,this.#u?.abortController.abort(),this.#D(),this.#v=void 0}reset(){this.#r?.close(),this.#r=void 0,this.#i.clear();let e=this.#u;this.#u=void 0,e?.resolveResponse(void 0),e?.resolveCompletion(),e?.abortController.abort(),this.#D(),this.#v=void 0,this.#a||(this.#y=void 0),this.#p=[],this.#l=createEventDeduper(),this.#m.reset(),this.#s.reset(),this.#f=void 0,this.#x=`ready`,this.#d.onSessionChange?.(this.#y?.state),this.#F(),this.#t&&this.#n&&this.prewarm().catch(()=>{})}async#w(e,t,n){if(t.message===void 0||t.turnPolicy!==`steer`)throw Error(`eve session is already processing a turn. Send a message with turnPolicy: "steer" to guide it at the next boundary.`);let r=this.#h,i=createAbortSignal(t.signal,e.abortController.signal),a=await waitWithSignal(Promise.resolve(n?.(t)),i)??t;if(r!==this.#h)return;if(assertExclusiveTurnInput(a),a.message===void 0||a.turnPolicy!==`steer`)throw Error(`An in-flight follow-up requires a message with turnPolicy: "steer".`);if(!this.#k(e))return await this.#S(a);let o=this.#m.submit(a,this.#p.length);o!==void 0&&e.followUpSubmissionIds.add(o),this.#F(),this.#E({headers:a.headers,streamReconnectPolicy:a.streamReconnectPolicy});let s;s=(async()=>{try{let t=createAbortSignal(a.signal,e.abortController.signal);if(await waitWithSignal(e.response,t),!this.#k(e)||this.#y===void 0)throw Error(`The active eve turn ended before the follow-up could be sent.`);let{message:n,...r}=a,i=await this.#y.send(n,{...r,signal:t});e.acceptedFollowUps+=1,this.#M(this.#m.correlate(o,getMessageResponseDeliveryId(i),this.#p))&&this.#F()}catch(t){throw this.#k(e)&&(this.#m.fail(toError(t),o),this.#F()),t}finally{e.followUpDispatches.delete(s)}})(),e.followUpDispatches.add(s),await s,await e.completion}async#T(e){let t={headers:e.headers,streamReconnectPolicy:e.streamReconnectPolicy};if(this.#g!==void 0&&(await waitWithSignal(this.#g.catch(e=>{if(this.#y!==void 0)throw e}),e.signal),e.signal?.throwIfAborted()),this.#y===void 0){if(this.#e===void 0)throw Error(`An external eve session is required before sending.`);if(e.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let n=await this.#e.sessions.create({...e,message:e.message});return e.signal?.throwIfAborted(),this.#y=n.session,this.#d.onSessionChange?.(n.session.state),this.#F(),{response:n.response,reader:this.#E(t).subscribe(e.signal)}}let n=this.#E(t).subscribe(e.signal);try{if(e.inputResponses===void 0){let{message:t,...r}=e;return{response:await this.#y.send(t,r),reader:n}}let{inputResponses:t,...r}=e;return{response:await this.#y.respond(t,r),reader:n}}catch(e){throw n[Symbol.dispose](),e}}#E(e={}){if(this.#r!==void 0&&!this.#r.ended)return this.#r.setOptions(e),this.#r;if(this.#y===void 0)throw Error(`A session is required before opening its stream.`);let t=this.#y,n=this.#h;return this.#r=new SessionEventStream(t,{...e,onEvent:e=>{n===this.#h&&this.#j(e)},onError:e=>{n===this.#h&&(this.#r=void 0,this.#u===void 0&&(this.#f=toError(e),this.#x=`error`,this.#d.onError?.(this.#f),this.#F()))}}),this.#r}#D(){this.#h+=1,this.#_?.abort(),this.#_=void 0,this.#g=void 0}#O(e){if(this.#k(e)){e.resolveResponse(void 0),this.#u=void 0;try{this.#d.onSessionChange?.(this.#y?.state),this.#F(),this.#d.onFinish?.(this.#b)}finally{e.resolveCompletion()}}}#k(e){return this.#u===e}#A(e){e.inputResponses!==void 0&&e.inputResponses.length!==0&&this.#s.append({data:{createdAt:Date.now(),responses:e.inputResponses},type:`client.input.responded`})}#j(e){if(!this.#l.admit(e))return;let t=this.#x===`streaming`;updatePendingAuthorizations(this.#i,e),this.#p=[...this.#p,e],this.#M(this.#m.apply(e)),this.#d.onEvent?.(e),this.#N(e);let n=isCurrentTurnBoundaryEvent(e)&&this.#i.size===0;this.#x!==`resuming`&&this.#f===void 0&&(`data`in e&&`turnId`in e.data&&(this.#x=`streaming`),this.#u===void 0&&n&&(this.#x=`ready`)),this.#d.onSessionChange?.(this.#y?.state),this.#F(),this.#u===void 0&&t&&n&&this.#d.onFinish?.(this.#b)}#M(e){if(e===void 0)return!1;let t=0;for(let n of e.ids)this.#u?.followUpSubmissionIds.delete(n)&&(t+=1);if(t>0&&this.#u!==void 0){if(e.alreadyProjected)this.#u.receivedFollowUps+=t;else{let n=this.#u.receivedFollowUpEvents.get(e.event)??0;this.#u.receivedFollowUpEvents.set(e.event,n+t)}}return!0}#N(e){let t=toTerminalStreamFailureError(e);t!==void 0&&(this.#x=`error`,this.#m.failAll(t),this.#f===void 0&&(this.#f=t,this.#d.onError?.(t)))}#P(){return{data:this.#s.data,error:this.#f,events:this.#p,session:this.#y?.state,status:this.#x}}#F(){this.#b=this.#P();for(let e of this.#c)e()}};function detachEveAgentStore(e){e[detachStore]()}function attachEveAgentStore(e){e[attachStore]()}export{EveAgentStore,attachEveAgentStore,detachEveAgentStore};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createAuthorizationCompletedPart,createAuthorizationRequiredPart}from"#client/authorization-message-parts.js";import{approvedApproval,createToolMetadata,mergeToolMetadata,normalizeActionRequest,normalizeActionResult,stringifyUnknown,toMessageInputRequest}from"#client/message-action-parts.js";import{optimisticUserMessageId,partKey,projectReceivedParts,removeStreamingToolPartsForTurn,upsertMessage}from"#client/message-reducer-primitives.js";import{messageRun}from"#client/message-run-parts.js";function defaultMessageReducer(){return{initial(){return{messages:[]}},reduce(e,t){return reduceMessageData(e,t)}}}function reduceMessageData(e,t){switch(t.type){case`client.message.submitted`:return upsertMessage(e,{id:optimisticUserMessageId(t.data.submissionId),metadata:{optimistic:!0,status:`submitted`},parts:[{type:`text`,text:t.data.message}],role:`user`});case`client.message.failed`:return upsertMessage(e,{id:optimisticUserMessageId(t.data.submissionId),metadata:{optimistic:!0,status:`failed`},parts:[{type:`text`,text:t.data.message}],role:`user`});case`client.input.responded`:{let n=e;for(let e of t.data.responses)n=respondToInputRequest(n,e);return n}case`input.resolved`:{let n=e;for(let e of t.data.resolutions)n=resolveInputRequest(n,e);return n}case`message.received`:return upsertMessage(e,{id:`${t.data.turnId}:user`,metadata:{status:`complete`,turnId:t.data.turnId},parts:projectReceivedParts(t.data.parts,t.data.message),role:`user`});case`step.started`:return updateAssistantMessage(e,t.data.turnId,e=>ensureStepStartPart(e,t.data.stepIndex));case`reasoning.appended`:return updateAssistantMessage(e,t.data.turnId,e=>messageRun.append(ensureStepStartPart(e,t.data.stepIndex),{delta:t.data.reasoningDelta,stepIndex:t.data.stepIndex,type:`reasoning`}));case`reasoning.completed`:return updateAssistantMessage(e,t.data.turnId,e=>messageRun.upsert(ensureStepStartPart(e,t.data.stepIndex),{state:`done`,stepIndex:t.data.stepIndex,text:t.data.reasoning,type:`reasoning`}));case`action.input.appended`:{let n=findToolPart(e,t.data.callId);if(n!==void 0&&n.state!==`input-streaming`)return e;let r={input:void 0,inputText:(n?.state===`input-streaming`?n.inputText:``)+t.data.inputTextDelta,state:`input-streaming`,stepIndex:t.data.stepIndex,toolCallId:t.data.callId,toolMetadata:n?.toolMetadata??{eve:{kind:`unknown`,name:t.data.toolName}},toolName:t.data.toolName,type:`dynamic-tool`};return n===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),r)):updateToolPart(e,t.data.callId,r)}case`actions.requested`:{let n=e;for(let e of t.data.actions){let r=normalizeActionRequest(e);n=updateAssistantMessage(n,t.data.turnId,n=>upsertPart(ensureStepStartPart(n,t.data.stepIndex),{input:`input`in e?e.input:void 0,state:`input-available`,stepIndex:t.data.stepIndex,toolCallId:e.callId,toolMetadata:createToolMetadata(r),toolName:r.toolName,type:`dynamic-tool`}))}return n}case`input.requested`:{let n=e;for(let e of t.data.requests){let r=normalizeActionRequest(e.action);n=updateAssistantMessage(n,t.data.turnId,n=>upsertPart(ensureStepStartPart(n,t.data.stepIndex),{approval:{id:e.requestId},input:e.action.input,state:`approval-requested`,stepIndex:t.data.stepIndex,toolCallId:e.action.callId,toolMetadata:createToolMetadata(r,{inputRequest:toMessageInputRequest(e)}),toolName:r.toolName,type:`dynamic-tool`}))}return n}case`approval.candidate`:return e;case`approval.settled`:{let n=findToolPartByApprovalId(e,t.data.requestId);return n===void 0?e:t.data.outcome===`approved`?updateToolPart(e,n.toolCallId,{approval:{approved:!0,id:t.data.requestId,reason:void 0},input:n.input,state:`approval-responded`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:n.toolMetadata,toolName:n.toolName,type:`dynamic-tool`}):updateToolPart(e,n.toolCallId,{approval:{approved:!1,id:t.data.requestId,reason:`Tool execution was cancelled.`},input:n.input,state:`output-denied`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:n.toolMetadata,toolName:n.toolName,type:`dynamic-tool`})}case`action.result`:{let n=normalizeActionResult(t.data.result),r=findToolPart(e,t.data.result.callId),i=t.data.error?.code===`TOOL_EXECUTION_DENIED`,a=t.data.status===`failed`&&!i,o=r?.approval?.id??t.data.result.callId,s=mergeToolMetadata(r?.toolMetadata,createToolMetadata(n)),c={input:r?.input,stepIndex:t.data.stepIndex,toolCallId:t.data.result.callId,toolMetadata:s,toolName:r?.toolName??n.toolName,type:`dynamic-tool`},l;return l=i?{...c,approval:{approved:!1,id:o,reason:t.data.error?.message},state:`output-denied`}:a?{...c,approval:approvedApproval(r),errorText:t.data.error?.message??stringifyUnknown(t.data.result.output),state:`output-error`}:{...c,approval:approvedApproval(r),output:t.data.result.output,state:`output-available`},r===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),l)):updateToolPart(e,t.data.result.callId,l)}case`action.partial`:{let n=findToolPart(e,t.data.result.callId);if(n!==void 0&&isSettledToolPart(n))return e;let r=normalizeActionResult(t.data.result),i={approval:approvedApproval(n),input:n?.input,output:t.data.result.output,partial:!0,state:`output-available`,stepIndex:t.data.stepIndex,toolCallId:t.data.result.callId,toolMetadata:mergeToolMetadata(n?.toolMetadata,createToolMetadata(r)),toolName:n?.toolName??r.toolName,type:`dynamic-tool`};return n===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),i)):updateToolPart(e,t.data.result.callId,i)}case`authorization.required`:return updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),createAuthorizationRequiredPart(t)));case`authorization.completed`:return completeAuthorization(e,t);case`message.appended`:return updateAssistantMessage(e,t.data.turnId,e=>messageRun.append(ensureStepStartPart(e,t.data.stepIndex),{delta:t.data.messageDelta,stepIndex:t.data.stepIndex,type:`text`}));case`message.completed`:return updateAssistantMessage(e,t.data.turnId,e=>t.data.message===null?removeTextPart(e,t.data.stepIndex):messageRun.upsert(ensureStepStartPart(e,t.data.stepIndex),{state:`done`,stepIndex:t.data.stepIndex,text:t.data.message,type:`text`}));case`result.completed`:return updateAssistantMetadata(e,t.data.turnId,{result:t.data.result});case`turn.completed`:return updateAssistantMessage(e,t.data.turnId,e=>({...e,metadata:{...e.metadata,status:`complete`},parts:removeStreamingToolParts(e.parts)}));case`turn.cancelled`:return updateAssistantMessage(e,t.data.turnId,e=>({...e,metadata:{...e.metadata,status:`complete`},parts:removeStreamingToolParts(e.parts.map(e=>(e.type===`text`||e.type===`reasoning`)&&e.state===`streaming`?{...e,state:`done`}:e))}));case`turn.failed`:return removeStreamingToolPartsForTurn(e,t.data.turnId);case`session.failed`:return e;default:return e}}function removeStreamingToolParts(e){return e.filter(e=>e.type!==`dynamic-tool`||e.state!==`input-streaming`)}function respondToInputRequest(e,t){let n=findToolPartByApprovalId(e,t.requestId);if(!n)return e;let r={id:t.requestId};return t.text!==void 0&&(r.reason=t.text),updateToolPart(e,n.toolCallId,{approval:r,input:n.input,state:`approval-responded`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:mergeToolMetadata(n.toolMetadata,{eve:{inputResponse:t,kind:n.toolMetadata?.eve?.kind??`unknown`,name:n.toolMetadata?.eve?.name??n.toolName}}),toolName:n.toolName,type:`dynamic-tool`})}function resolveInputRequest(e,t){if(t.response!==void 0)return respondToInputRequest(e,t.response);let n=findToolPartByApprovalId(e,t.requestId);return n?updateToolPart(e,n.toolCallId,{input:n.input,output:{status:t.outcome},state:`output-available`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:n.toolMetadata,toolName:n.toolName,type:`dynamic-tool`}):e}function updateAssistantMessage(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.metadata?.turnId===t)??createAssistantMessage(t);return upsertMessage(e,n(r))}function updateAssistantMetadata(e,t,n){return updateAssistantMessage(e,t,e=>({...e,metadata:{...e.metadata,...n}}))}function createAssistantMessage(e){return{id:`${e}:assistant`,metadata:{status:`streaming`,turnId:e},parts:[],role:`assistant`}}function ensureStepStartPart(e,t){let n=e.parts.filter(e=>e.type===`step-start`).length;if(n>t)return e;let r=t-n+1;return{...e,parts:[...e.parts,...Array.from({length:r},()=>({type:`step-start`}))]}}function upsertPart(e,t){let n=e.parts.findIndex(e=>partKey(e)===partKey(t)),r=n===-1?[...e.parts,t]:[...e.parts.slice(0,n),t,...e.parts.slice(n+1)];return{...e,metadata:{...e.metadata,status:t.type===`text`&&t.state===`done`?`complete`:`streaming`},parts:r}}function removeTextPart(e,t){let n=e.parts.filter(e=>e.type!==`text`||e.stepIndex!==t);return n.length===e.parts.length?e:{...e,metadata:{...e.metadata,status:`complete`},parts:n}}function updateToolPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`dynamic-tool`&&e.toolCallId===t));return r?upsertMessage(e,upsertPart(r,n)):e}function completeAuthorization(e,t){let n=findLatestPendingAuthorizationPart(e,t.data.name),r=createAuthorizationCompletedPart(t,n);return n===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),r)):updateAuthorizationPart(e,n,r)}function updateAuthorizationPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e===t));return r?upsertMessage(e,upsertPart(r,n)):e}function findToolPart(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.toolCallId===t)return e}function isSettledToolPart(e){return e.state===`output-denied`||e.state===`output-error`||e.state===`output-available`&&e.partial!==!0}function findLatestPendingAuthorizationPart(e,t){for(let n=e.messages.length-1;n>=0;--n){let r=e.messages[n];if(r?.role===`assistant`)for(let e=r.parts.length-1;e>=0;--e){let n=r.parts[e];if(n?.type===`authorization`&&n.state===`required`&&n.name===t)return n}}}function findToolPartByApprovalId(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.approval?.id===t)return e}export{defaultMessageReducer};
|
|
1
|
+
import{createAuthorizationCompletedPart,createAuthorizationRequiredPart}from"#client/authorization-message-parts.js";import{approvedApproval,createToolMetadata,mergeToolMetadata,normalizeActionRequest,normalizeActionResult,stringifyUnknown,toMessageInputRequest}from"#client/message-action-parts.js";import{optimisticUserMessageId,partKey,projectReceivedParts,removeStreamingToolPartsForTurn,upsertMessage}from"#client/message-reducer-primitives.js";import{messageRun}from"#client/message-run-parts.js";function receivedMessageEventId(e){return e.meta.id??`${e.data.turnId}:${e.data.sequence}`}function defaultMessageReducer(){return{initial(){return{messages:[]}},reduce(e,t){return reduceMessageData(e,t)}}}function reduceMessageData(e,t){switch(t.type){case`client.message.submitted`:return upsertMessage(e,{id:optimisticUserMessageId(t.data.submissionId),metadata:{optimistic:!0,status:`submitted`},parts:[{type:`text`,text:t.data.message}],role:`user`});case`client.message.failed`:return upsertMessage(e,{id:optimisticUserMessageId(t.data.submissionId),metadata:{optimistic:!0,status:`failed`},parts:[{type:`text`,text:t.data.message}],role:`user`});case`client.input.responded`:{let n=e;for(let e of t.data.responses)n=respondToInputRequest(n,e);return n}case`input.resolved`:{let n=e;for(let e of t.data.resolutions)n=resolveInputRequest(n,e);return n}case`message.received`:return t.data.kind===`execution.background_task`?e:upsertMessage(e,{id:`${receivedMessageEventId(t)}:user`,metadata:{status:`complete`,turnId:t.data.turnId},parts:projectReceivedParts(t.data.parts,t.data.message),role:`user`});case`step.started`:return updateAssistantMessage(e,t.data.turnId,e=>ensureStepStartPart(e,t.data.stepIndex));case`reasoning.appended`:return updateAssistantMessage(e,t.data.turnId,e=>messageRun.append(ensureStepStartPart(e,t.data.stepIndex),{delta:t.data.reasoningDelta,stepIndex:t.data.stepIndex,type:`reasoning`}));case`reasoning.completed`:return updateAssistantMessage(e,t.data.turnId,e=>messageRun.upsert(ensureStepStartPart(e,t.data.stepIndex),{state:`done`,stepIndex:t.data.stepIndex,text:t.data.reasoning,type:`reasoning`}));case`action.input.appended`:{let n=findToolPart(e,t.data.callId);if(n!==void 0&&n.state!==`input-streaming`)return e;let r={input:void 0,inputText:(n?.state===`input-streaming`?n.inputText:``)+t.data.inputTextDelta,state:`input-streaming`,stepIndex:t.data.stepIndex,toolCallId:t.data.callId,toolMetadata:n?.toolMetadata??{eve:{kind:`unknown`,name:t.data.toolName}},toolName:t.data.toolName,type:`dynamic-tool`};return n===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),r)):updateToolPart(e,t.data.callId,r)}case`actions.requested`:{let n=e;for(let e of t.data.actions){let r=normalizeActionRequest(e);n=updateAssistantMessage(n,t.data.turnId,n=>upsertPart(ensureStepStartPart(n,t.data.stepIndex),{input:`input`in e?e.input:void 0,state:`input-available`,stepIndex:t.data.stepIndex,toolCallId:e.callId,toolMetadata:createToolMetadata(r),toolName:r.toolName,type:`dynamic-tool`}))}return n}case`input.requested`:{let n=e;for(let e of t.data.requests){let r=normalizeActionRequest(e.action);n=updateAssistantMessage(n,t.data.turnId,n=>upsertPart(ensureStepStartPart(n,t.data.stepIndex),{approval:{id:e.requestId},input:e.action.input,state:`approval-requested`,stepIndex:t.data.stepIndex,toolCallId:e.action.callId,toolMetadata:createToolMetadata(r,{inputRequest:toMessageInputRequest(e)}),toolName:r.toolName,type:`dynamic-tool`}))}return n}case`approval.candidate`:return e;case`approval.settled`:{let n=findToolPartByApprovalId(e,t.data.requestId);return n===void 0?e:t.data.outcome===`approved`?updateToolPart(e,n.toolCallId,{approval:{approved:!0,id:t.data.requestId,reason:void 0},input:n.input,state:`approval-responded`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:n.toolMetadata,toolName:n.toolName,type:`dynamic-tool`}):updateToolPart(e,n.toolCallId,{approval:{approved:!1,id:t.data.requestId,reason:`Tool execution was cancelled.`},input:n.input,state:`output-denied`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:n.toolMetadata,toolName:n.toolName,type:`dynamic-tool`})}case`action.result`:{let n=normalizeActionResult(t.data.result),r=findToolPart(e,t.data.result.callId),i=t.data.error?.code===`TOOL_EXECUTION_DENIED`,a=t.data.status===`failed`&&!i,o=r?.approval?.id??t.data.result.callId,s=mergeToolMetadata(r?.toolMetadata,createToolMetadata(n)),c={input:r?.input,stepIndex:t.data.stepIndex,toolCallId:t.data.result.callId,toolMetadata:s,toolName:r?.toolName??n.toolName,type:`dynamic-tool`},l;return l=i?{...c,approval:{approved:!1,id:o,reason:t.data.error?.message},state:`output-denied`}:a?{...c,approval:approvedApproval(r),errorText:t.data.error?.message??stringifyUnknown(t.data.result.output),state:`output-error`}:{...c,approval:approvedApproval(r),output:t.data.result.output,state:`output-available`},r===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),l)):updateToolPart(e,t.data.result.callId,l)}case`action.partial`:{let n=findToolPart(e,t.data.result.callId);if(n!==void 0&&isSettledToolPart(n))return e;let r=normalizeActionResult(t.data.result),i={approval:approvedApproval(n),input:n?.input,output:t.data.result.output,partial:!0,state:`output-available`,stepIndex:t.data.stepIndex,toolCallId:t.data.result.callId,toolMetadata:mergeToolMetadata(n?.toolMetadata,createToolMetadata(r)),toolName:n?.toolName??r.toolName,type:`dynamic-tool`};return n===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),i)):updateToolPart(e,t.data.result.callId,i)}case`authorization.required`:return updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),createAuthorizationRequiredPart(t)));case`authorization.completed`:return completeAuthorization(e,t);case`message.appended`:return updateAssistantMessage(e,t.data.turnId,e=>messageRun.append(ensureStepStartPart(e,t.data.stepIndex),{delta:t.data.messageDelta,stepIndex:t.data.stepIndex,type:`text`}));case`message.completed`:return updateAssistantMessage(e,t.data.turnId,e=>t.data.message===null?removeTextPart(e,t.data.stepIndex):messageRun.upsert(ensureStepStartPart(e,t.data.stepIndex),{state:`done`,stepIndex:t.data.stepIndex,text:t.data.message,type:`text`}));case`result.completed`:return updateAssistantMetadata(e,t.data.turnId,{result:t.data.result});case`turn.completed`:return updateAssistantMessage(e,t.data.turnId,e=>({...e,metadata:{...e.metadata,status:`complete`},parts:removeStreamingToolParts(e.parts)}));case`turn.cancelled`:return updateAssistantMessage(e,t.data.turnId,e=>({...e,metadata:{...e.metadata,status:`complete`},parts:removeStreamingToolParts(e.parts.map(e=>(e.type===`text`||e.type===`reasoning`)&&e.state===`streaming`?{...e,state:`done`}:e))}));case`turn.failed`:return removeStreamingToolPartsForTurn(e,t.data.turnId);case`session.failed`:return e;default:return e}}function removeStreamingToolParts(e){return e.filter(e=>e.type!==`dynamic-tool`||e.state!==`input-streaming`)}function respondToInputRequest(e,t){let n=findToolPartByApprovalId(e,t.requestId);if(!n)return e;let r={id:t.requestId};return t.text!==void 0&&(r.reason=t.text),updateToolPart(e,n.toolCallId,{approval:r,input:n.input,state:`approval-responded`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:mergeToolMetadata(n.toolMetadata,{eve:{inputResponse:t,kind:n.toolMetadata?.eve?.kind??`unknown`,name:n.toolMetadata?.eve?.name??n.toolName}}),toolName:n.toolName,type:`dynamic-tool`})}function resolveInputRequest(e,t){if(t.response!==void 0)return respondToInputRequest(e,t.response);let n=findToolPartByApprovalId(e,t.requestId);return n?updateToolPart(e,n.toolCallId,{input:n.input,output:{status:t.outcome},state:`output-available`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:n.toolMetadata,toolName:n.toolName,type:`dynamic-tool`}):e}function updateAssistantMessage(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.metadata?.turnId===t)??createAssistantMessage(t);return upsertMessage(e,n(r))}function updateAssistantMetadata(e,t,n){return updateAssistantMessage(e,t,e=>({...e,metadata:{...e.metadata,...n}}))}function createAssistantMessage(e){return{id:`${e}:assistant`,metadata:{status:`streaming`,turnId:e},parts:[],role:`assistant`}}function ensureStepStartPart(e,t){let n=e.parts.filter(e=>e.type===`step-start`).length;if(n>t)return e;let r=t-n+1;return{...e,parts:[...e.parts,...Array.from({length:r},()=>({type:`step-start`}))]}}function upsertPart(e,t){let n=e.parts.findIndex(e=>partKey(e)===partKey(t)),r=n===-1?[...e.parts,t]:[...e.parts.slice(0,n),t,...e.parts.slice(n+1)];return{...e,metadata:{...e.metadata,status:t.type===`text`&&t.state===`done`?`complete`:`streaming`},parts:r}}function removeTextPart(e,t){let n=e.parts.filter(e=>e.type!==`text`||e.stepIndex!==t);return n.length===e.parts.length?e:{...e,metadata:{...e.metadata,status:`complete`},parts:n}}function updateToolPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`dynamic-tool`&&e.toolCallId===t));return r?upsertMessage(e,upsertPart(r,n)):e}function completeAuthorization(e,t){let n=findLatestPendingAuthorizationPart(e,t.data.name),r=createAuthorizationCompletedPart(t,n);return n===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),r)):updateAuthorizationPart(e,n,r)}function updateAuthorizationPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e===t));return r?upsertMessage(e,upsertPart(r,n)):e}function findToolPart(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.toolCallId===t)return e}function isSettledToolPart(e){return e.state===`output-denied`||e.state===`output-error`||e.state===`output-available`&&e.partial!==!0}function findLatestPendingAuthorizationPart(e,t){for(let n=e.messages.length-1;n>=0;--n){let r=e.messages[n];if(r?.role===`assistant`)for(let e=r.parts.length-1;e>=0;--e){let n=r.parts[e];if(n?.type===`authorization`&&n.state===`required`&&n.name===t)return n}}}function findToolPartByApprovalId(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.approval?.id===t)return e}export{defaultMessageReducer};
|
|
@@ -6,9 +6,11 @@ import type { CancelSessionResult, MessageResult } from "#client/types.js";
|
|
|
6
6
|
interface MessageResponseInput {
|
|
7
7
|
readonly cancelTurn: (turnId: string) => Promise<CancelSessionResult>;
|
|
8
8
|
readonly createStream: (source?: AsyncIterable<MessageStreamEvent>) => AsyncGenerator<MessageStreamEvent>;
|
|
9
|
+
readonly deliveryId?: string;
|
|
9
10
|
readonly sessionId: string;
|
|
10
11
|
}
|
|
11
12
|
declare const consumeResponse: unique symbol;
|
|
13
|
+
declare const acceptedDeliveryId: unique symbol;
|
|
12
14
|
/**
|
|
13
15
|
* The response from {@link ClientSession.send}.
|
|
14
16
|
*
|
|
@@ -22,6 +24,7 @@ export declare class MessageResponse<TOutput = unknown> implements AsyncIterable
|
|
|
22
24
|
* Session ID assigned by the server.
|
|
23
25
|
*/
|
|
24
26
|
readonly sessionId: string;
|
|
27
|
+
readonly [acceptedDeliveryId]: string | undefined;
|
|
25
28
|
/** @internal */
|
|
26
29
|
constructor(input: MessageResponseInput);
|
|
27
30
|
/**
|
|
@@ -44,6 +47,8 @@ export declare class MessageResponse<TOutput = unknown> implements AsyncIterable
|
|
|
44
47
|
[Symbol.asyncIterator](): AsyncIterator<MessageStreamEvent>;
|
|
45
48
|
[consumeResponse](source?: AsyncIterable<MessageStreamEvent>): AsyncGenerator<MessageStreamEvent>;
|
|
46
49
|
}
|
|
50
|
+
/** @internal Returns the accepted message identity without consuming its response stream. */
|
|
51
|
+
export declare function getMessageResponseDeliveryId(response: MessageResponse): string | undefined;
|
|
47
52
|
/** @internal Observe a turn through the frontend's existing session stream. */
|
|
48
53
|
export declare function consumeMessageResponse(response: MessageResponse, source: AsyncIterable<MessageStreamEvent>): AsyncIterable<MessageStreamEvent>;
|
|
49
54
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{summarizeTurnEvents}from"#client/session-utils.js";import{extractCompletedResult}from"#client/output-schema.js";const consumeResponse=Symbol(`consumeMessageResponse`);var MessageResponse=class{sessionId;#e;#t;#n=!1;#r;#i=!1;#a=Promise.withResolvers();constructor(e){this.#e=e.cancelTurn,this.sessionId=e.sessionId,this.#r=e.createStream}cancel(){if(this.#i)return Promise.resolve({status:`no_active_turn`});if(this.#t!==void 0)return this.#t;let e=this.#a.promise.then(e=>e===void 0?{status:`no_active_turn`}:this.#e(e));return this.#t=e,e.catch(()=>{!this.#i&&this.#t===e&&(this.#t=void 0)}),e}async result(){let e=[];for await(let t of this)e.push(t);let t=summarizeTurnEvents(e);return{data:extractCompletedResult(e),events:e,inputRequests:t.inputRequests,message:t.message,sessionId:this.sessionId,status:t.status}}[Symbol.asyncIterator](){return this[consumeResponse]()}[consumeResponse](e){if(this.#n)throw Error(`MessageResponse has already been consumed.`);return this.#n=!0,this.#o(e)}async*#o(e){try{for await(let t of this.#r(e))t.type===`turn.started`?this.#a.resolve(t.data.turnId):isCurrentTurnBoundaryEvent(t)&&(this.#i=!0,this.#a.resolve(void 0)),yield t}finally{this.#a.resolve(void 0)}}};function consumeMessageResponse(e,t){return e[consumeResponse](t)}export{MessageResponse,consumeMessageResponse};
|
|
1
|
+
import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{summarizeTurnEvents}from"#client/session-utils.js";import{extractCompletedResult}from"#client/output-schema.js";const consumeResponse=Symbol(`consumeMessageResponse`),acceptedDeliveryId=Symbol(`acceptedDeliveryId`);var MessageResponse=class{sessionId;[acceptedDeliveryId];#e;#t;#n=!1;#r;#i=!1;#a=Promise.withResolvers();constructor(e){this.#e=e.cancelTurn,this.sessionId=e.sessionId,this[acceptedDeliveryId]=e.deliveryId,this.#r=e.createStream}cancel(){if(this.#i)return Promise.resolve({status:`no_active_turn`});if(this.#t!==void 0)return this.#t;let e=this.#a.promise.then(e=>e===void 0?{status:`no_active_turn`}:this.#e(e));return this.#t=e,e.catch(()=>{!this.#i&&this.#t===e&&(this.#t=void 0)}),e}async result(){let e=[];for await(let t of this)e.push(t);let t=summarizeTurnEvents(e);return{data:extractCompletedResult(e),events:e,inputRequests:t.inputRequests,message:t.message,sessionId:this.sessionId,status:t.status}}[Symbol.asyncIterator](){return this[consumeResponse]()}[consumeResponse](e){if(this.#n)throw Error(`MessageResponse has already been consumed.`);return this.#n=!0,this.#o(e)}async*#o(e){try{for await(let t of this.#r(e))t.type===`turn.started`?this.#a.resolve(t.data.turnId):isCurrentTurnBoundaryEvent(t)&&(this.#i=!0,this.#a.resolve(void 0)),yield t}finally{this.#a.resolve(void 0)}}};function getMessageResponseDeliveryId(e){return e[acceptedDeliveryId]}function consumeMessageResponse(e,t){return e[consumeResponse](t)}export{MessageResponse,consumeMessageResponse,getMessageResponseDeliveryId};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { EveAgentProjection } from "#client/eve-agent-projection.js";
|
|
2
|
+
import type { MessageStreamEvent } from "#protocol/message.js";
|
|
3
|
+
import type { SendTurnPayload } from "#client/types.js";
|
|
4
|
+
interface ReconciledSubmissions {
|
|
5
|
+
readonly alreadyProjected: boolean;
|
|
6
|
+
readonly event: Extract<MessageStreamEvent, {
|
|
7
|
+
readonly type: "message.received";
|
|
8
|
+
}>;
|
|
9
|
+
readonly ids: readonly string[];
|
|
10
|
+
}
|
|
11
|
+
/** Owns optimistic message projection and server-delivery reconciliation. */
|
|
12
|
+
export declare class OptimisticMessageSubmissions<TData> {
|
|
13
|
+
#private;
|
|
14
|
+
constructor(projection: EveAgentProjection<TData>, optimistic: boolean);
|
|
15
|
+
reset(): void;
|
|
16
|
+
submit(input: SendTurnPayload, eventStartIndex: number): string | undefined;
|
|
17
|
+
apply(event: MessageStreamEvent): ReconciledSubmissions | undefined;
|
|
18
|
+
correlate(submissionId: string | undefined, deliveryId: string | undefined, events: readonly MessageStreamEvent[]): ReconciledSubmissions | undefined;
|
|
19
|
+
fail(error: Error, submissionId?: string): void;
|
|
20
|
+
failAll(error: Error): void;
|
|
21
|
+
}
|
|
22
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"#client/eve-agent-projection.js";import{createSubmissionId,summarizeUserContent}from"#client/eve-agent-store-helpers.js";var OptimisticMessageSubmissions=class{#e;#t;#n=[];constructor(e,t){this.#t=e,this.#e=t}reset(){this.#n=[]}submit(e,t){if(e.message===void 0)return;let n={createdAt:Date.now(),eventStartIndex:t,id:createSubmissionId(),message:summarizeUserContent(e.message),requiresDeliveryId:!0};return this.#n=[...this.#n,n],this.#e&&this.#t.append({data:{createdAt:n.createdAt,message:n.message,submissionId:n.id},type:`client.message.submitted`}),n.id}apply(e){if(e.type!==`message.received`){this.#t.append(e);return}if(e.data.kind===`execution.background_task`){this.#t.append(e);return}let t=this.#r(e);if(t.length===0){this.#t.append(e);return}return this.#i(t,e,!1)}correlate(e,t,n){if(e===void 0)return;this.#n=this.#n.map(n=>n.id===e?{...n,deliveryId:t,requiresDeliveryId:t!==void 0}:n);let r=this.#n.find(t=>t.id===e);if(r!==void 0)for(let t of n.slice(r.eventStartIndex)){if(t.type!==`message.received`||t.data.kind===`execution.background_task`)continue;let n=this.#r(t);if(n.some(t=>t.id===e))return this.#i(n,t,!0)}}fail(e,t){let n=t===void 0?this.#n[0]:this.#n.find(e=>e.id===t);n!==void 0&&(this.#n=this.#n.filter(e=>e.id!==n.id),this.#t.replace(e=>e.type===`client.message.submitted`&&e.data.submissionId===n.id,{data:{createdAt:n.createdAt,error:{message:e.message},message:n.message,submissionId:n.id},type:`client.message.failed`}))}failAll(e){for(let t of this.#n)this.fail(e,t.id)}#r(e){return this.#n.filter(t=>t.deliveryId===void 0?!t.requiresDeliveryId:e.meta.deliveryIds?.includes(t.deliveryId)===!0)}#i(e,t,n){let r=e.map(e=>e.id),i=new Set(r);return this.#n=this.#n.filter(e=>!i.has(e.id)),n||this.#t.replace(e=>e.type===`client.message.submitted`&&e.data.submissionId===r[0],t),this.#t.remove(e=>e.type===`client.message.submitted`&&i.has(e.data.submissionId)),{alreadyProjected:n,event:t,ids:r}}};export{OptimisticMessageSubmissions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#tools/schema.js";const followSession=Symbol(`followClientSession`);var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(e,t){let n=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0),{sessionId:r}=await readAcceptedMessage(n),i=new ClientSession(e,{sessionId:r,streamIndex:0});return{response:i.#r(n,t,0),session:i}}static async prewarm(e,t={}){let{sessionId:n}=await readAcceptedMessage(await postCreateSession(e,t));return new ClientSession(e,{sessionId:n,streamIndex:0})}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#s({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e},!0)}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e},!1)}async#n(e,t){let n=this.#t.streamIndex,r=createEveSessionRoutePath(this.#t.sessionId),i=t?await postSessionSend(this.#e,r,e):await postTurn(this.#e,r,e,!1),{sessionId:a,deliveryId:o}=await readAcceptedMessage(i,this.#t.sessionId);if(a!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);if(e.message!==void 0&&o===void 0)throw Error(`Message route did not return a delivery id. Update the server before sending with this client.`);return this.#r(i,e,n,e.message===void 0?void 0:o)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}[followSession](e){return this.#a({...e,keepAlive:!0})}#r(e,t,n,r){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:e=>this.#i(n,t,r,e),sessionId:this.#t.sessionId})}async*#i(e,t,n,r){let i=0,a=n===void 0,o=!1,s=new Set;try{for await(let c of r??this.#s({headers:t.headers,keepAlive:!0,signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy})){if(i+=1,n!==void 0){let e=c.meta?.deliveryIds?.includes(n)===!0,t=c.type===`session.failed`||c.type===`session.completed`;if(!e&&t&&(!a||c.type===`session.completed`))throw Error(`The session ended before the accepted message reached its turn boundary.`);if(!a&&!e||!t&&c.meta?.deliveryIds!==void 0&&!e)continue;a=!0}if(updatePendingAuthorizations(s,c),o=isCurrentTurnBoundaryEvent(c)&&(c.type!==`session.waiting`||s.size===0),yield c,o)break}if(n!==void 0&&!o&&!t.signal?.aborted)throw Error(`The response stream ended before the accepted message reached its turn boundary.`)}finally{this.#o(e+i)}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;for await(let r of this.#s({follow:e?.follow,headers:e?.headers,keepAlive:e?.keepAlive,onCaughtUp:e?.onCaughtUp,resolveHeaders:e?.resolveHeaders,resolveReconnectPolicy:e?.resolveReconnectPolicy,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,t>=0&&this.#o(t+n),yield r}#o(e){this.#t={sessionId:this.#t.sessionId,streamIndex:Math.max(this.#t.streamIndex,e)}}#s(e){return followStreamIterable({onCaughtUp:e.onCaughtUp,follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.resolveHeaders?.()??e.headers),redirect:this.#e.redirect,sessionId:this.#t.sessionId,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy,resolveReconnectPolicy:e.resolveReconnectPolicy})}};function followClientSession(e,t){return e[followSession](t)}async function postSessionSend(e,t,n){let r=Date.now()+2e4,i=250;for(;;){try{return await postTurn(e,t,n,!1)}catch(e){if(!isSessionNotReady(e))throw e;let t=r-Date.now();if(t<=0)throw e;await sleep(Math.min(i,t),n.signal)}n.signal?.throwIfAborted(),i=Math.min(i*2,2e3)}}async function postCreateSession(e,t){let n=await e.resolveHeaders(t.headers),r=await fetch(createClientUrl(e.host,EVE_SESSION_ROUTE_PATH),{headers:n,method:`POST`,redirect:e.redirect,signal:t.signal??null});if(!r.ok){let e=await r.text();throw new ClientError(r.status,e,r.headers)}return r}function isSessionNotReady(e){return e instanceof ClientError&&e.status===409&&e.code===`session_not_ready`}async function postTurn(e,t,n,r){let i=createMessageBody(n,r);if(i===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let a=await e.resolveHeaders(n.headers);a.set(`content-type`,`application/json`);let o=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(i),headers:a,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!o.ok){let e=await o.text();throw new ClientError(o.status,e,o.headers)}return o}async function readAcceptedMessage(e,t){let n=await e.json(),r=(typeof n.sessionId==`string`?n.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!r)throw Error(`Message route did not return a session id.`);return{sessionId:r,deliveryId:typeof n.deliveryId==`string`&&n.deliveryId.length>0?n.deliveryId:void 0}}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession,followClientSession};
|
|
1
|
+
import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{updatePendingAuthorizations}from"#client/session-utils.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#tools/schema.js";const followSession=Symbol(`followClientSession`);var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(e,t){let n=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0),{sessionId:r}=await readAcceptedMessage(n),i=new ClientSession(e,{sessionId:r,streamIndex:0});return{response:i.#r(n,t,0),session:i}}static async prewarm(e,t={}){let{sessionId:n}=await readAcceptedMessage(await postCreateSession(e,t));return new ClientSession(e,{sessionId:n,streamIndex:0})}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#s({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e},!0)}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e},!1)}async#n(e,t){let n=this.#t.streamIndex,r=createEveSessionRoutePath(this.#t.sessionId),i=t?await postSessionSend(this.#e,r,e):await postTurn(this.#e,r,e,!1),{sessionId:a,deliveryId:o}=await readAcceptedMessage(i,this.#t.sessionId);if(a!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);if(e.message!==void 0&&o===void 0)throw Error(`Message route did not return a delivery id. Update the server before sending with this client.`);return this.#r(i,e,n,e.message===void 0?void 0:o)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}[followSession](e){return this.#a({...e,keepAlive:!0})}#r(e,t,n,r){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:e=>this.#i(n,t,r,e),deliveryId:r,sessionId:this.#t.sessionId})}async*#i(e,t,n,r){let i=0,a=n===void 0,o=!1,s=new Set;try{for await(let c of r??this.#s({headers:t.headers,keepAlive:!0,signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy})){if(i+=1,n!==void 0){let e=c.meta?.deliveryIds?.includes(n)===!0,t=c.type===`session.failed`||c.type===`session.completed`;if(!e&&t&&(!a||c.type===`session.completed`))throw Error(`The session ended before the accepted message reached its turn boundary.`);if(!a&&!e||!t&&c.meta?.deliveryIds!==void 0&&!e)continue;a=!0}if(updatePendingAuthorizations(s,c),o=isCurrentTurnBoundaryEvent(c)&&(c.type!==`session.waiting`||s.size===0),yield c,o)break}if(n!==void 0&&!o&&!t.signal?.aborted)throw Error(`The response stream ended before the accepted message reached its turn boundary.`)}finally{this.#o(e+i)}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;for await(let r of this.#s({follow:e?.follow,headers:e?.headers,keepAlive:e?.keepAlive,onCaughtUp:e?.onCaughtUp,resolveHeaders:e?.resolveHeaders,resolveReconnectPolicy:e?.resolveReconnectPolicy,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,t>=0&&this.#o(t+n),yield r}#o(e){this.#t={sessionId:this.#t.sessionId,streamIndex:Math.max(this.#t.streamIndex,e)}}#s(e){return followStreamIterable({onCaughtUp:e.onCaughtUp,follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.resolveHeaders?.()??e.headers),redirect:this.#e.redirect,sessionId:this.#t.sessionId,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy,resolveReconnectPolicy:e.resolveReconnectPolicy})}};function followClientSession(e,t){return e[followSession](t)}async function postSessionSend(e,t,n){let r=Date.now()+2e4,i=250;for(;;){try{return await postTurn(e,t,n,!1)}catch(e){if(!isSessionNotReady(e))throw e;let t=r-Date.now();if(t<=0)throw e;await sleep(Math.min(i,t),n.signal)}n.signal?.throwIfAborted(),i=Math.min(i*2,2e3)}}async function postCreateSession(e,t){let n=await e.resolveHeaders(t.headers),r=await fetch(createClientUrl(e.host,EVE_SESSION_ROUTE_PATH),{headers:n,method:`POST`,redirect:e.redirect,signal:t.signal??null});if(!r.ok){let e=await r.text();throw new ClientError(r.status,e,r.headers)}return r}function isSessionNotReady(e){return e instanceof ClientError&&e.status===409&&e.code===`session_not_ready`}async function postTurn(e,t,n,r){let i=createMessageBody(n,r);if(i===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let a=await e.resolveHeaders(n.headers);a.set(`content-type`,`application/json`);let o=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(i),headers:a,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!o.ok){let e=await o.text();throw new ClientError(o.status,e,o.headers)}return o}async function readAcceptedMessage(e,t){let n=await e.json(),r=(typeof n.sessionId==`string`?n.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!r)throw Error(`Message route did not return a session id.`);return{sessionId:r,deliveryId:typeof n.deliveryId==`string`&&n.deliveryId.length>0?n.deliveryId:void 0}}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession,followClientSession};
|
|
@@ -45,17 +45,17 @@
|
|
|
45
45
|
"@vercel/oidc": "3.8.0",
|
|
46
46
|
"@vercel/otel": "2.1.3",
|
|
47
47
|
"@vercel/sandbox": "3.3.0",
|
|
48
|
-
"@workflow/builders": "5.0.0-beta.
|
|
49
|
-
"@workflow/core": "5.0.0-beta.
|
|
48
|
+
"@workflow/builders": "5.0.0-beta.53",
|
|
49
|
+
"@workflow/core": "5.0.0-beta.53",
|
|
50
50
|
"@workflow/errors": "5.0.0-beta.21",
|
|
51
51
|
"@workflow/serde": "5.0.0-beta.2",
|
|
52
|
-
"@workflow/world": "5.0.0-beta.
|
|
53
|
-
"@workflow/world-local": "5.0.0-beta.
|
|
54
|
-
"@workflow/world-vercel": "5.0.0-beta.
|
|
52
|
+
"@workflow/world": "5.0.0-beta.36",
|
|
53
|
+
"@workflow/world-local": "5.0.0-beta.45",
|
|
54
|
+
"@workflow/world-vercel": "5.0.0-beta.48",
|
|
55
55
|
"zod": "4.5.4",
|
|
56
56
|
"zod-validation-error": "5.0.0"
|
|
57
57
|
},
|
|
58
|
-
"scriptHash": "
|
|
58
|
+
"scriptHash": "efbe748923f97148f7dbe94494d70959a9af5556fbb1da88bc96644ac272cab2",
|
|
59
59
|
"toolVersions": {
|
|
60
60
|
"rolldown": "1.2.8",
|
|
61
61
|
"typescript": "7.0.2"
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"../../_chunks/workflow/dist-
|
|
1
|
+
import"../../_chunks/workflow/dist-D38gP7YF.js";import{An as e,Kn as t,Vn as n}from"../../_chunks/workflow/logger-NN5YHpYy.js";import{i as r,u as i}from"../../_chunks/workflow/dist-xTushGCp.js";import{G as a,W as o,b as s,ct as c,i as l,it as u,lt as d,nt as f,rt as p,st as m,tt as h,ut as g,w as _}from"../../_chunks/workflow/serialization-C5KgPESk.js";import{a as v,i as y,r as b,t as x}from"../../_chunks/workflow/attribute-changes-A6HfMNG3.js";import{n as S}from"../../_chunks/workflow/resume-hook-CAqlhwic.js";import{t as C}from"../../_chunks/workflow/sleep-CbUwdv6O.js";function w(e){y(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,w)}function T(e){y(`createWebhook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-webhook`,T)}function E({schema:e}={}){function t(e){y(`defineHook().create()`,`https://workflow-sdk.dev/docs/api-reference/workflow/define-hook`,t)}return{create:t,async resume(t,n){if(!e?.[`~standard`])return await S(t,n);let r=e[`~standard`].validate(n);if(r instanceof Promise&&(r=await r),r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>String(typeof e==`object`&&e?e.key:e)).join(`.`);return t?` at "${t}": ${e.message}`:` ${e.message}`});throw Error(`Hook payload did not match the defined schema:\n${e.join(`
|
|
2
2
|
`)}`)}return await S(t,r.value)}}}async function D(e,n={}){let i=a.getStore(),o=i?.workflowMetadata?.workflowRunId;if(!o)throw new r(`setAttributes() must be called from a 'use workflow' or 'use step' function. Calling it from plain host code is not supported.`);let s=x(e,n);if(s.length!==0){if(i.runReadyBarrier)try{await i.runReadyBarrier}catch{}await(await t()).events.create(o,{eventType:`attr_set`,specVersion:7,eventData:{changes:s,writer:{type:`step`,stepId:i.stepMetadata.stepId,attempt:i.stepMetadata.attempt},...n.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{}}})}}function O(){let e=a.getStore();return e||b(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,O),e.stepMetadata}function k(){let e=a.getStore();return e||v(`getWorkflowMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-workflow-metadata`,k),e.workflowMetadata}function A(t={}){let r=a.getStore();r||v(`getWritable()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-writable`,A);let{namespace:i}=t,y=r.workflowMetadata.workflowRunId,b=o(y,i);r.writables??=new Map;let x=r.writables,S=x.get(b);if(S)return S.writable;let C=h();C.deferReleaseSettlement=r.streamStates!==void 0;let w=_(s(globalThis,r.ops,y,r.encryptionKey,!0,r.runReadyBarrier),r.encryptionKey),T=new l(y,b,r.runReadyBarrier);r.streamStates??=[],r.streamStates.push(C),r.ops.push(C.promise),f(w.readable,T,C).catch(()=>{});let E=u(w.writable,C);return p(E,C),Object.defineProperty(E,m,{value:b,writable:!1}),Object.defineProperty(E,g,{value:y,writable:!1}),r.workflowDeploymentId&&Object.defineProperty(E,c,{value:r.workflowDeploymentId,writable:!1}),e(r.encryptionKey)&&Object.defineProperty(E,d,{value:n(r.encryptionKey.keyPair.publicKey),writable:!1}),x.set(b,{writable:E,state:C}),E}export{r as FatalError,i as RetryableError,w as createHook,T as createWebhook,E as defineHook,O as getStepMetadata,k as getWorkflowMetadata,A as getWritable,D as setAttributes,C as sleep};
|
|
@@ -7,10 +7,14 @@
|
|
|
7
7
|
* user error · FatalError
|
|
8
8
|
* run wrun_…
|
|
9
9
|
* step step_… · add (./workflows/x)
|
|
10
|
+
* cause TypeError: fetch failed
|
|
10
11
|
* hint: Move the call to a step function.
|
|
11
12
|
* FatalError: …
|
|
12
13
|
* at … (trimmed stack, internals collapsed)
|
|
13
14
|
*
|
|
15
|
+
* The stack body comes from the message when the caller embedded it there,
|
|
16
|
+
* and from the `errorStack` metadata field otherwise.
|
|
17
|
+
*
|
|
14
18
|
* Without this composition, callers passing `${framing}\n${stack}` as the
|
|
15
19
|
* message and structured fields as the metadata object got `util.inspect`'s
|
|
16
20
|
* default object dump appended *after* the stack, which buries the run ID
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,E as t,S as n,T as r,_ as i,a,b as o,c as s,d as c,f as l,g as u,h as d,i as f,l as p,m,n as h,o as g,p as _,r as v,s as y,t as b,u as x,v as S,w as C,x as w,y as T}from"../../../_chunks/workflow/helpers-
|
|
1
|
+
import{C as e,E as t,S as n,T as r,_ as i,a,b as o,c as s,d as c,f as l,g as u,h as d,i as f,l as p,m,n as h,o as g,p as _,r as v,s as y,t as b,u as x,v as S,w as C,x as w,y as T}from"../../../_chunks/workflow/helpers-6kObVbfS.js";export{b as SLOT_GAP_RECHECK_ATTEMPTS,h as absorbSkippedSlotReport,v as appendEventLog,f as appendUniqueEvents,a as findEventSlotGap,g as getQueueOverhead,y as getWorkflowQueueName,s as handleHealthCheckMessage,p as healthCheck,x as insertEventByEventId,c as isSlotGapCheckEnabled,l as loadWorkflowRunEvents,_ as maxEventSlot,m as memoizeEncryptionKey,d as mergeReportedEvents,u as parseHealthCheckPayload,i as preconditionEventDelta,S as queueMessage,T as queueMessages,o as resolveRunEncryptionKey,w as rootRunIdFrom,n as runDispatchContext,e as settleEventSlotGap,C as slotSnapshotParams,r as stepDispatchIdempotencyKey,t as withHealthCheck};
|