eve 0.86.0 → 0.87.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 +67 -0
- package/README.md +1 -1
- package/dist/src/acp/adapter.d.ts +2 -26
- package/dist/src/acp/adapter.js +1 -1
- package/dist/src/acp/server.d.ts +0 -3
- package/dist/src/ai/decision-adapter.d.ts +5 -3
- package/dist/src/ai/decision-adapter.js +1 -1
- package/dist/src/ai/decision-types.d.ts +4 -3
- package/dist/src/channel/adapter.d.ts +0 -14
- package/dist/src/channel/auth/definitions.d.ts +0 -4
- package/dist/src/channel/channel-address.d.ts +1 -1
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/channel-operations.d.ts +2 -2
- package/dist/src/channel/channel-operations.js +1 -1
- package/dist/src/channel/prompt-queue.d.ts +0 -2
- package/dist/src/channel/session-not-active-error.d.ts +10 -5
- package/dist/src/channel/session-not-active-error.js +1 -1
- package/dist/src/channel/session-stranded-error.d.ts +1 -1
- package/dist/src/channel/session.d.ts +3 -4
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +5 -14
- package/dist/src/chunks/{use-eve-agent-B2jCfcnG.js → use-eve-agent-BExXjBv6.js} +82 -72
- package/dist/src/chunks/{use-eve-agent-DCLFi26P.js → use-eve-agent-C0KHCyb9.js} +82 -72
- package/dist/src/cli/dev/command-options.d.ts +4 -4
- package/dist/src/cli/dev/command.js +1 -1
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/test/fake-eve-server.js +1 -1
- package/dist/src/cli/dev/tui/tool-format.d.ts +2 -2
- package/dist/src/cli/dev/ui-options.d.ts +4 -4
- package/dist/src/cli/dev/ui-options.js +1 -1
- package/dist/src/client/agent-info-error.d.ts +4 -1
- package/dist/src/client/agent-info-error.js +1 -1
- package/dist/src/client/agent-session.d.ts +1 -4
- package/dist/src/client/agent-session.js +1 -1
- package/dist/src/client/agent-stream-follower.js +1 -1
- package/dist/src/client/client-error.d.ts +13 -4
- package/dist/src/client/client-error.js +1 -1
- package/dist/src/client/delivery.d.ts +2 -17
- package/dist/src/client/health-response-error.d.ts +4 -1
- package/dist/src/client/health-response-error.js +1 -1
- package/dist/src/client/index.d.ts +5 -3
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/open-stream.d.ts +7 -12
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-controls.d.ts +2 -2
- package/dist/src/client/session-controls.js +1 -1
- package/dist/src/client/session-event-stream.d.ts +2 -2
- package/dist/src/client/session-event-stream.js +1 -1
- package/dist/src/client/session-store.d.ts +2 -6
- package/dist/src/client/session-store.js +1 -1
- package/dist/src/client/session.d.ts +4 -13
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/sessions.d.ts +3 -6
- package/dist/src/client/types.d.ts +23 -32
- package/dist/src/compiled/.vendor-stamp.json +3 -3
- package/dist/src/compiled/@vercel/agent-runs/LICENSE +202 -0
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-connection.d.ts +1 -1
- package/dist/src/compiler/normalize-connection.js +1 -1
- package/dist/src/compiler/normalize-instructions.js +1 -1
- package/dist/src/compiler/normalize-skill.js +1 -1
- package/dist/src/compiler/resolve-workspace-subagent.js +1 -1
- package/dist/src/context/memory-tools.d.ts +9 -5
- package/dist/src/discover/sandbox.js +1 -1
- package/dist/src/dynamic/definition.d.ts +11 -5
- package/dist/src/dynamic/definition.js +1 -1
- package/dist/src/evals/mock-model.d.ts +1 -1
- package/dist/src/evals/session-manager.d.ts +0 -2
- package/dist/src/evals/session.d.ts +1 -11
- package/dist/src/evals/session.js +1 -1
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/support.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/effective-agent-config.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash-runtime.d.ts +1 -2
- package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/instrumentation/ai-sdk-telemetry.d.ts +0 -2
- package/dist/src/instrumentation/providers.d.ts +1 -38
- package/dist/src/instrumentation/providers.js +1 -1
- package/dist/src/instrumentation/setup-context.d.ts +1 -7
- package/dist/src/internal/application/package.d.ts +1 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/classify-model-routing.d.ts +2 -3
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/runtime-model.d.ts +9 -4
- package/dist/src/internal/runtime-model.js +1 -1
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.d.ts +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +1 -1
- package/dist/src/models/auto.js +1 -1
- package/dist/src/protocol/delivery.d.ts +1 -0
- package/dist/src/protocol/reset-session.d.ts +0 -2
- package/dist/src/protocol/routes.d.ts +9 -2
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +1 -22
- package/dist/src/public/channels/discord/discordChannel.d.ts +3 -12
- package/dist/src/public/channels/discord/gateway/{index.d.ts → relay.d.ts} +2 -2
- package/dist/src/public/channels/discord/gateway/relay.js +1 -0
- package/dist/src/public/channels/discord/messages.d.ts +4 -4
- package/dist/src/public/channels/github/state.d.ts +0 -2
- package/dist/src/public/channels/index.d.ts +1 -2
- package/dist/src/public/channels/index.js +1 -1
- package/dist/src/public/channels/linear/index.d.ts +1 -1
- package/dist/src/public/channels/linear/index.js +1 -1
- package/dist/src/public/channels/linear/linearChannel.d.ts +0 -5
- package/dist/src/public/channels/linq/index.d.ts +1 -1
- package/dist/src/public/channels/linq/linqChannel.d.ts +7 -5
- package/dist/src/public/channels/photon/index.d.ts +1 -1
- package/dist/src/public/channels/photon/photonIMessageChannel.d.ts +15 -4
- package/dist/src/public/channels/slack/api.d.ts +1 -1
- package/dist/src/public/channels/slack/api.js +1 -1
- package/dist/src/public/channels/slack/blocks.d.ts +1 -1
- package/dist/src/public/channels/slack/blocks.js +2 -2
- package/dist/src/public/channels/slack/cards.d.ts +2 -297
- package/dist/src/public/channels/slack/cards.js +1 -1
- package/dist/src/public/channels/slack/index.d.ts +2 -2
- package/dist/src/public/channels/slack/index.js +1 -1
- package/dist/src/public/channels/slack/session-operations.d.ts +2 -2
- package/dist/src/public/channels/slack/session-operations.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +11 -72
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +4 -3
- package/dist/src/public/channels/telegram/hitl.d.ts +2 -9
- package/dist/src/public/channels/telegram/index.d.ts +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +0 -2
- package/dist/src/public/channels/twilio/twilioChannel.d.ts +0 -2
- package/dist/src/public/channels/undelivered-reply.d.ts +0 -5
- package/dist/src/public/definitions/agent.d.ts +15 -7
- package/dist/src/public/definitions/agent.js +1 -1
- package/dist/src/public/definitions/channel.d.ts +7 -5
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/connections/protocol.d.ts +1 -7
- package/dist/src/public/definitions/connections/protocol.js +1 -1
- package/dist/src/public/experimental/channels/discord/gateway.d.ts +1 -0
- package/dist/src/public/experimental/channels/discord/gateway.js +1 -0
- package/dist/src/public/experimental/sandbox/just-bash.d.ts +1 -0
- package/dist/src/public/experimental/sandbox/just-bash.js +1 -0
- package/dist/src/public/experimental/workspace/index.d.ts +1 -0
- package/dist/src/public/experimental/workspace/index.js +1 -0
- package/dist/src/public/index.d.ts +2 -2
- package/dist/src/public/index.js +1 -1
- package/dist/src/public/instrumentation/otel.d.ts +1 -1
- package/dist/src/public/instrumentation/provider.d.ts +1 -1
- package/dist/src/public/instrumentation/provider.js +1 -1
- package/dist/src/public/memory/file/backend.d.ts +1 -1
- package/dist/src/public/memory/file/backends/in-memory.js +1 -1
- package/dist/src/public/memory/file/backends/vercel-blob.js +1 -1
- package/dist/src/public/memory/file/provider.js +1 -1
- package/dist/src/public/memory/index.d.ts +3 -11
- package/dist/src/public/models/anthropic/index.d.ts +1 -1
- package/dist/src/public/models/index.d.ts +1 -0
- package/dist/src/public/models/openai/index.d.ts +2 -2
- package/dist/src/public/next/index.d.ts +2 -2
- package/dist/src/public/sandbox/just-bash-sandbox.d.ts +27 -20
- package/dist/src/public/sandbox/just-bash.d.ts +0 -1
- package/dist/src/public/sessions/index.d.ts +1 -0
- package/dist/src/public/sessions/index.js +1 -1
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/public/tools/index.js +1 -1
- package/dist/src/public/workflow/api.d.ts +25 -0
- package/dist/src/public/workflow/api.js +1 -0
- package/dist/src/public/workflow/index.d.ts +76 -0
- package/dist/src/public/workflow/index.js +1 -0
- package/dist/src/public/workflow-modules.d.ts +2 -17
- package/dist/src/react/use-eve-agent.d.ts +3 -2
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/reactions/kinds/model.js +1 -1
- package/dist/src/runtime/agent/resolve-model.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/resolve-dynamic.js +1 -1
- package/dist/src/runtime/subagents/dynamic-agent-config.js +1 -1
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/sandbox/providers/default.js +1 -1
- package/dist/src/self-modification/extension/subagents/agent/agent.d.ts +2 -2
- package/dist/src/self-modification/sandbox.js +1 -1
- package/dist/src/setup/integrations/discord/daemon.js +2 -2
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/create/web-template.d.ts +2 -2
- package/dist/src/setup/scaffold/create/web-template.js +2 -2
- package/dist/src/setup/verified-remote-agent.d.ts +1 -3
- package/dist/src/shared/agent-definition.d.ts +18 -9
- package/dist/src/shared/eve-error.d.ts +22 -0
- package/dist/src/shared/eve-error.js +1 -0
- package/dist/src/shared/session.d.ts +2 -2
- package/dist/src/shared/token-usage.d.ts +7 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +2 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/definition.d.ts +7 -5
- package/dist/src/tools/definition.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tracing/eve/batch-span-processor.d.ts +1 -1
- package/dist/src/tracing/eve/content-span-processor.d.ts +1 -19
- package/dist/src/tracing/eve/otel-configuration.d.ts +6 -0
- package/dist/src/tracing/eve/otel-declaration.d.ts +6 -19
- package/dist/src/tracing/eve/span-export-policy.d.ts +0 -2
- package/dist/src/tracing/local/instrumentation-runtime.d.ts +0 -3
- package/dist/src/tracing/local/traces.d.ts +0 -13
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +3 -2
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +15 -11
- package/docs/channels/custom.mdx +26 -10
- package/docs/channels/discord.mdx +10 -10
- package/docs/channels/eve.mdx +14 -8
- package/docs/channels/linear.mdx +11 -0
- package/docs/channels/linq.mdx +5 -1
- package/docs/channels/photon.mdx +6 -1
- package/docs/channels/slack.mdx +73 -14
- package/docs/channels/telegram.mdx +6 -0
- package/docs/code-extension.mdx +25 -0
- package/docs/concepts/default-harness.md +2 -2
- package/docs/concepts/execution-model-and-durability.mdx +11 -11
- package/docs/concepts/security-model.md +2 -2
- package/docs/concepts/sessions-runs-and-streaming.md +23 -10
- package/docs/concepts/upgrade-to-v27-events.md +2 -1
- package/docs/connections/overview.mdx +4 -0
- package/docs/evals/reporters.mdx +21 -0
- package/docs/extensions.md +12 -0
- package/docs/getting-started.mdx +5 -1
- package/docs/guides/auth-and-route-protection.md +1 -1
- package/docs/guides/client/continuations.mdx +12 -10
- package/docs/guides/client/messages.mdx +24 -1
- package/docs/guides/client/overview.mdx +8 -6
- package/docs/guides/client/streaming.mdx +24 -6
- package/docs/guides/decide.md +3 -3
- package/docs/guides/deployment/vercel.mdx +1 -1
- package/docs/guides/dev-tui.md +2 -2
- package/docs/guides/frontend/overview.mdx +1 -1
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +13 -11
- package/docs/guides/frontend/use-eve-agent-vue.mdx +13 -11
- package/docs/guides/frontend/use-eve-agent.mdx +4 -4
- package/docs/guides/instrumentation/otel.mdx +3 -1
- package/docs/guides/prepare-for-1-0.md +255 -0
- package/docs/guides/remote-agents.md +22 -20
- package/docs/instructions.mdx +1 -1
- package/docs/memory/custom-provider.md +1 -1
- package/docs/memory/file.md +11 -2
- package/docs/meta.json +1 -0
- package/docs/reference/agent-files.md +17 -17
- package/docs/reference/cli.md +14 -9
- package/docs/reference/typescript-api.md +46 -20
- package/docs/sandbox/custom-providers.mdx +2 -0
- package/docs/sandbox/default.mdx +6 -6
- package/docs/sandbox/index.mdx +5 -5
- package/docs/sandbox/just-bash.mdx +30 -21
- package/docs/subagents/index.mdx +4 -4
- package/docs/tools/human-in-the-loop.md +1 -1
- package/docs/tools/workflows.mdx +52 -8
- package/docs/tutorial/first-agent.mdx +1 -1
- package/package.json +36 -9
- package/dist/CHANGELOG.md +0 -38
- package/dist/src/public/channels/discord/gateway/index.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveDescendantStreamRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{followStreamIterable}from"#client/open-stream.js";import{EVE_OBSERVATION_KEY_HEADER}from"#protocol/descendant-observation.js";var ClientAgentSession=class ClientAgentSession{name;id;taskId;#e;#t;#n;constructor(e,t,n,r=[]){let i=n.meta?.position?.line;if(!Number.isSafeInteger(i)||i<0)throw TypeError(`Pass a received child.opened event with its committed source position.`);this.#e=e,this.#t=t,this.#n=[...r,{sessionId:n.data.sessionId,position:i}],this.name=n.data.name,this.id=n.data.sessionId,this.taskId=n.scope?.taskId??(`taskId`in n.data.owner?n.data.owner.taskId:void 0)}agent(e){return new ClientAgentSession(this.#e,this.#t,e,this.#n)}async*stream(e){for await(let{event:t}of this.follow(e))yield t}follow(e,t,n,r){return followStreamIterable({follow:e?.follow,onCaughtUp:n,onPosition:r,baseUrl:this.#e.baseUrl,path:createEveDescendantStreamRoutePath(this.#t),searchParams:{children:JSON.stringify(this.#n)},redirect:`error`,resolveHeaders:()=>this.#e.resolveHeaders(),signal:e?.signal,startIndex:e?.startIndex??0,
|
|
1
|
+
import{createEveDescendantStreamRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{followStreamIterable}from"#client/open-stream.js";import{EVE_OBSERVATION_KEY_HEADER}from"#protocol/descendant-observation.js";var ClientAgentSession=class ClientAgentSession{name;id;taskId;#e;#t;#n;constructor(e,t,n,r=[]){let i=n.meta?.position?.line;if(!Number.isSafeInteger(i)||i<0)throw TypeError(`Pass a received child.opened event with its committed source position.`);this.#e=e,this.#t=t,this.#n=[...r,{sessionId:n.data.sessionId,position:i}],this.name=n.data.name,this.id=n.data.sessionId,this.taskId=n.scope?.taskId??(`taskId`in n.data.owner?n.data.owner.taskId:void 0)}agent(e){return new ClientAgentSession(this.#e,this.#t,e,this.#n)}async*stream(e){for await(let{event:t}of this.follow(e))yield t}follow(e,t,n,r){return followStreamIterable({follow:e?.follow,onCaughtUp:n,onPosition:r,baseUrl:this.#e.baseUrl,path:createEveDescendantStreamRoutePath(this.#t),searchParams:{children:JSON.stringify(this.#n)},redirect:`error`,resolveHeaders:()=>this.#e.resolveHeaders(),signal:e?.signal,startIndex:e?.startIndex??0,reconnect:e?.reconnect,onOpen:e=>{if(t===void 0)return;let n=e.get(EVE_OBSERVATION_KEY_HEADER);if(n===null||n.length>8192)throw new ClientError(422,`Descendant reader provenance is unavailable.`);t(n)}})}};export{ClientAgentSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ClientError}from"#client/client-error.js";import{DEFAULT_STREAM_RECONNECT_POLICY,RECONNECT_BACKOFF,isRetryableStreamError}from"#client/open-stream.js";import{DESCENDANT_MAX_DEPTH,DESCENDANT_MAX_READS,DESCENDANT_MAX_SESSIONS,localObservationKey}from"#protocol/descendant-observation.js";import{Conversation}from"#client/conversation.js";var AgentStreamFollower=class{#e;#t=new Set;#n=new Map;#r;#i;#a=!1;#o=0;#s;constructor(e){this.#r=e.policy,this.#i=e.onChange,this.#e=this.#c(e.session,e.conversation,0),this.#e.key=localObservationKey(e.session.id),this.#n.set(this.#e.key,this.#e)}start(){if(!this.#a){this.#a=!0;for(let e of this.#t)e.readyAt=0,e.status===`interrupted`&&e.reason===`detached`&&(e.status=`queued`);this.reconcile()}}reconcile(){this.#a&&(this.#l(this.#e),this.#a&&(this.#f(),this.#u()))}abortAll(){this.#a=!1,this.#o+=1,clearTimeout(this.#s),this.#s=void 0;for(let e of this.#t)e.controller?.abort(),e.controller=void 0,e.conversation.discardUncommitted(),e.status!==`unavailable`&&(e.status=`interrupted`,e.reason=`detached`);this.#f()}#c(e,t,n){return{reader:e,conversation:t,readerDepth:n,depths:new Set([n]),edges:new Map,status:`queued`,caughtUp:!1,readyAt:0,failures:0,idleReads:0}}#l(e){let t=this.#o;for(let n of Object.values(e.conversation.view.children)){let r=e.edges.get(n.sessionId)??{depths:new Set};e.edges.set(n.sessionId,r);for(let i of e.depths){if(!this.#a||t!==this.#o)return;let a=i+1;if(r.depths.has(a))continue;r.depths.add(a);let o;if(a>DESCENDANT_MAX_DEPTH)o=`depth-limit`;else if(typeof this.#r==`function`)try{this.#r({depth:a,name:n.name,sessionId:n.sessionId,owner:n.owner})||(o=`predicate`)}catch{o=`predicate`}else this.#r||(o=`predicate`);if(!this.#a||t!==this.#o)return;if(o===void 0&&r.child===void 0&&this.#t.size>=DESCENDANT_MAX_SESSIONS&&(o=`session-limit`),o!==void 0){r.child===void 0&&(r.excluded=o);continue}let s=e.reader.agent({type:`child.opened`,data:n,meta:{at:n.startedAt,endOfLine:!0,position:{line:n.introducedAt,index:0}}});if(r.child===void 0)r.child=this.#c(s,new Conversation,a),r.child.readerDepth=e.readerDepth+1,r.excluded=void 0,this.#t.add(r.child);else{let t=r.child.alias??r.child;e.readerDepth+1<t.readerDepth&&(t.reader=s,t.readerDepth=e.readerDepth+1),t!==this.#e&&!t.depths.has(a)&&(t.depths.add(a),this.#l(t))}}}}#u(){if(clearTimeout(this.#s),this.#s=void 0,!this.#a)return;let e=this.#o,t=[...this.#t].filter(e=>e.controller!==void 0).length,n=1/0;for(let r of[...this.#t].sort((e,t)=>e.readyAt-t.readyAt)){if(!this.#a||e!==this.#o)return;r.alias===void 0&&r.controller===void 0&&r.status!==`unavailable`&&(t<DESCENDANT_MAX_READS&&r.readyAt<=Date.now()?(t+=1,this.#d(r)):n=Math.min(n,r.readyAt))}t<DESCENDANT_MAX_READS&&n!==1/0&&(this.#s=setTimeout(()=>this.#u(),Math.max(1,n-Date.now())))}#d(e){let t=this.#o,n=new AbortController,current=()=>this.#a&&t===this.#o&&!n.signal.aborted,{conversation:r}=e;if(e.controller=n,e.status=`following`,e.reason=void 0,e.caughtUp=!1,this.#f(),!current()){n.abort();return}let i=setTimeout(()=>n.abort(),1e4);n.signal.addEventListener(`abort`,()=>clearTimeout(i),{once:!0});let a=r.view.position;(async()=>{try{let t=e.reader,i=!1;for await(let{event:a}of t.follow({signal:n.signal,startIndex:r.view.position,follow:!1,
|
|
1
|
+
import{ClientError}from"#client/client-error.js";import{DEFAULT_STREAM_RECONNECT_POLICY,RECONNECT_BACKOFF,isRetryableStreamError}from"#client/open-stream.js";import{DESCENDANT_MAX_DEPTH,DESCENDANT_MAX_READS,DESCENDANT_MAX_SESSIONS,localObservationKey}from"#protocol/descendant-observation.js";import{Conversation}from"#client/conversation.js";var AgentStreamFollower=class{#e;#t=new Set;#n=new Map;#r;#i;#a=!1;#o=0;#s;constructor(e){this.#r=e.policy,this.#i=e.onChange,this.#e=this.#c(e.session,e.conversation,0),this.#e.key=localObservationKey(e.session.id),this.#n.set(this.#e.key,this.#e)}start(){if(!this.#a){this.#a=!0;for(let e of this.#t)e.readyAt=0,e.status===`interrupted`&&e.reason===`detached`&&(e.status=`queued`);this.reconcile()}}reconcile(){this.#a&&(this.#l(this.#e),this.#a&&(this.#f(),this.#u()))}abortAll(){this.#a=!1,this.#o+=1,clearTimeout(this.#s),this.#s=void 0;for(let e of this.#t)e.controller?.abort(),e.controller=void 0,e.conversation.discardUncommitted(),e.status!==`unavailable`&&(e.status=`interrupted`,e.reason=`detached`);this.#f()}#c(e,t,n){return{reader:e,conversation:t,readerDepth:n,depths:new Set([n]),edges:new Map,status:`queued`,caughtUp:!1,readyAt:0,failures:0,idleReads:0}}#l(e){let t=this.#o;for(let n of Object.values(e.conversation.view.children)){let r=e.edges.get(n.sessionId)??{depths:new Set};e.edges.set(n.sessionId,r);for(let i of e.depths){if(!this.#a||t!==this.#o)return;let a=i+1;if(r.depths.has(a))continue;r.depths.add(a);let o;if(a>DESCENDANT_MAX_DEPTH)o=`depth-limit`;else if(typeof this.#r==`function`)try{this.#r({depth:a,name:n.name,sessionId:n.sessionId,owner:n.owner})||(o=`predicate`)}catch{o=`predicate`}else this.#r||(o=`predicate`);if(!this.#a||t!==this.#o)return;if(o===void 0&&r.child===void 0&&this.#t.size>=DESCENDANT_MAX_SESSIONS&&(o=`session-limit`),o!==void 0){r.child===void 0&&(r.excluded=o);continue}let s=e.reader.agent({type:`child.opened`,data:n,meta:{at:n.startedAt,endOfLine:!0,position:{line:n.introducedAt,index:0}}});if(r.child===void 0)r.child=this.#c(s,new Conversation,a),r.child.readerDepth=e.readerDepth+1,r.excluded=void 0,this.#t.add(r.child);else{let t=r.child.alias??r.child;e.readerDepth+1<t.readerDepth&&(t.reader=s,t.readerDepth=e.readerDepth+1),t!==this.#e&&!t.depths.has(a)&&(t.depths.add(a),this.#l(t))}}}}#u(){if(clearTimeout(this.#s),this.#s=void 0,!this.#a)return;let e=this.#o,t=[...this.#t].filter(e=>e.controller!==void 0).length,n=1/0;for(let r of[...this.#t].sort((e,t)=>e.readyAt-t.readyAt)){if(!this.#a||e!==this.#o)return;r.alias===void 0&&r.controller===void 0&&r.status!==`unavailable`&&(t<DESCENDANT_MAX_READS&&r.readyAt<=Date.now()?(t+=1,this.#d(r)):n=Math.min(n,r.readyAt))}t<DESCENDANT_MAX_READS&&n!==1/0&&(this.#s=setTimeout(()=>this.#u(),Math.max(1,n-Date.now())))}#d(e){let t=this.#o,n=new AbortController,current=()=>this.#a&&t===this.#o&&!n.signal.aborted,{conversation:r}=e;if(e.controller=n,e.status=`following`,e.reason=void 0,e.caughtUp=!1,this.#f(),!current()){n.abort();return}let i=setTimeout(()=>n.abort(),1e4);n.signal.addEventListener(`abort`,()=>clearTimeout(i),{once:!0});let a=r.view.position;(async()=>{try{let t=e.reader,i=!1;for await(let{event:a}of t.follow({signal:n.signal,startIndex:r.view.position,follow:!1,reconnect:!1},t=>{if(!current())throw Error(`Observation stopped.`);if(e.key!==void 0&&e.key!==t)throw new ClientError(422,`Descendant reader identity changed.`);e.key=t;let r=this.#n.get(t);if(r!==void 0&&r!==e){if(e.alias=r,r!==this.#e){e.readerDepth<r.readerDepth&&(r.reader=e.reader,r.readerDepth=e.readerDepth);for(let t of e.depths)r.depths.add(t);this.#l(r)}n.abort()}else this.#n.set(t,e)},()=>{i=!0},e=>{!current()||e<=r.view.position||(r.advancePosition(e),this.#f())})){if(!current())return;if(r.observe(a),a.meta.endOfLine!==!1){if(this.#l(e),!current())return;this.#f(),this.#u()}}if(!current())return;if(!i)throw Error(`The descendant stream disconnected before its captured tail.`);e.caughtUp=!0,e.status=`caught-up`,e.failures=0,e.idleReads=r.view.position===a?e.idleReads+1:0,e.readyAt=Date.now()+Math.min(1e4,1e3*2**Math.min(e.idleReads,4))}catch(t){if(!current())return;e.failures+=1;let n=t instanceof ClientError?t.status:void 0;e.status=isRetryableStreamError(t)&&e.failures<DEFAULT_STREAM_RECONNECT_POLICY.maxAttempts?`interrupted`:`unavailable`,e.reason=n===401||n===403?`unauthorized`:n===410?`expired`:n===422?t instanceof ClientError&&t.code===`cycle`?`cycle`:`unsupported`:`transport`,e.readyAt=Date.now()+Math.min(RECONNECT_BACKOFF.maxDelayMs,RECONNECT_BACKOFF.baseDelayMs*2**Math.min(e.failures-1,5))}finally{clearTimeout(i),t===this.#o&&(e.controller=void 0,n.signal.aborted&&(e.status=`queued`,e.readyAt=Date.now()),r.discardUncommitted(),this.#a&&(this.#f(),this.#u()))}})()}#f(){let e=new Set,visit=(t,n)=>{if(e.has(t))return;e.add(t);let r=new Set([...n,t]);for(let[e,n]of t.edges){if(n.child===void 0){t.conversation.observeAgent(e,{status:`not-followed`,reason:n.excluded});continue}let i=n.child.alias??n.child;if(r.has(i)){t.conversation.observeAgent(e,{status:`not-followed`,reason:`cycle`});continue}visit(i,r),t.conversation.observeAgent(e,{status:i.status,key:i.key,conversation:i.conversation.state,position:i.conversation.view.position,caughtUp:i.caughtUp,reason:i.reason})}};visit(this.#e,new Set),this.#i()}};export{AgentStreamFollower};
|
|
@@ -1,10 +1,18 @@
|
|
|
1
|
+
import { EveError } from "#shared/eve-error.js";
|
|
1
2
|
import { SessionNotActiveError } from "#channel/session-not-active-error.js";
|
|
3
|
+
/**
|
|
4
|
+
* Codes eve's HTTP routes return. Custom auth and proxies can return others, and `http_error`
|
|
5
|
+
* means the response carried no code.
|
|
6
|
+
*/
|
|
7
|
+
export type ClientErrorCode = "unauthorized" | "forbidden" | "eve_production_auth_not_configured" | "session_stranded" | "session_expired" | "descendant_unavailable" | "cycle" | "unsupported" | "session_version_unsupported" | "invalid_stream_response" | "http_error" | (string & {});
|
|
2
8
|
/**
|
|
3
9
|
* Error thrown when the eve server returns a non-successful HTTP response.
|
|
10
|
+
* Narrow with `ClientError.is(error)`.
|
|
4
11
|
*/
|
|
5
|
-
export declare class ClientError extends
|
|
6
|
-
|
|
7
|
-
|
|
12
|
+
export declare class ClientError extends EveError {
|
|
13
|
+
static readonly errorName: string;
|
|
14
|
+
/** The response body's eve error code, or `http_error` when it has none. */
|
|
15
|
+
readonly code: ClientErrorCode;
|
|
8
16
|
/**
|
|
9
17
|
* HTTP status code returned by the server.
|
|
10
18
|
*/
|
|
@@ -22,10 +30,11 @@ export declare class ClientError extends Error {
|
|
|
22
30
|
/**
|
|
23
31
|
* Thrown by `ClientSession.send()`, `respond()`, `clear()`, and live stream connections when the server
|
|
24
32
|
* answers `409 session_stranded`: another eve version built the session's owner, so it can never
|
|
25
|
-
* execute on that deployment and new input is not delivered. Call `
|
|
33
|
+
* execute on that deployment and new input is not delivered. Call `end()` on the session, then
|
|
26
34
|
* create a new one. `stream({ follow: false })` still reads recorded history.
|
|
27
35
|
*/
|
|
28
36
|
export declare class ClientSessionStrandedError extends ClientError {
|
|
37
|
+
static readonly errorName = "ClientSessionStrandedError";
|
|
29
38
|
readonly code: "session_stranded";
|
|
30
39
|
/** The eve version that built the session, when it recorded one. */
|
|
31
40
|
readonly eveVersion: string | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";var ClientError=class extends
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{EveError}from"#shared/eve-error.js";var ClientError=class extends EveError{static errorName=`ClientError`;status;body;headers;constructor(e,t,n){let r=Object.freeze(Object.fromEntries(new Headers(n).entries())),i=r[`content-type`]?.toLowerCase(),a=parseJsonObject(t),o=t||`Server returned ${e}.`;typeof a?.error==`string`?o=a.error:a===void 0&&i?.includes(`text/html`)&&(o=`Server returned ${e} with an HTML response. Check the eve route and development server configuration.`),super(typeof a?.code==`string`?a.code:`http_error`,o),this.status=e,this.body=t,this.headers=r}},ClientSessionStrandedError=class extends ClientError{static errorName=`ClientSessionStrandedError`;eveVersion;constructor(e,t,n,r){super(e,t,n),this.eveVersion=r.eveVersion}};function createClientError(e,t,n){let r=e===409?parseJsonObject(t):void 0;return r?.code===`session_not_active`||r?.code===`session_not_ready`?new SessionNotActiveError({retryable:r.code===`session_not_ready`}):r?.code===`session_stranded`?new ClientSessionStrandedError(e,t,n,{eveVersion:typeof r.eveVersion==`string`?r.eveVersion:void 0}):new ClientError(e,t,n)}function parseJsonObject(e){try{let t=JSON.parse(e);return isObject(t)?t:void 0}catch{return}}export{ClientError,ClientSessionStrandedError,createClientError};
|
|
@@ -1,24 +1,10 @@
|
|
|
1
1
|
import type { SessionStreamEvent } from "#protocol/session-event.js";
|
|
2
2
|
import type { Delivery, DeliveryReadOptions, DeliveryResult } from "#shared/delivery.js";
|
|
3
3
|
export type { Delivery } from "#shared/delivery.js";
|
|
4
|
-
/**
|
|
5
|
-
* @internal When the client sent an accepted message or answer, in epoch
|
|
6
|
-
* milliseconds on the client's clock.
|
|
7
|
-
*/
|
|
8
|
-
export interface ClientSendReceipt {
|
|
9
|
-
readonly deliveryId?: string;
|
|
10
|
-
/** The first attempt was issued. */
|
|
11
|
-
readonly startedAt: number;
|
|
12
|
-
/** Retrying `409 session_not_ready` before the accepted attempt was issued. */
|
|
13
|
-
readonly notReadyMs: number;
|
|
14
|
-
/** The accepted response arrived. */
|
|
15
|
-
readonly acceptedAt: number;
|
|
16
|
-
}
|
|
17
4
|
interface DeliveryInput {
|
|
18
5
|
readonly inbox?: string;
|
|
19
6
|
readonly createStream: (options?: DeliveryReadOptions) => AsyncIterable<SessionStreamEvent>;
|
|
20
7
|
readonly deliveryId: string;
|
|
21
|
-
readonly receipt?: ClientSendReceipt;
|
|
22
8
|
readonly sessionId: string;
|
|
23
9
|
}
|
|
24
10
|
/** An accepted command: its receipt and independent reads through its own settlement. */
|
|
@@ -26,13 +12,12 @@ export declare class StreamDelivery<TOutput = unknown> implements Delivery<TOutp
|
|
|
26
12
|
#private;
|
|
27
13
|
readonly sessionId: string;
|
|
28
14
|
readonly deliveryId: string;
|
|
15
|
+
/** Opaque value to store with the session state; see `ClientSessionState.inbox`. */
|
|
29
16
|
readonly inbox?: string;
|
|
30
|
-
/**
|
|
17
|
+
/** Built by the eve client for each command the server accepts. */
|
|
31
18
|
constructor(input: DeliveryInput);
|
|
32
19
|
/** Independent, replayable read; exiting it never consumes the handle. */
|
|
33
20
|
stream(options?: DeliveryReadOptions): AsyncGenerator<SessionStreamEvent>;
|
|
34
21
|
/** Caches only a completed summary; failed/aborted reads can be retried. */
|
|
35
22
|
result(options?: DeliveryReadOptions): Promise<DeliveryResult<TOutput>>;
|
|
36
23
|
}
|
|
37
|
-
/** @internal Returns when the client sent the delivery's request, if it sent it. */
|
|
38
|
-
export declare function getDeliveryReceipt(delivery: Delivery): ClientSendReceipt | undefined;
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { EveError } from "#shared/eve-error.js";
|
|
1
2
|
/** A successful health request returned an unusable payload. */
|
|
2
|
-
export declare class HealthResponseError extends
|
|
3
|
+
export declare class HealthResponseError extends EveError {
|
|
4
|
+
static readonly errorName = "HealthResponseError";
|
|
5
|
+
readonly code: "invalid_health_response";
|
|
3
6
|
readonly issues: readonly string[];
|
|
4
7
|
constructor(issues?: readonly string[]);
|
|
5
8
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var HealthResponseError=class extends
|
|
1
|
+
import{EveError}from"#shared/eve-error.js";var HealthResponseError=class extends EveError{static errorName=`HealthResponseError`;issues;constructor(e=[]){let t=e.length===0?``:` (${e.join(`; `)})`;super(`invalid_health_response`,`The server returned an unrecognized eve health response.${t}`),this.issues=e}};export{HealthResponseError};
|
|
@@ -2,7 +2,9 @@ export { SessionStore } from "#client/session-store.js";
|
|
|
2
2
|
export { Client } from "#client/client.js";
|
|
3
3
|
export { AgentInfoResponseError } from "#client/agent-info-error.js";
|
|
4
4
|
export { HealthResponseError } from "#client/health-response-error.js";
|
|
5
|
-
export {
|
|
5
|
+
export { EveError } from "#shared/eve-error.js";
|
|
6
|
+
export { ClientError, ClientSessionStrandedError, type ClientErrorCode, } from "#client/client-error.js";
|
|
7
|
+
export { SessionNotActiveError } from "#channel/session-not-active-error.js";
|
|
6
8
|
export { conversationOf } from "#client/conversation.js";
|
|
7
9
|
export { agentCallActivity } from "#client/conversation-state.js";
|
|
8
10
|
export { transcriptOf, type TranscriptData, type TranscriptMessage, type TranscriptOptions, } from "#client/transcript.js";
|
|
@@ -12,10 +14,10 @@ export type { ClientAgentSession } from "#client/agent-session.js";
|
|
|
12
14
|
export type { ClientSession } from "#client/session.js";
|
|
13
15
|
export type { ClientSessions, CreatedClientSession, CreatedIdleClientSession, } from "#client/sessions.js";
|
|
14
16
|
export type { SessionStoreCallbacks, SessionStoreInit, SessionStoreSnapshot, SessionStoreStatus, PrepareSend, } from "#client/session-store.js";
|
|
15
|
-
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoRemoteAgentEntry, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, ClientAuth, ClientOptions, ClientRedirectPolicy, CreateSessionOptions, HeadersValue, HealthResult, RespondTurnOptions, SendTurnInput, SendTurnOptions, SessionSnapshot, ClientSessionState,
|
|
17
|
+
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoRemoteAgentEntry, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, ClientAuth, ClientOptions, ClientRedirectPolicy, CreateSessionOptions, HeadersValue, HealthResult, RespondTurnOptions, SendTurnInput, SendTurnOptions, SendTurnPayload, SessionSnapshot, ClientSessionState, ReconnectOptions, TokenValue, } from "#client/types.js";
|
|
16
18
|
export type { EveInteractionPart, EveMessage, EveMessageMetadata, EveMessagePart, EveToolPart, } from "#client/message-types.js";
|
|
17
19
|
export type { SessionEvent, SessionEventMeta, SessionStreamEvent, } from "#protocol/session-event.js";
|
|
18
|
-
export { endsTurn
|
|
20
|
+
export { endsTurn } from "#client/session-utils.js";
|
|
19
21
|
export type { AskedCall } from "#protocol/session-projection/reader.js";
|
|
20
22
|
export { isAnswer, parseAnswer, parseAnswers } from "#shared/input.js";
|
|
21
23
|
export type { AgentInfoMemoryEntry } from "#client/types.js";
|
package/dist/src/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{endsTurn
|
|
1
|
+
import{endsTurn}from"#client/session-utils.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{isAnswer,parseAnswer,parseAnswers}from"#shared/input.js";import{EveError}from"#shared/eve-error.js";import{agentCallActivity}from"#client/conversation-state.js";import{SessionStore}from"#client/session-store.js";import{ClientError,ClientSessionStrandedError}from"#client/client-error.js";import{conversationOf}from"#client/conversation.js";import{AgentInfoResponseError}from"#client/agent-info-error.js";import{HealthResponseError}from"#client/health-response-error.js";import{Client}from"#client/client.js";import{transcriptOf}from"#client/transcript.js";export{AgentInfoResponseError,Client,ClientError,ClientSessionStrandedError,EveError,HealthResponseError,SessionNotActiveError,SessionStore,agentCallActivity,conversationOf,endsTurn,isAnswer,parseAnswer,parseAnswers,transcriptOf};
|
|
@@ -1,16 +1,13 @@
|
|
|
1
1
|
import type { SessionStreamEvent } from "#protocol/session-event.js";
|
|
2
2
|
import type { StoredLine } from "#protocol/session-events/envelope.js";
|
|
3
|
-
import type { ClientRedirectPolicy,
|
|
4
|
-
interface RetryPolicy {
|
|
5
|
-
readonly baseDelayMs: number;
|
|
6
|
-
readonly maxAttempts: number;
|
|
7
|
-
readonly maxDelayMs: number;
|
|
8
|
-
}
|
|
3
|
+
import type { ClientRedirectPolicy, ReconnectOptions } from "#client/types.js";
|
|
9
4
|
interface ResolvedStreamReconnectPolicy {
|
|
10
5
|
/** False when the caller owns cursor recovery: one connection, then stop. */
|
|
11
6
|
readonly reconnect: boolean;
|
|
12
|
-
readonly
|
|
13
|
-
readonly
|
|
7
|
+
readonly retryableStatuses: ReadonlySet<number>;
|
|
8
|
+
readonly baseDelayMs: number;
|
|
9
|
+
readonly maxAttempts: number;
|
|
10
|
+
readonly maxDelayMs: number;
|
|
14
11
|
}
|
|
15
12
|
/** Backoff between reconnects after a transport failure. Following readers retry forever. */
|
|
16
13
|
export declare const RECONNECT_BACKOFF: {
|
|
@@ -30,10 +27,8 @@ interface FollowStreamInput {
|
|
|
30
27
|
/** Called once after consuming the durable tail captured when the connection opens. */
|
|
31
28
|
readonly onCaughtUp?: () => void;
|
|
32
29
|
readonly baseUrl: string;
|
|
33
|
-
readonly resolveReconnectPolicy?: () =>
|
|
34
|
-
readonly
|
|
35
|
-
/** @internal Test override for reconnecting an open stream that stops producing bytes. */
|
|
36
|
-
readonly streamReadIdleTimeoutMs?: number;
|
|
30
|
+
readonly resolveReconnectPolicy?: () => false | ReconnectOptions | undefined;
|
|
31
|
+
readonly reconnect?: false | ReconnectOptions;
|
|
37
32
|
readonly resolveHeaders: () => Promise<Headers>;
|
|
38
33
|
readonly redirect?: ClientRedirectPolicy;
|
|
39
34
|
/** eve stream route path, such as a session stream or a parent-origin subagent stream. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{ClientError,ClientSessionStrandedError,createClientError}from"#client/client-error.js";import{createEventReader}from"#protocol/session-lines.js";import{EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/session-http.js";import{createClientUrl}from"#client/url.js";import{throwIfAborted}from"#client/abort-signal.js";import{isV26Line}from"#protocol/v26-lines.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{readMessageStreamVersion}from"#client/stream-version.js";const RECONNECT_BACKOFF={baseDelayMs:250,maxDelayMs:5e3},DEFAULT_STREAM_RECONNECT_POLICY={reconnect:!0,
|
|
1
|
+
import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{ClientError,ClientSessionStrandedError,createClientError}from"#client/client-error.js";import{createEventReader}from"#protocol/session-lines.js";import{EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/session-http.js";import{createClientUrl}from"#client/url.js";import{throwIfAborted}from"#client/abort-signal.js";import{isV26Line}from"#protocol/v26-lines.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{readMessageStreamVersion}from"#client/stream-version.js";const RECONNECT_BACKOFF={baseDelayMs:250,maxDelayMs:5e3},DEFAULT_STREAM_RECONNECT_POLICY={reconnect:!0,retryableStatuses:new Set([404,409,425,500,502,503,504]),baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,reconnect:!1,maxAttempts:1};function isRetryableStreamError(e,t=DEFAULT_STREAM_RECONNECT_POLICY.retryableStatuses){return e instanceof ClientSessionStrandedError?!1:SessionNotActiveError.is(e)?t.has(409):e instanceof ClientError?e.code!==`session_version_unsupported`&&t.has(e.status):isStreamDisconnectError(e)}function resolveStreamReconnectPolicy(e){if(e===!1)return NO_STREAM_RECONNECT_POLICY;let t=DEFAULT_STREAM_RECONNECT_POLICY;return{reconnect:!0,retryableStatuses:e?.retryableStatuses?new Set(e.retryableStatuses):t.retryableStatuses,baseDelayMs:e?.baseDelayMs??t.baseDelayMs,maxAttempts:e?.maxAttempts??t.maxAttempts,maxDelayMs:e?.maxDelayMs??t.maxDelayMs}}async function*followStreamLines(e){let resolvePolicy=()=>resolveStreamReconnectPolicy(e.resolveReconnectPolicy===void 0?e.reconnect:e.resolveReconnectPolicy()),t=e.follow===!1||e.onCaughtUp!==void 0,n=e.startIndex,r=RECONNECT_BACKOFF.baseDelayMs,i=0,a,o=!1,passedTail=()=>a!==void 0&&n>a,noteProgress=()=>(!o&&passedTail()&&(o=!0,e.onCaughtUp?.()),e.follow===!1&&passedTail());for(;;){let o=resolvePolicy(),s;try{s=await openStreamBody({...e,retryPolicy:o,startIndex:n,requestTailIndex:(t||n<0)&&a===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if((t||n<0)&&a===void 0){if(a=s.tailIndex,a===void 0)throw s.close(),Error(`This read requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);n<0&&(n=Math.max(0,a+1+n))}try{e.onOpen?.(s.headers)}catch(e){throw s.close(),e}if(noteProgress()){s.close();return}let c=!1,l=!1;try{for await(let t of readNdjsonStream(s.body,{signal:e.signal,idleTimeoutMs:e.streamReadIdleTimeoutMs??3e4}))switch(t.kind){case`transport`:switch(t.record.$eve){case`position`:if(t.record.next>n&&(n=t.record.next),e.onPosition?.(n),noteProgress())return;break;case`stream.lease-ended`:l=!0;break;case`stream.ended`:c=!0}continue;case`unknown-transport`:continue;case`commit`:case`progress`:case`invalid`:{if(t.kind===`invalid`&&isV26Line(t.value))throw new ClientError(409,JSON.stringify({code:`session_version_unsupported`,error:`This session was started by an earlier eve version. Start a new session.`}));let a=n;if(n+=1,i=0,r=RECONNECT_BACKOFF.baseDelayMs,yield{line:t.kind===`invalid`?void 0:t.line,position:a},e.onPosition?.(n),noteProgress())return}}}catch(e){if(!isStreamDisconnectError(e))throw e}finally{s.close()}if(c||e.signal?.aborted||!resolvePolicy().reconnect)return;if(!l){if(i+=1,e.follow===!1&&i>=o.maxAttempts)throw Error(`The session stream kept disconnecting before the read reached its tail.`);if(await sleep(r,e.signal),e.signal?.aborted)return;r=Math.min(r*2,RECONNECT_BACKOFF.maxDelayMs)}}}async function*followStreamIterable(e){let t=createEventReader();for await(let{line:n,position:r}of followStreamLines(e)){if(n===void 0)continue;let e=t.read(n,r);for(let[t,n]of e.entries())yield{cursor:t===e.length-1?r+1:r,event:n}}}async function openStreamBody(e){let t=e.retryPolicy??resolveStreamReconnectPolicy(e.reconnect),n,r,i,a=t.baseDelayMs,o={...e.searchParams};e.startIndex!==0&&(o.startIndex=String(e.startIndex)),e.requestTailIndex===!0&&(o.includeTailIndex=`1`),e.follow===!1&&(o.follow=`false`);for(let s=0;s<t.maxAttempts;s+=1){throwIfAborted(e.signal);let c=createClientUrl(e.baseUrl,e.path,Object.keys(o).length>0?o:void 0),l=await e.resolveHeaders();throwIfAborted(e.signal);let u=new AbortController,d=e.signal?AbortSignal.any([e.signal,u.signal]):u.signal,f;try{f=await fetch(c,{cache:`no-store`,headers:l,redirect:e.redirect,signal:d})}catch(n){if(e.redirect===`error`&&n instanceof Error&&n.cause instanceof Error&&n.cause.message===`unexpected redirect`)throw Error(`The session stream refused a redirect. Use the final agent URL instead.`,{cause:n});if(e.signal?.aborted||!isStreamDisconnectError(n)||s===t.maxAttempts-1)throw n;await sleep(a,e.signal),a=Math.min(a*2,t.maxDelayMs);continue}if(f.ok){if(!f.body)throw new ClientError(f.status,`Response body is null.`,f.headers);try{readMessageStreamVersion(f.headers)}catch(e){throw f.body.cancel().catch(()=>{}),u.abort(),e}let e=!1;return{headers:f.headers,body:f.body,close:()=>{e||(e=!0,f.body?.cancel().catch(()=>{}),u.abort())},tailIndex:parseTailIndexHeader(f.headers)}}n=f.status,r=await f.text(),i=f.headers;let p=createClientError(f.status,r,f.headers);if(!isRetryableStreamError(p,t.retryableStatuses))throw p;s<t.maxAttempts-1&&(await sleep(a,e.signal),a=Math.min(a*2,t.maxDelayMs))}throw new ClientError(n??0,r??`Failed to open message stream.`,i)}function parseTailIndexHeader(e){let t=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(t===null||!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}async function sleep(e,t){t?.aborted||await new Promise(n=>{let onAbort=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e);t?.addEventListener(`abort`,onAbort,{once:!0})})}export{DEFAULT_STREAM_RECONNECT_POLICY,RECONNECT_BACKOFF,followStreamIterable,followStreamLines,isRetryableStreamError,openStreamBody,sleep};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { type PrewarmSessionResult } from "#protocol/prewarm-session.js";
|
|
2
2
|
import type { ClientRedirectPolicy } from "#client/types.js";
|
|
3
3
|
import { type DeliveryReceipt } from "#protocol/delivery.js";
|
|
4
|
-
import { createEveSessionCancelRoutePath, createEveSessionClearRoutePath, createEveSessionCompactRoutePath,
|
|
4
|
+
import { createEveSessionCancelRoutePath, createEveSessionClearRoutePath, createEveSessionCompactRoutePath, createEveSessionEndRoutePath } from "#protocol/routes.js";
|
|
5
5
|
declare const paths: {
|
|
6
6
|
cancel: typeof createEveSessionCancelRoutePath;
|
|
7
7
|
clear: typeof createEveSessionClearRoutePath;
|
|
8
8
|
compact: typeof createEveSessionCompactRoutePath;
|
|
9
|
-
|
|
9
|
+
end: typeof createEveSessionEndRoutePath;
|
|
10
10
|
};
|
|
11
11
|
export declare function prewarmClientSession(input: {
|
|
12
12
|
readonly context: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveSessionCancelRoutePath,createEveSessionClearRoutePath,createEveSessionCompactRoutePath,
|
|
1
|
+
import{createEveSessionCancelRoutePath,createEveSessionClearRoutePath,createEveSessionCompactRoutePath,createEveSessionEndRoutePath,createEveSessionRoutePath}from"#protocol/routes.js";import{createClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{PrewarmResponseSchema}from"#protocol/prewarm-session.js";import{DeliveryResponseSchema}from"#protocol/delivery.js";const paths={cancel:createEveSessionCancelRoutePath,clear:createEveSessionClearRoutePath,compact:createEveSessionCompactRoutePath,end:createEveSessionEndRoutePath};async function prewarmClientSession(e){let t=await fetch(createClientUrl(e.context.baseUrl,createEveSessionRoutePath(e.sessionId)),{headers:await e.context.resolveHeaders(),method:`POST`,signal:e.signal,redirect:e.context.redirect}),n=await t.text();if(!t.ok)throw createClientError(t.status,n,t.headers);let r;try{r=JSON.parse(n)}catch{throw Error(`Prewarm route returned invalid JSON (${t.status}).`)}let i=PrewarmResponseSchema.safeParse(r);if(!i.success)throw Error(`Prewarm route returned an invalid response.`);return{status:i.data.status}}async function sendClientControl(e){let{signal:t,turnId:n,reason:r}=e.options??{},i=e.kind===`cancel`?{turnId:n}:e.kind===`end`?{reason:r}:{},a=await e.context.resolveHeaders();a.set(`content-type`,`application/json`);let o=await fetch(createClientUrl(e.context.baseUrl,paths[e.kind](e.sessionId)),{body:JSON.stringify(i),headers:a,method:`POST`,signal:t,redirect:e.context.redirect}),s=await o.text();if(!o.ok)throw createClientError(o.status,s,o.headers);let c;try{c=JSON.parse(s)}catch{throw Error(`${e.kind} route returned invalid JSON (${o.status}).`)}let l=DeliveryResponseSchema.safeParse(c);if(!l.success||l.data.sessionId!==e.sessionId)throw Error(`${e.kind} route returned an invalid delivery receipt.`);return{sessionId:l.data.sessionId,deliveryId:l.data.deliveryId}}export{prewarmClientSession,sendClientControl};
|
|
@@ -4,7 +4,7 @@ import type { SessionStreamOptions } from "#client/types.js";
|
|
|
4
4
|
export interface SessionEventStreamOptions {
|
|
5
5
|
readonly startIndex?: number;
|
|
6
6
|
readonly headers?: Readonly<Record<string, string>>;
|
|
7
|
-
readonly
|
|
7
|
+
readonly reconnect?: SessionStreamOptions["reconnect"];
|
|
8
8
|
readonly onEvent: (event: SessionStreamEvent, historical: boolean) => void;
|
|
9
9
|
readonly onError: (error: unknown) => void;
|
|
10
10
|
}
|
|
@@ -14,6 +14,6 @@ export declare class SessionEventStream {
|
|
|
14
14
|
readonly caughtUp: Promise<void>;
|
|
15
15
|
constructor(session: ClientSession, options: SessionEventStreamOptions);
|
|
16
16
|
get ended(): boolean;
|
|
17
|
-
setOptions(options: Pick<SessionEventStreamOptions, "headers" | "
|
|
17
|
+
setOptions(options: Pick<SessionEventStreamOptions, "headers" | "reconnect">): void;
|
|
18
18
|
close(): void;
|
|
19
19
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{followClientSession}from"#client/session.js";var SessionEventStream=class{#e=new AbortController;#t=Promise.withResolvers();caughtUp=this.#t.promise;#n=!1;#r;#i;constructor(e,t){this.setOptions(t),this.caughtUp.catch(()=>{}),(async()=>{let n=!0;try{for await(let r of followClientSession(e,{signal:this.#e.signal,resolveHeaders:()=>this.#r,resolveReconnectPolicy:()=>this.#i,startIndex:t.startIndex,onCaughtUp:()=>{n=!1,this.#t.resolve()}})){if(this.#e.signal.aborted)return;if(t.onEvent(r,n),r.type===`session.ended`)break}this.#t.resolve()}catch(e){this.#n=!0,this.#t.reject(e),this.#e.signal.aborted||t.onError(e)}finally{this.#n=!0}})()}get ended(){return this.#n}setOptions(e){`headers`in e&&(this.#r=e.headers),`
|
|
1
|
+
import{followClientSession}from"#client/session.js";var SessionEventStream=class{#e=new AbortController;#t=Promise.withResolvers();caughtUp=this.#t.promise;#n=!1;#r;#i;constructor(e,t){this.setOptions(t),this.caughtUp.catch(()=>{}),(async()=>{let n=!0;try{for await(let r of followClientSession(e,{signal:this.#e.signal,resolveHeaders:()=>this.#r,resolveReconnectPolicy:()=>this.#i,startIndex:t.startIndex,onCaughtUp:()=>{n=!1,this.#t.resolve()}})){if(this.#e.signal.aborted)return;if(t.onEvent(r,n),r.type===`session.ended`)break}this.#t.resolve()}catch(e){this.#n=!0,this.#t.reject(e),this.#e.signal.aborted||t.onError(e)}finally{this.#n=!0}})()}get ended(){return this.#n}setOptions(e){`headers`in e&&(this.#r=e.headers),`reconnect`in e&&(this.#i=e.reconnect)}close(){this.#n=!0;let e=new DOMException(`Session stream was detached.`,`AbortError`);this.#e.abort(e),this.#t.reject(e)}};export{SessionEventStream};
|
|
@@ -24,7 +24,7 @@ export declare class SessionStore {
|
|
|
24
24
|
/**
|
|
25
25
|
* Follow an accepted delivery in this session until it settles or the session ends.
|
|
26
26
|
* The receipt may come from another store. Repeating it is safe and retries a closed stream.
|
|
27
|
-
* Pass only a receipt returned by `send`, `respond`, `clear`, `compact`, or `
|
|
27
|
+
* Pass only a receipt returned by `send`, `respond`, `clear`, `compact`, or `end`: a receipt
|
|
28
28
|
* may arrive before its delivery is admitted, so an id the stream never admits keeps the store
|
|
29
29
|
* busy and its stream open until the session ends or `newSession()`.
|
|
30
30
|
* Catch-up updates recorded failures without replaying live completion callbacks.
|
|
@@ -37,12 +37,8 @@ export declare class SessionStore {
|
|
|
37
37
|
cancel(): Promise<Delivery>;
|
|
38
38
|
compact(): Promise<Delivery>;
|
|
39
39
|
clear(): Promise<Delivery>;
|
|
40
|
-
|
|
40
|
+
end(): Promise<Delivery>;
|
|
41
41
|
[attachStore](): void;
|
|
42
42
|
[detachStore](): void;
|
|
43
43
|
newSession(): void;
|
|
44
44
|
}
|
|
45
|
-
/** @internal Detaches local transport without cancelling durable server work. */
|
|
46
|
-
export declare function detachSessionStore(store: SessionStore): void;
|
|
47
|
-
/** @internal Starts mount-scoped session work after the framework commits. */
|
|
48
|
-
export declare function attachSessionStore(store: SessionStore): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{activeTurn,failure,idle}from"#protocol/session-projection/selectors.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{StreamDelivery}from"#client/delivery.js";import{toError}from"#shared/errors.js";import{assertAnswerable,assertExclusiveTurnInput,isAbortError}from"#client/session-store-helpers.js";import{throwIfAborted}from"#client/abort-signal.js";import{Client}from"#client/client.js";import{OptimisticMessageSubmissions}from"#client/optimistic-message-submissions.js";import{ConversationClient}from"#client/conversation-client.js";import{waitWithSignal}from"#shared/wait-with-signal.js";const detachStore=Symbol(`detachSessionStore`),attachStore=Symbol(`attachSessionStore`);var SessionStore=class{#e;#t;#n;#r;#i;#a=new Set;#o=new Set;#s;#c;#l=new Set;#u=new Set;#d=!1;#f=!1;#p=0;#m=!1;#h={};#g=new AbortController;#_;#v;#y;#b;#x;#S;#C;#w;#T=!1;#E=0;#D=0;#O=new Set;#k=[];constructor(e){this.#t=e.prewarm??!1,this.#n=e.followAgents??!1,this.#r=e.followWhile??(()=>!0),this.#i=e.session!==void 0,this.#e=this.#i?void 0:e.client??new Client({auth:e.auth,headers:e.headers,baseUrl:e.baseUrl??``}),this.#s=new ConversationClient(()=>this.#Z()),this.#S=(e.initialEvents??[]).filter(e=>this.#s.hydrate(e)),this.#c=new OptimisticMessageSubmissions(e=>this.#s.showSubmissions(e),e.optimistic??!0),this.#b=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex,inbox:e.initialSession.inbox})),this.#x=this.#q(),this.#C=this.#X()}get snapshot(){return this.#C}observe(){this.#p+=1,this.#M();let e=!1;return()=>{e||(e=!0,--this.#p,!this.#f&&this.#p===0&&this.#N())}}setCallbacks(e){this.#h=e}subscribe(e){return this.#a.add(e),()=>void this.#a.delete(e)}async prewarm(){if(this.#b!==void 0)return await this.#L(this.#b);let e=this.#g;try{await this.#I()}catch(t){throw e===this.#g&&!isAbortError(t)&&this.#l.size===0&&this.#J(t),t}e===this.#g&&this.#r(this.#s.conversation.view)&&this.#z()}async send(e){if(this.#y!==void 0)throw Error(`eve session is resuming.`);assertExclusiveTurnInput(e),assertAnswerable(e,this.#s.conversation);let t=this.#g,n=e.signal?AbortSignal.any([t.signal,e.signal]):t.signal,r=Promise.withResolvers();this.#l.add(r.promise),this.#x=void 0;let i=this.#c.submit(e,e.turnPolicy===`steer`?activeTurn(this.#s.view)?.turnId:void 0),a=this.#s.projectAnswers(e.answers);this.#Z();let o=!1;try{let s=this.#h.prepareSend===void 0?e:await waitWithSignal(Promise.resolve(this.#h.prepareSend(e)),n);throwIfAborted(n),assertExclusiveTurnInput(s),s!==e&&(i=this.#c.resubmit(i,s),a=this.#s.replaceAnswers(a,s),this.#Z()),o=!0,this.#E+=1;let c=await this.#R({...s,signal:n});throwIfAborted(n);let l=c.deliveryId;if(l===void 0)throw Error(`The server did not identify the accepted delivery.`);return a?.accept(l),a=void 0,t===this.#g&&(i!==void 0&&(this.#s.confirmSubmission(i,l),this.#c.correlate(i,l)),this.#H(l),this.#h.onSessionChange?.(this.#Y)),r.resolve(l),new StreamDelivery({sessionId:c.sessionId,deliveryId:l,createStream:e=>c.stream(e)})}catch(e){throw t===this.#g&&(a?.(),this.#c.fail(toError(e),i),isAbortError(e)||this.#J(e)),e}finally{r.resolve(void 0),t===this.#g&&(this.#l.delete(r.promise),o&&--this.#E,this.#Z(),this.#G())}}follow(e){if(this.#b===void 0)throw Error(`An eve session is required before following.`);if(e.sessionId!==this.#b.id)throw Error(`The delivery belongs to a different eve session.`);let t=this.#s.view,n=t.deliveries[e.deliveryId];t.session.status!==`ended`&&n?.status!==`settled`&&(this.#x=void 0,this.#H(e.deliveryId),this.#u.has(e.deliveryId)&&this.#z(),this.#Z())}resume(){if(this.#y!==void 0)return this.#y;if(this.#b===void 0)return Promise.reject(Error(`An eve session is required before resuming.`));if(this.#l.size>0)return Promise.reject(Error(`eve session has pending submissions.`));let e=this.#g;this.#x=void 0;let t=this.#z({startIndex:this.#s.view.position}).caughtUp.then(()=>{e===this.#g&&(this.#x??=this.#q())}).finally(()=>{e===this.#g&&(this.#y=void 0,this.#Z(),this.#G())});return this.#y=t,this.#Z(!0),t}async cancel(){let e=this.#g,t=activeTurn(this.#s.view)?.turnId??await this.#A(e.signal);return throwIfAborted(e.signal),this.#j(e=>e.cancel({turnId:t??null}))}async#A(e){let t=new Set(this.#u.keys()),n=[...this.#l],r=n.length,i=Promise.withResolvers(),check=()=>{let e=this.#s.view;if(e.session.status===`ended`)return i.resolve(void 0);for(let n of t){let r=e.deliveries[n],a=r?.turnId===void 0?void 0:e.turns[r.turnId];if(a?.status===`running`)return i.resolve(a.turnId);(r?.status===`settled`||a?.status===`settled`)&&t.delete(n)}r===0&&t.size===0?i.resolve(void 0):this.#x!==void 0&&i.reject(this.#x)};this.#o.add(check);for(let e of n)e.then(e=>{--r,e!==void 0&&t.add(e),check()});try{return check(),await waitWithSignal(i.promise,e)}finally{this.#o.delete(check)}}compact(){return this.#j(e=>e.compact())}clear(){return this.#j(e=>e.clear())}reset(){return this.#j(e=>e.reset())}async#j(e){let t=this.#b;if(t===void 0)throw new SessionNotActiveError;let n=this.#g;this.#E+=1,this.#z(),this.#Z();try{let r=await e(t);return throwIfAborted(n.signal),this.#H(r.deliveryId),r}finally{n===this.#g&&(--this.#E,this.#Z(),this.#G())}}[attachStore](){this.#f=!0,this.#M()}#M(){if(this.#d)return;this.#d=!0,this.#B();let e=this.#m&&this.#r(this.#s.conversation.view);this.#m=!1,this.#b!==void 0&&(this.#W||e)&&this.#z(),this.#t&&this.#b===void 0&&this.prewarm().catch(()=>{})}[detachStore](){this.#f=!1,this.#p===0&&this.#N()}#N(){this.#d=!1,this.#m=this.#s.streaming,this.#P()}newSession(){this.#P(),this.#i||(this.#b=void 0),this.#u.clear(),this.#O.clear(),this.#S=[],this.#s.reset(),this.#c.reset(),this.#x=void 0,this.#d&&this.#B(),this.#h.onSessionChange?.(this.#Y),this.#Z(),this.#t&&this.#d&&this.prewarm().catch(()=>{})}#P(){this.#s.stop(),this.#g.abort(),this.#g=new AbortController,this.#_=void 0,this.#y=void 0,this.#l.clear(),this.#E=0,this.#D=0,this.#F()}#F(){this.#s.closeStream();let e=this.#S.length;for(;e>0&&this.#S[e-1].meta.endOfLine===!1;)--e;e<this.#S.length&&(this.#S=this.#S.slice(0,e)),this.#k=[],this.#T=!1}#I(e){if(this.#_!==void 0)return this.#_;let t=this.#e;if(t===void 0)return Promise.reject(Error(`This store cannot create a session.`));let n=this.#g,r=e?.signal??n.signal,i=(async()=>{let i,a;return e?.message===void 0?{session:i}=await t.sessions.create({signal:r}):{session:i,delivery:a}=await t.sessions.create({...e,message:e.message,signal:r}),throwIfAborted(n.signal),this.#b=i,this.#x=void 0,this.#h.onSessionChange?.(this.#Y),this.#B(),this.#Z(),a})();this.#_=i;let clear=()=>{this.#_===i&&(this.#_=void 0)};return i.then(clear,clear),i}#L(e){let t=this.#g;if(this.#v?.lifetime===t)return this.#v.promise;let n=e.prewarm({signal:t.signal}).then(()=>void 0),r={lifetime:t,promise:n};this.#v=r;let clear=()=>{this.#v===r&&(this.#v=void 0)};return n.then(clear,clear),n}async#R(e){if(this.#_!==void 0&&await waitWithSignal(this.#_.catch(()=>void 0),e.signal),throwIfAborted(e.signal),this.#b===void 0){if(e.message===void 0)throw Error(`Cannot answer before the session starts.`);let t=await this.#I(e);if(this.#z(e),t===void 0)throw Error(`The session was created without accepting a message.`);return t}return this.#z(e),e.answers===void 0?await this.#b.send(e.message,e):await this.#b.respond(e.answers,e)}#z(e={}){if(this.#b===void 0)throw Error(`A session is required before opening its stream.`);this.#B();let t=this.#g;return this.#s.stream(this.#b,{startIndex:this.#s.view.position,...e,onEvent:(e,n)=>{t===this.#g&&this.#V(e,n)},onError:e=>{t===this.#g&&(this.#F(),this.#J(e))}})}#B(){this.#n&&this.#b&&this.#s.follow(this.#b,this.#n)}#V(e,t){let n=this.#g;if(this.#T=e.meta.endOfLine===!1,!this.#s.observe(e,{notify:!1})||(this.#S=[...this.#S,e],this.#h.onEvent?.(e),n!==this.#g)||(e.type===`turn.started`&&!t&&(this.#x=void 0),(e.type===`turn.settled`||e.type===`session.ended`)&&this.#k.push({event:e,historical:t}),this.#T))return;let r=this.#s.view,i=new Set([...this.#u].map(e=>r.deliveries[e]?.turnId).filter(e=>e!==void 0));this.#U();for(let e of this.#k.splice(0)){if(e.event.type===`turn.settled`)e.historical?i.has(e.event.data.turnId)&&this.#l.size===0&&(this.#x??=this.#q(e.event.data.turnId)):this.#K(e.event.data.turnId);else if(e.event.data.outcome===`failed`){let t=Object.assign(Error(e.event.data.error?.message??`The session failed.`),{name:e.event.data.error?.code??`SESSION_FAILED`});e.historical?this.#l.size===0&&(this.#x??=t):this.#J(t)}if(n!==this.#g)return}for(let e of this.#o)e();this.#h.onSessionChange?.(this.#Y),n===this.#g&&(this.#Z(),n===this.#g&&(this.#s.reconcileFollowing(),n===this.#g&&this.#G()))}#H(e){this.#u.add(e),this.#U();let t=this.#s.view,n=t.deliveries[e]?.turnId;n!==void 0&&t.turns[n]?.status===`settled`&&(this.#x??=this.#q(n)),t.session.status===`ended`&&(this.#x??=this.#q())}#U(){let e=this.#s.view;e.session.status===`ended`&&this.#u.clear(),this.#c.reconcile(e);for(let t of this.#u)e.deliveries[t]?.status===`settled`&&this.#u.delete(t)}get#W(){return this.#y!==void 0||this.#E>0||this.#l.size>0||this.#u.size>0}#G(){this.#T||this.#W||this.#r(this.#s.conversation.view)||this.#s.closeStream()}#K(e){if(this.#O.has(e)||this.#s.view.turns[e]?.status!==`settled`)return;this.#O.add(e),this.#D+=1;let t=failure(this.#s.view,e);t!==void 0&&this.#J(Object.assign(Error(t.message),{name:t.code}))}#q(e=this.#s.view.session.latestTurnId){let t=this.#s.view,n=failure(t,e);return n===void 0?void 0:Object.assign(Error(n.message),{name:n.code})}#J(e){let t=this.#x!==void 0;this.#x=toError(e);for(let e of this.#o)e();t||this.#h.onError?.(this.#x),this.#Z()}get#Y(){if(this.#b===void 0)return this.#w=void 0;let e=this.#b.id,t=this.#s.view.position,{inbox:n}=this.#b.state;return(this.#w?.sessionId!==e||this.#w.streamIndex!==t||this.#w.inbox!==n)&&(this.#w={sessionId:e,streamIndex:t,inbox:n}),this.#w}#X(){this.#s.holdUnconfirmedMessages(this.#E>0&&this.#c.awaitingReceipt);let e=this.#s.conversation,{view:t}=e;return{...e,view:t,error:this.#x,events:this.#S,session:this.#Y,status:this.#y===void 0?this.#W||!idle(this.#s.view)?`busy`:`idle`:`resuming`}}#Z(e=!1){if(this.#y!==void 0&&!e)return;if(this.#T){if(this.#x===void 0&&!this.#W)return;this.#C={...this.#C,error:this.#x,status:this.#y===void 0?this.#W?`busy`:this.#C.status:`resuming`};for(let e of this.#a)e();return}this.#C=this.#X();let t=this.#D,n=this.#g;this.#D=0;for(let e of this.#a)e();for(let e=0;e<t&&n===this.#g;e+=1)this.#h.onFinish?.(this.#C)}};function detachSessionStore(e){e[detachStore]()}function attachSessionStore(e){e[attachStore]()}export{SessionStore,attachSessionStore,detachSessionStore};
|
|
1
|
+
import{activeTurn,failure,idle}from"#protocol/session-projection/selectors.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{StreamDelivery}from"#client/delivery.js";import{toError}from"#shared/errors.js";import{assertAnswerable,assertExclusiveTurnInput,isAbortError}from"#client/session-store-helpers.js";import{throwIfAborted}from"#client/abort-signal.js";import{Client}from"#client/client.js";import{OptimisticMessageSubmissions}from"#client/optimistic-message-submissions.js";import{ConversationClient}from"#client/conversation-client.js";import{waitWithSignal}from"#shared/wait-with-signal.js";const detachStore=Symbol(`detachSessionStore`),attachStore=Symbol(`attachSessionStore`);var SessionStore=class{#e;#t;#n;#r;#i;#a=new Set;#o=new Set;#s;#c;#l=new Set;#u=new Set;#d=!1;#f=!1;#p=0;#m=!1;#h={};#g=new AbortController;#_;#v;#y;#b;#x;#S;#C;#w;#T=!1;#E=0;#D=0;#O=new Set;#k=[];constructor(e){this.#t=e.prewarm??!1,this.#n=e.followAgents??!1,this.#r=e.followWhile??(()=>!0),this.#i=e.session!==void 0,this.#e=this.#i?void 0:e.client??new Client({auth:e.auth,headers:e.headers,baseUrl:e.baseUrl??``}),this.#s=new ConversationClient(()=>this.#Z()),this.#S=(e.initialEvents??[]).filter(e=>this.#s.hydrate(e)),this.#c=new OptimisticMessageSubmissions(e=>this.#s.showSubmissions(e),e.optimistic??!0),this.#b=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex,inbox:e.initialSession.inbox})),this.#x=this.#q(),this.#C=this.#X()}get snapshot(){return this.#C}observe(){this.#p+=1,this.#M();let e=!1;return()=>{e||(e=!0,--this.#p,!this.#f&&this.#p===0&&this.#N())}}setCallbacks(e){this.#h=e}subscribe(e){return this.#a.add(e),()=>void this.#a.delete(e)}async prewarm(){if(this.#b!==void 0)return await this.#L(this.#b);let e=this.#g;try{await this.#I()}catch(t){throw e===this.#g&&!isAbortError(t)&&this.#l.size===0&&this.#J(t),t}e===this.#g&&this.#r(this.#s.conversation.view)&&this.#z()}async send(e){if(this.#y!==void 0)throw Error(`eve session is resuming.`);assertExclusiveTurnInput(e),assertAnswerable(e,this.#s.conversation);let t=this.#g,n=e.signal?AbortSignal.any([t.signal,e.signal]):t.signal,r=Promise.withResolvers();this.#l.add(r.promise),this.#x=void 0;let i=this.#c.submit(e,e.turnPolicy===`steer`?activeTurn(this.#s.view)?.turnId:void 0),a=this.#s.projectAnswers(e.answers);this.#Z();let o=!1;try{let s=this.#h.prepareSend===void 0?e:await waitWithSignal(Promise.resolve(this.#h.prepareSend(e)),n);throwIfAborted(n),assertExclusiveTurnInput(s),s!==e&&(i=this.#c.resubmit(i,s),a=this.#s.replaceAnswers(a,s),this.#Z()),o=!0,this.#E+=1;let c=await this.#R({...s,signal:n});throwIfAborted(n);let l=c.deliveryId;if(l===void 0)throw Error(`The server did not identify the accepted delivery.`);return a?.accept(l),a=void 0,t===this.#g&&(i!==void 0&&(this.#s.confirmSubmission(i,l),this.#c.correlate(i,l)),this.#H(l),this.#h.onSessionChange?.(this.#Y)),r.resolve(l),new StreamDelivery({sessionId:c.sessionId,deliveryId:l,createStream:e=>c.stream(e)})}catch(e){throw t===this.#g&&(a?.(),this.#c.fail(toError(e),i),isAbortError(e)||this.#J(e)),e}finally{r.resolve(void 0),t===this.#g&&(this.#l.delete(r.promise),o&&--this.#E,this.#Z(),this.#G())}}follow(e){if(this.#b===void 0)throw Error(`An eve session is required before following.`);if(e.sessionId!==this.#b.id)throw Error(`The delivery belongs to a different eve session.`);let t=this.#s.view,n=t.deliveries[e.deliveryId];t.session.status!==`ended`&&n?.status!==`settled`&&(this.#x=void 0,this.#H(e.deliveryId),this.#u.has(e.deliveryId)&&this.#z(),this.#Z())}resume(){if(this.#y!==void 0)return this.#y;if(this.#b===void 0)return Promise.reject(Error(`An eve session is required before resuming.`));if(this.#l.size>0)return Promise.reject(Error(`eve session has pending submissions.`));let e=this.#g;this.#x=void 0;let t=this.#z({startIndex:this.#s.view.position}).caughtUp.then(()=>{e===this.#g&&(this.#x??=this.#q())}).finally(()=>{e===this.#g&&(this.#y=void 0,this.#Z(),this.#G())});return this.#y=t,this.#Z(!0),t}async cancel(){let e=this.#g,t=activeTurn(this.#s.view)?.turnId??await this.#A(e.signal);return throwIfAborted(e.signal),this.#j(e=>e.cancel({turnId:t??null}))}async#A(e){let t=new Set(this.#u.keys()),n=[...this.#l],r=n.length,i=Promise.withResolvers(),check=()=>{let e=this.#s.view;if(e.session.status===`ended`)return i.resolve(void 0);for(let n of t){let r=e.deliveries[n],a=r?.turnId===void 0?void 0:e.turns[r.turnId];if(a?.status===`running`)return i.resolve(a.turnId);(r?.status===`settled`||a?.status===`settled`)&&t.delete(n)}r===0&&t.size===0?i.resolve(void 0):this.#x!==void 0&&i.reject(this.#x)};this.#o.add(check);for(let e of n)e.then(e=>{--r,e!==void 0&&t.add(e),check()});try{return check(),await waitWithSignal(i.promise,e)}finally{this.#o.delete(check)}}compact(){return this.#j(e=>e.compact())}clear(){return this.#j(e=>e.clear())}end(){return this.#j(e=>e.end())}async#j(e){let t=this.#b;if(t===void 0)throw new SessionNotActiveError;let n=this.#g;this.#E+=1,this.#z(),this.#Z();try{let r=await e(t);return throwIfAborted(n.signal),this.#H(r.deliveryId),r}finally{n===this.#g&&(--this.#E,this.#Z(),this.#G())}}[attachStore](){this.#f=!0,this.#M()}#M(){if(this.#d)return;this.#d=!0,this.#B();let e=this.#m&&this.#r(this.#s.conversation.view);this.#m=!1,this.#b!==void 0&&(this.#W||e)&&this.#z(),this.#t&&this.#b===void 0&&this.prewarm().catch(()=>{})}[detachStore](){this.#f=!1,this.#p===0&&this.#N()}#N(){this.#d=!1,this.#m=this.#s.streaming,this.#P()}newSession(){this.#P(),this.#i||(this.#b=void 0),this.#u.clear(),this.#O.clear(),this.#S=[],this.#s.reset(),this.#c.reset(),this.#x=void 0,this.#d&&this.#B(),this.#h.onSessionChange?.(this.#Y),this.#Z(),this.#t&&this.#d&&this.prewarm().catch(()=>{})}#P(){this.#s.stop(),this.#g.abort(),this.#g=new AbortController,this.#_=void 0,this.#y=void 0,this.#l.clear(),this.#E=0,this.#D=0,this.#F()}#F(){this.#s.closeStream();let e=this.#S.length;for(;e>0&&this.#S[e-1].meta.endOfLine===!1;)--e;e<this.#S.length&&(this.#S=this.#S.slice(0,e)),this.#k=[],this.#T=!1}#I(e){if(this.#_!==void 0)return this.#_;let t=this.#e;if(t===void 0)return Promise.reject(Error(`This store cannot create a session.`));let n=this.#g,r=e?.signal??n.signal,i=(async()=>{let i,a;return e?.message===void 0?{session:i}=await t.sessions.create({signal:r}):{session:i,delivery:a}=await t.sessions.create({...e,message:e.message,signal:r}),throwIfAborted(n.signal),this.#b=i,this.#x=void 0,this.#h.onSessionChange?.(this.#Y),this.#B(),this.#Z(),a})();this.#_=i;let clear=()=>{this.#_===i&&(this.#_=void 0)};return i.then(clear,clear),i}#L(e){let t=this.#g;if(this.#v?.lifetime===t)return this.#v.promise;let n=e.prewarm({signal:t.signal}).then(()=>void 0),r={lifetime:t,promise:n};this.#v=r;let clear=()=>{this.#v===r&&(this.#v=void 0)};return n.then(clear,clear),n}async#R(e){if(this.#_!==void 0&&await waitWithSignal(this.#_.catch(()=>void 0),e.signal),throwIfAborted(e.signal),this.#b===void 0){if(e.message===void 0)throw Error(`Cannot answer before the session starts.`);let t=await this.#I(e);if(this.#z(e),t===void 0)throw Error(`The session was created without accepting a message.`);return t}return this.#z(e),e.answers===void 0?await this.#b.send(e.message,e):await this.#b.respond(e.answers,e)}#z(e={}){if(this.#b===void 0)throw Error(`A session is required before opening its stream.`);this.#B();let t=this.#g;return this.#s.stream(this.#b,{startIndex:this.#s.view.position,...e,onEvent:(e,n)=>{t===this.#g&&this.#V(e,n)},onError:e=>{t===this.#g&&(this.#F(),this.#J(e))}})}#B(){this.#n&&this.#b&&this.#s.follow(this.#b,this.#n)}#V(e,t){let n=this.#g;if(this.#T=e.meta.endOfLine===!1,!this.#s.observe(e,{notify:!1})||(this.#S=[...this.#S,e],this.#h.onEvent?.(e),n!==this.#g)||(e.type===`turn.started`&&!t&&(this.#x=void 0),(e.type===`turn.settled`||e.type===`session.ended`)&&this.#k.push({event:e,historical:t}),this.#T))return;let r=this.#s.view,i=new Set([...this.#u].map(e=>r.deliveries[e]?.turnId).filter(e=>e!==void 0));this.#U();for(let e of this.#k.splice(0)){if(e.event.type===`turn.settled`)e.historical?i.has(e.event.data.turnId)&&this.#l.size===0&&(this.#x??=this.#q(e.event.data.turnId)):this.#K(e.event.data.turnId);else if(e.event.data.outcome===`failed`){let t=Object.assign(Error(e.event.data.error?.message??`The session failed.`),{name:e.event.data.error?.code??`SESSION_FAILED`});e.historical?this.#l.size===0&&(this.#x??=t):this.#J(t)}if(n!==this.#g)return}for(let e of this.#o)e();this.#h.onSessionChange?.(this.#Y),n===this.#g&&(this.#Z(),n===this.#g&&(this.#s.reconcileFollowing(),n===this.#g&&this.#G()))}#H(e){this.#u.add(e),this.#U();let t=this.#s.view,n=t.deliveries[e]?.turnId;n!==void 0&&t.turns[n]?.status===`settled`&&(this.#x??=this.#q(n)),t.session.status===`ended`&&(this.#x??=this.#q())}#U(){let e=this.#s.view;e.session.status===`ended`&&this.#u.clear(),this.#c.reconcile(e);for(let t of this.#u)e.deliveries[t]?.status===`settled`&&this.#u.delete(t)}get#W(){return this.#y!==void 0||this.#E>0||this.#l.size>0||this.#u.size>0}#G(){this.#T||this.#W||this.#r(this.#s.conversation.view)||this.#s.closeStream()}#K(e){if(this.#O.has(e)||this.#s.view.turns[e]?.status!==`settled`)return;this.#O.add(e),this.#D+=1;let t=failure(this.#s.view,e);t!==void 0&&this.#J(Object.assign(Error(t.message),{name:t.code}))}#q(e=this.#s.view.session.latestTurnId){let t=this.#s.view,n=failure(t,e);return n===void 0?void 0:Object.assign(Error(n.message),{name:n.code})}#J(e){let t=this.#x!==void 0;this.#x=toError(e);for(let e of this.#o)e();t||this.#h.onError?.(this.#x),this.#Z()}get#Y(){if(this.#b===void 0)return this.#w=void 0;let e=this.#b.id,t=this.#s.view.position,{inbox:n}=this.#b.state;return(this.#w?.sessionId!==e||this.#w.streamIndex!==t||this.#w.inbox!==n)&&(this.#w={sessionId:e,streamIndex:t,inbox:n}),this.#w}#X(){this.#s.holdUnconfirmedMessages(this.#E>0&&this.#c.awaitingReceipt);let e=this.#s.conversation,{view:t}=e;return{...e,view:t,error:this.#x,events:this.#S,session:this.#Y,status:this.#y===void 0?this.#W||!idle(this.#s.view)?`busy`:`idle`:`resuming`}}#Z(e=!1){if(this.#y!==void 0&&!e)return;if(this.#T){if(this.#x===void 0&&!this.#W)return;this.#C={...this.#C,error:this.#x,status:this.#y===void 0?this.#W?`busy`:this.#C.status:`resuming`};for(let e of this.#a)e();return}this.#C=this.#X();let t=this.#D,n=this.#g;this.#D=0;for(let e of this.#a)e();for(let e=0;e<t&&n===this.#g;e+=1)this.#h.onFinish?.(this.#C)}};function detachSessionStore(e){e[detachStore]()}function attachSessionStore(e){e[attachStore]()}export{SessionStore,attachSessionStore,detachSessionStore};
|
|
@@ -3,12 +3,12 @@ import { ClientAgentSession } from "#client/agent-session.js";
|
|
|
3
3
|
import { type Delivery } from "#client/delivery.js";
|
|
4
4
|
import type { PrewarmSessionResult } from "#protocol/prewarm-session.js";
|
|
5
5
|
import type { Answer } from "#shared/input.js";
|
|
6
|
-
import type { ClientSessionState, ClientRedirectPolicy,
|
|
6
|
+
import type { ClientSessionState, ClientRedirectPolicy, RespondTurnOptions, SendTurnInput, SendTurnOptions, SessionSnapshot, SessionStreamOptions } from "#client/types.js";
|
|
7
7
|
declare const followSession: unique symbol;
|
|
8
8
|
interface FollowSessionOptions extends SessionStreamOptions {
|
|
9
9
|
readonly headers?: Readonly<Record<string, string>>;
|
|
10
10
|
readonly onCaughtUp?: () => void;
|
|
11
|
-
readonly resolveReconnectPolicy?: () => SessionStreamOptions["
|
|
11
|
+
readonly resolveReconnectPolicy?: () => SessionStreamOptions["reconnect"];
|
|
12
12
|
readonly resolveHeaders?: () => Readonly<Record<string, string>> | undefined;
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
@@ -23,15 +23,8 @@ export interface ClientSessionContext {
|
|
|
23
23
|
/** One fixed, ID-addressed conversation with an eve agent. */
|
|
24
24
|
export declare class ClientSession {
|
|
25
25
|
#private;
|
|
26
|
-
/**
|
|
26
|
+
/** Built by the eve client, which supplies the session's transport context. */
|
|
27
27
|
constructor(context: ClientSessionContext, state: ClientSessionState);
|
|
28
|
-
/** @internal */
|
|
29
|
-
static create<TOutput = unknown>(context: ClientSessionContext, input: SendTurnInput<TOutput> & CreateSessionOptions): Promise<{
|
|
30
|
-
readonly delivery: Delivery<TOutput>;
|
|
31
|
-
readonly session: ClientSession;
|
|
32
|
-
}>;
|
|
33
|
-
/** @internal */
|
|
34
|
-
static prewarm(context: ClientSessionContext, options?: CreateSessionOptions): Promise<ClientSession>;
|
|
35
28
|
/** The fixed session ID; reading it performs no I/O. */
|
|
36
29
|
get id(): string;
|
|
37
30
|
/** Current fixed session identity and durable stream cursor. */
|
|
@@ -62,7 +55,7 @@ export declare class ClientSession {
|
|
|
62
55
|
readonly signal?: AbortSignal;
|
|
63
56
|
}): Promise<Delivery>;
|
|
64
57
|
/** Terminally retires this exact session ID. The handle remains pinned to it. */
|
|
65
|
-
|
|
58
|
+
end(options?: {
|
|
66
59
|
readonly reason?: string;
|
|
67
60
|
readonly signal?: AbortSignal;
|
|
68
61
|
}): Promise<Delivery>;
|
|
@@ -79,6 +72,4 @@ export declare class ClientSession {
|
|
|
79
72
|
}>): ClientAgentSession;
|
|
80
73
|
[followSession](options: FollowSessionOptions): AsyncIterable<SessionStreamEvent>;
|
|
81
74
|
}
|
|
82
|
-
/** @internal Follow continuously while the frontend owns the session. */
|
|
83
|
-
export declare function followClientSession(session: ClientSession, options: FollowSessionOptions): AsyncIterable<SessionStreamEvent>;
|
|
84
75
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{StreamDelivery}from"#client/delivery.js";import{deliveryEvents}from"#client/delivery-events.js";import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath,createEveSessionStreamRoutePath}from"#protocol/routes.js";import{ClientError,createClientError}from"#client/client-error.js";import{EVE_SESSION_ID_HEADER}from"#protocol/session-http.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{createClientUrl}from"#client/url.js";import{throwIfAborted}from"#client/abort-signal.js";import{ClientAgentSession}from"#client/agent-session.js";import{messageForRequest}from"#client/file-parts.js";import{prewarmClientSession,sendClientControl}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=Date.now(),r=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0,t.stubs),i=Date.now(),{sessionId:a,deliveryId:o}=await readAcceptedMessage(r),s=new ClientSession(e,{sessionId:a,streamIndex:0}),c={deliveryId:o,startedAt:n,notReadyMs:0,acceptedAt:i};return{delivery:s.#i(r,t,0,o,c),session:s}}static async prewarm(e,t={}){let{sessionId:n}=await readAcceptedMessage(await postCreateSession(e,t));return new ClientSession(e,{sessionId:n,streamIndex:0})}get id(){return this.#t.sessionId}get state(){return this.#t}async snapshot(e){throwIfAborted(e?.signal);let t=[],n=0;for await(let{cursor:r,event:i}of this.#c({follow:!1,signal:e?.signal,startIndex:0}))t.push(i),n=r;return throwIfAborted(e?.signal),{events:t,session:{
|
|
1
|
+
import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{StreamDelivery}from"#client/delivery.js";import{deliveryEvents}from"#client/delivery-events.js";import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath,createEveSessionStreamRoutePath}from"#protocol/routes.js";import{ClientError,createClientError}from"#client/client-error.js";import{EVE_SESSION_ID_HEADER}from"#protocol/session-http.js";import{followStreamIterable,sleep}from"#client/open-stream.js";import{createClientUrl}from"#client/url.js";import{throwIfAborted}from"#client/abort-signal.js";import{ClientAgentSession}from"#client/agent-session.js";import{messageForRequest}from"#client/file-parts.js";import{prewarmClientSession,sendClientControl}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=Date.now(),r=await postTurn(e,EVE_SESSION_ROUTE_PATH,t,!0,t.stubs),i=Date.now(),{sessionId:a,deliveryId:o}=await readAcceptedMessage(r),s=new ClientSession(e,{sessionId:a,streamIndex:0}),c={deliveryId:o,startedAt:n,notReadyMs:0,acceptedAt:i};return{delivery:s.#i(r,t,0,o,c),session:s}}static async prewarm(e,t={}){let{sessionId:n}=await readAcceptedMessage(await postCreateSession(e,t));return new ClientSession(e,{sessionId:n,streamIndex:0})}get id(){return this.#t.sessionId}get state(){return this.#t}async snapshot(e){throwIfAborted(e?.signal);let t=[],n=0;for await(let{cursor:r,event:i}of this.#c({follow:!1,signal:e?.signal,startIndex:0}))t.push(i),n=r;return throwIfAborted(e?.signal),{events:t,session:{...this.#t,streamIndex:n}}}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 answer.`);return await this.#n({...t,answers:e},!1)}async#n(e,t){let n=this.#t.streamIndex,r=createEveSessionRoutePath(this.#t.sessionId),{response:i,timing:a}=await postSessionSend(this.#e,r,e,t,this.#t.inbox),{sessionId:o,deliveryId:s,inbox:c}=await readAcceptedMessage(i,this.#t.sessionId);if(o!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);if(this.#t={...this.#t,inbox:c},s===void 0)throw Error(`Message route did not return a delivery id. Update the server before sending with this client.`);return this.#i(i,e,n,s,{...a,deliveryId:s})}async prewarm(e){return await prewarmClientSession({context:this.#e,sessionId:this.#t.sessionId,signal:e?.signal})}async cancel(e){return this.#r(`cancel`,e)}async clear(e){return this.#r(`clear`,e)}async compact(e){return this.#r(`compact`,e)}async end(e){return this.#r(`end`,e)}async#r(e,t){let n=this.#t.streamIndex,r=await sendClientControl({context:this.#e,kind:e,options:t,sessionId:this.#t.sessionId});return new StreamDelivery({...r,createStream:t=>this.#a(n,{signal:t?.signal},r.deliveryId,e!==`end`)})}stream(e){return this.#o(e)}agent(e){return new ClientAgentSession(this.#e,this.id,e)}[followSession](e){return this.#o(e)}#i(e,t,n,r,i){if(e.body?.cancel().catch(()=>{}),r===void 0)throw Error(`Message route did not return a delivery id.`);return new StreamDelivery({createStream:e=>this.#a(n,{...t,signal:e?.signal},r),deliveryId:r,receipt:i,sessionId:this.#t.sessionId})}#a(e,t,n,r=!0){return deliveryEvents(this.#o({follow:r,headers:t.headers,signal:t.signal,startIndex:e,reconnect:t.reconnect}),n,t.signal)}async*#o(e){let t=e?.startIndex??this.#t.streamIndex;for await(let{cursor:n,event:r}of this.#c({follow:e?.follow,headers:e?.headers,onCaughtUp:e?.onCaughtUp,resolveHeaders:e?.resolveHeaders,resolveReconnectPolicy:e?.resolveReconnectPolicy,signal:e?.signal,startIndex:t,reconnect:e?.reconnect}))this.#s(n),yield r}#s(e){this.#t={...this.#t,streamIndex:Math.max(this.#t.streamIndex,e)}}#c(e){return followStreamIterable({onCaughtUp:e.onCaughtUp,follow:e.follow,baseUrl:this.#e.baseUrl,resolveHeaders:()=>this.#e.resolveHeaders(e.resolveHeaders?.()??e.headers),path:createEveSessionStreamRoutePath(this.#t.sessionId),redirect:this.#e.redirect,signal:e.signal,startIndex:e.startIndex,reconnect:e.reconnect,resolveReconnectPolicy:e.resolveReconnectPolicy})}};function followClientSession(e,t){return e[followSession](t)}async function postSessionSend(e,t,n,r,i){let a=Date.now(),o=a+2e4,s=250;for(;;){let c=Date.now();try{return{response:await postTurn(e,t,n,!1,void 0,i),timing:{startedAt:a,notReadyMs:c-a,acceptedAt:Date.now()}}}catch(e){if(!r||!isSessionNotReady(e))throw e;let t=o-Date.now();if(t<=0)throw e;await sleep(Math.min(s,t),n.signal)}throwIfAborted(n.signal),s=Math.min(s*2,2e3)}}async function postCreateSession(e,t){let n=await e.resolveHeaders(t.headers),r=t.stubs===void 0?void 0:JSON.stringify({stubs:t.stubs});r!==void 0&&n.set(`content-type`,`application/json`);let i=await fetch(createClientUrl(e.baseUrl,EVE_SESSION_ROUTE_PATH),{body:r,headers:n,method:`POST`,redirect:e.redirect,signal:t.signal??null});if(!i.ok){let e=await i.text();throw new ClientError(i.status,e,i.headers)}return i}function isSessionNotReady(e){return SessionNotActiveError.is(e)&&e.retryable}async function postTurn(e,t,n,r,i,a){let o=createMessageBody(n,r);if(o===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or answers.`);i!==void 0&&(o.stubs=i),a!==void 0&&(o.inbox=a);let s=await e.resolveHeaders(n.headers);s.set(`content-type`,`application/json`);let c=await fetch(createClientUrl(e.baseUrl,t),{body:JSON.stringify(o),headers:s,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!c.ok){let e=await c.text();throw createClientError(c.status,e,c.headers)}return c}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,inbox:typeof n.inbox==`string`?n.inbox:void 0,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=messageForRequest(e.message)),e.answers!==void 0&&e.answers.length>0&&(n.answers=e.answers),!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.answers===void 0?null:n}export{ClientSession,followClientSession};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ClientSession, type ClientSessionContext } from "#client/session.js";
|
|
2
2
|
import type { Delivery } from "#client/delivery.js";
|
|
3
|
-
import type { CreateSessionOptions, SendTurnInput } from "#client/types.js";
|
|
3
|
+
import type { ClientSessionState, CreateSessionOptions, SendTurnInput } from "#client/types.js";
|
|
4
4
|
/** Result of explicitly creating an ID-addressed client session. */
|
|
5
5
|
export interface CreatedClientSession<TOutput = unknown> {
|
|
6
6
|
readonly delivery: Delivery<TOutput>;
|
|
@@ -13,15 +13,12 @@ export interface CreatedIdleClientSession {
|
|
|
13
13
|
/** Collection surface for explicitly creating or attaching ID-addressed sessions. */
|
|
14
14
|
export declare class ClientSessions {
|
|
15
15
|
#private;
|
|
16
|
-
/**
|
|
16
|
+
/** Built by the eve client, which supplies its transport context. */
|
|
17
17
|
constructor(context: ClientSessionContext);
|
|
18
18
|
/** Creates a session and starts its first turn with a message. */
|
|
19
19
|
create<TOutput = unknown>(input: SendTurnInput<TOutput> & CreateSessionOptions): Promise<CreatedClientSession<TOutput>>;
|
|
20
20
|
/** Creates a conversation session before its first turn. */
|
|
21
21
|
create(options?: CreateSessionOptions): Promise<CreatedIdleClientSession>;
|
|
22
22
|
/** Attaches a fixed handle to a known session ID without performing I/O. */
|
|
23
|
-
attach(sessionId: string, options?:
|
|
24
|
-
readonly streamIndex?: number;
|
|
25
|
-
readonly inbox?: string;
|
|
26
|
-
}): ClientSession;
|
|
23
|
+
attach(sessionId: string, options?: Partial<Pick<ClientSessionState, "inbox" | "streamIndex">>): ClientSession;
|
|
27
24
|
}
|
|
@@ -4,7 +4,6 @@ import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index
|
|
|
4
4
|
import type { CancelTurnResult } from "#protocol/cancel-turn.js";
|
|
5
5
|
import type { ClearStatus } from "#protocol/clear-session.js";
|
|
6
6
|
import type { CompactStatus } from "#protocol/compact-session.js";
|
|
7
|
-
import type { ResetStatus } from "#protocol/reset-session.js";
|
|
8
7
|
import type { TurnPolicy } from "#channel/types.js";
|
|
9
8
|
import type { Answer } from "#shared/input.js";
|
|
10
9
|
import type { JsonObject } from "#shared/json.js";
|
|
@@ -118,9 +117,9 @@ export interface SendTurnOptions<TOutput = unknown> {
|
|
|
118
117
|
readonly outputSchema?: StandardJSONSchemaV1<unknown, TOutput> | JsonObject;
|
|
119
118
|
/**
|
|
120
119
|
* Reconnection policy for the response event stream. Omit to use the default
|
|
121
|
-
* policy, or pass `
|
|
120
|
+
* policy, or pass `false` when the caller owns cursor recovery.
|
|
122
121
|
*/
|
|
123
|
-
readonly
|
|
122
|
+
readonly reconnect?: false | ReconnectOptions;
|
|
124
123
|
/**
|
|
125
124
|
* Abort signal for cancelling the request.
|
|
126
125
|
*/
|
|
@@ -133,7 +132,11 @@ export interface SendTurnOptions<TOutput = unknown> {
|
|
|
133
132
|
}
|
|
134
133
|
/** Options for answering pending HITL input requests on a client session. */
|
|
135
134
|
export type RespondTurnOptions<TOutput = unknown> = Omit<SendTurnOptions<TOutput>, "turnPolicy">;
|
|
136
|
-
/**
|
|
135
|
+
/**
|
|
136
|
+
* One outbound turn accepted by `SessionStore.send` and passed through `prepareSend`: either a
|
|
137
|
+
* `message` with {@link SendTurnOptions}, or `answers` to pending input requests with
|
|
138
|
+
* {@link RespondTurnOptions}. Never both.
|
|
139
|
+
*/
|
|
137
140
|
export type SendTurnPayload<TOutput = unknown> = (SendTurnOptions<TOutput> & {
|
|
138
141
|
readonly answers?: never;
|
|
139
142
|
readonly message: MessageContent;
|
|
@@ -142,30 +145,23 @@ export type SendTurnPayload<TOutput = unknown> = (SendTurnOptions<TOutput> & {
|
|
|
142
145
|
readonly turnPolicy?: never;
|
|
143
146
|
readonly message?: never;
|
|
144
147
|
});
|
|
145
|
-
/**
|
|
146
|
-
export interface
|
|
147
|
-
/** Initial delay before retrying, in milliseconds. */
|
|
148
|
+
/** Settings for opening client stream connections and retrying bounded reads. */
|
|
149
|
+
export interface ReconnectOptions {
|
|
150
|
+
/** Initial delay before retrying a connection open, in milliseconds (default: 250). */
|
|
148
151
|
readonly baseDelayMs?: number;
|
|
149
|
-
/**
|
|
152
|
+
/**
|
|
153
|
+
* Maximum attempts to open each HTTP connection (default: 12). Also bounds consecutive
|
|
154
|
+
* transport failures for `follow: false`; following reads reconnect until stopped.
|
|
155
|
+
*/
|
|
150
156
|
readonly maxAttempts?: number;
|
|
151
|
-
/** Maximum delay between retries, in milliseconds. */
|
|
157
|
+
/** Maximum delay between connection-open retries, in milliseconds (default: 5000). */
|
|
152
158
|
readonly maxDelayMs?: number;
|
|
153
|
-
}
|
|
154
|
-
/** Configurable policy used when automatic stream reconnection is enabled. */
|
|
155
|
-
export interface ResolvedStreamReconnectPolicy {
|
|
156
159
|
/**
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
* retries failures for as long as it runs, and stops on what it reads.
|
|
160
|
+
* HTTP response statuses to retry; replaces the default list
|
|
161
|
+
* (404, 409, 425, 500, 502, 503, 504).
|
|
160
162
|
*/
|
|
161
|
-
readonly
|
|
162
|
-
/** HTTP response statuses that may be retried while opening a stream. */
|
|
163
|
-
readonly retryableErrorStatuses?: readonly number[];
|
|
163
|
+
readonly retryableStatuses?: readonly number[];
|
|
164
164
|
}
|
|
165
|
-
/** Automatic stream reconnection configuration. */
|
|
166
|
-
export type StreamReconnectPolicy = ResolvedStreamReconnectPolicy | {
|
|
167
|
-
readonly reconnect: false;
|
|
168
|
-
};
|
|
169
165
|
export type { SessionStreamOptions } from "#shared/session.js";
|
|
170
166
|
/** Result of requesting cancellation for a client session's active turn. */
|
|
171
167
|
export type CancelSessionResult = CancelTurnResult;
|
|
@@ -187,15 +183,6 @@ export type CompactResult = {
|
|
|
187
183
|
/** The fixed session ID was unknown or no longer active. */
|
|
188
184
|
readonly status: Extract<CompactStatus, "no_active_session">;
|
|
189
185
|
};
|
|
190
|
-
/** Result of terminally resetting a client session. */
|
|
191
|
-
export type ResetResult = {
|
|
192
|
-
/** The prior session was terminally retired. */
|
|
193
|
-
readonly previousSessionId: string;
|
|
194
|
-
readonly status: Extract<ResetStatus, "reset">;
|
|
195
|
-
} | {
|
|
196
|
-
/** The fixed session ID was unknown or no longer active. */
|
|
197
|
-
readonly status: Extract<ResetStatus, "no_active_session">;
|
|
198
|
-
};
|
|
199
186
|
export type { Delivery, DeliveryResult } from "#shared/delivery.js";
|
|
200
187
|
/**
|
|
201
188
|
* Response from the health endpoint.
|
|
@@ -204,7 +191,11 @@ export type { Delivery, DeliveryResult } from "#shared/delivery.js";
|
|
|
204
191
|
* Serializable cursor for one fixed, ID-addressed client session.
|
|
205
192
|
*/
|
|
206
193
|
export interface ClientSessionState {
|
|
207
|
-
/**
|
|
194
|
+
/**
|
|
195
|
+
* Opaque value the server issues so later sends reach the session faster. Persist it with the
|
|
196
|
+
* rest of the state and pass it back unchanged; eve may change or extend it in any release.
|
|
197
|
+
* A missing, stale, or rejected value only costs a slower lookup.
|
|
198
|
+
*/
|
|
208
199
|
readonly inbox?: string;
|
|
209
200
|
readonly sessionId: string;
|
|
210
201
|
readonly streamIndex: number;
|