eve 0.44.0 → 0.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/src/chunks/{use-eve-agent-C0SG1Ttk.js → use-eve-agent-BsLJiIbc.js} +224 -62
  3. package/dist/src/chunks/{use-eve-agent-D71oDil7.js → use-eve-agent-DpUEwS23.js} +222 -62
  4. package/dist/src/cli/commands/extension-init.js +1 -1
  5. package/dist/src/cli/commands/init.js +1 -1
  6. package/dist/src/cli/dev/tui/setup-commands.js +1 -1
  7. package/dist/src/client/eve-agent-store-helpers.d.ts +12 -0
  8. package/dist/src/client/eve-agent-store-helpers.js +2 -0
  9. package/dist/src/client/eve-agent-store.d.ts +8 -6
  10. package/dist/src/client/eve-agent-store.js +1 -2
  11. package/dist/src/client/ndjson.d.ts +3 -1
  12. package/dist/src/client/ndjson.js +3 -3
  13. package/dist/src/client/open-stream.d.ts +3 -0
  14. package/dist/src/client/open-stream.js +1 -1
  15. package/dist/src/context/build-dynamic-tools.js +1 -1
  16. package/dist/src/context/dynamic-tool-lifecycle.d.ts +5 -1
  17. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  18. package/dist/src/context/keys.d.ts +4 -2
  19. package/dist/src/context/keys.js +1 -1
  20. package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
  21. package/dist/src/execution/dispatch-turn-step.js +1 -1
  22. package/dist/src/execution/eve-workflow-attributes.d.ts +3 -0
  23. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  24. package/dist/src/execution/pending-turn-state.d.ts +9 -0
  25. package/dist/src/execution/pending-turn-state.js +1 -0
  26. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  27. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  28. package/dist/src/execution/turn-workflow.js +1 -1
  29. package/dist/src/execution/workflow-steps.js +1 -1
  30. package/dist/src/harness/channel-delivery-instrumentation.js +1 -1
  31. package/dist/src/harness/instrumentation/content-policy.d.ts +6 -0
  32. package/dist/src/harness/instrumentation/content-policy.js +1 -0
  33. package/dist/src/harness/instrumentation/lifecycle.d.ts +2 -0
  34. package/dist/src/harness/instrumentation/runtime-context.js +1 -1
  35. package/dist/src/harness/runtime-actions.js +1 -1
  36. package/dist/src/harness/tool-loop.js +2 -2
  37. package/dist/src/internal/application/package.js +1 -1
  38. package/dist/src/internal/workflow-bundle/dynamic-remote-agent-transform.js +2 -2
  39. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.d.ts +4 -4
  40. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +3 -4
  41. package/dist/src/internal/workflow-bundle/stable-module-id.d.ts +6 -0
  42. package/dist/src/internal/workflow-bundle/stable-module-id.js +1 -0
  43. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  44. package/dist/src/public/tools/approval/approval-helpers.js +1 -1
  45. package/dist/src/react/use-eve-agent.d.ts +10 -1
  46. package/dist/src/react/use-eve-agent.js +1 -1
  47. package/dist/src/runtime/attributes/emit.d.ts +1 -1
  48. package/dist/src/runtime/attributes/normalize.d.ts +1 -1
  49. package/dist/src/runtime/attributes/normalize.js +1 -1
  50. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
  51. package/dist/src/runtime/framework-tools/subagent/local.js +1 -1
  52. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  53. package/dist/src/setup/integrations/linq/connect.js +1 -1
  54. package/dist/src/setup/primitives/pm/npm.js +1 -1
  55. package/dist/src/setup/primitives/pm/pnpm.js +5 -9
  56. package/dist/src/setup/primitives/pm/types.d.ts +0 -2
  57. package/dist/src/setup/scaffold/create/project.js +1 -1
  58. package/dist/src/setup/scaffold/create/web-template.d.ts +9 -4
  59. package/dist/src/setup/scaffold/create/web-template.js +296 -73
  60. package/dist/src/shared/durable-dynamic-tool-callbacks.d.ts +43 -19
  61. package/dist/src/shared/durable-dynamic-tool-callbacks.js +1 -1
  62. package/dist/src/svelte/index.js +1 -1
  63. package/dist/src/svelte/use-eve-agent.d.ts +4 -0
  64. package/dist/src/svelte/use-eve-agent.js +1 -1
  65. package/dist/src/tasks/delivery-context.d.ts +9 -0
  66. package/dist/src/tasks/delivery-context.js +5 -2
  67. package/dist/src/vue/index.js +1 -1
  68. package/dist/src/vue/use-eve-agent.d.ts +4 -0
  69. package/dist/src/vue/use-eve-agent.js +1 -1
  70. package/docs/concepts/sessions-runs-and-streaming.md +1 -1
  71. package/docs/guides/dynamic-capabilities.md +10 -2
  72. package/docs/guides/frontend/nextjs.mdx +23 -0
  73. package/docs/guides/frontend/overview.mdx +24 -9
  74. package/docs/guides/frontend/use-eve-agent-svelte.mdx +9 -9
  75. package/docs/guides/frontend/use-eve-agent-vue.mdx +9 -9
  76. package/docs/tools/overview.mdx +5 -4
  77. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import type { EveAgentReducer } from "#client/reducer.js";
2
2
  import type { ClientSession } from "#client/session.js";
3
- import type { MessageStreamEvent } from "#protocol/message.js";
3
+ import { type MessageStreamEvent } from "#protocol/message.js";
4
4
  import type { CancelSessionResult, ClientAuth, HeadersValue, SendTurnPayload, ClientSessionState } from "#client/types.js";
5
5
  /**
6
6
  * Lifecycle state of an {@link EveAgentStore}: `ready` (idle), `submitted`
@@ -75,11 +75,11 @@ declare const detachStore: unique symbol;
75
75
  * notification; framework integrations (React, Vue) wrap it with their own
76
76
  * reactivity primitives.
77
77
  *
78
- * Drives one turn at a time: `send` rejects if a turn is already submitted or
79
- * streaming. Read the latest projection via the `snapshot` getter, observe
80
- * changes with `subscribe`, register lifecycle hooks with `setCallbacks`,
81
- * cancel the durable in-flight turn with `cancel`, and discard all state with
82
- * `reset`.
78
+ * Drives one turn at a time: `send` rejects while a turn is active, and
79
+ * concurrent `resume` calls share one replay. Read the latest projection via
80
+ * the `snapshot` getter, observe changes with `subscribe`, register lifecycle
81
+ * hooks with `setCallbacks`, cancel the durable in-flight turn with `cancel`,
82
+ * and discard all state with `reset`.
83
83
  */
84
84
  export declare class EveAgentStore<TData> {
85
85
  #private;
@@ -88,6 +88,8 @@ export declare class EveAgentStore<TData> {
88
88
  setCallbacks(callbacks: EveAgentStoreCallbacks<TData>): void;
89
89
  subscribe(callback: () => void): () => void;
90
90
  send<TOutput = unknown>(input: SendTurnPayload<TOutput>): Promise<void>;
91
+ /** Replays this store's attached durable session and follows an in-flight turn. */
92
+ resume(): Promise<void>;
91
93
  /**
92
94
  * Requests cooperative cancellation of the active durable turn.
93
95
  *
@@ -1,2 +1 @@
1
- import{toError}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{Client}from"#client/client.js";const detachStore=Symbol(`detachEveAgentStore`);var EveAgentStore=class{#e;#t;#n;#r;#i=new Set;#a=createEventDeduper();#o;#s={};#c;#l;#u;#d;#f;#p;#m;#h=`ready`;constructor(e){this.#t=e.session!==void 0,this.#e=this.#t?void 0:new Client({auth:e.auth,headers:e.headers,host:e.host??``});let t=[];for(let n of e.initialEvents??[])this.#a.admit(n)&&t.push(n);this.#u=t,this.#f=[...this.#u],this.#n=e.optimistic??!0,this.#r=e.reducer,this.#p=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#c=this.#E(this.#f),this.#m=this.#D()}get snapshot(){return this.#m}setCallbacks(e){this.#s=e}subscribe(e){return this.#i.add(e),()=>{this.#i.delete(e)}}async send(t){if(this.#h===`streaming`||this.#h===`submitted`)throw Error(`eve session is already processing a turn.`);let n=Promise.withResolvers(),r={abortController:new AbortController,response:n.promise,resolveResponse:n.resolve};this.#o=r,this.#l=void 0,this.#h=`submitted`,this.#O();try{let e=await this.#s.prepareSend?.(t)??t;if(assertExclusiveTurnInput(e),!this.#v(r))return;this.#y(e),this.#b(e),this.#O();let n={...e,signal:createAbortSignal(e.signal,r.abortController.signal)},i=await this.#_(n);if(!this.#v(r))return;r.resolveResponse(i);let a=!1;for await(let e of i){if(!this.#v(r))return;a||(a=!0,this.#h=`streaming`),this.#a.admit(e)&&(this.#u=[...this.#u,e],this.#x(e),this.#s.onEvent?.(e),this.#S(e),this.#O())}if(!this.#v(r))return;this.#h=this.#l===void 0?`ready`:`error`}catch(t){if(!this.#v(r))return;isAbortError(t)?(this.#h=`ready`,this.#C(toError(t))):(this.#l=toError(t),this.#h=`error`,this.#C(this.#l),this.#s.onError?.(this.#l))}finally{this.#v(r)&&(r.resolveResponse(void 0),this.#o=void 0,this.#s.onSessionChange?.(this.#p?.state),this.#O(),this.#s.onFinish?.(this.#m))}}cancel(){let e=this.#o;return e===void 0?Promise.resolve({status:`no_active_turn`}):e.response.then(e=>e===void 0?{status:`no_active_turn`}:e.cancel())}[detachStore](){this.#o?.abortController.abort()}reset(){let e=this.#o;this.#o=void 0,e?.resolveResponse(void 0),e?.abortController.abort(),this.#t||(this.#p=void 0),this.#u=[],this.#a=createEventDeduper(),this.#d=void 0,this.#f=[],this.#c=this.#r.initial(),this.#l=void 0,this.#h=`ready`,this.#s.onSessionChange?.(this.#p?.state),this.#O()}async#g(e){if(this.#e===void 0)throw Error(`An external eve session is required before sending.`);if(e.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let t=await this.#e.sessions.create({...e,message:e.message});return this.#p=t.session,this.#s.onSessionChange?.(t.session.state),this.#O(),t.response}async#_(e){if(this.#p===void 0)return await this.#g(e);if(e.inputResponses===void 0){let{message:t,...n}=e;return await this.#p.send(t,n)}let{inputResponses:t,...n}=e;return await this.#p.respond(t,n)}#v(e){return this.#o===e}#y(e){if(!this.#n||e.message===void 0)return;let t=createSubmissionId(),n={createdAt:Date.now(),id:t,message:summarizeUserContent(e.message)};this.#d=n,this.#w({data:{createdAt:n.createdAt,message:n.message,submissionId:n.id},type:`client.message.submitted`})}#b(e){e.inputResponses===void 0||e.inputResponses.length===0||this.#w({data:{createdAt:Date.now(),responses:e.inputResponses},type:`client.input.responded`})}#x(e){if(e.type===`message.received`&&this.#d!==void 0){let t=this.#d.id;this.#d=void 0,this.#T(e=>e.type===`client.message.submitted`&&e.data.submissionId===t,e);return}this.#w(e)}#S(e){let t=toTerminalStreamFailureError(e);t!==void 0&&(this.#h=`error`,this.#C(t),this.#l===void 0&&(this.#l=t,this.#s.onError?.(t)))}#C(e){let t=this.#d;t!==void 0&&(this.#d=void 0,this.#T(e=>e.type===`client.message.submitted`&&e.data.submissionId===t.id,{data:{createdAt:t.createdAt,error:{message:e.message},message:t.message,submissionId:t.id},type:`client.message.failed`}))}#w(e){this.#f=[...this.#f,e],this.#c=this.#r.reduce(this.#c,e)}#T(e,t){let n=!1;this.#f=this.#f.map(r=>!n&&e(r)?(n=!0,t):r),n||(this.#f=[...this.#f,t]),this.#c=this.#E(this.#f)}#E(e){let t=this.#r.initial();for(let n of e)t=this.#r.reduce(t,n);return t}#D(){return{data:this.#c,error:this.#l,events:this.#u,session:this.#p?.state,status:this.#h}}#O(){this.#m=this.#D();for(let e of this.#i)e()}};function detachEveAgentStore(e){e[detachStore]()}function assertExclusiveTurnInput(e){if(e.message!==void 0==(e.inputResponses!==void 0))throw Error(`A turn requires exactly one of message or inputResponses.`)}let submissionSequence=0;function createSubmissionId(){let e=globalThis.crypto?.randomUUID;return e===void 0?(submissionSequence+=1,`submission_${submissionSequence.toString()}`):e.call(globalThis.crypto)}function createAbortSignal(e,t){return e?AbortSignal.any([e,t]):t}function summarizeUserContent(e){if(typeof e==`string`)return e;let t=[];for(let n of e){if(n.type===`text`){t.push(n.text);continue}n.type===`file`&&t.push(n.filename?`[file: ${n.filename}]`:`[file]`)}return t.join(`
2
- `)}function isAbortError(e){return e instanceof Error&&e.name===`AbortError`}function toTerminalStreamFailureError(e){if(e.type!==`session.failed`)return;let t=Error(e.data.message);return t.name=e.data.code,t}export{EveAgentStore,detachEveAgentStore};
1
+ import{toError}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{Client}from"#client/client.js";import{assertExclusiveTurnInput,collectPendingAuthorizations,createAbortSignal,createSubmissionId,isAbortError,isSettledSessionTail,summarizeUserContent,toTerminalStreamFailureError,updatePendingAuthorizations}from"#client/eve-agent-store-helpers.js";const detachStore=Symbol(`detachEveAgentStore`);var EveAgentStore=class{#e;#t;#n;#r;#i=new Set;#a=createEventDeduper();#o;#s={};#c;#l;#u;#d=[];#f;#p;#m;#h;#g=`ready`;constructor(e){this.#t=e.session!==void 0,this.#e=this.#t?void 0:new Client({auth:e.auth,headers:e.headers,host:e.host??``});let t=[];for(let n of e.initialEvents??[])this.#a.admit(n)&&t.push(n);this.#u=t,this.#f=[...this.#u],this.#n=e.optimistic??!0,this.#r=e.reducer,this.#m=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#c=this.#j(this.#f),this.#h=this.#M()}get snapshot(){return this.#h}setCallbacks(e){this.#s=e}subscribe(e){return this.#i.add(e),()=>{this.#i.delete(e)}}async send(t){if(this.#o!==void 0)return await this.#v(this.#o,t);let n=Promise.withResolvers(),r=Promise.withResolvers(),a={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>a.acceptedFollowUps>0&&this.#m!==void 0?this.#m.cancel():n.promise.then(e=>e===void 0?{status:`no_active_turn`}:e.cancel()),completion:r.promise,followUpDispatches:new Set,receivedFollowUps:0,resolveCompletion:r.resolve,response:n.promise,resolveResponse:n.resolve};this.#o=a,this.#l=void 0,this.#g=`submitted`,this.#N();try{let e=await this.#s.prepareSend?.(t)??t;if(assertExclusiveTurnInput(e),!this.#S(a))return;this.#C(e),this.#w(e),this.#N();let n={...e,signal:createAbortSignal(e.signal,a.abortController.signal)},r=await this.#x(n);if(!this.#S(a))return;a.resolveResponse(r);for await(let e of r){if(!this.#S(a))return;this.#T(e)}if(!this.#S(a)||(await this.#y(a),!this.#S(a)))return;this.#g=this.#l===void 0?`ready`:`error`}catch(t){if(!this.#S(a))return;isAbortError(t)?(this.#g=`ready`,this.#O(toError(t))):(this.#l=toError(t),this.#g=`error`,this.#O(this.#l),this.#s.onError?.(this.#l))}finally{this.#S(a)&&(a.resolveResponse(void 0),this.#o=void 0,this.#s.onSessionChange?.(this.#m?.state),this.#N(),this.#s.onFinish?.(this.#h),a.resolveCompletion())}}resume(){if(this.#p!==void 0)return this.#p;let e=this.#_();this.#p=e;let clear=()=>{this.#p===e&&(this.#p=void 0)};return e.then(clear,clear),e}async#_(){if(this.#g===`streaming`||this.#g===`submitted`)throw Error(`eve session is already processing a turn.`);if(this.#m===void 0)throw Error(`An eve session is required before resuming.`);let t=Promise.withResolvers(),r=Promise.withResolvers(),i=this.#m,o={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>i.cancel(),completion:r.promise,followUpDispatches:new Set,receivedFollowUps:0,resolveCompletion:r.resolve,response:t.promise,resolveResponse:t.resolve};this.#o=o,o.resolveResponse(void 0),this.#l=void 0,this.#g=`submitted`,this.#N();try{let e=[];for await(let t of i.stream({follow:!1,signal:o.abortController.signal,startIndex:0})){if(!this.#S(o))return;e.push(t),this.#T(t,!1)}if(!this.#S(o))return;if(this.#N(),!isSettledSessionTail(e)){let t=collectPendingAuthorizations(e);for await(let e of i.stream({signal:o.abortController.signal})){if(!this.#S(o))return;if(this.#T(e),updatePendingAuthorizations(t,e),isCurrentTurnBoundaryEvent(e)&&(e.type!==`session.waiting`||t.size===0))break}}await this.#y(o),this.#S(o)&&(this.#g=this.#l===void 0?`ready`:`error`)}catch(t){if(!this.#S(o))return;isAbortError(t)?this.#g=`ready`:(this.#l=toError(t),this.#g=`error`,this.#s.onError?.(this.#l))}finally{this.#S(o)&&(o.resolveResponse(void 0),this.#o=void 0,this.#s.onSessionChange?.(i.state),this.#N(),this.#s.onFinish?.(this.#h),o.resolveCompletion())}}cancel(){let e=this.#o;return e===void 0?Promise.resolve({status:`no_active_turn`}):e.cancel()}[detachStore](){this.#o?.abortController.abort()}reset(){let e=this.#o;this.#o=void 0,e?.resolveResponse(void 0),e?.resolveCompletion(),e?.abortController.abort(),this.#t||(this.#m=void 0),this.#u=[],this.#a=createEventDeduper(),this.#d=[],this.#f=[],this.#c=this.#r.initial(),this.#l=void 0,this.#g=`ready`,this.#s.onSessionChange?.(this.#m?.state),this.#N()}async#v(t,n){if(n.message===void 0||n.turnPolicy!==`steer`)throw Error(`eve session is already processing a turn. Send a message with turnPolicy: "steer" to replace it.`);let r=await this.#s.prepareSend?.(n)??n;if(assertExclusiveTurnInput(r),r.message===void 0||r.turnPolicy!==`steer`)throw Error(`An in-flight follow-up requires a message with turnPolicy: "steer".`);if(!this.#S(t))return await this.send(r);let a=this.#C(r);this.#N();let o;o=(async()=>{try{if(await t.response,!this.#S(t)||this.#m===void 0)throw Error(`The active eve turn ended before the follow-up could be sent.`);let{message:e,...n}=r;await this.#m.send(e,n),t.acceptedFollowUps+=1}catch(t){throw this.#O(toError(t),a),this.#N(),t}finally{t.followUpDispatches.delete(o)}})(),t.followUpDispatches.add(o),await o,await t.completion}async#y(e){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(!(e.receivedFollowUps>=e.acceptedFollowUps||this.#m===void 0))for await(let t of this.#m.stream({signal:e.abortController.signal})){if(!this.#S(e))return;if(t.type===`message.received`&&(e.receivedFollowUps+=1),this.#T(t),isCurrentTurnBoundaryEvent(t)){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(e.receivedFollowUps>=e.acceptedFollowUps)return}}}async#b(e){if(this.#e===void 0)throw Error(`An external eve session is required before sending.`);if(e.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let t=await this.#e.sessions.create({...e,message:e.message});return this.#m=t.session,this.#s.onSessionChange?.(t.session.state),this.#N(),t.response}async#x(e){if(this.#m===void 0)return await this.#b(e);if(e.inputResponses===void 0){let{message:t,...n}=e;return await this.#m.send(t,n)}let{inputResponses:t,...n}=e;return await this.#m.respond(t,n)}#S(e){return this.#o===e}#C(e){if(!this.#n||e.message===void 0)return;let t=createSubmissionId(),n={createdAt:Date.now(),id:t,message:summarizeUserContent(e.message)};return this.#d=[...this.#d,n],this.#k({data:{createdAt:n.createdAt,message:n.message,submissionId:n.id},type:`client.message.submitted`}),t}#w(e){e.inputResponses===void 0||e.inputResponses.length===0||this.#k({data:{createdAt:Date.now(),responses:e.inputResponses},type:`client.input.responded`})}#T(e,t=!0){this.#a.admit(e)&&(this.#u=[...this.#u,e],this.#E(e),this.#s.onEvent?.(e),this.#g=`streaming`,this.#D(e),t&&this.#N())}#E(e){let t=this.#d[0];if(e.type===`message.received`&&t!==void 0){let n=t.id;this.#d=this.#d.slice(1),this.#A(e=>e.type===`client.message.submitted`&&e.data.submissionId===n,e);return}this.#k(e)}#D(e){let t=toTerminalStreamFailureError(e);t!==void 0&&(this.#g=`error`,this.#O(t),this.#l===void 0&&(this.#l=t,this.#s.onError?.(t)))}#O(e,t){let n=t===void 0?this.#d[0]:this.#d.find(e=>e.id===t);n!==void 0&&(this.#d=this.#d.filter(e=>e.id!==n.id),this.#A(e=>e.type===`client.message.submitted`&&e.data.submissionId===n.id,{data:{createdAt:n.createdAt,error:{message:e.message},message:n.message,submissionId:n.id},type:`client.message.failed`}))}#k(e){this.#f=[...this.#f,e],this.#c=this.#r.reduce(this.#c,e)}#A(e,t){let n=!1;this.#f=this.#f.map(r=>!n&&e(r)?(n=!0,t):r),n||(this.#f=[...this.#f,t]),this.#c=this.#j(this.#f)}#j(e){let t=this.#r.initial();for(let n of e)t=this.#r.reduce(t,n);return t}#M(){return{data:this.#c,error:this.#l,events:this.#u,session:this.#m?.state,status:this.#g}}#N(){this.#h=this.#M();for(let e of this.#i)e()}};function detachEveAgentStore(e){e[detachStore]()}export{EveAgentStore,detachEveAgentStore};
@@ -13,4 +13,6 @@ export declare function isStreamDisconnectError(error: unknown): boolean;
13
13
  * All read errors — including socket disconnections — propagate to the caller.
14
14
  * Use {@link isStreamDisconnectError} to classify them.
15
15
  */
16
- export declare function readNdjsonStream(body: ReadableStream<Uint8Array>): AsyncGenerator<MessageStreamEvent>;
16
+ export declare function readNdjsonStream(body: ReadableStream<Uint8Array>, options?: {
17
+ readonly idleTimeoutMs?: number;
18
+ }): AsyncGenerator<MessageStreamEvent>;
@@ -1,3 +1,3 @@
1
- function isStreamDisconnectError(e){if(e instanceof DOMException)return e.name===`AbortError`;if(!(e instanceof Error))return!1;let t=`code`in e&&typeof e.code==`string`?e.code:void 0;return e.name===`AbortError`||e.message===`terminated`||t===`UND_ERR_SOCKET`||e instanceof TypeError&&/^(?:failed to fetch|fetch failed)$/i.test(e.message)||/abort|cancel|disconnect|premature close|socket|terminated/i.test(e.message)}async function*readNdjsonStream(e){let t=e.getReader(),n=new TextDecoder,r=``,i=!1;try{for(;;){let e=await t.read();if(e.done){i=!0,r+=n.decode();break}e.value&&(r+=n.decode(e.value,{stream:!0}));let a=r.indexOf(`
2
- `);for(;a!==-1;){let e=r.slice(0,a).trim();r=r.slice(a+1),e.length>0&&(yield JSON.parse(e)),a=r.indexOf(`
3
- `)}}let e=r.trim();e.length>0&&(yield JSON.parse(e))}finally{i||await t.cancel().catch(()=>{}),t.releaseLock()}}export{isStreamDisconnectError,readNdjsonStream};
1
+ function isStreamDisconnectError(e){if(e instanceof DOMException)return e.name===`AbortError`;if(!(e instanceof Error))return!1;let t=`code`in e&&typeof e.code==`string`?e.code:void 0;return e.name===`AbortError`||e.message===`terminated`||t===`UND_ERR_SOCKET`||e instanceof TypeError&&/^(?:failed to fetch|fetch failed)$/i.test(e.message)||/abort|cancel|disconnect|premature close|socket|terminated/i.test(e.message)}async function*readNdjsonStream(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=!1;try{for(;;){let e=await readWithIdleTimeout(n,t?.idleTimeoutMs);if(e.done){a=!0,i+=r.decode();break}e.value&&(i+=r.decode(e.value,{stream:!0}));let o=i.indexOf(`
2
+ `);for(;o!==-1;){let e=i.slice(0,o).trim();i=i.slice(o+1),e.length>0&&(yield JSON.parse(e)),o=i.indexOf(`
3
+ `)}}let e=i.trim();e.length>0&&(yield JSON.parse(e))}finally{a||await n.cancel().catch(()=>{}),n.releaseLock()}}async function readWithIdleTimeout(e,t){if(t===void 0)return await e.read();let n;try{return await Promise.race([e.read(),new Promise((e,r)=>{n=setTimeout(()=>r(new DOMException(`Session stream was idle.`,`AbortError`)),t)})])}finally{n!==void 0&&clearTimeout(n)}}export{isStreamDisconnectError,readNdjsonStream};
@@ -18,6 +18,8 @@ interface FollowStreamInput {
18
18
  /** Keep reconnecting after empty streams until the consumer aborts or stops iteration. */
19
19
  readonly keepAlive?: boolean;
20
20
  readonly streamReconnectPolicy?: StreamReconnectPolicy;
21
+ /** @internal Test override for reconnecting an open stream that stops producing bytes. */
22
+ readonly streamReadIdleTimeoutMs?: number;
21
23
  readonly resolveHeaders: () => Promise<Headers>;
22
24
  readonly redirect?: ClientRedirectPolicy;
23
25
  readonly sessionId: string;
@@ -47,6 +49,7 @@ export declare function followStreamIterable(input: FollowStreamInput): AsyncGen
47
49
  /** An opened connection: the response body plus the tail index from the response header, if any. */
48
50
  interface OpenedStream {
49
51
  readonly body: ReadableStream<Uint8Array>;
52
+ close(): void;
50
53
  readonly tailIndex: number | undefined;
51
54
  }
52
55
  /**
@@ -1 +1 @@
1
- import{createEveSessionStreamRoutePath}from"#protocol/routes.js";import{EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/message.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let t=e;return{retryableErrorStatuses:t?.retryableErrorStatuses?new Set(t.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(t?.streamIdleReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy),streamOpenReconnectPolicy:resolveRetryPolicy(t?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){if(e.follow===!1&&e.startIndex<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);let i=resolveStreamReconnectPolicy(e.streamReconnectPolicy),a=i.streamIdleReconnectPolicy,o=e.startIndex,s=a.baseDelayMs,c=0,l=!0,u;for(;;){let d;try{d=await openStreamBody({...e,retryPolicy:i,startIndex:o,requestTailIndex:e.follow===!1&&u===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if(e.follow===!1&&u===void 0&&(u=d.tailIndex,u===void 0))throw await d.body.cancel().catch(()=>{}),Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);if(u!==void 0&&o>u){await d.body.cancel().catch(()=>{});return}let f=!1;try{for await(let e of readNdjsonStream(d.body))if(o+=1,f=!0,s=a.baseDelayMs,c=0,yield e,u!==void 0&&o>u)return}catch(e){if(!isStreamDisconnectError(e))throw e}if(e.signal?.aborted||e.startIndex<0||a.maxAttempts===0||e.keepAlive!==!0&&!f&&!l&&(c+=1)>=a.maxAttempts||(l=!1,await sleep(s,e.signal),e.signal?.aborted))return;s=Math.min(s*2,a.maxDelayMs)}}async function openStreamBody(t){let r=t.retryPolicy??DEFAULT_STREAM_RECONNECT_POLICY,s=r.streamOpenReconnectPolicy,c,l,u,d=s.baseDelayMs,f={};t.startIndex!==0&&(f.startIndex=String(t.startIndex)),t.requestTailIndex===!0&&(f.includeTailIndex=`1`);for(let o=0;o<s.maxAttempts;o+=1){let p=createClientUrl(t.host,createEveSessionStreamRoutePath(t.sessionId),Object.keys(f).length>0?f:void 0),m=await t.resolveHeaders(),h;try{h=await fetch(p,{cache:`no-store`,headers:m,redirect:t.redirect,signal:t.signal??null})}catch(e){if(t.signal?.aborted||!isStreamDisconnectError(e)||o===s.maxAttempts-1)throw e;await sleep(d,t.signal),d=Math.min(d*2,s.maxDelayMs);continue}if(h.ok){if(!h.body)throw new ClientError(h.status,`Response body is null.`,h.headers);return{body:h.body,tailIndex:parseTailIndexHeader(h.headers)}}if(c=h.status,l=await h.text(),u=h.headers,!r.retryableErrorStatuses.has(h.status))throw new ClientError(h.status,l,h.headers);o<s.maxAttempts-1&&(await sleep(d,t.signal),d=Math.min(d*2,s.maxDelayMs))}throw new ClientError(c??0,l??`Failed to open message stream.`,u)}function parseTailIndexHeader(e){let n=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(n===null||!/^-?\d+$/.test(n))return;let r=Number(n);return Number.isSafeInteger(r)?r: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{followStreamIterable,openStreamBody};
1
+ import{createEveSessionStreamRoutePath}from"#protocol/routes.js";import{EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/message.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let t=e;return{retryableErrorStatuses:t?.retryableErrorStatuses?new Set(t.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(t?.streamIdleReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy),streamOpenReconnectPolicy:resolveRetryPolicy(t?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){if(e.follow===!1&&e.startIndex<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);let i=resolveStreamReconnectPolicy(e.streamReconnectPolicy),a=i.streamIdleReconnectPolicy,o=e.startIndex,s=a.baseDelayMs,c=0,l=!0,u;for(;;){let d;try{d=await openStreamBody({...e,retryPolicy:i,startIndex:o,requestTailIndex:e.follow===!1&&u===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if(e.follow===!1&&u===void 0&&(u=d.tailIndex,u===void 0))throw d.close(),Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);if(u!==void 0&&o>u){d.close();return}let f=!1;try{for await(let t of readNdjsonStream(d.body,{idleTimeoutMs:e.streamReadIdleTimeoutMs??15e3}))if(o+=1,f=!0,s=a.baseDelayMs,c=0,yield t,u!==void 0&&o>u)return}catch(e){if(!isStreamDisconnectError(e))throw e}finally{d.close()}if(e.signal?.aborted||e.startIndex<0||a.maxAttempts===0||e.keepAlive!==!0&&!f&&!l&&(c+=1)>=a.maxAttempts||(l=!1,await sleep(s,e.signal),e.signal?.aborted))return;s=Math.min(s*2,a.maxDelayMs)}}async function openStreamBody(t){let r=t.retryPolicy??DEFAULT_STREAM_RECONNECT_POLICY,s=r.streamOpenReconnectPolicy,c,l,u,d=s.baseDelayMs,f={};t.startIndex!==0&&(f.startIndex=String(t.startIndex)),t.requestTailIndex===!0&&(f.includeTailIndex=`1`);for(let o=0;o<s.maxAttempts;o+=1){let p=createClientUrl(t.host,createEveSessionStreamRoutePath(t.sessionId),Object.keys(f).length>0?f:void 0),m=await t.resolveHeaders(),h=new AbortController,g=t.signal?AbortSignal.any([t.signal,h.signal]):h.signal,_;try{_=await fetch(p,{cache:`no-store`,headers:m,redirect:t.redirect,signal:g})}catch(e){if(t.signal?.aborted||!isStreamDisconnectError(e)||o===s.maxAttempts-1)throw e;await sleep(d,t.signal),d=Math.min(d*2,s.maxDelayMs);continue}if(_.ok){if(!_.body)throw new ClientError(_.status,`Response body is null.`,_.headers);return{body:_.body,close:()=>h.abort(),tailIndex:parseTailIndexHeader(_.headers)}}if(c=_.status,l=await _.text(),u=_.headers,!r.retryableErrorStatuses.has(_.status))throw new ClientError(_.status,l,_.headers);o<s.maxAttempts-1&&(await sleep(d,t.signal),d=Math.min(d*2,s.maxDelayMs))}throw new ClientError(c??0,l??`Failed to open message stream.`,u)}function parseTailIndexHeader(e){let n=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(n===null||!/^-?\d+$/.test(n))return;let r=Number(n);return Number.isSafeInteger(r)?r: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{followStreamIterable,openStreamBody};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{SessionDynamicToolMetadataKey,StepDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toInputSchema,toOutputSchema}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";const log=createLogger(`dynamic-tools`);function lookupStepFunction(e){return globalThis[Symbol.for(`@workflow/core//registeredSteps`)]?.get(e)||null}function missingCallbackError(e,t,n){return Error(`Dynamic tool "${e.name}" cannot replay its ${t} callback because step function "${n.stepId}" is not registered. Rebuild the agent and ensure the callback is created at module scope or transformed from authored source.`)}function buildReplayedApproval(e){let t=e.callbacks.approvalRequest;if(t===void 0)return;let n=lookupStepFunction(t.stepId),r=n===null?async()=>(log.error(missingCallbackError(e,`approvalRequest`,t).message),`user-approval`):async e=>await n(t.closure,e),i=e.callbacks.approvalResponse;if(i===void 0)return r;let a=lookupStepFunction(i.stepId);return{request:r,response:a===null?async()=>{let t=missingCallbackError(e,`approvalResponse`,i);return log.error(t.message),{reason:t.message,status:`rejected`}}:async e=>await a(i.closure,e)}}function replayDynamicTools(e){return e.map(e=>{let t=e.callbacks.execute,n=lookupStepFunction(t.stepId),r=e.callbacks.toModelOutput,s=r===void 0?void 0:lookupStepFunction(r.stepId);return{description:e.description,execute:createToolExecuteWithAuth({scope:e.name,execute:(r,i)=>{if(n===null)throw missingCallbackError(e,`execute`,t);return n(t.closure,r,i)}}),inputSchema:toInputSchema(e.inputSchema),name:e.name,approval:buildReplayedApproval(e),outputSchema:toOutputSchema(e.outputSchema),...r===void 0?{}:{toModelOutput:t=>{if(s===null)throw missingCallbackError(e,`toModelOutput`,r);return s(r.closure,t)}}}})}function buildResponseAuthorizationTools(e){let t=new Map;for(let n of e.context===void 0?[]:buildDynamicTools(e.context))t.has(n.name)||t.set(n.name,n);for(let[n,r]of e.authoredTools)t.has(n)||t.set(n,r);return t}function buildDynamicTools(e){let i=replayDynamicTools(e.get(StepDynamicToolMetadataKey)??[]),a=replayDynamicTools(e.get(TurnDynamicToolMetadataKey)??[]),o=replayDynamicTools(e.get(SessionDynamicToolMetadataKey)??[]);return[...i,...a,...o]}export{buildDynamicTools,buildResponseAuthorizationTools,replayDynamicTools};
1
+ import{createLogger}from"#internal/logging.js";import{SessionDynamicToolMetadataKey,StepDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toInputSchema,toOutputSchema}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{callDurableDynamicCallback,lookupDurableDynamicCallback}from"#shared/durable-dynamic-tool-callbacks.js";const log=createLogger(`dynamic-tools`);function missingCallbackError(e,t){return Error(`Dynamic tool "${e.name}" cannot replay its ${t} callback because it is not registered in this process. The tool was removed or renamed since this call was parked, or its resolver did not run. Restore the tool definition or start a new session.`)}function buildReplayedApproval(e){let t=e.callbacks.approvalRequest;if(t===void 0)return;let n=lookupDurableDynamicCallback(e.name,`approvalRequest`),r=n===void 0?async()=>(log.error(missingCallbackError(e,`approvalRequest`).message),`user-approval`):async e=>await callDurableDynamicCallback(n,t.closure,e),i=e.callbacks.approvalResponse;if(i===void 0)return r;let a=lookupDurableDynamicCallback(e.name,`approvalResponse`);return{request:r,response:a===void 0?async()=>{let t=missingCallbackError(e,`approvalResponse`);return log.error(t.message),{reason:t.message,status:`rejected`}}:async e=>await callDurableDynamicCallback(a,i.closure,e)}}function replayDynamicTools(e){return e.map(e=>{let t=e.callbacks.execute,n=lookupDurableDynamicCallback(e.name,`execute`),r=e.callbacks.toModelOutput,s=r===void 0?void 0:lookupDurableDynamicCallback(e.name,`toModelOutput`);return{description:e.description,execute:createToolExecuteWithAuth({scope:e.name,execute:(r,i)=>{if(n===void 0)throw missingCallbackError(e,`execute`);return callDurableDynamicCallback(n,t.closure,r,i)}}),inputSchema:toInputSchema(e.inputSchema),name:e.name,approval:buildReplayedApproval(e),outputSchema:toOutputSchema(e.outputSchema),...r===void 0?{}:{toModelOutput:t=>{if(s===void 0)throw missingCallbackError(e,`toModelOutput`);return callDurableDynamicCallback(s,r.closure,t)}}}})}function buildResponseAuthorizationTools(e){let t=new Map;for(let n of e.context===void 0?[]:buildDynamicTools(e.context))t.has(n.name)||t.set(n.name,n);for(let[n,r]of e.authoredTools)t.has(n)||t.set(n,r);return t}function buildDynamicTools(e){let i=replayDynamicTools(e.get(StepDynamicToolMetadataKey)??[]),a=replayDynamicTools(e.get(TurnDynamicToolMetadataKey)??[]),o=replayDynamicTools(e.get(SessionDynamicToolMetadataKey)??[]);return[...i,...a,...o]}export{buildDynamicTools,buildResponseAuthorizationTools,replayDynamicTools};
@@ -22,7 +22,11 @@ export declare function dispatchDynamicToolEvent(input: {
22
22
  readonly event: UnstampedMessageStreamEvent;
23
23
  readonly messages: readonly ModelMessage[];
24
24
  }): Promise<void>;
25
- /** Refreshes session-scoped definitions only when the deployed code revision changes. */
25
+ /**
26
+ * Refreshes session-scoped definitions when the deployed code revision changes
27
+ * or when persisted callbacks have no registered binding (fresh process after
28
+ * a crash, or a redeploy), so replay always resolves against current code.
29
+ */
26
30
  export declare function refreshDynamicSessionToolsForRuntimeRevision(input: {
27
31
  readonly ctx: ContextContainer;
28
32
  readonly resolvers: readonly ResolvedDynamicToolResolver[];
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,StepDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{serializeInputSchema,serializeOutputSchema}from"#shared/tool-schema.js";import{parseJsonObject}from"#shared/json.js";import{ALLOWED_DYNAMIC_TOOL_EVENTS,isBrandedToolEntry}from"#shared/dynamic-tool-definition.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{replayDynamicTools}from"#context/build-dynamic-tools.js";import{readDurableDynamicToolCallbacks}from"#shared/durable-dynamic-tool-callbacks.js";const log=createLogger(`dynamic-tools`);function qualifyDynamicToolNames(e,t,n){let r=Object.keys(n);if(r.length===0)return[];if(t){let t=r[0];return[{name:e.slug,entryKey:t,entry:n[t]}]}let i=e.extensionNamespace===void 0?``:`${e.extensionNamespace}__`;return r.map(e=>({entry:n[e],entryKey:e,name:`${i}${e}`}))}function replayDynamicSessionTools(e,t){return replayDynamicTools(e)}function durableKeyForEvent(e){switch(e){case`session.started`:return SessionDynamicToolMetadataKey;case`turn.started`:return TurnDynamicToolMetadataKey;case`step.started`:return StepDynamicToolMetadataKey;default:return}}function readDynamicToolResult(e,t){if(isBrandedToolEntry(t))return{entries:{_single:t},isSingle:!0};if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Dynamic tool resolver "${e.logicalPath}" must return defineTool(), a map of defineTool() values, or null.`);let n={};for(let[r,i]of Object.entries(t)){if(!isBrandedToolEntry(i))throw Error(`Dynamic tool resolver "${e.logicalPath}" returned "${r}" without defineTool(). Wrap every dynamic tool entry in defineTool().`);n[r]=i}return{entries:n,isSingle:!1}}function validateReference(e){if(e.reference===void 0){if(e.required)throw Error(`Dynamic tool "${e.name}" callback "${e.phase}" does not have a durable descriptor. Author the callback inline in transformed source or use an eve durable callback helper.`);return}let t=Object.keys(e.reference).filter(e=>e!==`closure`&&e!==`stepId`);if(t.length>0)throw Error(`Dynamic tool "${e.name}" has invalid ${e.phase} callback metadata: unknown key(s) ${t.join(`, `)}.`);if(typeof e.reference.stepId!=`string`||e.reference.stepId.length===0)throw Error(`Dynamic tool "${e.name}" has invalid ${e.phase} callback metadata: stepId must be a non-empty string.`);let n;try{n=parseJsonObject(e.reference.closure)}catch(t){throw Error(`Dynamic tool "${e.name}" callback "${e.phase}" has a non-serializable capture. ${toErrorMessage(t)}`)}if(globalThis[Symbol.for(`@workflow/core//registeredSteps`)]?.has(e.reference.stepId)!==!0)throw Error(`Dynamic tool "${e.name}" callback "${e.phase}" references "${e.reference.stepId}", but that step function is not registered. Author the callback inline in transformed source or register it from an eve callback helper.`);return{closure:n,stepId:e.reference.stepId}}function validateDurableDynamicToolCallbacks(e,t){let n=readDurableDynamicToolCallbacks(t)??{},r=Object.keys(n).filter(e=>e!==`execute`&&e!==`approvalRequest`&&e!==`approvalResponse`&&e!==`toModelOutput`);if(r.length>0)throw Error(`Dynamic tool "${e}" has unknown durable callback phase(s): ${r.join(`, `)}.`);let i=t.approval!==void 0,a=t.approval!==void 0&&typeof t.approval!=`function`&&t.approval.response!==void 0,o=validateReference({name:e,phase:`execute`,reference:n.execute,required:!0}),s=validateReference({name:e,phase:`approvalRequest`,reference:n.approvalRequest,required:i}),c=validateReference({name:e,phase:`approvalResponse`,reference:n.approvalResponse,required:a}),l=validateReference({name:e,phase:`toModelOutput`,reference:n.toModelOutput,required:t.toModelOutput!==void 0}),u={execute:o};return s!==void 0&&(u.approvalRequest=s),c!==void 0&&(u.approvalResponse=c),l!==void 0&&(u.toModelOutput=l),u}function createMetadata(e){return{callbacks:validateDurableDynamicToolCallbacks(e.name,e.entry),description:e.entry.description,entryKey:e.entryKey,inputSchema:serializeInputSchema(e.entry.inputSchema),name:e.name,outputSchema:serializeOutputSchema(e.entry.outputSchema),resolverSlug:e.resolver.slug}}async function resolveToolsFromEvent(e,t,n,r){let i=await Promise.allSettled(t.map(async t=>{let i=t.events[n.type];if(i===void 0)return null;let a=await i(n,buildResolveContext(e,r));if(a==null)return null;let{entries:o,isSingle:s}=readDynamicToolResult(t,a);return{metadata:qualifyDynamicToolNames(t,s,o).map(({name:e,entryKey:n,entry:r})=>createMetadata({entry:r,entryKey:n,name:e,resolver:t})),resolver:t}})),o=[],s=new Map;for(let e of i){if(e.status===`rejected`){log.error(`Dynamic tool resolver (${n.type}) failed — skipping its complete result.`,{error:toErrorMessage(e.reason)});continue}if(e.value!==null){for(let t of e.value.metadata){let n=s.get(t.name);if(n!==void 0&&n!==e.value.resolver.slug)throw Error(`Dynamic tool "${t.name}" from resolver "${e.value.resolver.slug}" collides with dynamic resolver "${n}". Namespace the map key manually.`);s.set(t.name,e.value.resolver.slug)}o.push(...e.value.metadata)}}return{metadata:o}}const resolvedStepTools=new WeakMap;async function resolveStepDynamicTools(e){let t=`data`in e.event?e.event.data:void 0,n=typeof t?.turnId==`string`&&typeof t.stepIndex==`number`?`${t.turnId}:${String(t.stepIndex)}`:void 0,i=resolvedStepTools.get(e.ctx);if(n!==void 0&&i?.coordinate===n){e.ctx.set(StepDynamicToolMetadataKey,i.metadata);return}let a=e.resolvers.filter(e=>e.eventNames.includes(`step.started`)),{metadata:o}=a.length===0?{metadata:[]}:await resolveToolsFromEvent(e.ctx,a,e.event,e.messages);e.ctx.set(StepDynamicToolMetadataKey,o),n!==void 0&&resolvedStepTools.set(e.ctx,{coordinate:n,metadata:o})}async function dispatchDynamicToolEvent(e){if(!ALLOWED_DYNAMIC_TOOL_EVENTS.has(e.event.type))return;if(e.event.type===`step.started`){await resolveStepDynamicTools(e);return}e.event.type===`turn.started`&&e.ctx.set(StepDynamicToolMetadataKey,[]);let n=e.resolvers.filter(t=>t.eventNames.includes(e.event.type)),{metadata:i}=n.length===0?{metadata:[]}:await resolveToolsFromEvent(e.ctx,n,e.event,e.messages),a=durableKeyForEvent(e.event.type);if(a===void 0)return;if(e.event.type===`session.started`){e.ctx.set(SessionDynamicToolMetadataKey,i);return}let o=new Set(n.map(e=>e.slug)),s=(e.ctx.get(a)??[]).filter(e=>!o.has(e.resolverSlug));e.ctx.set(a,[...s,...i])}async function refreshDynamicSessionToolsForRuntimeRevision(e){if(e.ctx.get(SessionDynamicToolRuntimeRevisionKey)===e.runtimeRevision)return;let r=e.resolvers.filter(e=>e.eventNames.includes(`session.started`)),{metadata:i}=r.length===0?{metadata:[]}:await resolveToolsFromEvent(e.ctx,r,e.event,e.messages);e.ctx.set(SessionDynamicToolMetadataKey,i),e.ctx.set(SessionDynamicToolRuntimeRevisionKey,e.runtimeRevision)}export{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision,replayDynamicSessionTools,resolveStepDynamicTools,validateDurableDynamicToolCallbacks};
1
+ import{createLogger}from"#internal/logging.js";import{SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,StepDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{serializeInputSchema,serializeOutputSchema}from"#shared/tool-schema.js";import{parseJsonObject}from"#shared/json.js";import{ALLOWED_DYNAMIC_TOOL_EVENTS,isBrandedToolEntry}from"#shared/dynamic-tool-definition.js";import{hasUnregisteredDurableDynamicCallbacks,readDurableDynamicToolCallbacks,registerDurableDynamicCallback}from"#shared/durable-dynamic-tool-callbacks.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{replayDynamicTools}from"#context/build-dynamic-tools.js";const log=createLogger(`dynamic-tools`);function qualifyDynamicToolNames(e,t,n){let r=Object.keys(n);if(r.length===0)return[];if(t){let t=r[0];return[{name:e.slug,entryKey:t,entry:n[t]}]}let i=e.extensionNamespace===void 0?``:`${e.extensionNamespace}__`;return r.map(e=>({entry:n[e],entryKey:e,name:`${i}${e}`}))}function replayDynamicSessionTools(e,t){return replayDynamicTools(e)}function durableKeyForEvent(e){switch(e){case`session.started`:return SessionDynamicToolMetadataKey;case`turn.started`:return TurnDynamicToolMetadataKey;case`step.started`:return StepDynamicToolMetadataKey;default:return}}function readDynamicToolResult(e,t){if(isBrandedToolEntry(t))return{entries:{_single:t},isSingle:!0};if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Dynamic tool resolver "${e.logicalPath}" must return defineTool(), a map of defineTool() values, or null.`);let n={};for(let[r,i]of Object.entries(t)){if(!isBrandedToolEntry(i))throw Error(`Dynamic tool resolver "${e.logicalPath}" returned "${r}" without defineTool(). Wrap every dynamic tool entry in defineTool().`);n[r]=i}return{entries:n,isSingle:!1}}function validateReference(e){if(e.stamped===void 0){if(e.required)throw Error(`Dynamic tool "${e.name}" callback "${e.phase}" does not have a durable descriptor. Author the callback inline in transformed source or use an eve durable callback helper.`);return}let t=Object.keys(e.stamped).filter(e=>e!==`closure`&&e!==`callback`);if(t.includes(`stepId`))throw Error(`Dynamic tool "${e.name}" callback "${e.phase}" was persisted by a pre-release eve version that identified callbacks by build offset. Start a new session to re-resolve it.`);if(t.length>0)throw Error(`Dynamic tool "${e.name}" has invalid ${e.phase} callback metadata: unknown key(s) ${t.join(`, `)}.`);if(typeof e.stamped.callback!=`function`)throw Error(`Dynamic tool "${e.name}" callback "${e.phase}" does not have a durable descriptor. Author the callback inline in transformed source or use an eve durable callback helper.`);let n;try{n=parseJsonObject(e.stamped.closure)}catch(t){throw Error(`Dynamic tool "${e.name}" callback "${e.phase}" has a non-serializable capture. ${toErrorMessage(t)}`)}return registerDurableDynamicCallback({callback:e.stamped.callback,phase:e.phase,toolName:e.name}),{closure:n}}function validateDurableDynamicToolCallbacks(e,t){let n=readDurableDynamicToolCallbacks(t)??{},r=Object.keys(n).filter(e=>e!==`execute`&&e!==`approvalRequest`&&e!==`approvalResponse`&&e!==`toModelOutput`);if(r.length>0)throw Error(`Dynamic tool "${e}" has unknown durable callback phase(s): ${r.join(`, `)}.`);let i=t.approval!==void 0,a=t.approval!==void 0&&typeof t.approval!=`function`&&t.approval.response!==void 0,o=validateReference({name:e,phase:`execute`,stamped:n.execute,required:!0}),s=validateReference({name:e,phase:`approvalRequest`,stamped:n.approvalRequest,required:i}),c=validateReference({name:e,phase:`approvalResponse`,stamped:n.approvalResponse,required:a}),l=validateReference({name:e,phase:`toModelOutput`,stamped:n.toModelOutput,required:t.toModelOutput!==void 0}),u={execute:o};return s!==void 0&&(u.approvalRequest=s),c!==void 0&&(u.approvalResponse=c),l!==void 0&&(u.toModelOutput=l),u}function createMetadata(e){return{callbacks:validateDurableDynamicToolCallbacks(e.name,e.entry),description:e.entry.description,entryKey:e.entryKey,inputSchema:serializeInputSchema(e.entry.inputSchema),name:e.name,outputSchema:serializeOutputSchema(e.entry.outputSchema),resolverSlug:e.resolver.slug}}async function resolveToolsFromEvent(e,t,n,r){let i=await Promise.allSettled(t.map(async t=>{let i=t.events[n.type];if(i===void 0)return null;let a=await i(n,buildResolveContext(e,r));if(a==null)return null;let{entries:o,isSingle:s}=readDynamicToolResult(t,a);return{metadata:qualifyDynamicToolNames(t,s,o).map(({name:e,entryKey:n,entry:r})=>createMetadata({entry:r,entryKey:n,name:e,resolver:t})),resolver:t}})),o=[],s=new Map;for(let e of i){if(e.status===`rejected`){log.error(`Dynamic tool resolver (${n.type}) failed — skipping its complete result.`,{error:toErrorMessage(e.reason)});continue}if(e.value!==null){for(let t of e.value.metadata){let n=s.get(t.name);if(n!==void 0&&n!==e.value.resolver.slug)throw Error(`Dynamic tool "${t.name}" from resolver "${e.value.resolver.slug}" collides with dynamic resolver "${n}". Namespace the map key manually.`);s.set(t.name,e.value.resolver.slug)}o.push(...e.value.metadata)}}return{metadata:o}}const resolvedStepTools=new WeakMap;async function resolveStepDynamicTools(e){let t=`data`in e.event?e.event.data:void 0,n=typeof t?.turnId==`string`&&typeof t.stepIndex==`number`?`${t.turnId}:${String(t.stepIndex)}`:void 0,i=resolvedStepTools.get(e.ctx);if(n!==void 0&&i?.coordinate===n){e.ctx.set(StepDynamicToolMetadataKey,i.metadata);return}let a=e.resolvers.filter(e=>e.eventNames.includes(`step.started`)),{metadata:o}=a.length===0?{metadata:[]}:await resolveToolsFromEvent(e.ctx,a,e.event,e.messages);e.ctx.set(StepDynamicToolMetadataKey,o),n!==void 0&&resolvedStepTools.set(e.ctx,{coordinate:n,metadata:o})}async function dispatchDynamicToolEvent(e){if(!ALLOWED_DYNAMIC_TOOL_EVENTS.has(e.event.type))return;if(e.event.type===`step.started`){await resolveStepDynamicTools(e);return}e.event.type===`turn.started`&&e.ctx.set(StepDynamicToolMetadataKey,[]);let n=e.resolvers.filter(t=>t.eventNames.includes(e.event.type)),{metadata:i}=n.length===0?{metadata:[]}:await resolveToolsFromEvent(e.ctx,n,e.event,e.messages),a=durableKeyForEvent(e.event.type);if(a===void 0)return;if(e.event.type===`session.started`){e.ctx.set(SessionDynamicToolMetadataKey,i);return}let o=new Set(n.map(e=>e.slug)),s=(e.ctx.get(a)??[]).filter(e=>!o.has(e.resolverSlug));e.ctx.set(a,[...s,...i])}async function refreshDynamicSessionToolsForRuntimeRevision(e){let r=e.ctx.get(SessionDynamicToolRuntimeRevisionKey)!==e.runtimeRevision,i=hasUnregisteredDurableDynamicCallbacks(e.ctx.get(SessionDynamicToolMetadataKey)??[]);if(!r&&!i)return;let a=e.resolvers.filter(e=>e.eventNames.includes(`session.started`)),{metadata:o}=a.length===0?{metadata:[]}:await resolveToolsFromEvent(e.ctx,a,e.event,e.messages);e.ctx.set(SessionDynamicToolMetadataKey,o),e.ctx.set(SessionDynamicToolRuntimeRevisionKey,e.runtimeRevision)}export{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision,replayDynamicSessionTools,resolveStepDynamicTools,validateDurableDynamicToolCallbacks};
@@ -47,8 +47,10 @@ export declare const SessionIdKey: ContextKey<string>;
47
47
  export declare const ContinuationTokenKey: ContextKey<string>;
48
48
  export declare const ChannelRequestIdKey: ContextKey<string>;
49
49
  export declare const ChannelDeliveryKey: ContextKey<ChannelDeliveryMetadata>;
50
- /** Task-cohort phase when the active turn began from a task-addressed durable delivery. */
51
- export declare const TurnTaskDeliveryKey: ContextKey<"none" | "pending" | "settled">;
50
+ /** Task-reporting phase for the active root turn. */
51
+ export declare const TurnTaskDeliveryKey: ContextKey<"initiating" | "none" | "pending" | "settled">;
52
+ /** Framework-authored task state supplied to the model without altering user-message history. */
53
+ export declare const TurnTaskStateKey: ContextKey<string>;
52
54
  export interface ActiveChannelDelivery {
53
55
  readonly agentName?: string;
54
56
  readonly delivery: InstrumentationChannelDeliveryRef;
@@ -1 +1 @@
1
- import{ContextKey}from"#context/key.js";const AuthKey=new ContextKey(`eve.auth`),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),ChannelDeliveryKey=new ContextKey(`eve.channelDelivery`),TurnTaskDeliveryKey=new ContextKey(`eve.turnTaskDelivery`),ActiveChannelDeliveriesKey=new ContextKey(`eve.activeChannelDeliveries`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ModeKey=new ContextKey(`eve.mode`),ParentSessionKey=new ContextKey(`eve.parentSession`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SubagentDepthKey=new ContextKey(`eve.subagentDepth`),CapabilitiesKey=new ContextKey(`eve.capabilities`),SessionCallbackKey=new ContextKey(`eve.sessionCallback`),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),HandleEventKey=new ContextKey(`eve.internal.handleEvent`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),RuntimeModelMetadataCacheKey=new ContextKey(`eve.runtimeModelMetadataCache`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),StepDynamicToolMetadataKey=new ContextKey(`eve.stepDynamicToolMetadata`),TasksEnabledKey=new ContextKey(`eve.tasksEnabled`),SessionDynamicSubagentSelectionsKey=new ContextKey(`eve.sessionDynamicSubagentSelections`),TurnDynamicSubagentSelectionsKey=new ContextKey(`eve.turnDynamicSubagentSelections`),SessionDynamicSubagentRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicSubagentRuntimeRevision`),DynamicSubagentAgentConfigKey=new ContextKey(`eve.dynamicSubagentAgentConfig`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`),DynamicInstructionResolveMessagesKey=new ContextKey(`eve.dynamicInstructionResolveMessages`),PendingDynamicInstructionUserMessagesKey=new ContextKey(`eve.pendingDynamicInstructionUserMessages`);export{ActiveChannelDeliveriesKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,DynamicInstructionResolveMessagesKey,DynamicSkillManifestKey,DynamicSubagentAgentConfigKey,HandleEventKey,InitiatorAuthKey,LiveStepDynamicModelSelectionKey,ModeKey,ParentSessionKey,ParentTraceContextKey,PendingDynamicInstructionUserMessagesKey,RuntimeModelMetadataCacheKey,SandboxKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionKey,StepDynamicToolMetadataKey,SubagentDepthKey,TasksEnabledKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicSubagentSelectionsKey,TurnDynamicToolMetadataKey,TurnTaskDeliveryKey};
1
+ import{ContextKey}from"#context/key.js";const AuthKey=new ContextKey(`eve.auth`),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),ChannelDeliveryKey=new ContextKey(`eve.channelDelivery`),TurnTaskDeliveryKey=new ContextKey(`eve.turnTaskDelivery`),TurnTaskStateKey=new ContextKey(`eve.turnTaskState`),ActiveChannelDeliveriesKey=new ContextKey(`eve.activeChannelDeliveries`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ModeKey=new ContextKey(`eve.mode`),ParentSessionKey=new ContextKey(`eve.parentSession`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SubagentDepthKey=new ContextKey(`eve.subagentDepth`),CapabilitiesKey=new ContextKey(`eve.capabilities`),SessionCallbackKey=new ContextKey(`eve.sessionCallback`),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),HandleEventKey=new ContextKey(`eve.internal.handleEvent`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),RuntimeModelMetadataCacheKey=new ContextKey(`eve.runtimeModelMetadataCache`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),StepDynamicToolMetadataKey=new ContextKey(`eve.stepDynamicToolMetadata`),TasksEnabledKey=new ContextKey(`eve.tasksEnabled`),SessionDynamicSubagentSelectionsKey=new ContextKey(`eve.sessionDynamicSubagentSelections`),TurnDynamicSubagentSelectionsKey=new ContextKey(`eve.turnDynamicSubagentSelections`),SessionDynamicSubagentRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicSubagentRuntimeRevision`),DynamicSubagentAgentConfigKey=new ContextKey(`eve.dynamicSubagentAgentConfig`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`),DynamicInstructionResolveMessagesKey=new ContextKey(`eve.dynamicInstructionResolveMessages`),PendingDynamicInstructionUserMessagesKey=new ContextKey(`eve.pendingDynamicInstructionUserMessages`);export{ActiveChannelDeliveriesKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,DynamicInstructionResolveMessagesKey,DynamicSkillManifestKey,DynamicSubagentAgentConfigKey,HandleEventKey,InitiatorAuthKey,LiveStepDynamicModelSelectionKey,ModeKey,ParentSessionKey,ParentTraceContextKey,PendingDynamicInstructionUserMessagesKey,RuntimeModelMetadataCacheKey,SandboxKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionKey,StepDynamicToolMetadataKey,SubagentDepthKey,TasksEnabledKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicSubagentSelectionsKey,TurnDynamicToolMetadataKey,TurnTaskDeliveryKey,TurnTaskStateKey};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{cancelRemoteAgentTurn,isRetryableRemoteAgentCancelError,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";const log=createLogger(`execution.cancel-descendant-turns`);async function cancelDescendantTurnsStep(e){"use step";let r;try{r=(getAgentHandleStore((await readDurableSession(e.sessionState)).state)?.handles??[]).filter(e=>e.phase===`running`)}catch(n){logError(log,`failed to read pending descendants during cancellation`,n,{sessionId:e.sessionState.sessionId});return}if(r.length===0){log.warn(`no running agent handles found while cancelling descendants; nothing to cancel`,{sessionId:e.sessionState.sessionId});return}let i,getRemoteContext=()=>i??=deserializeContext(e.serializedContext).then(e=>({ctx:e,registry:e.require(BundleKey).subagentRegistry.subagentsByNodeId}));await Promise.all(r.map(e=>e.address.kind===`agent/remote`?cancelRemoteDescendant({handle:e,remoteContext:getRemoteContext()}):cancelLocalDescendant({handle:e})))}async function cancelLocalDescendant(e){let{handle:n}=e;try{let e=await requestCancellationWithRetry({request:()=>requestWorkflowTurnCancellation({sessionId:n.address.sessionId}),shouldRetryError:()=>!1});e.status!==`accepted`&&log.warn(`descendant cancel was never accepted; the child may run to completion`,{callId:n.operation.callId,childSessionId:n.address.sessionId,finalStatus:e.status,subagentName:n.identity.name})}catch(e){logError(log,`failed to cancel local descendant turn`,e,{callId:n.operation.callId,childSessionId:n.address.sessionId,subagentName:n.identity.name})}}async function cancelRemoteDescendant(e){let{handle:n}=e;if(n.address.kind!==`agent/remote`)return;let a=n.address.url;try{let{ctx:t,registry:o}=await e.remoteContext,s=getDynamicSubagentSelection(t,n.identity.nodeId),c={...await resolveRemoteAgentForAction({dynamicRemoteAgent:s?.kind===`remote`?s.remoteAgent:void 0,nodeId:n.identity.nodeId,remoteAgentName:n.identity.name,registry:o}),url:a},l=await requestCancellationWithRetry({request:()=>cancelRemoteAgentTurn({remote:c,sessionId:n.address.sessionId}),shouldRetryError:isRetryableRemoteAgentCancelError});l.status!==`accepted`&&log.warn(`remote descendant cancel was never accepted; the child may run to completion`,{callId:n.operation.callId,childSessionId:n.address.sessionId,finalStatus:l.status,remoteAgentName:n.identity.name})}catch(e){logError(log,`failed to cancel remote descendant turn`,e,{callId:n.operation.callId,childSessionId:n.address.sessionId,remoteAgentName:n.identity.name})}}async function requestCancellationWithRetry(e){let t=250,n={status:`no_active_turn`};for(let r=1;r<=8;r+=1){try{if(n=await e.request(),n.status===`accepted`||r===8)return n}catch(t){if(!e.shouldRetryError(t)||r===8)throw t}await new Promise(e=>setTimeout(e,t)),t=Math.min(t*2,1500)}return n}export{cancelDescendantTurnsStep};
1
+ import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{cancelRemoteAgentTurn,isRetryableRemoteAgentCancelError,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";const log=createLogger(`execution.cancel-descendant-turns`);async function cancelDescendantTurnsStep(e){"use step";let r;try{r=(getAgentHandleStore((await readDurableSession(e.sessionState)).state)?.handles??[]).filter(e=>e.phase===`running`)}catch(n){logError(log,`failed to read pending descendants during cancellation`,n,{sessionId:e.sessionState.sessionId});return}if(r.length===0)return;let i,getRemoteContext=()=>i??=deserializeContext(e.serializedContext).then(e=>({ctx:e,registry:e.require(BundleKey).subagentRegistry.subagentsByNodeId}));await Promise.all(r.map(e=>e.address.kind===`agent/remote`?cancelRemoteDescendant({handle:e,remoteContext:getRemoteContext()}):cancelLocalDescendant({handle:e})))}async function cancelLocalDescendant(e){let{handle:n}=e;try{let e=await requestCancellationWithRetry({request:()=>requestWorkflowTurnCancellation({sessionId:n.address.sessionId}),shouldRetryError:()=>!1});e.status!==`accepted`&&log.warn(`descendant cancel was never accepted; the child may run to completion`,{callId:n.operation.callId,childSessionId:n.address.sessionId,finalStatus:e.status,subagentName:n.identity.name})}catch(e){logError(log,`failed to cancel local descendant turn`,e,{callId:n.operation.callId,childSessionId:n.address.sessionId,subagentName:n.identity.name})}}async function cancelRemoteDescendant(e){let{handle:n}=e;if(n.address.kind!==`agent/remote`)return;let a=n.address.url;try{let{ctx:t,registry:o}=await e.remoteContext,s=getDynamicSubagentSelection(t,n.identity.nodeId),c={...await resolveRemoteAgentForAction({dynamicRemoteAgent:s?.kind===`remote`?s.remoteAgent:void 0,nodeId:n.identity.nodeId,remoteAgentName:n.identity.name,registry:o}),url:a},l=await requestCancellationWithRetry({request:()=>cancelRemoteAgentTurn({remote:c,sessionId:n.address.sessionId}),shouldRetryError:isRetryableRemoteAgentCancelError});l.status!==`accepted`&&log.warn(`remote descendant cancel was never accepted; the child may run to completion`,{callId:n.operation.callId,childSessionId:n.address.sessionId,finalStatus:l.status,remoteAgentName:n.identity.name})}catch(e){logError(log,`failed to cancel remote descendant turn`,e,{callId:n.operation.callId,childSessionId:n.address.sessionId,remoteAgentName:n.identity.name})}}async function requestCancellationWithRetry(e){let t=250,n={status:`no_active_turn`};for(let r=1;r<=8;r+=1){try{if(n=await e.request(),n.status===`accepted`||r===8)return n}catch(t){if(!e.shouldRetryError(t)||r===8)throw t}await new Promise(e=>setTimeout(e,t)),t=Math.min(t*2,1500)}return n}export{cancelDescendantTurnsStep};
@@ -1 +1 @@
1
- import{startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep};
1
+ import{startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId,serializedContext:e.serializedContext}))})).runId}}export{dispatchTurnStep};
@@ -25,6 +25,7 @@
25
25
  * - `$eve.channel_request_id` — inbound channel request id
26
26
  * - `$eve.invocation_token` — channel-local continuation token for an external invocation
27
27
  * - `$eve.invocation_owner` — SHA-256 fingerprint of the invocation's initiating principal
28
+ * - `$eve.is_trace_content_visible` — whether observability may read content-bearing workflow data
28
29
  */
29
30
  import type { EveAttributeValue } from "#runtime/attributes/normalize.js";
30
31
  /**
@@ -53,6 +54,7 @@ export interface SessionParentLineage {
53
54
  * tag emission silently drops undefined values.
54
55
  */
55
56
  export declare function readChannelKind(serializedContext: Record<string, unknown>): string | undefined;
57
+ export declare function isWorkflowTraceContentVisible(serializedContext: Record<string, unknown>): boolean;
56
58
  /**
57
59
  * Reads parent session lineage from a deserialized context map. Returns
58
60
  * an empty object for top-level runs or malformed delegated contexts.
@@ -144,4 +146,5 @@ export declare function buildTurnAttributes(input: {
144
146
  readonly parentSessionId: string;
145
147
  readonly requestId?: string;
146
148
  readonly rootSessionId: string;
149
+ readonly serializedContext: Record<string, unknown>;
147
150
  }): Record<string, EveAttributeValue>;
@@ -1 +1 @@
1
- import{ChannelRequestIdKey}from"#context/keys.js";import{isNonEmptyString}from"#shared/guards.js";function readChannelKind(e){let n=e[`eve.channel`]?.kind;return isNonEmptyString(n)?n:void 0}function readParentLineage(e){let n=e[`eve.parentSession`],r=n?.callId,i=n?.rootSessionId,a=n?.sessionId,o=n?.turn?.id;return{callId:isNonEmptyString(r)?r:void 0,rootSessionId:isNonEmptyString(i)?i:void 0,sessionId:isNonEmptyString(a)?a:void 0,turnId:isNonEmptyString(o)?o:void 0}}function readParentSessionId(e){return readParentLineage(e).sessionId}function readRootSessionId(e){return readParentLineage(e).rootSessionId}function readChannelRequestId(n){let r=n[ChannelRequestIdKey.name];return isNonEmptyString(r)?r:void 0}const EVE_SESSION_TITLE_MAX_CHARS=125;function deriveSessionTitle(e){let t=collectMessageText(e);if(t===void 0||t.length===0)return;let n=t.replace(/\s+/gu,` `).trim();if(n.length===0)return;let r=Array.from(n);return r.length<=125?n:`${r.slice(0,124).join(``)}…`}function collectMessageText(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return;let t=[];for(let n of e)n&&typeof n==`object`&&n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.length>0?t.join(` `):void 0}function buildSessionAttributes(e){return{"$eve.channel_request_id":readChannelRequestId(e.serializedContext),"$eve.type":`session`,"$eve.trigger":readChannelKind(e.serializedContext),"$eve.title":deriveSessionTitle(e.inputMessage)}}function buildSubagentRootAttributes(e){return{"$eve.channel_request_id":readChannelRequestId(e.serializedContext),"$eve.type":`subagent`,"$eve.parent":e.parentSessionId,"$eve.parent_call":e.parentCallId,"$eve.parent_turn":e.parentTurnId,"$eve.root":e.rootSessionId,"$eve.subagent":e.identity.nodeId,"$eve.trigger":readChannelKind(e.serializedContext)}}function buildTurnAttributes(e){return{"$eve.channel_request_id":e.requestId,"$eve.type":`turn`,"$eve.parent":e.parentSessionId,"$eve.root":e.rootSessionId}}export{EVE_SESSION_TITLE_MAX_CHARS,buildSessionAttributes,buildSubagentRootAttributes,buildTurnAttributes,deriveSessionTitle,readChannelKind,readChannelRequestId,readParentLineage,readParentSessionId,readRootSessionId};
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{ChannelRequestIdKey}from"#context/keys.js";import{isNonEmptyString}from"#shared/guards.js";import{shouldCaptureInstrumentationContent}from"#harness/instrumentation/content-policy.js";function readChannelKind(e){let t=e[`eve.channel`]?.kind;return isNonEmptyString(t)?t:void 0}function isWorkflowTraceContentVisible(t){let n=t[`eve.channel`];return shouldCaptureInstrumentationContent(normalizeChannelAudience(n?.audience))}function readParentLineage(e){let t=e[`eve.parentSession`],r=t?.callId,i=t?.rootSessionId,a=t?.sessionId,o=t?.turn?.id;return{callId:isNonEmptyString(r)?r:void 0,rootSessionId:isNonEmptyString(i)?i:void 0,sessionId:isNonEmptyString(a)?a:void 0,turnId:isNonEmptyString(o)?o:void 0}}function readParentSessionId(e){return readParentLineage(e).sessionId}function readRootSessionId(e){return readParentLineage(e).rootSessionId}function readChannelRequestId(e){let r=e[ChannelRequestIdKey.name];return isNonEmptyString(r)?r:void 0}const EVE_SESSION_TITLE_MAX_CHARS=125;function deriveSessionTitle(e){let t=collectMessageText(e);if(t===void 0||t.length===0)return;let n=t.replace(/\s+/gu,` `).trim();if(n.length===0)return;let r=Array.from(n);return r.length<=125?n:`${r.slice(0,124).join(``)}…`}function collectMessageText(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return;let t=[];for(let n of e)n&&typeof n==`object`&&n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.length>0?t.join(` `):void 0}function buildSessionAttributes(e){let t=isWorkflowTraceContentVisible(e.serializedContext);return{"$eve.channel_request_id":readChannelRequestId(e.serializedContext),"$eve.is_trace_content_visible":t,"$eve.type":`session`,"$eve.trigger":readChannelKind(e.serializedContext),"$eve.title":t?deriveSessionTitle(e.inputMessage):void 0}}function buildSubagentRootAttributes(e){return{"$eve.channel_request_id":readChannelRequestId(e.serializedContext),"$eve.is_trace_content_visible":isWorkflowTraceContentVisible(e.serializedContext),"$eve.type":`subagent`,"$eve.parent":e.parentSessionId,"$eve.parent_call":e.parentCallId,"$eve.parent_turn":e.parentTurnId,"$eve.root":e.rootSessionId,"$eve.subagent":e.identity.nodeId,"$eve.trigger":readChannelKind(e.serializedContext)}}function buildTurnAttributes(e){return{"$eve.channel_request_id":e.requestId,"$eve.is_trace_content_visible":isWorkflowTraceContentVisible(e.serializedContext),"$eve.type":`turn`,"$eve.parent":e.parentSessionId,"$eve.root":e.rootSessionId}}export{EVE_SESSION_TITLE_MAX_CHARS,buildSessionAttributes,buildSubagentRootAttributes,buildTurnAttributes,deriveSessionTitle,isWorkflowTraceContentVisible,readChannelKind,readChannelRequestId,readParentLineage,readParentSessionId,readRootSessionId};
@@ -0,0 +1,9 @@
1
+ import type { HarnessSession } from "#harness/types.js";
2
+ /** Derives the workflow fields used to select the next action at the park boundary. */
3
+ export declare function derivePendingState(session: HarnessSession): {
4
+ readonly authorizationAttemptIds?: readonly string[];
5
+ readonly authorizationNames?: readonly string[];
6
+ readonly hasPendingAuthorization: boolean;
7
+ readonly hasPendingInputBatch: boolean;
8
+ readonly pendingRuntimeActionKeys?: readonly string[];
9
+ };
@@ -0,0 +1 @@
1
+ import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getPendingAuthorization}from"#harness/authorization.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";function derivePendingState(t){let n=getPendingRuntimeActionBatch(t.state),r=getPendingAuthorization(t.state),i={authorizationAttemptIds:r?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:r?.challenges.map(e=>e.name),hasPendingAuthorization:r!==void 0,hasPendingInputBatch:hasPendingInputBatch(t.state)};return n===void 0?i:{...i,pendingRuntimeActionKeys:n.actions.map(e=>getRuntimeActionRequestKey(e))}}export{derivePendingState};
@@ -1 +1 @@
1
- import{callAdapterEventHandler}from"#channel/adapter.js";import{ChannelInstrumentationKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{abandonRunningAgentTurns}from"#harness/handles/transitions.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{withContextScope}from"#context/run-step.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{clearAllProxyInputRequests,getProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{createInstrumentationHandleEvent}from"#harness/instrumentation/native-events.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";async function settleCancelledTurnStep(a){"use step";let o=await readDurableSession(a.sessionState),s=await deserializeContext(a.serializedContext),c=s.require(ChannelKey),l=buildAdapterContext(c,s),u=s.require(BundleKey),d=resolveEffectiveAgentRuntime(u,s),f=getInstrumentationRuntime(),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:o,turnAgent:d.turnAgent}),m=getHarnessEmissionState(o.state),h=[...getProxyInputRequests(o.state).values()].some(e=>e.kind===`session-limit`);if(!(isHarnessBetweenTurns(p)&&hasProxyInputRequests(o.state)&&!h)){let n=a.parentWritable.getWriter();try{let r=await withContextScope(s,p,async r=>{let baseEmit=async t=>{let r=await callAdapterEventHandler(c,t,l);setChannelContext(s,{...c,state:{...l.state}});let i=stampMessageStreamEvent(r);await n.write(encodeMessageStreamEvent(i)),await dispatchStreamEventHooks({ctx:s,event:i,registry:u.hookRegistry})};return{result:await emitCancelledTurn(createInstrumentationHandleEvent({agentName:u.turnAgent.id,channelKind:s.get(ChannelInstrumentationKey)?.kind,handleEvent:baseEmit,hooks:f?.hooks,sessionId:p.sessionId,turnId:activeTurnId(m)})??baseEmit,m),session:r}});m=r.result,p=r.session}finally{await f?.forceFlush(),n.releaseLock()}}let g=reconcileSessionContinuationToken(s,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(abandonRunningAgentTurns(p))))),m)),_=getTurnUsageState(p.state)?.session,v={serializedContext:serializeContext(s),sessionState:createDurableSessionState({session:g})};return _===void 0?v:{...v,usage:toUsage(_)}}export{settleCancelledTurnStep};
1
+ import{callAdapterEventHandler}from"#channel/adapter.js";import{ChannelInstrumentationKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{abandonRunningAgentTurns}from"#harness/handles/transitions.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{withContextScope}from"#context/run-step.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{clearAllProxyInputRequests,getProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{createInstrumentationHandleEvent}from"#harness/instrumentation/native-events.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";async function settleCancelledTurnStep(a){"use step";let o=await readDurableSession(a.sessionState),s=await deserializeContext(a.serializedContext),c=s.require(ChannelKey),l=buildAdapterContext(c,s),u=s.require(BundleKey),d=resolveEffectiveAgentRuntime(u,s),f=getInstrumentationRuntime(),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:o,turnAgent:d.turnAgent}),m=getHarnessEmissionState(o.state),h=[...getProxyInputRequests(o.state).values()].some(e=>e.kind===`session-limit`);if(!(isHarnessBetweenTurns(p)&&hasProxyInputRequests(o.state)&&!h)){let n=a.parentWritable.getWriter();try{let r=await withContextScope(s,p,async r=>{let baseEmit=async t=>{let r=await callAdapterEventHandler(c,t,l);setChannelContext(s,{...c,state:{...l.state}});let i=stampMessageStreamEvent(r);await n.write(encodeMessageStreamEvent(i)),await dispatchStreamEventHooks({ctx:s,event:i,registry:u.hookRegistry})};return{result:await emitCancelledTurn(createInstrumentationHandleEvent({agentName:u.turnAgent.id,channelKind:s.get(ChannelInstrumentationKey)?.kind,handleEvent:baseEmit,hooks:f?.hooks,sessionId:p.sessionId,turnId:activeTurnId(m)})??baseEmit,m),session:r}});m=r.result,p=r.session}finally{await f?.forceFlush(),n.releaseLock()}}let g=reconcileSessionContinuationToken(s,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(abandonRunningAgentTurns(p))))),m)),_=getTurnUsageState(p.state)?.session,v={serializedContext:serializeContext(s),sessionState:createDurableSessionState({session:g})};return _===void 0?v:{...v,usage:toUsage(_)}}export{settleCancelledTurnStep};
@@ -1 +1 @@
1
- import{createEveCallbackRoutePath}from"#protocol/routes.js";import{parseJsonValue}from"#shared/json.js";import{loadContext}from"#context/container.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{recordTaskAgentAddress}from"#harness/handles/transitions.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{runStep}from"#context/run-step.js";import{propagateSubagentExecutorCancel}from"#execution/tasks/parent/dispatch.js";import{sendTaskCommand,sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{recordSessionTask}from"#tasks/session-index.js";import{activeTurnId}from"#harness/active-turn-id.js";import{readSubagentExecutor}from"#tasks/types.js";import{beginBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{CallbackBaseUrlKey,isAuthorizationSignal}from"#harness/authorization.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{createTaskDelegated,isTaskDelegated}from"#shared/tool-task.js";function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t,e.get(BundleKey))}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{bundle;executions=new Map;records=[];retained=!1;initialSession;constructor(e,t){this.bundle=t,this.initialSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await compensateBackgroundToolExecution(t,Error(`Background tool execution did not delegate or complete its task.`),this.bundle),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await compensateBackgroundToolExecution(n,e,this.bundle),t.length!==0){if(isTurnCancellation(e)){this.retained=!0;return}await compensateBackgroundToolExecution(t,e,this.bundle)}}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records){if(!e.settled||e.task===void 0)continue;let n=readSubagentExecutor(e.task.executor);n!==void 0&&(t=recordTaskAgentAddress(t,n)),t=recordSessionTask(t,e.task)}return t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[e.task]:[]);if(e.length!==0)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e.map(({taskInboxToken:e,taskId:t,taskRunId:n})=>({taskInboxToken:e,taskId:t,taskRunId:n}))}}async start(r){let a={settled:!1};this.records.push(a);let o=getHarnessEmissionState(this.initialSession.state),s=await beginBackgroundTask({callId:r.options.toolCallId,metadata:{kind:`tool`,name:r.definition.name},parentSessionId:this.initialSession.sessionId,parentStepIndex:o.stepIndex,parentTurnId:activeTurnId(o),session:this.initialSession});a.task=s;let c=loadContext().get(CallbackBaseUrlKey),l={taskId:s.taskId,token:s.taskInboxToken,...c===void 0?{}:{url:createWorkflowCallbackUrl(c,createEveCallbackRoutePath(s.taskInboxToken))}},u={batch:r.batch.calls,binding:l,delegated:({executor:e,receipt:t})=>createTaskDelegated({binding:l,executor:e,receipt:t}),send:createTaskSender(s,r.options.toolCallId),session:this.initialSession,task:s},d=r.definition.execute(r.toolInput,r.options,u);if(isAsyncIterable(d))throw Error(`Background tools cannot return AsyncIterable output.`);let f=await d;return isAuthorizationSignal(f)?f:isTaskDelegated(f)?(await deliverTaskCommand(s,{executor:f.executor,kind:`bind`}),a.task={...s,executor:f.executor},a.settled=!0,f.receipt):(await deliverTaskCommand(s,{data:parseJsonValue(f),kind:`complete`}),a.settled=!0,f)}};function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}async function deliverTaskCommand(e,t){if(await sendTaskCommand({command:t,taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${t.kind}".`)}function createTaskSender(e,t){let n=0;return async r=>{if(r.kind!==`update`){await deliverTaskCommand(e,r);return}if(await sendTaskInboundPayload({payload:{callId:t,kind:`task-update`,message:r.message,updateEpoch:e.taskId,updateIndex:n++},taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${r.kind}".`)}}async function compensateBackgroundToolExecution(e,t,n){let r=[];for(let i of e.toReversed()){if(i.task===void 0)continue;try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:i.task})}catch(e){r.push(e)}let e=readSubagentExecutor(i.task.executor);e!==void 0&&await propagateSubagentExecutorCancel({bundle:n,executor:e,taskId:i.task.taskId})}if(r.length>0)throw AggregateError([t,...r],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
1
+ import{createEveCallbackRoutePath}from"#protocol/routes.js";import{parseJsonValue}from"#shared/json.js";import{loadContext}from"#context/container.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{recordTaskAgentAddress}from"#harness/handles/transitions.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{runStep}from"#context/run-step.js";import{propagateSubagentExecutorCancel}from"#execution/tasks/parent/dispatch.js";import{CallbackBaseUrlKey,isAuthorizationSignal}from"#harness/authorization.js";import{sendTaskCommand,sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{recordSessionTask}from"#tasks/session-index.js";import{activeTurnId}from"#harness/active-turn-id.js";import{readSubagentExecutor}from"#tasks/types.js";import{beginBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{createTaskDelegated,isTaskDelegated}from"#shared/tool-task.js";function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t,e.get(BundleKey))}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{bundle;executions=new Map;records=[];retained=!1;initialSession;constructor(e,t){this.bundle=t,this.initialSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await compensateBackgroundToolExecution(t,Error(`Background tool execution did not delegate or complete its task.`),this.bundle),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await compensateBackgroundToolExecution(n,e,this.bundle),t.length!==0){if(isTurnCancellation(e)){this.retained=!0;return}await compensateBackgroundToolExecution(t,e,this.bundle)}}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records){if(!e.settled||e.task===void 0)continue;let n=readSubagentExecutor(e.task.executor);n!==void 0&&(t=recordTaskAgentAddress(t,n)),t=recordSessionTask(t,e.task)}return t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[e.task]:[]);if(e.length!==0)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e.map(({taskInboxToken:e,taskId:t,taskRunId:n})=>({taskInboxToken:e,taskId:t,taskRunId:n}))}}async start(r){let a={settled:!1};this.records.push(a);let o=getHarnessEmissionState(this.initialSession.state),s=await beginBackgroundTask({callId:r.options.toolCallId,metadata:{kind:`tool`,name:r.definition.name},parentSessionId:this.initialSession.sessionId,parentStepIndex:o.stepIndex,parentTurnId:activeTurnId(o),session:this.initialSession});a.task=s;let c=loadContext().get(CallbackBaseUrlKey),l={taskId:s.taskId,token:s.taskInboxToken,...c===void 0?{}:{url:createWorkflowCallbackUrl(c,createEveCallbackRoutePath(s.taskInboxToken))}},u={batch:r.batch.calls,binding:l,delegated:({executor:e,receipt:t})=>createTaskDelegated({binding:l,executor:e,receipt:t}),send:createTaskSender(s,r.options.toolCallId),session:this.initialSession,task:s},d=r.definition.execute(r.toolInput,r.options,u);if(isAsyncIterable(d))throw Error(`Background tools cannot return AsyncIterable output.`);let f=await d;return isAuthorizationSignal(f)?f:isTaskDelegated(f)?(await deliverTaskCommand(s,{executor:f.executor,kind:`bind`}),a.task={...s,executor:f.executor},a.settled=!0,f.receipt):(await deliverTaskCommand(s,{data:parseJsonValue(f),kind:`complete`}),a.settled=!0,f)}};function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}async function deliverTaskCommand(e,t){if(await sendTaskCommand({command:t,taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${t.kind}".`)}function createTaskSender(e,t){let n=0;return async r=>{if(r.kind!==`update`){await deliverTaskCommand(e,r);return}if(await sendTaskInboundPayload({payload:{callId:t,kind:`task-update`,message:r.message,updateEpoch:e.taskId,updateIndex:n++},taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${r.kind}".`)}}async function compensateBackgroundToolExecution(e,t,n){let r=[];for(let i of e.toReversed()){if(i.task===void 0)continue;try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:i.task})}catch(e){r.push(e)}let e=readSubagentExecutor(i.task.executor);e!==void 0&&await propagateSubagentExecutorCancel({bundle:n,executor:e,taskId:i.task.taskId})}if(r.length>0)throw AggregateError([t,...r],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
@@ -1 +1 @@
1
- import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{dispatchTaskStep}from"#execution/tasks/parent/dispatch-task-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{acknowledgeDelegatedTasksStep}from"#execution/tasks/parent/delegate.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{turnStep}from"#execution/workflow-steps.js";import{getRuntimeActionResultKey}from"#runtime/actions/keys.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";async function turnWorkflow(e){"use workflow";let n=migrateTurnWorkflowInput(e);return n.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(n):runLegacyTurnWorkflow(n)}async function runTurnOwnedWorkflow(t){let i=createHook({token:`${t.completionToken}:inbox`}),a=i[Symbol.asyncIterator](),c=new TurnExecutionCursor({controlToken:t.completionToken,parentWritable:t.stepInput.parentWritable,serializedContext:t.stepInput.serializedContext,sessionState:t.stepInput.sessionState}),m=0,nextDeliveryRequestId=()=>`${i.token}:delivery:${String(m++)}`,h=[],g=t.stepInput.input,_=!1,v;try{try{await claimHookOwnership(i),_=!0}catch(e){if(isHookConflictError(e))return;throw e}for(t.driverCapabilities?.cancelledTurnSettle===!0&&(v=await createTurnCancellationControl({controlToken:t.completionToken,expectedTurnId:activeTurnId(t.stepInput.sessionState.emissionState)}));;){let o={serializedContext:c.serializedContext,sessionState:c.sessionState},l=await turnStep(c.createStepInput(g,v?.signal)),u=l.action===`dispatch-workflow-runtime-actions`||l.action===`park`?l.pendingRuntimeActionKeys:void 0,d=(l.backgroundTasks?.length??0)>0;if(d){if(l.backgroundTaskState===void 0)throw Error(`Background tasks were returned without their committed session state.`);await c.adopt({serializedContext:o.serializedContext,sessionState:l.backgroundTaskState}),await acknowledgeDelegatedTasksStep({tasks:l.backgroundTasks??[]})}if(l.action===`cancelled`){await c.adopt({serializedContext:l.serializedContext,sessionState:c.sessionState}),await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(v?.signal.aborted===!0&&(u===void 0||d)){await c.adopt({serializedContext:preserveSerializedSessionDynamicModelSelection(o.serializedContext,l.serializedContext),sessionState:c.sessionState}),await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(l.sleepDurationMs!==void 0&&await waitForTurnSleep(l.sleepDurationMs,v)===`cancel`){await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(l.action===`done`){await v?.dispose(),await c.finish(l,{kind:`done`,output:l.output??``,isError:l.isError,usage:l.usage,usageDelta:l.usageDelta},h);return}if(u!==void 0){await c.adopt(l);let t=l.action===`park`&&l.tasksEnabled,o;o=l.action===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:t?dispatchTaskStep:dispatchRuntimeActionsStep;let d=await o({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentContinuationToken:i.token,parentWritable:c.parentWritable,serializedContext:c.serializedContext,sessionState:c.sessionState}),f=d.results.length===0?void 0:Date.now();await c.adopt(d),await acknowledgeDelegatedTasksStep({tasks:d.pendingTasks});let p=await waitForRuntimeActionResults({bufferedDeliveries:h,cancellation:v,cursor:c,inboxToken:i.token,initialAcceptedAtMs:f,initialResults:d.results,iterator:a,nextDeliveryRequestId,pendingActionKeys:u});if(p===`cancelled`){g=void 0;continue}if(p===`cancel-turn`){await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}g={kind:`runtime-action-result`,...p};continue}if(l.action===`park`){if(!(l.hasPendingAuthorization||l.hasPendingInputBatch&&t.capabilities?.requestInput===!0||t.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);await v?.dispose(),await c.finish(l,{authorizationAttemptIds:l.authorizationAttemptIds,authorizationNames:l.authorizationNames,kind:`park`,settled:l.settled},h);return}await c.adopt(l),g=void 0}}catch(e){throw await c.send({error:normalizeSerializableError(e),kind:`turn-error`}),e}finally{v!==void 0&&await v.dispose(),_&&await disposeHook(i)}}async function finishCancelledTurn(e){await cancelDescendantTurnsStep({serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}),await e.cancellation?.dispose(),await e.cursor.finish({sessionState:e.cursor.sessionState},{cancelled:!0,kind:`park`},e.bufferedDeliveries)}async function waitForTurnSleep(e,t){if(t?.signal.aborted===!0)return`cancel`;let n=sleep(e).then(()=>`slept`);return t===void 0?n:Promise.race([n,t.requested])}async function waitForRuntimeActionResults(e){let t,n=[...e.initialResults],r=new Map;if(e.initialAcceptedAtMs!==void 0)for(let t of e.initialResults)r.set(getRuntimeActionResultKey(t),e.initialAcceptedAtMs);for(;;){let o=resolveRuntimeActionResultsForKeys({pendingKeys:e.pendingActionKeys,results:n});if(o!==void 0)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),{acceptedAtMsByCallId:Object.fromEntries(o.map(e=>[e.callId,r.get(getRuntimeActionResultKey(e))])),results:o};e.cursor.sessionState.hasProxyInputRequests&&t===void 0&&(t=e.nextDeliveryRequestId(),await e.cursor.send({continuationToken:e.cursor.sessionState.continuationToken,inboxToken:e.inboxToken,kind:`turn-delivery-request`,requestId:t}));let s=e.iterator.next();s.catch(()=>{});let c=await(e.cancellation===void 0?s:Promise.race([s,e.cancellation.requested]));if(c===`cancel`)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),`cancelled`;if(c.done)throw Error(`Turn inbox closed before runtime actions completed.`);let l=c.value;if(l.kind===`runtime-action-result`){let t=e.cursor.sessionState.snapshot?.session.state,i=l.results.filter(e=>isInboxSubagentResultFromRunningHandle(t,e));if(i.length>0){let e=Date.now();n.push(...i);for(let t of i)r.set(getRuntimeActionResultKey(t),e)}continue}if(l.kind===`subagent-input-request`||l.kind===`subagent-authorization-event`){let t=await runProxySubagentEventStep({hookPayload:l,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});await e.cursor.adopt(t);continue}if(l.kind===`driver-delivery`&&l.requestId===t){await e.cursor.send({kind:`turn-delivery-accepted`,requestId:l.requestId}),t=void 0;let n=await routeDeliverToChildren({delivery:l.delivery,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});if(await e.cursor.adopt({serializedContext:n.serializedContext??e.cursor.serializedContext,sessionState:n.sessionState??e.cursor.sessionState}),n.kind===`cancel-turn`)return n.kind;n.remainder!==void 0&&e.bufferedDeliveries.push(n.remainder)}}}async function runLegacyTurnWorkflow(e){let t=e.stepInput;try{for(;;){let n=await turnStep(t);if(n.action!==`cancelled`&&n.sleepDurationMs!==void 0&&await sleep(n.sleepDurationMs),n.action===`done`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`done`,output:n.output??``,isError:n.isError,serializedContext:n.serializedContext,sessionState:n.sessionState,usage:n.usage,usageDelta:n.usageDelta},kind:`turn-result`}});return}if(n.action===`dispatch-workflow-runtime-actions`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`dispatch-workflow-runtime-actions`,pendingActionKeys:n.pendingRuntimeActionKeys,serializedContext:n.serializedContext,sessionState:n.sessionState},kind:`turn-result`}});return}if(n.action===`park`){let t=n.pendingRuntimeActionKeys;if(!(t!==void 0||n.hasPendingAuthorization||n.hasPendingInputBatch&&e.capabilities?.requestInput===!0||e.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);let r=t===void 0?{kind:`park`,serializedContext:n.serializedContext,sessionState:n.sessionState,authorizationAttemptIds:n.authorizationAttemptIds,authorizationNames:n.authorizationNames,settled:n.settled}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:n.serializedContext,sessionState:n.sessionState};await sendTurnControlStep({controlToken:e.completionToken,payload:{action:r,kind:`turn-result`}});return}t={input:void 0,parentWritable:t.parentWritable,serializedContext:n.serializedContext,sessionState:n.sessionState}}}catch(t){throw await sendTurnControlStep({controlToken:e.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}export{turnWorkflow};
1
+ import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{dispatchTaskStep}from"#execution/tasks/parent/dispatch-task-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{getRuntimeActionResultKey}from"#runtime/actions/keys.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{acknowledgeDelegatedTasksStep}from"#execution/tasks/parent/delegate.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{turnStep}from"#execution/workflow-steps.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";async function turnWorkflow(e){"use workflow";let n=migrateTurnWorkflowInput(e);return n.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(n):runLegacyTurnWorkflow(n)}async function runTurnOwnedWorkflow(t){let i=createHook({token:`${t.completionToken}:inbox`}),a=i[Symbol.asyncIterator](),o=new TurnExecutionCursor({controlToken:t.completionToken,parentWritable:t.stepInput.parentWritable,serializedContext:t.stepInput.serializedContext,sessionState:t.stepInput.sessionState}),l=0,nextDeliveryRequestId=()=>`${i.token}:delivery:${String(l++)}`,m=[],h=t.stepInput.input,g=!1,_;try{try{await claimHookOwnership(i),g=!0}catch(e){if(isHookConflictError(e))return;throw e}for(t.driverCapabilities?.cancelledTurnSettle===!0&&(_=await createTurnCancellationControl({controlToken:t.completionToken,expectedTurnId:activeTurnId(t.stepInput.sessionState.emissionState)}));;){let s={serializedContext:o.serializedContext,sessionState:o.sessionState},l=await turnStep(o.createStepInput(h,_?.signal)),u=l.action===`dispatch-workflow-runtime-actions`||l.action===`park`?l.pendingRuntimeActionKeys:void 0,d=(l.backgroundTasks?.length??0)>0;if(d){if(l.backgroundTaskState===void 0)throw Error(`Background tasks were returned without their committed session state.`);await o.adopt({serializedContext:s.serializedContext,sessionState:l.backgroundTaskState}),await acknowledgeDelegatedTasksStep({tasks:l.backgroundTasks??[]})}if(l.action===`cancelled`){await o.adopt({serializedContext:l.serializedContext,sessionState:l.backgroundTaskState??l.sessionState}),await finishCancelledTurn({bufferedDeliveries:m,cancellation:_,cursor:o});return}if(_?.signal.aborted===!0&&(u===void 0||d)){await o.adopt({serializedContext:preserveSerializedSessionDynamicModelSelection(s.serializedContext,l.serializedContext),sessionState:o.sessionState}),await finishCancelledTurn({bufferedDeliveries:m,cancellation:_,cursor:o});return}if(l.sleepDurationMs!==void 0&&await waitForTurnSleep(l.sleepDurationMs,_)===`cancel`){await finishCancelledTurn({bufferedDeliveries:m,cancellation:_,cursor:o});return}if(l.action===`done`){await _?.dispose(),await o.finish(l,{kind:`done`,output:l.output??``,isError:l.isError,usage:l.usage,usageDelta:l.usageDelta},m);return}if(u!==void 0){await o.adopt(l);let t=l.action===`park`&&l.tasksEnabled,s;s=l.action===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:t?dispatchTaskStep:dispatchRuntimeActionsStep;let d=await s({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentContinuationToken:i.token,parentWritable:o.parentWritable,serializedContext:o.serializedContext,sessionState:o.sessionState}),f=d.results.length===0?void 0:Date.now();await o.adopt(d),await acknowledgeDelegatedTasksStep({tasks:d.pendingTasks});let p=await waitForRuntimeActionResults({bufferedDeliveries:m,cancellation:_,cursor:o,inboxToken:i.token,initialAcceptedAtMs:f,initialResults:d.results,iterator:a,nextDeliveryRequestId,pendingActionKeys:u});if(p===`cancelled`){h=void 0;continue}if(p===`cancel-turn`){await finishCancelledTurn({bufferedDeliveries:m,cancellation:_,cursor:o});return}h={kind:`runtime-action-result`,...p};continue}if(l.action===`park`){if(!(l.hasPendingAuthorization||l.hasPendingInputBatch&&t.capabilities?.requestInput===!0||t.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);await _?.dispose(),await o.finish(l,{authorizationAttemptIds:l.authorizationAttemptIds,authorizationNames:l.authorizationNames,kind:`park`,settled:l.settled},m);return}await o.adopt(l),h=void 0}}catch(e){throw await o.send({error:normalizeSerializableError(e),kind:`turn-error`}),e}finally{_!==void 0&&await _.dispose(),g&&await disposeHook(i)}}async function finishCancelledTurn(e){await cancelDescendantTurnsStep({serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}),await e.cancellation?.dispose(),await e.cursor.finish({sessionState:e.cursor.sessionState},{cancelled:!0,kind:`park`},e.bufferedDeliveries)}async function waitForTurnSleep(e,t){if(t?.signal.aborted===!0)return`cancel`;let n=sleep(e).then(()=>`slept`);return t===void 0?n:Promise.race([n,t.requested])}async function waitForRuntimeActionResults(e){let t,n=[...e.initialResults],r=new Map;if(e.initialAcceptedAtMs!==void 0)for(let t of e.initialResults)r.set(getRuntimeActionResultKey(t),e.initialAcceptedAtMs);for(;;){let s=resolveRuntimeActionResultsForKeys({pendingKeys:e.pendingActionKeys,results:n});if(s!==void 0)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),{acceptedAtMsByCallId:Object.fromEntries(s.map(e=>[e.callId,r.get(getRuntimeActionResultKey(e))])),results:s};e.cursor.sessionState.hasProxyInputRequests&&t===void 0&&(t=e.nextDeliveryRequestId(),await e.cursor.send({continuationToken:e.cursor.sessionState.continuationToken,inboxToken:e.inboxToken,kind:`turn-delivery-request`,requestId:t}));let c=e.iterator.next();c.catch(()=>{});let l=await(e.cancellation===void 0?c:Promise.race([c,e.cancellation.requested]));if(l===`cancel`)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),`cancelled`;if(l.done)throw Error(`Turn inbox closed before runtime actions completed.`);let u=l.value;if(u.kind===`runtime-action-result`){let t=e.cursor.sessionState.snapshot?.session.state,i=u.results.filter(e=>isInboxSubagentResultFromRunningHandle(t,e));if(i.length>0){let e=Date.now();n.push(...i);for(let t of i)r.set(getRuntimeActionResultKey(t),e)}continue}if(u.kind===`subagent-input-request`||u.kind===`subagent-authorization-event`){let t=await runProxySubagentEventStep({hookPayload:u,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});await e.cursor.adopt(t);continue}if(u.kind===`driver-delivery`&&u.requestId===t){await e.cursor.send({kind:`turn-delivery-accepted`,requestId:u.requestId}),t=void 0;let n=await routeDeliverToChildren({delivery:u.delivery,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});if(await e.cursor.adopt({serializedContext:n.serializedContext??e.cursor.serializedContext,sessionState:n.sessionState??e.cursor.sessionState}),n.kind===`cancel-turn`)return n.kind;n.remainder!==void 0&&e.bufferedDeliveries.push(n.remainder)}}}async function runLegacyTurnWorkflow(e){let t=e.stepInput;try{for(;;){let n=await turnStep(t);if(n.action!==`cancelled`&&n.sleepDurationMs!==void 0&&await sleep(n.sleepDurationMs),n.action===`done`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`done`,output:n.output??``,isError:n.isError,serializedContext:n.serializedContext,sessionState:n.sessionState,usage:n.usage,usageDelta:n.usageDelta},kind:`turn-result`}});return}if(n.action===`dispatch-workflow-runtime-actions`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`dispatch-workflow-runtime-actions`,pendingActionKeys:n.pendingRuntimeActionKeys,serializedContext:n.serializedContext,sessionState:n.sessionState},kind:`turn-result`}});return}if(n.action===`park`){let t=n.pendingRuntimeActionKeys;if(!(t!==void 0||n.hasPendingAuthorization||n.hasPendingInputBatch&&e.capabilities?.requestInput===!0||e.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);let r=t===void 0?{kind:`park`,serializedContext:n.serializedContext,sessionState:n.sessionState,authorizationAttemptIds:n.authorizationAttemptIds,authorizationNames:n.authorizationNames,settled:n.settled}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:n.serializedContext,sessionState:n.sessionState};await sendTurnControlStep({controlToken:e.completionToken,payload:{action:r,kind:`turn-result`}});return}t={input:void 0,parentWritable:t.parentWritable,serializedContext:n.serializedContext,sessionState:n.sessionState}}}catch(t){throw await sendTurnControlStep({controlToken:e.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}export{turnWorkflow};
@@ -1 +1 @@
1
- import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TasksEnabledKey,TurnTaskDeliveryKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{TASK_UPDATE_TOOL_NAME,isTaskToolAvailable}from"#runtime/framework-tools/tasks.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext);a.input?.kind===`deliver`&&c.set(TurnTaskDeliveryKey,`none`);let l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0;c.set(TasksEnabledKey,d);let f=resolveEffectiveAgentRuntime(u,c),p=isTaskOwnedSerializedContext(o.serializedContext)&&isTaskToolAvailable({disabledFrameworkTools:u.resolvedAgent.disabledFrameworkTools??[],hasAuthoredTool:f.turnAgent.tools.some(e=>e.name===TASK_UPDATE_TOOL_NAME),tasksEnabled:d,toolName:TASK_UPDATE_TOOL_NAME});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(s.state),h;if(m&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(m,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},h=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),_=createExecutionHistoryView(g),v=getInstrumentationRuntime(),y=getHarnessEmissionState(g.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:v?.hooks,rootSessionId:g.rootSessionId??g.sessionId,sequence:y.sequence,sessionId:g.sessionId,turnId:activeTurnId(y)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:v?.hooks,includeTurn:!1,outcome:`failed`})),await v?.forceFlush()},b=buildAdapterContext(l,c),x;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,b):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}x=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),x={runtimeActionResults:o.input.results});if(x!==void 0&&a.input?.kind===`deliver`&&a.input.taskDeliveryId!==void 0){let e=resolveTaskDeliveryContext({state:s.state,taskDeliveryId:a.input.taskDeliveryId});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),x={...x,context:[...x.context??[],e.context]})}if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...b.state}}),o.input?.kind===`deliver`&&x===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:v?.hooks,includeTurn:!1,outcome:`completed`})),await v?.forceFlush();let e=reconcileSessionContinuationToken(c,g),t=serializeContext(c),n=e===g?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n,tasksEnabled:d}}let S=u.hookRegistry,C=u.resolvedAgent.dynamicInstructionsResolvers??[],w=u.resolvedAgent.dynamicSkillResolvers??[],T=u.subagentRegistry.dynamicResolvers??[],E=d||u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,D=u.resolvedAgent.dynamicToolResolvers??[],O={...u.graph.root,turnAgent:f.turnAgent},k=buildRuntimeIdentity(O);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!y.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:k});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:T,event:e,messages:_.initial.messages,persistentSessions:E,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:D,event:e,messages:_.initial.messages,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let A=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,b);setChannelContext(c,{...l,state:{...b.state}});let r=stampMessageStreamEvent(n);return await A.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(c,e)?stampMessageStreamEvent(e):await emit(e);await dispatchStreamEventHooks({ctx:c,registry:S,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:T,event:n,messages:t??[],persistentSessions:E}),await dispatchDynamicToolEvent({ctx:c,resolvers:D,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:w,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:C,event:n,messages:t??[]})},j=c.require(ModeKey),M;try{throwIfTurnAborted(o.abortSignal),M=await runBackgroundStep(c,g,async e=>{c.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:x,mode:j,session:e});if(h){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,_.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:k,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,k,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of h){let r=m?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,systemPromptAdditions:p?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r,_.messages(r)):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:_.projector,historyView:_.prepare(i),mode:j,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:O,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,x)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;A.releaseLock();let t=serializeContext(c),n=readRetainedBackgroundToolResult(c);return{action:`cancelled`,...n===void 0?{}:{backgroundTaskState:createDurableSessionState({session:n.backgroundTaskSession}),backgroundTasks:n.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:o.sessionState}}let N=reconcileSessionContinuationToken(c,M.session),P=serializeContext(c);M={...M,session:N};let F=createDurableSessionState({session:M.session}),I=readTurnSleepDurationMs(c),L=I===void 0?{}:{sleepDurationMs:I},R=M.backgroundTasks===void 0||M.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:M.backgroundTaskSession}),backgroundTasks:M.backgroundTasks};if(M.next!==null&&typeof M.next==`object`&&`done`in M.next){if(j===`task`&&hasPendingInputBatch(M.session.state))throw A.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await A.close();let e=getTurnUsageState(M.session.state)?.session;return{action:`done`,...R,output:M.next.output,isError:M.next.isError,...L,serializedContext:P,sessionState:F,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(M.session).delta}}if(M.next===null){A.releaseLock();let e=getPendingWorkflowInterrupt(M.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,...R,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...L,serializedContext:P,sessionState:F};let t=derivePendingState(M.session);if(M.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(M.session);return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:createDurableSessionState({session:n}),settled:{output:M.settledTurn.output,isError:M.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:F,tasksEnabled:d}}return A.releaseLock(),{action:`continue`,...R,...L,serializedContext:P,sessionState:F}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}export{turnStep};
1
+ import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TasksEnabledKey,TurnTaskDeliveryKey,TurnTaskStateKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{TASK_UPDATE_TOOL_NAME,isTaskToolAvailable}from"#runtime/framework-tools/tasks.js";import{coalesceTurnInputs,normalizeUserContent}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{derivePendingState}from"#execution/pending-turn-state.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{stageAttachmentsToSandbox}from"#harness/attachment-staging.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext);a.input?.kind===`deliver`&&(c.set(TurnTaskDeliveryKey,`none`),c.delete(TurnTaskStateKey));let l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0;c.set(TasksEnabledKey,d);let f=resolveEffectiveAgentRuntime(u,c),p=isTaskOwnedSerializedContext(o.serializedContext)&&isTaskToolAvailable({disabledFrameworkTools:u.resolvedAgent.disabledFrameworkTools??[],hasAuthoredTool:f.turnAgent.tools.some(e=>e.name===TASK_UPDATE_TOOL_NAME),tasksEnabled:d,toolName:TASK_UPDATE_TOOL_NAME});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(s.state),h;if(m&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(m,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},h=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),_=createExecutionHistoryView(g),v=getInstrumentationRuntime(),y=getHarnessEmissionState(g.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:v?.hooks,rootSessionId:g.rootSessionId??g.sessionId,sequence:y.sequence,sessionId:g.sessionId,turnId:activeTurnId(y)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:v?.hooks,includeTurn:!1,outcome:`failed`})),await v?.forceFlush()},b=buildAdapterContext(l,c),x;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,b):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}x=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),x={runtimeActionResults:o.input.results});if(x!==void 0&&a.input?.kind===`deliver`&&a.input.taskDeliveryId!==void 0){let e=resolveTaskDeliveryContext({state:s.state,taskDeliveryId:a.input.taskDeliveryId});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),x={...x,context:[...x.context??[],e.context]})}if(d&&c.get(TurnTaskDeliveryKey)===`none`){let e=resolveInitiatingTaskContext({state:s.state,turnId:activeTurnId(y)});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),c.set(TurnTaskStateKey,e.context))}if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...b.state}}),o.input?.kind===`deliver`&&x===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:v?.hooks,includeTurn:!1,outcome:`completed`})),await v?.forceFlush();let e=reconcileSessionContinuationToken(c,g),t=serializeContext(c),n=e===g?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n,tasksEnabled:d}}let S=u.hookRegistry,C=u.resolvedAgent.dynamicInstructionsResolvers??[],w=u.resolvedAgent.dynamicSkillResolvers??[],T=u.subagentRegistry.dynamicResolvers??[],E=d||u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,D=u.resolvedAgent.dynamicToolResolvers??[],O={...u.graph.root,turnAgent:f.turnAgent},k=buildRuntimeIdentity(O);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!y.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:k});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:T,event:e,messages:_.initial.messages,persistentSessions:E,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:D,event:e,messages:_.initial.messages,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let A=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,b);setChannelContext(c,{...l,state:{...b.state}});let r=stampMessageStreamEvent(n);return await A.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(c,e)?stampMessageStreamEvent(e):await emit(e);await dispatchStreamEventHooks({ctx:c,registry:S,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:T,event:n,messages:t??[],persistentSessions:E}),await dispatchDynamicToolEvent({ctx:c,resolvers:D,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:w,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:C,event:n,messages:t??[]})},j=c.require(ModeKey),M;try{throwIfTurnAborted(o.abortSignal),M=await runBackgroundStep(c,g,async e=>{c.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:x,mode:j,session:e});if(h){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,_.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:k,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,k,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of h){let r=m?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,systemPromptAdditions:p?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r,_.messages(r)):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:_.projector,historyView:_.prepare(i),mode:j,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:O,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,x)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;A.releaseLock();let t=serializeContext(c),n=readRetainedBackgroundToolResult(c),r=await preserveCancelledTurnMessage(n?.backgroundTaskSession??g,x);return{action:`cancelled`,...n===void 0?{}:{backgroundTaskState:createDurableSessionState({session:r}),backgroundTasks:n.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:createDurableSessionState({session:r})}}let N=reconcileSessionContinuationToken(c,M.session),P=serializeContext(c);M={...M,session:N};let F=createDurableSessionState({session:M.session}),I=readTurnSleepDurationMs(c),L=I===void 0?{}:{sleepDurationMs:I},R=M.backgroundTasks===void 0||M.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:M.backgroundTaskSession}),backgroundTasks:M.backgroundTasks};if(M.next!==null&&typeof M.next==`object`&&`done`in M.next){if(j===`task`&&hasPendingInputBatch(M.session.state))throw A.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await A.close();let e=getTurnUsageState(M.session.state)?.session;return{action:`done`,...R,output:M.next.output,isError:M.next.isError,...L,serializedContext:P,sessionState:F,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(M.session).delta}}if(M.next===null){A.releaseLock();let e=getPendingWorkflowInterrupt(M.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,...R,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...L,serializedContext:P,sessionState:F};let t=derivePendingState(M.session);if(M.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(M.session);return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:createDurableSessionState({session:n}),settled:{output:M.settledTurn.output,isError:M.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:F,tasksEnabled:d}}return A.releaseLock(),{action:`continue`,...R,...L,serializedContext:P,sessionState:F}}async function preserveCancelledTurnMessage(e,t){let n=normalizeUserContent(t?.message);if(n===void 0)return e;let r=await stageAttachmentsToSandbox(n);return{...e,history:[...e.history,{content:r,role:`user`}]}}export{turnStep};
@@ -1 +1 @@
1
- import{normalizeChannelAudience}from"#shared/channel-audience.js";import{ActiveChannelDeliveriesKey,ChannelInstrumentationKey,ParentTraceContextKey}from"#context/keys.js";import{channelDeliveryIdempotencyKey}from"#harness/instrumentation/lifecycle.js";async function instrumentChannelDelivery(r){if(!(`delivery`in r)){let e=r.ctx.get(ActiveChannelDeliveriesKey);if(e===void 0||r.hooks===void 0)return;let n=`channel.delivery.${r.outcome}`;for(let t of e)await r.hooks.publish({agentName:t.agentName,delivery:t.delivery,error:r.error,errorCode:r.errorCode,idempotencyKey:channelDeliveryIdempotencyKey(t.sessionId,t.delivery.deliveryId),outcome:r.outcome,rootSessionId:t.rootSessionId,sequence:r.includeTurn?t.sequence:void 0,sessionId:t.sessionId,turnId:r.includeTurn?t.turnId:void 0,type:n});r.ctx.delete(ActiveChannelDeliveriesKey);return}if(r.hooks===void 0||r.delivery.deliveryMetadata===void 0)return;let i=[],a=normalizeChannelAudience(r.ctx.get(ChannelInstrumentationKey)?.metadata.audience);for(let e of r.delivery.deliveryMetadata){let t=r.delivery.payloads[e.payloadIndex],n={channelAudience:a,channelKind:e.channelKind,channelName:e.channelName,deliveryId:e.deliveryId,requestId:e.requestId,requestTraceContext:e.requestTraceContext},o=!r.hooks.capturesContent||t===void 0?void 0:projectDeliveryInput(t),s={agentName:r.agentName,delivery:n,rootSessionId:r.rootSessionId,sequence:r.sequence,sessionId:r.sessionId,turnId:r.turnId};i.push(s),await r.hooks.publish({agentName:s.agentName,delivery:n,idempotencyKey:channelDeliveryIdempotencyKey(r.sessionId,n.deliveryId),input:o,parentTraceContext:r.ctx.get(ParentTraceContextKey),rootSessionId:r.rootSessionId,sessionId:r.sessionId,type:`channel.delivery.started`})}i.length>0&&r.ctx.set(ActiveChannelDeliveriesKey,i)}function projectDeliveryInput(e){let t={};return e.context!==void 0&&(t.context=e.context),e.message!==void 0&&(t.message=e.message),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.inputResponses!==void 0&&(t.inputResponses=e.inputResponses.map(e=>{let t={};return e.optionId!==void 0&&(t.optionId=e.optionId),e.text!==void 0&&(t.text=e.text),t})),t}function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}export{channelDeliveryErrorCode,instrumentChannelDelivery};
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{ActiveChannelDeliveriesKey,ChannelInstrumentationKey,ParentTraceContextKey}from"#context/keys.js";import{instrumentationHooksForAudience}from"#harness/instrumentation/content-policy.js";import{channelDeliveryIdempotencyKey}from"#harness/instrumentation/lifecycle.js";async function instrumentChannelDelivery(a){if(!(`delivery`in a)){let n=a.ctx.get(ActiveChannelDeliveriesKey);if(n===void 0||a.hooks===void 0)return;let r=`channel.delivery.${a.outcome}`;for(let t of n)await instrumentationHooksForAudience(a.hooks,normalizeChannelAudience(t.delivery.channelAudience))?.publish({agentName:t.agentName,delivery:t.delivery,error:a.error,errorCode:a.errorCode,idempotencyKey:channelDeliveryIdempotencyKey(t.sessionId,t.delivery.deliveryId),outcome:a.outcome,rootSessionId:t.rootSessionId,sequence:a.includeTurn?t.sequence:void 0,sessionId:t.sessionId,turnId:a.includeTurn?t.turnId:void 0,type:r});a.ctx.delete(ActiveChannelDeliveriesKey);return}if(a.hooks===void 0||a.delivery.deliveryMetadata===void 0)return;let o=[],s=normalizeChannelAudience(a.ctx.get(ChannelInstrumentationKey)?.metadata.audience),c=instrumentationHooksForAudience(a.hooks,s);for(let e of a.delivery.deliveryMetadata){let t=a.delivery.payloads[e.payloadIndex],n={channelAudience:s,channelKind:e.channelKind,channelName:e.channelName,deliveryId:e.deliveryId,requestId:e.requestId,requestTraceContext:e.requestTraceContext},i=!c?.capturesContent||t===void 0?void 0:projectDeliveryInput(t),l={agentName:a.agentName,delivery:n,rootSessionId:a.rootSessionId,sequence:a.sequence,sessionId:a.sessionId,turnId:a.turnId};o.push(l),await c?.publish({agentName:l.agentName,delivery:n,idempotencyKey:channelDeliveryIdempotencyKey(a.sessionId,n.deliveryId),input:i,parentTraceContext:a.ctx.get(ParentTraceContextKey),rootSessionId:a.rootSessionId,sessionId:a.sessionId,type:`channel.delivery.started`})}o.length>0&&a.ctx.set(ActiveChannelDeliveriesKey,o)}function projectDeliveryInput(e){let t={};return e.context!==void 0&&(t.context=e.context),e.message!==void 0&&(t.message=e.message),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.inputResponses!==void 0&&(t.inputResponses=e.inputResponses.map(e=>{let t={};return e.optionId!==void 0&&(t.optionId=e.optionId),e.text!==void 0&&(t.text=e.text),t})),t}function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}export{channelDeliveryErrorCode,instrumentChannelDelivery};
@@ -0,0 +1,6 @@
1
+ import type { InstrumentationHooks } from "#harness/instrumentation/lifecycle.js";
2
+ import type { ChannelAudience } from "#shared/channel-audience.js";
3
+ /** Hosted instrumentation records conversation content only for known-public channels. */
4
+ export declare function shouldCaptureInstrumentationContent(audience: ChannelAudience): boolean;
5
+ /** Applies the audience ceiling before any content-capable provider sees an event. */
6
+ export declare function instrumentationHooksForAudience(hooks: InstrumentationHooks | undefined, audience: ChannelAudience): InstrumentationHooks | undefined;
@@ -0,0 +1 @@
1
+ import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{withoutInstrumentationContent}from"#harness/instrumentation/content.js";function shouldCaptureInstrumentationContent(t){return t===`public`||t===`unknown`&&isEveDevEnvironment()}function instrumentationHooksForAudience(e,n){return e===void 0||!e.capturesContent||shouldCaptureInstrumentationContent(n)?e:{capturesContent:!1,publish:n=>e.publish(withoutInstrumentationContent(n))}}export{instrumentationHooksForAudience,shouldCaptureInstrumentationContent};
@@ -104,6 +104,8 @@ export type InstrumentationActionOutput = {
104
104
  * some provider asked for it, and a provider that did not ask never receives
105
105
  * it — which is the same guarantee a destination that declines content gets,
106
106
  * one layer lower and without an OpenTelemetry pipeline to route it through.
107
+ * Runtime audience policy can still lower hosted private or unknown events to
108
+ * metadata before this provider-level projection.
107
109
  */
108
110
  export type InstrumentationCapture = "content" | "metadata";
109
111
  /**
@@ -1 +1 @@
1
- import{createLogger,formatError}from"#internal/logging.js";import{normalizeInstrumentationChannelKind,resolveInstrumentationProjection}from"#internal/instrumentation.js";import{AuthKey,ChannelInstrumentationKey,InitiatorAuthKey,ParentSessionKey}from"#context/keys.js";import{parseJsonObject,parseJsonValue}from"#shared/json.js";import{contextStorage}from"#context/container.js";const log=createLogger(`harness.instrumentation-runtime-context`);function buildTelemetryRuntimeContext(e){let t=e.authored!==void 0,r=e.providerResolvers!==void 0&&e.providerResolvers.length>0;if(!t&&!r)return;let i=resolveStepStartedRuntimeContext(e),o=resolveProviderRuntimeContext(e),s=contextStorage.getStore()?.get(ChannelInstrumentationKey);return{...i,...o,"eve.channel.kind":normalizeInstrumentationChannelKind(s?.kind),"eve.environment":e.environment,"eve.session.id":e.session.sessionId,"eve.step.index":String(e.emissionState.stepIndex),"eve.turn.id":e.emissionState.turnId,"eve.turn.sequence":String(e.emissionState.sequence),"eve.version":e.eveVersion}}function buildInstrumentationStepStartedInput(e){let t=contextStorage.getStore(),r=t?.get(ChannelInstrumentationKey);return{channel:{kind:normalizeInstrumentationChannelKind(r?.kind),metadata:snapshotForInstrumentation(r?.metadata,`channel.metadata`)??{}},modelInput:snapshotForInstrumentation(e.modelInput,`modelInput`)??{instructions:void 0,messages:[]},session:{auth:projectSessionAuth(t),id:e.session.sessionId,parent:snapshotForInstrumentation(t?.get(ParentSessionKey),`session.parent`)},step:{index:e.emissionState.stepIndex},turn:{id:e.emissionState.turnId,sequence:e.emissionState.sequence}}}function filterAuthoredRuntimeContext(e,t){let n={};for(let[r,i]of Object.entries(e)){if(r.startsWith(`eve.`)){log.warn(`ignoring reserved instrumentation runtime context key`,{key:r,source:t});continue}n[r]=i}return Object.keys(n).length>0?n:void 0}function resolveStepStartedRuntimeContext(e){let n=e.authored?.events?.[`step.started`];if(n===void 0)return;let i=`events["step.started"]`,a=resolveInstrumentationProjection({invoke:()=>{let t=buildInstrumentationStepStartedInput(e);return n(t)},log,source:i});if(a===void 0)return;if(!(`runtimeContext`in a)){log.warn(`ignoring instrumentation event result because runtimeContext is missing`,{source:i});return}let o;try{o=parseJsonObject(a.runtimeContext)}catch(e){log.warn(`ignoring instrumentation event result because runtimeContext is invalid`,{error:formatError(e),source:i});return}return filterAuthoredRuntimeContext(o,i)}function resolveProviderRuntimeContext(e){let t=e.providerResolvers;if(t===void 0||t.length===0)return;let n={},i=!1;for(let a of t){let t=`provider.runtimeContext`,o=resolveInstrumentationProjection({invoke:()=>{let t=buildInstrumentationStepStartedInput(e);return a(t)},log,source:t});if(o===void 0)continue;let s=filterAuthoredRuntimeContext(o,t);s!==void 0&&(Object.assign(n,s),i=!0)}return i?n:void 0}function projectSessionAuth(e){let t=e?.get(AuthKey)??null,n=e?.get(InitiatorAuthKey)??t;return{current:snapshotForInstrumentation(t,`session.auth.current`)??null,initiator:snapshotForInstrumentation(n,`session.auth.initiator`)??null}}function snapshotForInstrumentation(e,n){if(e!==void 0)try{return parseJsonValue(e)}catch(e){log.warn(`dropping non-serializable instrumentation snapshot`,{error:formatError(e),source:n});return}}export{buildTelemetryRuntimeContext};
1
+ import{createLogger,formatError}from"#internal/logging.js";import{normalizeInstrumentationChannelKind,resolveInstrumentationProjection}from"#internal/instrumentation.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{AuthKey,ChannelInstrumentationKey,InitiatorAuthKey,ParentSessionKey}from"#context/keys.js";import{parseJsonObject,parseJsonValue}from"#shared/json.js";import{contextStorage}from"#context/container.js";import{shouldCaptureInstrumentationContent}from"#harness/instrumentation/content-policy.js";const log=createLogger(`harness.instrumentation-runtime-context`);function buildTelemetryRuntimeContext(e){let t=e.authored!==void 0,r=e.providerResolvers!==void 0&&e.providerResolvers.length>0;if(!t&&!r)return;let i=resolveStepStartedRuntimeContext(e),a=resolveProviderRuntimeContext(e),s=contextStorage.getStore()?.get(ChannelInstrumentationKey);return{...i,...a,"eve.channel.kind":normalizeInstrumentationChannelKind(s?.kind),"eve.environment":e.environment,"eve.session.id":e.session.sessionId,"eve.step.index":String(e.emissionState.stepIndex),"eve.turn.id":e.emissionState.turnId,"eve.turn.sequence":String(e.emissionState.sequence),"eve.version":e.eveVersion}}function buildInstrumentationStepStartedInput(e){let t=contextStorage.getStore(),r=t?.get(ChannelInstrumentationKey),a=shouldCaptureInstrumentationContent(normalizeChannelAudience(r?.metadata.audience));return{channel:{kind:normalizeInstrumentationChannelKind(r?.kind),metadata:snapshotForInstrumentation(r?.metadata,`channel.metadata`)??{}},modelInput:a?snapshotForInstrumentation(e.modelInput,`modelInput`)??{instructions:void 0,messages:[]}:{instructions:void 0,messages:[]},session:{auth:projectSessionAuth(t),id:e.session.sessionId,parent:snapshotForInstrumentation(t?.get(ParentSessionKey),`session.parent`)},step:{index:e.emissionState.stepIndex},turn:{id:e.emissionState.turnId,sequence:e.emissionState.sequence}}}function filterAuthoredRuntimeContext(e,t){let n={};for(let[r,i]of Object.entries(e)){if(r.startsWith(`eve.`)){log.warn(`ignoring reserved instrumentation runtime context key`,{key:r,source:t});continue}n[r]=i}return Object.keys(n).length>0?n:void 0}function resolveStepStartedRuntimeContext(e){let n=e.authored?.events?.[`step.started`];if(n===void 0)return;let i=`events["step.started"]`,a=resolveInstrumentationProjection({invoke:()=>{let t=buildInstrumentationStepStartedInput(e);return n(t)},log,source:i});if(a===void 0)return;if(!(`runtimeContext`in a)){log.warn(`ignoring instrumentation event result because runtimeContext is missing`,{source:i});return}let o;try{o=parseJsonObject(a.runtimeContext)}catch(e){log.warn(`ignoring instrumentation event result because runtimeContext is invalid`,{error:formatError(e),source:i});return}return filterAuthoredRuntimeContext(o,i)}function resolveProviderRuntimeContext(e){let t=e.providerResolvers;if(t===void 0||t.length===0)return;let n={},i=!1;for(let a of t){let t=`provider.runtimeContext`,o=resolveInstrumentationProjection({invoke:()=>{let t=buildInstrumentationStepStartedInput(e);return a(t)},log,source:t});if(o===void 0)continue;let s=filterAuthoredRuntimeContext(o,t);s!==void 0&&(Object.assign(n,s),i=!0)}return i?n:void 0}function projectSessionAuth(e){let t=e?.get(AuthKey)??null,n=e?.get(InitiatorAuthKey)??t;return{current:snapshotForInstrumentation(t,`session.auth.current`)??null,initiator:snapshotForInstrumentation(n,`session.auth.initiator`)??null}}function snapshotForInstrumentation(e,n){if(e!==void 0)try{return parseJsonValue(e)}catch(e){log.warn(`dropping non-serializable instrumentation snapshot`,{error:formatError(e),source:n});return}}export{buildTelemetryRuntimeContext};