eve 0.16.2 → 0.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/src/chunks/{use-eve-agent-BEOUv37s.js → use-eve-agent-Bh1NmXO9.js} +8 -5
- package/dist/src/chunks/{use-eve-agent-C25KOe9i.js → use-eve-agent-Dvy_Wjvq.js} +8 -5
- package/dist/src/cli/dev/tui/tui.d.ts +2 -0
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/dev/url-target.d.ts +14 -0
- package/dist/src/cli/dev/url-target.js +1 -0
- package/dist/src/cli/run.js +3 -3
- package/dist/src/client/client.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +3 -3
- package/dist/src/compiled/@workflow/core/classify-error.d.ts +15 -0
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/runtime.js +27 -27
- package/dist/src/compiled/@workflow/core/serialization.d.ts +12 -3
- package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +10 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/_chunks/workflow/{attribute-changes-DUxG-Gic.js → attribute-changes-zAifvEhb.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{resume-hook-CUCPW67D.js → resume-hook-C15uJ2ik.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/run-BJUPZ0Ni.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{sleep-Dxuzj5to.js → sleep-C8B-TYir.js} +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/subagent-invocation.d.ts +20 -5
- package/dist/src/execution/subagent-invocation.js +2 -2
- package/dist/src/execution/subagent-tool.d.ts +7 -0
- package/dist/src/execution/subagent-tool.js +1 -1
- package/dist/src/harness/types.d.ts +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/http/basic-auth.d.ts +1 -0
- package/dist/src/internal/http/basic-auth.js +1 -0
- package/dist/src/public/channels/telegram/api.d.ts +3 -0
- package/dist/src/public/channels/telegram/api.js +2 -2
- package/dist/src/public/channels/telegram/inbound.d.ts +2 -0
- package/dist/src/public/channels/telegram/inbound.js +1 -1
- package/dist/src/public/channels/telegram/index.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/definitions/tool.d.ts +0 -33
- package/dist/src/public/definitions/tool.js +1 -1
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/public/tools/index.js +1 -1
- package/dist/src/services/dev-client/client-options.d.ts +5 -1
- package/dist/src/services/dev-client/client-options.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/telegram.mdx +2 -0
- package/docs/concepts/default-harness.md +0 -10
- package/docs/guides/dev-tui.md +7 -1
- package/docs/guides/meta.json +0 -1
- package/docs/guides/remote-agents.md +0 -1
- package/docs/reference/cli.md +10 -1
- package/docs/reference/typescript-api.md +26 -26
- package/docs/subagents.mdx +0 -1
- package/package.json +5 -5
- package/dist/src/compiled/_chunks/workflow/run-CVlF84yI.js +0 -1
- package/docs/guides/dynamic-workflows.md +0 -70
|
@@ -93,7 +93,16 @@ export declare const FRAMED_STREAM_MAX_TOTAL_RECONNECTS = 1000;
|
|
|
93
93
|
*/
|
|
94
94
|
export declare function createReconnectingFramedStream(runId: string, name: string, startIndex?: number): ReadableStream<Uint8Array>;
|
|
95
95
|
export declare class WorkflowServerWritableStream extends WritableStream<Uint8Array> {
|
|
96
|
-
|
|
96
|
+
/**
|
|
97
|
+
* @param runReadyBarrier Turbo mode only: a promise that resolves once the
|
|
98
|
+
* backgrounded `run_started` has landed. When the step body runs
|
|
99
|
+
* optimistically (before `run_started` is durable), the first chunk write to
|
|
100
|
+
* a brand-new stream would otherwise reach the World before the run exists
|
|
101
|
+
* and be rejected as run-not-found. Awaiting this once before the first
|
|
102
|
+
* flush/close orders the write after the run's creation. `undefined` outside
|
|
103
|
+
* turbo and on the await path, where the run was already durable.
|
|
104
|
+
*/
|
|
105
|
+
constructor(runId: string, name: string, runReadyBarrier?: Promise<unknown>);
|
|
97
106
|
}
|
|
98
107
|
export type { ByteStreamFraming, Reducers, Revivers, SerializableSpecial, } from './serialization/types.js';
|
|
99
108
|
import type { ByteStreamFraming, Reducers, Revivers } from './serialization/types.js';
|
|
@@ -112,7 +121,7 @@ import type { ByteStreamFraming, Reducers, Revivers } from './serialization/type
|
|
|
112
121
|
* to `false` for backwards compatibility with older runs.
|
|
113
122
|
* @returns
|
|
114
123
|
*/
|
|
115
|
-
export declare function getExternalReducers(global: Record<string, any> | undefined, ops: Promise<void>[], runId: string, cryptoKey: EncryptionKeyParam, framedByteStreams?: boolean): Partial<Reducers>;
|
|
124
|
+
export declare function getExternalReducers(global: Record<string, any> | undefined, ops: Promise<void>[], runId: string, cryptoKey: EncryptionKeyParam, framedByteStreams?: boolean, runReadyBarrier?: Promise<unknown>): Partial<Reducers>;
|
|
116
125
|
/**
|
|
117
126
|
* Reducers for serialization boundary from within the workflow execution
|
|
118
127
|
* environment, passing return value to the client side and into step arguments.
|
|
@@ -380,7 +389,7 @@ export declare function hydrateStepArguments(value: Uint8Array | unknown, runId:
|
|
|
380
389
|
* backwards compatibility with older runs.
|
|
381
390
|
* @returns The dehydrated value as binary data (Uint8Array) with format prefix
|
|
382
391
|
*/
|
|
383
|
-
export declare function dehydrateStepReturnValue(value: unknown, runId: string, key: CryptoKey | undefined, ops?: Promise<any>[], global?: Record<string, any>, v1Compat?: boolean, framedByteStreams?: boolean, compression?: boolean): Promise<Uint8Array | unknown>;
|
|
392
|
+
export declare function dehydrateStepReturnValue(value: unknown, runId: string, key: CryptoKey | undefined, ops?: Promise<any>[], global?: Record<string, any>, v1Compat?: boolean, framedByteStreams?: boolean, compression?: boolean, runReadyBarrier?: Promise<unknown>): Promise<Uint8Array | unknown>;
|
|
384
393
|
/**
|
|
385
394
|
* Called from the step handler when a step throws. Dehydrates the thrown
|
|
386
395
|
* value from within the step execution environment into a format that can
|
|
@@ -51,6 +51,16 @@ export type StepContext = {
|
|
|
51
51
|
closureVars?: Record<string, any>;
|
|
52
52
|
encryptionKey?: CryptoKey;
|
|
53
53
|
writables?: Map<string, CachedWritable>;
|
|
54
|
+
/**
|
|
55
|
+
* Turbo mode only: a promise that resolves once the backgrounded
|
|
56
|
+
* `run_started` has landed (the run exists). Set when the step body runs
|
|
57
|
+
* optimistically — before `run_started`/`step_started` are confirmed — so a
|
|
58
|
+
* direct step-body world write (e.g. `experimental_setAttributes`, which
|
|
59
|
+
* resolves to a host-side `attr_set` create) can gate on it and never race
|
|
60
|
+
* ahead of the run's creation. `undefined` outside turbo and on the await
|
|
61
|
+
* path, where `run_started` was already durable before the body ran.
|
|
62
|
+
*/
|
|
63
|
+
runReadyBarrier?: Promise<unknown>;
|
|
54
64
|
};
|
|
55
65
|
export declare const contextStorage: AsyncLocalStorage<StepContext>;
|
|
56
66
|
//# sourceMappingURL=context-storage.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const version = "5.0.0-beta.
|
|
1
|
+
export declare const version = "5.0.0-beta.26";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e,i as t}from"../../_chunks/workflow/dist-Dxrjttr2.js";import{dn as n,fn as r,fr as i,lr as a,mr as o,nn as s,on as c,t as l,tn as u,un as d,ur as f}from"../../_chunks/workflow/attribute-changes-
|
|
1
|
+
import{c as e,i as t}from"../../_chunks/workflow/dist-Dxrjttr2.js";import{dn as n,fn as r,fr as i,lr as a,mr as o,nn as s,on as c,t as l,tn as u,un as d,ur as f}from"../../_chunks/workflow/attribute-changes-zAifvEhb.js";import{t as p}from"../../_chunks/workflow/sleep-C8B-TYir.js";import{t as m}from"../../_chunks/workflow/run-BJUPZ0Ni.js";async function h(e,n={}){let i=l(e,n);if(i.length===0)return;let a=n.allowReservedAttributes===!0,o=globalThis[r];if(!o)throw new t("experimental_setAttributes() called outside a workflow runtime context. It must be called from within a workflow body (`use workflow`).");await o(i,a?{allowReservedAttributes:!0}:{})}s(u,m);function g(e){let t=globalThis[d];return t||f(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,g),t(e)}function _(e){let{respondWith:t,token:n,...r}=e??{};if(n!==void 0)throw Error("`createWebhook()` does not accept a `token` option. Webhook tokens are always randomly generated. Use `createHook()` with `resumeHook()` for deterministic token patterns.");let i;t!==void 0&&(i={respondWith:t});let a=g({...r,metadata:i,isWebhook:!0}),{url:s}=o();return a.url=`${s}/.well-known/workflow/v1/webhook/${encodeURIComponent(a.token)}`,a}function v(){function e(t,n){i(`defineHook().resume()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,e)}return{create(e){return g(e)},resume:e}}function y(e={}){let{namespace:t}=e,r=globalThis[n](t);return Object.create(globalThis.WritableStream.prototype,{[c]:{value:r,writable:!1}})}function b(){a(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,b)}function x(){i(`resumeHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook`,x)}export{t as FatalError,e as RetryableError,g as createHook,_ as createWebhook,v as defineHook,h as experimental_setAttributes,b as getStepMetadata,o as getWorkflowMetadata,y as getWritable,x as resumeHook,p as sleep};
|
|
@@ -56,4 +56,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
56
56
|
`)?e.split(`
|
|
57
57
|
`).map((e,t)=>t===0?e:` ${e}`).join(`
|
|
58
58
|
`):e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var Wv=class e extends Error{steps;globalThis;stepCount;hookCount;waitCount;attributeCount;hookDisposedCount;abortCount;constructor(e,t){let n=[...e.values()],r=0,i=0,o=0,s=0,c=0,l=0;for(let e of n)e.type===`step`?r++:e.type===`hook`?e.disposed?c++:e.abortRequested?l++:i++:e.type===`wait`?o++:e.type===`attribute`&&s++;let u=[];r>0&&u.push(`${r} ${a(`step`,`steps`,r)}`),i>0&&u.push(`${i} ${a(`hook`,`hooks`,i)}`),o>0&&u.push(`${o} ${a(`wait`,`waits`,o)}`),s>0&&u.push(`${s} ${a(`attribute write`,`attribute writes`,s)}`),c>0&&u.push(`${c} hook ${a(`disposal`,`disposals`,c)}`);let d=a(`has`,`have`,r+i+o+s+c),f=+(r>0)+ +(i>0)+ +(o>0)+ +(s>0)+ +(c>0),p;p=f>1?`processed`:r>0?`run`:i>0||o>0?`created`:s>0?`written`:c>0?`processed`:`received`;let m=u.length>0?`${u.join(` and `)} ${d} not been ${p} yet`:`0 steps have not been run yet`;super(m),this.name=`WorkflowSuspension`,this.steps=n,this.globalThis=t,this.stepCount=r,this.hookCount=i,this.waitCount=o,this.attributeCount=s,this.hookDisposedCount=c,this.abortCount=l}static is(t){return t instanceof e}};function Gv(){throw new v(`This API is not available inside a workflow function. Workflow functions run in a deterministic VM; move the call to a step function for full Node.js access.`)}function $(...e){return t=>Object.fromEntries(e.map(e=>[e,t]))}const Kv=$(`workflow.name`),qv=$(`workflow.operation`),Jv=$(`workflow.run.id`),Yv=$(`workflow.run.status`),Xv=$(`workflow.started_at`),Zv=$(`workflow.events.count`),Qv=$(`workflow.arguments.count`),$v=$(`workflow.result.type`),ey=$(`workflow.trace.propagated`),ty=$(`workflow.trace.mode`),ny=$(`workflow.turbo`),ry=$(`workflow.error.name`),iy=$(`workflow.error.message`),ay=$(`workflow.error.code`),oy=$(`workflow.steps.created`),sy=$(`workflow.hooks.created`),cy=$(`workflow.waits.created`),ly=$(`workflow.route.type`),uy=$(`workflow.route.handler_cached`),dy=$(`workflow.route.invocation_count`),fy=$(`workflow.route.entrypoint_age_ms`),py=$(`workflow.route.module_body_init_ms`),my=$(`step.name`),hy=$(`step.id`),gy=$(`step.attempt`),_y=$(`step.status`),vy=$(`step.max_retries`),yy=$(`step.skipped`),by=$(`step.skip_reason`),xy=$(`step.arguments.count`),Sy=$(`step.result.type`),Cy=$(`step.error.name`),wy=$(`step.error.message`),Ty=$(`step.fatal_error`),Ey=$(`step.retry.exhausted`),Dy=$(`step.retry.timeout_seconds`),Oy=$(`step.retry.will_retry`),ky=$(`messaging.system`),Ay=$(`messaging.destination.name`),jy=$(`messaging.message.id`),My=$(`messaging.operation.type`),Ny=$(`workflow.queue.overhead_ms`),Py=$(`deployment.id`),Fy=$(`workflow.hook.token`),Iy=$(`workflow.hook.id`),Ly=$(`workflow.hook.found`),Ry=$(`workflow.suspension.state`),zy=$(`workflow.suspension.hook_count`),By=$(`workflow.suspension.step_count`),Vy=$(`workflow.suspension.wait_count`),Hy=$(`http.request.method`),Uy=$(`http.route`),Wy=$(`http.response.status_code`),Gy=$(`error.type`),Ky=$(`workflow.events.pages_loaded`),qy=$(`workflow.queue.deserialize_time_ms`),Jy=$(`workflow.queue.execution_time_ms`),Yy=$(`workflow.queue.serialize_time_ms`),Xy=$(`workflow.serialization.operation`),Zy=$(`workflow.serialization.compressed`),Qy=$(`workflow.serialization.codec`),$y=$(`workflow.serialization.uncompressed_bytes`),eb=$(`workflow.serialization.stored_bytes`),tb=$(`workflow.serialization.compression_ratio`),nb=$(`peer.service`),rb=$(`rpc.system`),ib=$(`rpc.service`),ab=$(`rpc.method`),ob=$(`error.retryable`),sb=$(`error.category`),cb=new Set;function lb(){let e=process.env.WORKFLOW_TRACE_MODE;return e===`continuous`?`continuous`:(e&&e!==`linked`&&!cb.has(e)&&(cb.add(e),Ab.warn(`Unrecognized WORKFLOW_TRACE_MODE value "${e}"; expected "linked" or "continuous". Falling back to "linked".`)),`linked`)}function ub(e){return e!==void 0&&Object.keys(e).length>0}function db(e,t){return e===`linked`&&ub(t)?Promise.resolve(t):pb()}async function fb(e,t){if(e!==`linked`)return wb();let n=await Tb(ub(t)?t:void 0);return n?[n]:void 0}async function pb(){let e=await gb.value;if(!e)return{};let t={};return e.propagation.inject(e.context.active(),t),t}async function mb(e){let t=await gb.value;if(t)return t.propagation.extract(t.context.active(),e)}async function hb(e,t){if(!e)return t();let n=await gb.value;if(!n)return t();let r=await mb(e);return r?n.context.with(r,async()=>await t()):t()}const gb=o(async()=>{try{return await import(`./src-CQuMexnO.js`).then(t=>e(t.t(),1))}catch{return Ab.info(`OpenTelemetry not available, tracing will be disabled`),null}}),_b=o(async()=>{let e=await gb.value;return e?e.trace.getTracer(`workflow`):null});async function vb(e,...t){let[n,r]=await Promise.all([_b.value,gb.value]),{fn:i,opts:a}=typeof t[0]==`function`?{fn:t[0],opts:{}}:{fn:t[1],opts:t[0]};if(!i)throw Error(`Function to trace must be provided`);return!n||!r?await i():n.startActiveSpan(e,a,async e=>{try{let t=await i(e);return e.setStatus({code:r.SpanStatusCode.OK}),t}catch(t){throw e.setStatus({code:r.SpanStatusCode.ERROR,message:t.message}),yb(t,r,e),t}finally{e.end()}})}function yb(e,t,n){!e||!Wv.is(e)||(n.setStatus({code:t.SpanStatusCode.OK}),n.setAttributes({...Ry(`suspended`),...By(e.stepCount),...zy(e.hookCount),...Vy(e.waitCount)}))}async function bb(e){let[t,n]=await Promise.all([mb(e),gb.value]);if(!(!t||!n))return n.trace.getSpanContext(t)}async function xb(){return await Cb(e=>e.trace.getActiveSpan())}async function Sb(e){return Cb(t=>t.SpanKind[e])}async function Cb(e){let t=await gb.value;if(t)return await e(t)}function wb(){return Cb(e=>{let t=e.trace.getActiveSpan()?.spanContext();if(t)return[{context:t}]})}async function Tb(e){if(!e)return;let[t,n]=await Promise.all([bb(e),gb.value]);if(!(!t||!n)&&n.trace.isSpanContextValid(t))return{context:t}}async function Eb(e,t){let n=await gb.value;if(!n)return t();let r=n.propagation.createBaggage({"workflow.run_id":{value:e.workflowRunId},"workflow.name":{value:e.workflowName}}),i=n.propagation.setBaggage(n.context.active(),r);return n.context.with(i,()=>t())}function Db(e,t){if(!t)return!1;let n=!1;for(let r of t.split(`,`)){let t=r.trim();if(!t)continue;let i=t.startsWith(`-`),a=i?t.slice(1):t;RegExp(`^${a.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`)}$`).test(e)&&(n=!i)}return n}function Ob(e,t={}){let n=r=>{let i=n=>t.debugNamespace??`workflow:${e}:${n}`,a=t=>{let n=i(t);return(i,a)=>{let o=Object.keys(r).length>0,s=a&&Object.keys(a).length>0,c=o||s?{...r,...a??{}}:void 0;(t===`error`||t===`warn`)&&(t===`error`?console.error:console.warn)(Iv(`[workflow-sdk]`,i,c)),Db(n,process.env.DEBUG)&&(console.debug(`[${n}] ${i}`,c??``),xb().then(n=>{n?.addEvent(`${t}.${e}`,{message:i,...c})}).catch(()=>{}))}};return{debug:a(`debug`),info:a(`info`),warn:a(`warn`),error:a(`error`),child:e=>n({...r,...e}),forRun:(e,t,i)=>n({...r,workflowRunId:e,...t===void 0?{}:{workflowName:t},...i??{}})}};return n({})}const kb=Ob(`step`),Ab=Ob(`runtime`),jb=Ob(`webhook`),Mb=Ob(`events`);Ob(`adapter`),Ob(`build`,{debugNamespace:`workflow:build`});function Nb(e){if(m.is(e))throw e}function Pb(e,t){let n=e.includes(`return value`)?`returning`:`passing`,r=`Failed to serialize ${e}`;t instanceof qg&&t.path&&(r+=` at path "${t.path}"`);let i=`Ensure you're ${n} workflow serializable types. Check the serialization docs to see what's serializable: https://workflow-sdk.dev/docs/foundations/serialization`;return t instanceof qg&&t.value!==void 0&&Ab.error(`Serialization failed`,{context:e,problematicValue:t.value}),{message:r,hint:i}}async function Fb(e,t,n){try{let r=pv.serialize(e,`client`,n);return Pv(await jv(gv(Q.DEVALUE_V1,r),n?.compression===!0,n?.compressionStats),t)}catch(e){Nb(e);let{message:t,hint:n}=Pb(`client value`,e);throw new h(t,{hint:n,cause:e})}}async function Ib(e,t,n){let r=await Mv(await Fv(e,t),n?.compressionStats);if(!(r instanceof Uint8Array)){if(pv.deserializeLegacy)return pv.deserializeLegacy(r,`client`,n);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:i,payload:a}=vv(r);if(i===Q.DEVALUE_V1)return pv.deserialize(a,`client`,n);throw Error(`Unsupported serialization format: ${i}`)}async function Lb(e,t,n){try{let r=pv.serialize(e,`step`,n);return Pv(await jv(gv(Q.DEVALUE_V1,r),n?.compression===!0,n?.compressionStats),t)}catch(e){Nb(e);let{message:t,hint:n}=Pb(`step value`,e);throw new h(t,{hint:n,cause:e})}}async function Rb(e,t,n){let r=await Mv(await Fv(e,t),n?.compressionStats);if(!(r instanceof Uint8Array)){if(pv.deserializeLegacy)return pv.deserializeLegacy(r,`step`,n);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:i,payload:a}=vv(r);if(i===Q.DEVALUE_V1)return pv.deserialize(a,`step`,n);throw Error(`Unsupported serialization format: ${i}`)}function zb(e,t){if(!(e instanceof Uint8Array)){if(pv.deserializeLegacy)return pv.deserializeLegacy(e,`workflow`,t);throw Error(`Cannot deserialize non-binary data without legacy support`)}let{format:n,payload:r}=vv(e);if(n===Q.DEVALUE_V1)return pv.deserialize(r,`workflow`,t);throw Error(`Unsupported serialization format: ${n}`)}const Bb=Symbol.for(`WORKFLOW_STEP_CONTEXT_STORAGE`),Vb=globalThis[Bb]??(globalThis[Bb]=new ne);function Hb(e,t,n){if(e===0&&t===0&&n===0)return null;let r=[];e>0&&r.push(`${e} ${a(`step`,`steps`,e)}`),t>0&&r.push(`${t} ${a(`hook`,`hooks`,t)}`),n>0&&r.push(`${n} ${a(`timer`,`timers`,n)}`);let i=[];e>0&&i.push(`steps are completed`),t>0&&i.push(`hooks are received`),n>0&&i.push(`timers have elapsed`);let o=i.join(` and `);return`${r.join(` and `)} to be enqueued\n Workflow will suspend and resume when ${o}`}function Ub(e,t){let n=`${e.replace(`wrun_`,`strm_`)}_user`;return t?`${n}_${Buffer.from(t,`utf-8`).toString(`base64url`)}`:n}function Wb(e){return`strm_${e}_system_abort`}function Gb(e){if(!e.startsWith(`abrt_`))throw Error(`Invalid abort hook token format: expected "abrt_" prefix, got "${e}"`);return Wb(e.slice(5))}var Kb;(function(e){e[e.Consumed=0]=`Consumed`,e[e.NotConsumed=1]=`NotConsumed`,e[e.Finished=2]=`Finished`})(Kb||={});var qb=class{eventIndex;events=[];callbacks=[];onConsumedEvent;onUnconsumedEvent;getPromiseQueue;pendingUnconsumedCheck=null;pendingUnconsumedTimeout=null;unconsumedCheckVersion=0;constructor(e,t){this.events=e,this.eventIndex=0,this.onConsumedEvent=t.onConsumedEvent,this.onUnconsumedEvent=t.onUnconsumedEvent,this.getPromiseQueue=t.getPromiseQueue}subscribe(e){this.callbacks.push(e),this.pendingUnconsumedCheck!==null&&(this.unconsumedCheckVersion++,this.pendingUnconsumedCheck=null,this.pendingUnconsumedTimeout!==null&&(clearTimeout(this.pendingUnconsumedTimeout),this.pendingUnconsumedTimeout=null)),process.nextTick(this.consume)}notifyConsumedEvent(e){if(this.onConsumedEvent)try{this.onConsumedEvent(e)}catch(e){Mb.error(`onConsumedEvent callback threw an error`,{error:e})}}consume=()=>{for(;;){let e=this.events[this.eventIndex]??null;if(!this.consumeOne(e)){this.handleUnconsumed(e);return}}};consumeOne(e){for(let t=0;t<this.callbacks.length;t++){let n=this.callbacks[t],r=Kb.NotConsumed;try{r=n(e)}catch(e){Mb.error(`EventConsumer callback threw an error`,{error:e})}if(!(r!==Kb.Consumed&&r!==Kb.Finished))return e!==null&&this.notifyConsumedEvent(e),this.eventIndex++,r===Kb.Finished&&this.callbacks.splice(t,1),e!==null}return!1}handleUnconsumed(e){if(e!==null){let t=++this.unconsumedCheckVersion;this.pendingUnconsumedCheck=this.getPromiseQueue().then(()=>new Promise(e=>setTimeout(e,0))).then(()=>this.getPromiseQueue()).then(()=>{this.pendingUnconsumedTimeout=setTimeout(()=>{this.pendingUnconsumedTimeout=null,this.unconsumedCheckVersion===t&&(this.pendingUnconsumedCheck=null,this.onUnconsumedEvent(e))},100)})}}},Jb=class{aborted=!1;reason=void 0;[X];[Z];#e=[];#t=null;get onabort(){return this.#t}set onabort(e){this.#t=e,e&&this.aborted&&e.call(this)}constructor(e,t){this[X]=e,this[Z]=t}_setAborted(e){if(!this.aborted){this.aborted=!0,this.reason=e,this.#t&&this.#t.call(this);for(let e of this.#e)e();this.#e=[]}}addEventListener(e,t){if(e===`abort`){if(this.aborted){t();return}this.#e.push(t)}}removeEventListener(e,t){e===`abort`&&(this.#e=this.#e.filter(e=>e!==t))}throwIfAborted(){if(this.aborted)throw this.reason??new DOMException(`The operation was aborted.`,`AbortError`)}};function Yb(e){return class{signal;[X];[Z];constructor(){let t=e.generateUlid(),n=Wb(t),r=`abrt_${t}`;this[X]=n,this[Z]=r,this.signal=new Jb(n,r);let i=`hook_${e.generateUlid()}`;e.invocationsQueue.set(i,{type:`hook`,correlationId:i,token:r,isWebhook:!1,isSystem:!0}),e.eventsConsumer.subscribe(t=>{if(!t||t.correlationId!==i)return Kb.NotConsumed;let n=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof n==`string`&&n!==this[Z])return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new _(`Replay divergence: abort hook event ${t.eventType} for ${i} belongs to token "${n}", but the current abort hook expects "${this[Z]}"`,{eventId:t.eventId}))}),Kb.Finished;if(t.eventType===`hook_created`){let t=e.invocationsQueue.get(i);return t&&t.type===`hook`&&(t.hasCreatedEvent=!0),Kb.Consumed}if(t.eventType===`hook_received`){let n=t.eventData?.payload;return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{let t;try{if(n!==void 0)try{let r=await zx(n,e.runId,e.encryptionKey,e.globalThis);r&&typeof r==`object`&&`reason`in r&&(t=r.reason)}catch{}this.signal._setAborted(t)}finally{e.pendingDeliveries--}}),e.invocationsQueue.delete(i),Kb.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(i),Kb.Finished):Kb.NotConsumed})}abort(t){if(!this.signal.aborted){this.signal._setAborted(t);for(let[,n]of e.invocationsQueue)if(n.type===`hook`&&n.token===this[Z]){n.abortRequested=!0,n.abortReason=t;break}}}}}function Xb(){return{abort(e){let t=new Jb(``,``);return t._setAborted(e??new DOMException(`The operation was aborted.`,`AbortError`)),t},any(e){let t=new Jb(``,``),n=Array.from(e);for(let e of n)if(e.aborted)return t._setAborted(e.reason),t;let r=[],i=()=>{for(let{signal:e,listener:t}of r)e.removeEventListener&&e.removeEventListener(`abort`,t);r.length=0};for(let e of n){if(!e.addEventListener)continue;let n=()=>{t.aborted||(t._setAborted(e.reason),i())};r.push({signal:e,listener:n}),e.addEventListener(`abort`,n)}return t},timeout(){throw Error(`AbortSignal.timeout() is not supported in workflow functions. Use sleep() with an AbortController instead. See: /docs/errors/abort-signal-timeout-in-workflow`)}}}const Zb=Ih();function Qb(e){try{return e.getReader({mode:`byob`}).releaseLock(),`bytes`}catch{}}function $b(e){return Nb(e),e instanceof h&&e.cause!==void 0||e instanceof v&&e.cause!==void 0?e.cause:e}async function ex(e,t){if(e.recorded)try{let n=await xb();if(!n)return;let r=e.uncompressedBytes??0,i=e.storedBytes??0;n.setAttributes({...Xy(t),...Zy(e.compressed??!1),...Qy(e.codec??`none`),...$y(r),...eb(i),...e.compressed&&r>0?tb(1-i/r):{}})}catch{}}function tx(e,t){let n=new TextEncoder,r={resolved:!1,key:void 0};return new TransformStream({async transform(i,a){try{r.resolved||=(r.key=await Nv(t),!0);let o=l_(i,e),s=n.encode(o),c=gv(Q.DEVALUE_V1,s);if(r.key){let e=await m_(r.key,c);c=gv(Q.ENCRYPTED,e)}let l=new Uint8Array(4+c.length);new DataView(l.buffer).setUint32(0,c.length,!1),l.set(c,4),a.enqueue(l)}catch(e){if(m.is(e)){a.error(e);return}let{message:t,hint:n}=Pb(`stream chunk`,e);a.error(new h(t,{hint:n,cause:e}))}}})}function nx(e,t){let n=new TextDecoder,r=new Uint8Array,i={resolved:!1,key:void 0};function a(e){let t=new Uint8Array(r.length+e.length);t.set(r,0),t.set(e,r.length),r=t}async function o(a){for(i.resolved||=(i.key=await Nv(t),!0);r.length>=4;){let t=new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,!1);if(r.length<4+t)break;let o=r.slice(4,4+t);r=r.slice(4+t);let{format:s,payload:c}=vv(o);if(s===Q.ENCRYPTED){if(!i.key){a.error(new m(`Encrypted stream data encountered but no encryption key is available. Encryption is not configured or no key was provided for this run.`,{context:{operation:`decrypt`,byteLength:c.byteLength,formatPrefix:`encr`}}));return}let e;try{e=await h_(i.key,c)}catch(e){throw m.is(e)&&e.context&&(e.context.formatPrefix=s),e}({format:s,payload:c}=vv(e))}if(s===Q.DEVALUE_V1){let t=n.decode(c);a.enqueue(s_(t,e))}}}return new TransformStream({async transform(t,i){if(r.length===0&&t.length>=4){let e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1);if(e>0&&e<1e8){a(t),await o(i);return}}else if(r.length>0){a(t),await o(i);return}let s=n.decode(t).split(`
|
|
59
|
-
`);for(let t of s)t.length>0&&i.enqueue(s_(t,e))},async flush(e){r.length>0&&await o(e)}})}const rx=1e8;function ix(){return new TransformStream({transform(e,t){if(e.length===0)return;if(e.length>rx){t.error(new v(`Byte-stream chunk of ${e.length} bytes exceeds the maximum framed chunk size (${rx}). Split the data into smaller chunks before writing.`,{slug:`serialization-failed`}));return}let n=new Uint8Array(4+e.length);new DataView(n.buffer).setUint32(0,e.length,!1),n.set(e,4),t.enqueue(n)}})}function ax(){let e=new Uint8Array;function t(t){let n=new Uint8Array(e.length+t.length);n.set(e,0),n.set(t,e.length),e=n}return new TransformStream({transform(n,r){for(n.length>0&&t(n);e.length>=4;){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!1);if(t>rx){r.error(new v(`Byte-stream frame length ${t} exceeds maximum (${rx}). This usually means a non-framed byte stream is being read as framed.`,{slug:`serialization-failed`}));return}let n=4+t;if(e.length<n)break;r.enqueue(e.slice(4,n)),e=e.slice(n)}},flush(t){e.length>0&&t.error(new v(`Byte-stream ended with ${e.length} bytes of incomplete frame data. The stream was truncated mid-frame.`,{slug:`serialization-failed`}))}})}var ox=class extends ReadableStream{#e;constructor(e,t,n){if(typeof t!=`string`||t.length===0)throw new v(`"name" is required, got "${t}"`);super({type:`bytes`,pull:async r=>{let i=this.#e;if(!i){let r=await(await T_()).streams.get(e,t,n);i=this.#e=r.getReader()}if(!i){r.error(Error(`Failed to get reader`));return}let a=await i.read();a.done?(this.#e=void 0,r.close()):r.enqueue(a.value)},cancel:async e=>{this.#e&&=(await this.#e.cancel(e).catch(()=>{}),void 0)}})}};function sx(e,t,n){let r=n===void 0||n>=0,i=n??0,a=0,o=0,s=0,c,l=new Uint8Array;async function u(){let o=await T_(),s=r?i+a:n;c=(await o.streams.get(e,t,s)).getReader()}async function d(){for(c&&=(await c.cancel().catch(()=>{}),void 0),i+=a,a=0,l=new Uint8Array;;){if(o++,s++,o>50)throw Error(`Stream "${t}" exceeded maximum reconnection attempts (50)`);if(s>1e3)throw Error(`Stream "${t}" exceeded maximum total reconnection attempts (1000)`);try{await u();return}catch{}}}return new ReadableStream({pull:async e=>{for(;;){if(!c)try{await u()}catch(t){e.error(t);return}let t;try{t=await c.read()}catch(t){if(!r){e.error(t);return}try{await d()}catch(t){e.error(t);return}continue}if(t.done||!t.value){c=void 0,e.close();return}let n=t.value;if(n.length>0){let e=new Uint8Array(l.length+n.length);e.set(l,0),e.set(n,l.length),l=e}let i=!1;for(;l.length>=4;){let t=4+new DataView(l.buffer,l.byteOffset,l.byteLength).getUint32(0,!1);if(l.length<t)break;e.enqueue(l.slice(0,t)),l=l.slice(t),a++,i=!0}if(i){o=0;return}}},cancel:async()=>{c&&=(await c.cancel().catch(e=>{console.warn(`Error closing ReadableStream reader:`,e)}),void 0)}})}var cx=class extends WritableStream{constructor(e,t){if(typeof e!=`string`)throw new v(`"runId" must be a string, got "${typeof e}"`);if(typeof t!=`string`||t.length===0)throw new v(`"name" is required, got "${t}"`);let n=T_(),r=[],i=null,a=null,o,s=async()=>{if(i&&=(clearTimeout(i),null),r.length===0)return;let a=r.slice(),s=await n;if(o===void 0&&(o=s.streamFlushIntervalMs??10),typeof s.streams.writeMulti==`function`&&a.length>1)await s.streams.writeMulti(e,t,a);else for(let n of a)await s.streams.write(e,t,n);r=[]},c=[],l=()=>{i||=setTimeout(()=>{i=null;let e=c;c=[],a=s().then(()=>{for(let t of e)t.resolve()},t=>{for(let n of e)n.reject(t)})},o??10)};super({async write(e){a&&=(await a,null),r.push(e),l(),await new Promise((e,t)=>{c.push({resolve:e,reject:t})})},async close(){a&&=(await a,null),await s(),await(await n).streams.close(e,t)},abort(e){i&&=(clearTimeout(i),null),r=[];let t=c;c=[];let n=e??Error(`Stream aborted`);for(let e of t)e.reject(n)}})}};function lx(e=globalThis){return{...J_(),...ov(),...iv(e),Request:t=>{if(!(t instanceof e.Request))return!1;let n={method:t.method,url:t.url,headers:t.headers,body:t.body,duplex:t.duplex},r=t[B_];return r&&(n.responseWritable=r),t.signal&&(t.signal.aborted||t.signal[X])&&(n.signal=t.signal),n},Response:t=>t instanceof e.Response?{type:t.type,url:t.url,status:t.status,statusText:t.statusText,headers:t.headers,body:t.body,redirected:t.redirected}:!1}}function ux(e,t,n,r,i,a){let o=t[X],s=t[Z];if(!o){let e=(n[N_]||Zb)();o=Wb(e),s=`abrt_${e}`,t[X]=o,t[Z]=s,t.signal&&(t.signal[X]=o,t.signal[Z]=s)}return fx(e,o,i,a,r),{streamName:o,hookToken:s,aborted:e.aborted,reason:e.aborted?e.reason:void 0}}function dx(e,t){let n=t[X]??t.signal?.[X],r=t[Z]??t.signal?.[Z];if(!n)throw Error(`AbortController/AbortSignal stream name is not set`);return{streamName:n,hookToken:r,aborted:e.aborted,reason:e.aborted?e.reason:void 0}}function fx(e,t,n,r,i){e.aborted||e[H_]||(e[H_]=!0,e.addEventListener(`abort`,()=>{i.push((async()=>{try{let i=await Nv(r),a=await Mx({aborted:!0,reason:e.reason},n,i),o=new cx(n,t).getWriter();await o.write(a),await o.close()}catch{}})())},{once:!0}))}function px(e=globalThis,t,n,r,i=!1){return{...lx(e),ReadableStream:a=>{if(!(a instanceof e.ReadableStream))return!1;if(a.locked)throw new h(`ReadableStream is locked and cannot be passed across a workflow boundary.`,{hint:`Pass the stream before calling .getReader() / .pipeThrough() / .pipeTo(), or tee it with .tee() and pass one of the branches.`});let o=`strm_${(e[N_]||Zb)()}`,s=Qb(a),c=new cx(n,o);s===`bytes`?i?t.push(a.pipeThrough(ix()).pipeTo(c)):t.push(a.pipeTo(c)):t.push(a.pipeThrough(tx(px(e,t,n,r,i),r)).pipeTo(c));let l={name:o};return s&&(l.type=s),s===`bytes`&&i&&(l.framing=`framed-v1`),l},WritableStream:r=>{if(!(r instanceof e.WritableStream))return!1;let i=r[P_],a=r[L_];if(typeof i==`string`&&typeof a==`string`){let e={name:i,runId:a},t=r[R_];return typeof t==`string`&&(e.deploymentId=t),e}let o=`strm_${(e[N_]||Zb)()}`,s=new ox(n,o);return t.push(s.pipeTo(r)),{name:o}},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:ux(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:ux(i,i,e,t,n,r)}}function mx(e=globalThis){return{...lx(e),ReadableStream:t=>{if(!(t instanceof e.ReadableStream))return!1;let n=t[z_];if(n!==void 0)return{bodyInit:n};let r=t[P_];if(!r)throw new v("ReadableStream `name` is not set");let i={name:r},a=t[F_];a&&(i.type=a);let o=t[I_];return o&&(i.framing=o),i},WritableStream:t=>{if(!(t instanceof e.WritableStream))return!1;let n=t[P_];if(!n)throw new v("WritableStream `name` is not set");let r={name:n},i=t[L_];typeof i==`string`&&(r.runId=i);let a=t[R_];return typeof a==`string`&&(r.deploymentId=a),r},AbortController:t=>{if(!t||!t.signal)return!1;let n=t,r=n[X]??n.signal?.[X],i=e.AbortController&&typeof e.AbortController==`function`&&t instanceof e.AbortController;return!r&&!i?!1:dx(t.signal,n)},AbortSignal:t=>{let n=t?.[X],r=e.AbortSignal&&typeof e.AbortSignal==`function`&&t instanceof e.AbortSignal;return!n&&!r?!1:dx(t,t)}}}function hx(e=globalThis,t,n,r,i=!1){return{...lx(e),ReadableStream:a=>{if(!(a instanceof e.ReadableStream))return!1;if(a.locked)throw new h(`ReadableStream is locked and cannot be passed across a workflow boundary.`,{hint:`Pass the stream before calling .getReader() / .pipeThrough() / .pipeTo(), or tee it with .tee() and pass one of the branches.`});let o=a[P_],s=a[F_],c=a[I_];if(!o){o=`strm_${(e[N_]||Zb)()}`,s=Qb(a),c=s===`bytes`&&i?`framed-v1`:c;let l=new cx(n,o);s===`bytes`?c===`framed-v1`?t.push(a.pipeThrough(ix()).pipeTo(l)):t.push(a.pipeTo(l)):t.push(a.pipeThrough(tx(hx(e,t,n,r,i),r)).pipeTo(l))}let l={name:o};return s&&(l.type=s),c&&(l.framing=c),l},WritableStream:i=>{if(!(i instanceof e.WritableStream))return!1;let a=i[P_],o=i[L_];a||(a=`strm_${(e[N_]||Zb)()}`,t.push(new ox(n,a).pipeThrough(nx(Tx(e,t,n,r),r)).pipeTo(i)));let s={name:a};typeof o==`string`&&(s.runId=o);let c=i[R_];return typeof c==`string`&&(s.deploymentId=c),s},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:ux(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:ux(i,i,e,t,n,r)}}function gx(e,t,n,r){let i=new AbortController;return r.push((async()=>{try{let r=new ox(t,n).getReader(),a=await Promise.race([r.read(),new Promise(e=>{if(i.signal.aborted){e({value:void 0,done:!0});return}i.signal.addEventListener(`abort`,()=>e({value:void 0,done:!0}),{once:!0})})]);if(r.releaseLock(),a.value&&!a.done)try{let n=Vb.getStore(),r=await Nx(a.value,t,n?.encryptionKey);e.abort(r?.reason)}catch{e.abort()}}catch{}})()),i}function _x(e,t,n){let r=e,i=e.signal;r[X]=t.streamName,r[Z]=t.hookToken,i[X]=t.streamName,i[Z]=t.hookToken,n&&(r[U_]=n,i[U_]=n)}function vx(e,t){let n=e,r=t;n[X]!==void 0&&(r[X]=n[X]),n[Z]!==void 0&&(r[Z]=n[Z]),n[U_]!==void 0&&(r[U_]=n[U_])}function yx(e,t,n){let r=new AbortController;e.aborted?(_x(r,e),r.abort(e.reason)):e.streamName?_x(r,e,gx(r,n,e.streamName,t)):_x(r,e);let i=r.abort.bind(r);return r.abort=t=>{if(r.signal.aborted)return;i(t);let n=Vb.getStore();if(n&&(n.ops.push((async()=>{try{let r=await Mx({aborted:!0,reason:t},n.workflowMetadata.workflowRunId,n.encryptionKey),i=new cx(n.workflowMetadata.workflowRunId,e.streamName).getWriter();await i.write(r),await i.close()}catch{}})()),e.hookToken)){let r=(async()=>{try{let{resumeHook:n}=await import(`./resume-hook-CUCPW67D.js`).then(e=>e.i);await n(e.hookToken,{aborted:!0,reason:t})}catch{}})();n.preCompletionOps.push(r)}},r}function bx(e,t,n){let r=new AbortController;return e.aborted?(_x(r,e),r.abort(e.reason)):e.streamName?_x(r,e,gx(r,n,e.streamName,t)):_x(r,e),r.signal}function xx(e=globalThis){return{...Y_(e),...av(e)}}async function Sx(e,t){let n=await T_();if(!n.getEncryptionKeyForRun)return;let r=t?await n.getEncryptionKeyForRun(e,{deploymentId:t}):await n.getEncryptionKeyForRun(await n.runs.get(e));return r?await p_(r,[`encrypt`]):void 0}function Cx(e=globalThis,t,n,r){return{...xx(e),StepFunction:()=>{throw new h(`Step functions cannot be deserialized in client context. Step functions should not be returned from workflows.`,{hint:`A step function reference reached the client. Return a serializable value (e.g. the step result) instead of the step itself.`})},WorkflowFunction:e=>Object.assign(()=>{throw new h(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Request:t=>{let n={method:t.method,headers:new e.Headers(t.headers),body:t.body,duplex:t.duplex};t.signal&&(n.signal=t.signal);let r=new e.Request(t.url,n);return t.signal&&vx(t.signal,r.signal),r},Response:t=>new e.Response(t.body,{status:t.status,statusText:t.statusText,headers:new e.Headers(t.headers)}),ReadableStream:i=>{if(`bodyInit`in i){let t=i.bodyInit;return new e.Response(t).body}if(i.type===`bytes`){let r=new ox(n,i.name,i.startIndex),a=g_();t.push(a.promise);let{readable:o,writable:s}=i.framing===`framed-v1`?ax():new e.TransformStream;return x_(r,s,a).catch(()=>{}),b_(o,a),o}else{let a=sx(n,i.name,i.startIndex),o=nx(Cx(e,t,n,r),r),s=g_();return t.push(s.promise),x_(a,o.writable,s).catch(()=>{}),b_(o.readable,s),o.readable}},WritableStream:i=>{let a=typeof i.runId==`string`?i.runId:n,o=a===n?r:Sx(a,i.deploymentId),s=tx(px(e,t,a,o),o),c=new cx(a,i.name),l=g_();return t.push(l.promise),x_(s.readable,c,l).catch(()=>{}),y_(s.writable,l),Object.defineProperty(s.writable,P_,{value:i.name,writable:!1}),Object.defineProperty(s.writable,L_,{value:a,writable:!1}),typeof i.deploymentId==`string`&&Object.defineProperty(s.writable,R_,{value:i.deploymentId,writable:!1}),s.writable},AbortController:e=>yx(e,t,n),AbortSignal:e=>bx(e,t,n)}}function wx(e=globalThis){return{...xx(e),...sv(e),Request:t=>{Object.setPrototypeOf(t,e.Request.prototype);let n=t.responseWritable;return n&&(t[B_]=n,delete t.responseWritable,t.respondWith=()=>{throw new h("`respondWith()` must be called from within a step function.",{hint:'Move the `respondWith(...)` call inside a `"use step"` function — it cannot be invoked from a workflow context.'})}),t},WorkflowFunction:e=>Object.assign(()=>{throw new h(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Response:t=>(Object.setPrototypeOf(t,e.Response.prototype),t),ReadableStream:t=>`bodyInit`in t?Object.create(e.ReadableStream.prototype,{[z_]:{value:t.bodyInit,writable:!1}}):Object.create(e.ReadableStream.prototype,{[P_]:{value:t.name,writable:!1},[F_]:{value:t.type,writable:!1},[I_]:{value:t.framing,writable:!1}}),WritableStream:t=>{let n={[P_]:{value:t.name,writable:!1}};return typeof t.runId==`string`&&(n[L_]={value:t.runId,writable:!1}),typeof t.deploymentId==`string`&&(n[R_]={value:t.deploymentId,writable:!1}),Object.create(e.WritableStream.prototype,n)},AbortController:e=>{let t=new Jb(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),{[X]:e.streamName,[Z]:e.hookToken,signal:t,abort:()=>{}}},AbortSignal:e=>{let t=new Jb(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),t}}}function Tx(e=globalThis,t,n,r,i){return{...xx(e),StepFunction:e=>{let t=e.stepId,n=e.closureVars,r=`boundThis`in e,i=r?e.boundThis:void 0,a=Array.isArray(e.boundArgs)?e.boundArgs:[],o=y(t);if(!o)throw new h(`Step function "${t}" not found. Make sure the step function is registered.`,{hint:`Make sure the step file is included in your build (i.e. it is listed in the workflow manifest), and that the SWC plugin is configured for the file.`});if(!n&&!r&&a.length===0)return o;let s=function(...e){let t=r?i:this,s=a.length>0?[...a,...e]:e;if(n){let e=Vb.getStore();if(!e)throw new v(`Cannot call step function with closure variables outside step context`);let r={...e,closureVars:n};return Vb.run(r,()=>o.apply(t,s))}return o.apply(t,s)};return Object.defineProperty(s,"name",{value:o.name}),Object.defineProperty(s,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),o.maxRetries!==void 0&&(s.maxRetries=o.maxRetries),s},WorkflowFunction:e=>Object.assign(()=>{throw new h(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Request:t=>{let n=t.responseWritable,r={method:t.method,headers:new e.Headers(t.headers),body:t.body,duplex:t.duplex};t.signal&&(r.signal=t.signal);let i=new e.Request(t.url,r);return t.signal&&vx(t.signal,i.signal),n&&(i.respondWith=async e=>{let t=n.getWriter();await t.write(e),await t.close()}),i},Response:t=>new e.Response(t.body,{status:t.status,statusText:t.statusText,headers:new e.Headers(t.headers)}),ReadableStream:a=>{if(`bodyInit`in a){let t=a.bodyInit;return new e.Response(t).body}let o=new ox(n,a.name);if(a.type===`bytes`){let n=g_();t.push(n.promise);let{readable:r,writable:i}=a.framing===`framed-v1`?ax():new e.TransformStream;return x_(o,i,n).catch(()=>{}),b_(r,n),r}else{let a=nx(Tx(e,t,n,r,i),r),s=g_();return t.push(s.promise),x_(o,a.writable,s).catch(()=>{}),b_(a.readable,s),a.readable}},WritableStream:a=>{let o=typeof a.runId==`string`?a.runId:n,s=typeof a.deploymentId==`string`?a.deploymentId:o===n?i:void 0,c=o===n?r:Sx(o,s),l=tx(hx(e,t,o,c),c),u=new cx(o,a.name),d=g_();return t.push(d.promise),x_(l.readable,u,d).catch(()=>{}),y_(l.writable,d),Object.defineProperty(l.writable,P_,{value:a.name,writable:!1}),Object.defineProperty(l.writable,L_,{value:o,writable:!1}),s&&Object.defineProperty(l.writable,R_,{value:s,writable:!1}),l.writable},AbortController:e=>yx(e,t,n),AbortSignal:e=>bx(e,t,n)}}async function Ex(e,t){return await Pv(e,t)}async function Dx(e,t){return Fv(e,t)}async function Ox(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1){if(a)return $_(l_(e,px(i,r,t,n,o)));try{let a={},c=await Fb(e,n,{global:i,extraReducers:Vx(px(i,r,t,n,o)),compression:s,compressionStats:a});return await ex(a,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`workflow arguments`,t);throw new h(n,{hint:r,cause:t})}}async function kx(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);return await ex(a,`deserialize`),zb(o,{global:r,extraRevivers:{...Hx(wx(r)),...i}})}async function Ax(e,t,n,r=globalThis,i=!1,a=!1){if(i)return $_(l_(e,mx(r)));try{let t={},i=await Lb(e,n,{global:r,extraReducers:Vx(mx(r)),compression:a,compressionStats:t});return await ex(t,`serialize`),i}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`workflow return value`,t);throw new h(n,{hint:r,cause:t})}}async function jx(e,t,n,r=[],i=globalThis,a={}){let o={},s=await Ib(e,n,{global:i,extraRevivers:{...Hx(Cx(i,r,t,n)),...a},compressionStats:o});return await ex(o,`deserialize`),s}async function Mx(e,t,n,r=globalThis,i=!1,a=!1){if(i)return $_(l_(e,mx(r)));try{let t={},i=await Lb(e,n,{global:r,extraReducers:Vx(mx(r)),compression:a,compressionStats:t});return await ex(t,`serialize`),i}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step arguments`,t);throw new h(n,{hint:r,cause:t})}}async function Nx(e,t,n,r=[],i=globalThis,a={},o){let s={},c=await Rb(e,n,{global:i,extraRevivers:{...Hx(Tx(i,r,t,n,o)),...a},compressionStats:s});return await ex(s,`deserialize`),c}async function Px(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1){if(a)return $_(l_(e,hx(i,r,t,n,o)));try{let a={},c=await Lb(e,n,{global:i,extraReducers:Vx(hx(i,r,t,n,o)),compression:s,compressionStats:a});return await ex(a,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step return value`,t);throw new h(n,{hint:r,cause:t})}}async function Fx(e,t,n,r=[],i=globalThis,a=!1){try{let o=l_(e,hx(i,r,t,n)),s=new TextEncoder().encode(o),c=gv(Q.DEVALUE_V1,s),l={},u=await Ex(await jv(c,a,l),n);return await ex(l,`serialize`),u}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step error`,t);throw new h(n,{hint:r,cause:t})}}async function Ix(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);if(await ex(a,`deserialize`),!(o instanceof Uint8Array))return c_(o,{...wx(r),...i});let{format:s,payload:c}=vv(o);if(s===Q.DEVALUE_V1)return s_(new TextDecoder().decode(c),{...wx(r),...i});throw Error(`Unsupported serialization format: ${s}`)}async function Lx(e,t,n,r=globalThis,i=!1){try{let t=l_(e,mx(r)),a=new TextEncoder().encode(t),o=gv(Q.DEVALUE_V1,a),s={},c=await Ex(await jv(o,i,s),n);return await ex(s,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`run error`,t);throw new h(n,{hint:r,cause:t})}}async function Rx(e,t,n,r=[],i=globalThis,a={}){let o={},s=await Mv(await Dx(e,n),o);if(await ex(o,`deserialize`),!(s instanceof Uint8Array))return c_(s,{...Cx(i,r,t,n),...a});let{format:c,payload:l}=vv(s);if(c===Q.DEVALUE_V1)return s_(new TextDecoder().decode(l),{...Cx(i,r,t,n),...a});throw Error(`Unsupported serialization format: ${c}`)}async function zx(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);return await ex(a,`deserialize`),zb(o,{global:r,extraRevivers:{...Hx(wx(r)),...i}})}const Bx=[`ReadableStream`,`WritableStream`,`Request`,`Response`,`StepFunction`,`AbortController`,`AbortSignal`];function Vx(e){let t={};for(let n of Bx)n in e&&(t[n]=e[n]);return t}function Hx(e){let t={};for(let n of Bx)n in e&&(t[n]=e[n]);return t}const Ux=[{format:Q.ENCRYPTED,minVersion:`4.2.0-beta.64`},{format:Q.GZIP,minVersion:`5.0.0-beta.18`},{format:Q.ZSTD,minVersion:`5.0.0-beta.18`}],Wx=[{capability:`framedByteStreams`,minVersion:`5.0.0-beta.15`}],Gx=new Set([Q.DEVALUE_V1]);function Kx(e){if(!e||!f_.default.valid(e))return{supportedFormats:Gx,framedByteStreams:!1};let t=new Set(Gx);for(let{format:n,minVersion:r}of Ux)f_.default.gte(e,r)&&t.add(n);let n={supportedFormats:t,framedByteStreams:!1};for(let{capability:t,minVersion:r}of Wx)f_.default.gte(e,r)&&(n[t]=!0);return n}const qx=`5.0.0-beta.24`,Jx=/^[a-zA-Z0-9_\-./@]+$/;function Yx(e,t){if(!Jx.test(e))throw Error(`Invalid workflow name "${e}": must only contain alphanumeric characters, underscores, hyphens, dots, forward slashes, or at signs`);return`${ah(`workflow`,ih(t))}${e}`}const Xx=Ih();function Zx(e){return`__health_check__${e}`}function Qx(e){let t=fh.safeParse(e);if(t.success)return t.data}function $x(e){return`wrun_hc_${e}`}async function eS(e,t,n){let r=await T_(),i=Zx(e.correlationId),a=JSON.stringify({healthy:!0,endpoint:t,correlationId:e.correlationId,specVersion:n??5,workflowCoreVersion:qx,timestamp:Date.now()}),o=$x(e.correlationId);await r.streams.write(o,i,a),await r.streams.close(o,i)}async function tS(e,t){let n=[],r=!1,i=!1;for(;!r&&!i;){let a=e.read(),o=new Promise(e=>setTimeout(()=>{i=!0,e({done:!0,value:void 0})},t)),s=await Promise.race([a,o]);r=s.done,s.value&&n.push(s.value)}return{chunks:n,timedOut:i}}function nS(e){if(e.length===0)return null;let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;let i=new TextDecoder().decode(n),a;try{a=JSON.parse(i)}catch{return i.length>0?{healthy:!0}:null}if(typeof a!=`object`||!a||!(`healthy`in a)||typeof a.healthy!=`boolean`)return null;let o=a,s={healthy:o.healthy};return typeof o.specVersion==`number`&&(s.specVersion=o.specVersion),typeof o.workflowCoreVersion==`string`&&(s.workflowCoreVersion=o.workflowCoreVersion),s}async function rS(e,t,n){let r=n?.timeout??3e4,i=Xx(),a=Zx(i),o=`${ah(t,ih(n?.namespace))}health_check`,s=Date.now();try{for(await e.queue(o,{__healthCheck:!0,correlationId:i},{specVersion:1,deploymentId:n?.deploymentId});Date.now()-s<r;)try{let t=(await e.streams.get($x(i),a)).getReader(),{chunks:n,timedOut:r}=await tS(t,500);if(r){try{t.cancel()}catch{}await new Promise(e=>setTimeout(e,100));continue}let o=nS(n);if(o)return{...o,latencyMs:Date.now()-s};await new Promise(e=>setTimeout(e,100))}catch{await new Promise(e=>setTimeout(e,100))}return{healthy:!1,error:`Health check timed out after ${r}ms`}}catch(e){return{healthy:!1,error:e instanceof Error?e.message:String(e)}}}function iS(e,t){return new d(`Event pagination ${t} for workflow run "${e}".`,{code:u.WORLD_CONTRACT_ERROR})}function aS(e,t,n){if(t){if(n.has(t))throw iS(e,`did not advance`);n.add(t)}}function oS(e,t,n){for(let r of n)t.has(r.eventId)||(t.add(r.eventId),e.push(r))}function sS(e,t,n,r){if(t){if(n===null)throw iS(e,`returned more pages without a cursor`);if(r.has(n))throw iS(e,`repeated a cursor`)}}function cS(e,t,n){return t!==null&&!n&&d.is(e)&&e.status===400}async function lS(e,t){let n=t!==void 0;return vb(n?`workflow.loadNewEvents`:`workflow.loadEvents`,async r=>{r?.setAttributes({...Jv(e)});let i=[],a=new Set,o=new Set,s=t??null,c=!0,l=0,u=!1,d=await T_(),f=Date.now();for(;c;){let t=Date.now(),r=s;aS(e,r,o);let f;try{f=await d.events.list({runId:e,pagination:{sortOrder:`asc`,cursor:r??void 0}})}catch(t){if(cS(t,r,u)){Ab.warn(`Event cursor was rejected; retrying with a full event reload.`,{workflowRunId:e}),i.length=0,a.clear(),o.clear(),s=null,u=!0;continue}throw t}oS(i,a,f.data),c=f.hasMore,sS(e,c,f.cursor,o),s=f.cursor??s,l++,Ab.debug(`Loaded event page`,{workflowRunId:e,incremental:n,page:l,pageEvents:f.data.length,totalEvents:i.length,hasMore:c,pageMs:Date.now()-t})}return Ab.debug(`Event load complete`,{workflowRunId:e,incremental:n,totalEvents:i.length,pagesLoaded:l,totalMs:Date.now()-f}),r?.setAttributes({...Zv(i.length),...Ky(l)}),{events:i,cursor:s}})}const uS={"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, OPTIONS, GET, HEAD`,"Access-Control-Allow-Headers":`Content-Type`};function dS(e,t){return async n=>{let r=new URL(n.url);return r.searchParams.has(`__health`)?n.method===`OPTIONS`?new Response(null,{status:204,headers:uS}):new Response(JSON.stringify({healthy:!0,endpoint:r.pathname,specVersion:t??5,workflowCoreVersion:qx}),{status:200,headers:{"Content-Type":`application/json`,...uS}}):await e(n)}}async function fS(e,...t){let n=t[0];await vb(`queue.publish`,{attributes:{...ky(`vercel-queue`),...Ay(n),...My(`publish`),...nb(`vercel-queue`),...rb(`vercel-queue`),...ib(`vqs`),...ab(`publish`)},kind:await Sb(`PRODUCER`)},async n=>{let{messageId:r}=await e.queue(...t);r&&n?.setAttributes(jy(r))})}function pS(e){if(e.requestedAt)try{return Ny(Date.now()-e.requestedAt.getTime())}catch{return}}function mS(e,t){let n;return()=>(n||=(async()=>{let n=await e.getEncryptionKeyForRun?.(t);return n?await p_(n):void 0})(),n)}function hS(t){import(`./functions-CnVBREsg.js`).then(t=>e(t.default,1)).then(({waitUntil:e})=>{e(t)})}function gS(e,t){hS(e.catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))try{t(e)}catch{}}))}async function _S(e){let t=e();return hS(t.catch(()=>{})),t}function vS(e,t={}){if(typeof e!=`object`||!e||Array.isArray(e))throw new g(`experimental_setAttributes requires a plain object, got ${e===null?`null`:Array.isArray(e)?`array`:typeof e}`);let n=Object.entries(e).map(([e,t])=>({key:e,value:t===void 0?null:t}));if(n.length===0)return n;let r=t.allowReservedAttributes===!0;try{Am(n,{allowReservedAttributes:r})}catch(e){throw e instanceof Em?new g(e.message):e}return n}export{sb as $,Nf as $n,Wv as $t,jx as A,xh as An,Qv as At,kb as B,oh as Bn,uy as Bt,Cx as C,Uh as Cn,Sy as Ct,Ix as D,Ih as Dn,by as Dt,Nx as E,Ah as En,Oy as Et,Hb as F,sh as Fn,sy as Ft,lb as G,Nm as Gn,Yv as Gt,fb as H,eh as Hn,py as Ht,Gb as I,ph as In,Kv as It,pb as J,jm as Jn,ty as Jt,ub as K,q as Kn,Xv as Kt,Ub as L,nh as Ln,qv as Lt,Yb as M,gh as Mn,iy as Mt,Kb as N,_h as Nn,ry as Nt,zx as O,Ch as On,yy as Ot,qb as P,mh as Pn,Zv as Pt,Py as Q,am as Qn,Gv as Qt,Vb as R,uh as Rn,$v as Rt,px as S,Wh as Sn,my as St,Rx as T,Vh as Tn,Dy as Tt,db as U,$m as Un,ly as Ut,jb as V,ih as Vn,dy as Vt,Sb as W,Pm as Wn,Jv as Wt,hb as X,wm as Xn,ny as Xt,vb as Y,Am as Yn,ey as Yt,Eb as Z,bm as Zn,cy as Zt,Mx as _,T_ as _n,Te as _r,wy as _t,Yx as a,N_ as an,R as ar,Hy as at,Ox as b,y_ as bn,hy as bt,lS as c,L_ as cn,Oe as cr,Ay as ct,fS as d,M_ as dn,je as dr,ky as dt,Q as en,Uf as er,ob as et,dS as f,k_ as fn,Me as fr,qy as ft,Lx as g,E_ as gn,Ce as gr,gy as gt,cx as h,D_ as hn,we as hr,xy as ht,pS as i,z_ as in,H as ir,Fy as it,Xb as j,yh as jn,ay as jt,kx as k,bh as kn,_y as kt,mS as l,B_ as ln,Ae as lr,jy as lt,Kx as m,O_ as mn,De as mr,Yy as mt,gS as n,K_ as nn,B as nr,Ly as nt,eS as o,P_ as on,Yf as or,Wy as ot,qx as p,j_ as pn,Ee as pr,Jy as pt,Tb as q,Em as qn,oy as qt,_S as r,q_ as rn,V as rr,Iy as rt,rS as s,R_ as sn,ed as sr,Uy as st,vS as t,G_ as tn,bf as tr,Gy as tt,Qx as u,A_ as un,ke as ur,My as ut,Fx as v,g_ as vn,Cy as vt,tx as w,Bh as wn,Ey as wt,Ax as x,p_ as xn,vy as xt,Px as y,x_ as yn,Ty as yt,Ab as z,ah as zn,fy as zt};
|
|
59
|
+
`);for(let t of s)t.length>0&&i.enqueue(s_(t,e))},async flush(e){r.length>0&&await o(e)}})}const rx=1e8;function ix(){return new TransformStream({transform(e,t){if(e.length===0)return;if(e.length>rx){t.error(new v(`Byte-stream chunk of ${e.length} bytes exceeds the maximum framed chunk size (${rx}). Split the data into smaller chunks before writing.`,{slug:`serialization-failed`}));return}let n=new Uint8Array(4+e.length);new DataView(n.buffer).setUint32(0,e.length,!1),n.set(e,4),t.enqueue(n)}})}function ax(){let e=new Uint8Array;function t(t){let n=new Uint8Array(e.length+t.length);n.set(e,0),n.set(t,e.length),e=n}return new TransformStream({transform(n,r){for(n.length>0&&t(n);e.length>=4;){let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!1);if(t>rx){r.error(new v(`Byte-stream frame length ${t} exceeds maximum (${rx}). This usually means a non-framed byte stream is being read as framed.`,{slug:`serialization-failed`}));return}let n=4+t;if(e.length<n)break;r.enqueue(e.slice(4,n)),e=e.slice(n)}},flush(t){e.length>0&&t.error(new v(`Byte-stream ended with ${e.length} bytes of incomplete frame data. The stream was truncated mid-frame.`,{slug:`serialization-failed`}))}})}var ox=class extends ReadableStream{#e;constructor(e,t,n){if(typeof t!=`string`||t.length===0)throw new v(`"name" is required, got "${t}"`);super({type:`bytes`,pull:async r=>{let i=this.#e;if(!i){let r=await(await T_()).streams.get(e,t,n);i=this.#e=r.getReader()}if(!i){r.error(Error(`Failed to get reader`));return}let a=await i.read();a.done?(this.#e=void 0,r.close()):r.enqueue(a.value)},cancel:async e=>{this.#e&&=(await this.#e.cancel(e).catch(()=>{}),void 0)}})}};function sx(e,t,n){let r=n===void 0||n>=0,i=n??0,a=0,o=0,s=0,c,l=new Uint8Array;async function u(){let o=await T_(),s=r?i+a:n;c=(await o.streams.get(e,t,s)).getReader()}async function d(){for(c&&=(await c.cancel().catch(()=>{}),void 0),i+=a,a=0,l=new Uint8Array;;){if(o++,s++,o>50)throw Error(`Stream "${t}" exceeded maximum reconnection attempts (50)`);if(s>1e3)throw Error(`Stream "${t}" exceeded maximum total reconnection attempts (1000)`);try{await u();return}catch{}}}return new ReadableStream({pull:async e=>{for(;;){if(!c)try{await u()}catch(t){e.error(t);return}let t;try{t=await c.read()}catch(t){if(!r){e.error(t);return}try{await d()}catch(t){e.error(t);return}continue}if(t.done||!t.value){c=void 0,e.close();return}let n=t.value;if(n.length>0){let e=new Uint8Array(l.length+n.length);e.set(l,0),e.set(n,l.length),l=e}let i=!1;for(;l.length>=4;){let t=4+new DataView(l.buffer,l.byteOffset,l.byteLength).getUint32(0,!1);if(l.length<t)break;e.enqueue(l.slice(0,t)),l=l.slice(t),a++,i=!0}if(i){o=0;return}}},cancel:async()=>{c&&=(await c.cancel().catch(e=>{console.warn(`Error closing ReadableStream reader:`,e)}),void 0)}})}var cx=class extends WritableStream{constructor(e,t,n){if(typeof e!=`string`)throw new v(`"runId" must be a string, got "${typeof e}"`);if(typeof t!=`string`||t.length===0)throw new v(`"name" is required, got "${t}"`);let r=T_(),i=n,a=async()=>{if(i){try{await i}catch{}i=void 0}},o=[],s=null,c=null,l,u=async()=>{if(s&&=(clearTimeout(s),null),o.length===0)return;await a();let n=o.slice(),i=await r;if(l===void 0&&(l=i.streamFlushIntervalMs??10),typeof i.streams.writeMulti==`function`&&n.length>1)await i.streams.writeMulti(e,t,n);else for(let r of n)await i.streams.write(e,t,r);o=[]},d=[],f=()=>{s||=setTimeout(()=>{s=null;let e=d;d=[],c=u().then(()=>{for(let t of e)t.resolve()},t=>{for(let n of e)n.reject(t)})},l??10)};super({async write(e){c&&=(await c,null),o.push(e),f(),await new Promise((e,t)=>{d.push({resolve:e,reject:t})})},async close(){c&&=(await c,null),await u(),await a(),await(await r).streams.close(e,t)},abort(e){s&&=(clearTimeout(s),null),o=[];let t=d;d=[];let n=e??Error(`Stream aborted`);for(let e of t)e.reject(n)}})}};function lx(e=globalThis){return{...J_(),...ov(),...iv(e),Request:t=>{if(!(t instanceof e.Request))return!1;let n={method:t.method,url:t.url,headers:t.headers,body:t.body,duplex:t.duplex},r=t[B_];return r&&(n.responseWritable=r),t.signal&&(t.signal.aborted||t.signal[X])&&(n.signal=t.signal),n},Response:t=>t instanceof e.Response?{type:t.type,url:t.url,status:t.status,statusText:t.statusText,headers:t.headers,body:t.body,redirected:t.redirected}:!1}}function ux(e,t,n,r,i,a){let o=t[X],s=t[Z];if(!o){let e=(n[N_]||Zb)();o=Wb(e),s=`abrt_${e}`,t[X]=o,t[Z]=s,t.signal&&(t.signal[X]=o,t.signal[Z]=s)}return fx(e,o,i,a,r),{streamName:o,hookToken:s,aborted:e.aborted,reason:e.aborted?e.reason:void 0}}function dx(e,t){let n=t[X]??t.signal?.[X],r=t[Z]??t.signal?.[Z];if(!n)throw Error(`AbortController/AbortSignal stream name is not set`);return{streamName:n,hookToken:r,aborted:e.aborted,reason:e.aborted?e.reason:void 0}}function fx(e,t,n,r,i){e.aborted||e[H_]||(e[H_]=!0,e.addEventListener(`abort`,()=>{i.push((async()=>{try{let i=await Nv(r),a=await Mx({aborted:!0,reason:e.reason},n,i),o=new cx(n,t).getWriter();await o.write(a),await o.close()}catch{}})())},{once:!0}))}function px(e=globalThis,t,n,r,i=!1,a){return{...lx(e),ReadableStream:o=>{if(!(o instanceof e.ReadableStream))return!1;if(o.locked)throw new h(`ReadableStream is locked and cannot be passed across a workflow boundary.`,{hint:`Pass the stream before calling .getReader() / .pipeThrough() / .pipeTo(), or tee it with .tee() and pass one of the branches.`});let s=`strm_${(e[N_]||Zb)()}`,c=Qb(o),l=new cx(n,s,a);c===`bytes`?i?t.push(o.pipeThrough(ix()).pipeTo(l)):t.push(o.pipeTo(l)):t.push(o.pipeThrough(tx(px(e,t,n,r,i,a),r)).pipeTo(l));let u={name:s};return c&&(u.type=c),c===`bytes`&&i&&(u.framing=`framed-v1`),u},WritableStream:r=>{if(!(r instanceof e.WritableStream))return!1;let i=r[P_],a=r[L_];if(typeof i==`string`&&typeof a==`string`){let e={name:i,runId:a},t=r[R_];return typeof t==`string`&&(e.deploymentId=t),e}let o=`strm_${(e[N_]||Zb)()}`,s=new ox(n,o);return t.push(s.pipeTo(r)),{name:o}},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:ux(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:ux(i,i,e,t,n,r)}}function mx(e=globalThis){return{...lx(e),ReadableStream:t=>{if(!(t instanceof e.ReadableStream))return!1;let n=t[z_];if(n!==void 0)return{bodyInit:n};let r=t[P_];if(!r)throw new v("ReadableStream `name` is not set");let i={name:r},a=t[F_];a&&(i.type=a);let o=t[I_];return o&&(i.framing=o),i},WritableStream:t=>{if(!(t instanceof e.WritableStream))return!1;let n=t[P_];if(!n)throw new v("WritableStream `name` is not set");let r={name:n},i=t[L_];typeof i==`string`&&(r.runId=i);let a=t[R_];return typeof a==`string`&&(r.deploymentId=a),r},AbortController:t=>{if(!t||!t.signal)return!1;let n=t,r=n[X]??n.signal?.[X],i=e.AbortController&&typeof e.AbortController==`function`&&t instanceof e.AbortController;return!r&&!i?!1:dx(t.signal,n)},AbortSignal:t=>{let n=t?.[X],r=e.AbortSignal&&typeof e.AbortSignal==`function`&&t instanceof e.AbortSignal;return!n&&!r?!1:dx(t,t)}}}function hx(e=globalThis,t,n,r,i=!1,a){return{...lx(e),ReadableStream:o=>{if(!(o instanceof e.ReadableStream))return!1;if(o.locked)throw new h(`ReadableStream is locked and cannot be passed across a workflow boundary.`,{hint:`Pass the stream before calling .getReader() / .pipeThrough() / .pipeTo(), or tee it with .tee() and pass one of the branches.`});let s=o[P_],c=o[F_],l=o[I_];if(!s){s=`strm_${(e[N_]||Zb)()}`,c=Qb(o),l=c===`bytes`&&i?`framed-v1`:l;let u=new cx(n,s,a);c===`bytes`?l===`framed-v1`?t.push(o.pipeThrough(ix()).pipeTo(u)):t.push(o.pipeTo(u)):t.push(o.pipeThrough(tx(hx(e,t,n,r,i,a),r)).pipeTo(u))}let u={name:s};return c&&(u.type=c),l&&(u.framing=l),u},WritableStream:i=>{if(!(i instanceof e.WritableStream))return!1;let a=i[P_],o=i[L_];a||(a=`strm_${(e[N_]||Zb)()}`,t.push(new ox(n,a).pipeThrough(nx(Tx(e,t,n,r),r)).pipeTo(i)));let s={name:a};typeof o==`string`&&(s.runId=o);let c=i[R_];return typeof c==`string`&&(s.deploymentId=c),s},AbortController:i=>!e.AbortController||typeof e.AbortController!=`function`||!(i instanceof e.AbortController)?!1:ux(i.signal,i,e,t,n,r),AbortSignal:i=>!e.AbortSignal||typeof e.AbortSignal!=`function`||!(i instanceof e.AbortSignal)?!1:ux(i,i,e,t,n,r)}}function gx(e,t,n,r){let i=new AbortController;return r.push((async()=>{try{let r=new ox(t,n).getReader(),a=await Promise.race([r.read(),new Promise(e=>{if(i.signal.aborted){e({value:void 0,done:!0});return}i.signal.addEventListener(`abort`,()=>e({value:void 0,done:!0}),{once:!0})})]);if(r.releaseLock(),a.value&&!a.done)try{let n=Vb.getStore(),r=await Nx(a.value,t,n?.encryptionKey);e.abort(r?.reason)}catch{e.abort()}}catch{}})()),i}function _x(e,t,n){let r=e,i=e.signal;r[X]=t.streamName,r[Z]=t.hookToken,i[X]=t.streamName,i[Z]=t.hookToken,n&&(r[U_]=n,i[U_]=n)}function vx(e,t){let n=e,r=t;n[X]!==void 0&&(r[X]=n[X]),n[Z]!==void 0&&(r[Z]=n[Z]),n[U_]!==void 0&&(r[U_]=n[U_])}function yx(e,t,n){let r=new AbortController;e.aborted?(_x(r,e),r.abort(e.reason)):e.streamName?_x(r,e,gx(r,n,e.streamName,t)):_x(r,e);let i=r.abort.bind(r);return r.abort=t=>{if(r.signal.aborted)return;i(t);let n=Vb.getStore();if(n&&(n.ops.push((async()=>{try{let r=await Mx({aborted:!0,reason:t},n.workflowMetadata.workflowRunId,n.encryptionKey),i=new cx(n.workflowMetadata.workflowRunId,e.streamName).getWriter();await i.write(r),await i.close()}catch{}})()),e.hookToken)){let r=(async()=>{try{let{resumeHook:n}=await import(`./resume-hook-C15uJ2ik.js`).then(e=>e.i);await n(e.hookToken,{aborted:!0,reason:t})}catch{}})();n.preCompletionOps.push(r)}},r}function bx(e,t,n){let r=new AbortController;return e.aborted?(_x(r,e),r.abort(e.reason)):e.streamName?_x(r,e,gx(r,n,e.streamName,t)):_x(r,e),r.signal}function xx(e=globalThis){return{...Y_(e),...av(e)}}async function Sx(e,t){let n=await T_();if(!n.getEncryptionKeyForRun)return;let r=t?await n.getEncryptionKeyForRun(e,{deploymentId:t}):await n.getEncryptionKeyForRun(await n.runs.get(e));return r?await p_(r,[`encrypt`]):void 0}function Cx(e=globalThis,t,n,r){return{...xx(e),StepFunction:()=>{throw new h(`Step functions cannot be deserialized in client context. Step functions should not be returned from workflows.`,{hint:`A step function reference reached the client. Return a serializable value (e.g. the step result) instead of the step itself.`})},WorkflowFunction:e=>Object.assign(()=>{throw new h(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Request:t=>{let n={method:t.method,headers:new e.Headers(t.headers),body:t.body,duplex:t.duplex};t.signal&&(n.signal=t.signal);let r=new e.Request(t.url,n);return t.signal&&vx(t.signal,r.signal),r},Response:t=>new e.Response(t.body,{status:t.status,statusText:t.statusText,headers:new e.Headers(t.headers)}),ReadableStream:i=>{if(`bodyInit`in i){let t=i.bodyInit;return new e.Response(t).body}if(i.type===`bytes`){let r=new ox(n,i.name,i.startIndex),a=g_();t.push(a.promise);let{readable:o,writable:s}=i.framing===`framed-v1`?ax():new e.TransformStream;return x_(r,s,a).catch(()=>{}),b_(o,a),o}else{let a=sx(n,i.name,i.startIndex),o=nx(Cx(e,t,n,r),r),s=g_();return t.push(s.promise),x_(a,o.writable,s).catch(()=>{}),b_(o.readable,s),o.readable}},WritableStream:i=>{let a=typeof i.runId==`string`?i.runId:n,o=a===n?r:Sx(a,i.deploymentId),s=tx(px(e,t,a,o),o),c=new cx(a,i.name),l=g_();return t.push(l.promise),x_(s.readable,c,l).catch(()=>{}),y_(s.writable,l),Object.defineProperty(s.writable,P_,{value:i.name,writable:!1}),Object.defineProperty(s.writable,L_,{value:a,writable:!1}),typeof i.deploymentId==`string`&&Object.defineProperty(s.writable,R_,{value:i.deploymentId,writable:!1}),s.writable},AbortController:e=>yx(e,t,n),AbortSignal:e=>bx(e,t,n)}}function wx(e=globalThis){return{...xx(e),...sv(e),Request:t=>{Object.setPrototypeOf(t,e.Request.prototype);let n=t.responseWritable;return n&&(t[B_]=n,delete t.responseWritable,t.respondWith=()=>{throw new h("`respondWith()` must be called from within a step function.",{hint:'Move the `respondWith(...)` call inside a `"use step"` function — it cannot be invoked from a workflow context.'})}),t},WorkflowFunction:e=>Object.assign(()=>{throw new h(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Response:t=>(Object.setPrototypeOf(t,e.Response.prototype),t),ReadableStream:t=>`bodyInit`in t?Object.create(e.ReadableStream.prototype,{[z_]:{value:t.bodyInit,writable:!1}}):Object.create(e.ReadableStream.prototype,{[P_]:{value:t.name,writable:!1},[F_]:{value:t.type,writable:!1},[I_]:{value:t.framing,writable:!1}}),WritableStream:t=>{let n={[P_]:{value:t.name,writable:!1}};return typeof t.runId==`string`&&(n[L_]={value:t.runId,writable:!1}),typeof t.deploymentId==`string`&&(n[R_]={value:t.deploymentId,writable:!1}),Object.create(e.WritableStream.prototype,n)},AbortController:e=>{let t=new Jb(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),{[X]:e.streamName,[Z]:e.hookToken,signal:t,abort:()=>{}}},AbortSignal:e=>{let t=new Jb(e.streamName,e.hookToken);return e.aborted&&t._setAborted(e.reason),t}}}function Tx(e=globalThis,t,n,r,i){return{...xx(e),StepFunction:e=>{let t=e.stepId,n=e.closureVars,r=`boundThis`in e,i=r?e.boundThis:void 0,a=Array.isArray(e.boundArgs)?e.boundArgs:[],o=y(t);if(!o)throw new h(`Step function "${t}" not found. Make sure the step function is registered.`,{hint:`Make sure the step file is included in your build (i.e. it is listed in the workflow manifest), and that the SWC plugin is configured for the file.`});if(!n&&!r&&a.length===0)return o;let s=function(...e){let t=r?i:this,s=a.length>0?[...a,...e]:e;if(n){let e=Vb.getStore();if(!e)throw new v(`Cannot call step function with closure variables outside step context`);let r={...e,closureVars:n};return Vb.run(r,()=>o.apply(t,s))}return o.apply(t,s)};return Object.defineProperty(s,"name",{value:o.name}),Object.defineProperty(s,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),o.maxRetries!==void 0&&(s.maxRetries=o.maxRetries),s},WorkflowFunction:e=>Object.assign(()=>{throw new h(`Workflow functions cannot be called directly. Use start() to invoke them.`,{hint:"Wrap the workflow with `start(workflowFn, { ... })` from `workflow` to begin a run instead of invoking it like a normal function."})},{workflowId:e.workflowId}),Request:t=>{let n=t.responseWritable,r={method:t.method,headers:new e.Headers(t.headers),body:t.body,duplex:t.duplex};t.signal&&(r.signal=t.signal);let i=new e.Request(t.url,r);return t.signal&&vx(t.signal,i.signal),n&&(i.respondWith=async e=>{let t=n.getWriter();await t.write(e),await t.close()}),i},Response:t=>new e.Response(t.body,{status:t.status,statusText:t.statusText,headers:new e.Headers(t.headers)}),ReadableStream:a=>{if(`bodyInit`in a){let t=a.bodyInit;return new e.Response(t).body}let o=new ox(n,a.name);if(a.type===`bytes`){let n=g_();t.push(n.promise);let{readable:r,writable:i}=a.framing===`framed-v1`?ax():new e.TransformStream;return x_(o,i,n).catch(()=>{}),b_(r,n),r}else{let a=nx(Tx(e,t,n,r,i),r),s=g_();return t.push(s.promise),x_(o,a.writable,s).catch(()=>{}),b_(a.readable,s),a.readable}},WritableStream:a=>{let o=typeof a.runId==`string`?a.runId:n,s=typeof a.deploymentId==`string`?a.deploymentId:o===n?i:void 0,c=o===n?r:Sx(o,s),l=tx(hx(e,t,o,c),c),u=new cx(o,a.name),d=g_();return t.push(d.promise),x_(l.readable,u,d).catch(()=>{}),y_(l.writable,d),Object.defineProperty(l.writable,P_,{value:a.name,writable:!1}),Object.defineProperty(l.writable,L_,{value:o,writable:!1}),s&&Object.defineProperty(l.writable,R_,{value:s,writable:!1}),l.writable},AbortController:e=>yx(e,t,n),AbortSignal:e=>bx(e,t,n)}}async function Ex(e,t){return await Pv(e,t)}async function Dx(e,t){return Fv(e,t)}async function Ox(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1){if(a)return $_(l_(e,px(i,r,t,n,o)));try{let a={},c=await Fb(e,n,{global:i,extraReducers:Vx(px(i,r,t,n,o)),compression:s,compressionStats:a});return await ex(a,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`workflow arguments`,t);throw new h(n,{hint:r,cause:t})}}async function kx(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);return await ex(a,`deserialize`),zb(o,{global:r,extraRevivers:{...Hx(wx(r)),...i}})}async function Ax(e,t,n,r=globalThis,i=!1,a=!1){if(i)return $_(l_(e,mx(r)));try{let t={},i=await Lb(e,n,{global:r,extraReducers:Vx(mx(r)),compression:a,compressionStats:t});return await ex(t,`serialize`),i}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`workflow return value`,t);throw new h(n,{hint:r,cause:t})}}async function jx(e,t,n,r=[],i=globalThis,a={}){let o={},s=await Ib(e,n,{global:i,extraRevivers:{...Hx(Cx(i,r,t,n)),...a},compressionStats:o});return await ex(o,`deserialize`),s}async function Mx(e,t,n,r=globalThis,i=!1,a=!1){if(i)return $_(l_(e,mx(r)));try{let t={},i=await Lb(e,n,{global:r,extraReducers:Vx(mx(r)),compression:a,compressionStats:t});return await ex(t,`serialize`),i}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step arguments`,t);throw new h(n,{hint:r,cause:t})}}async function Nx(e,t,n,r=[],i=globalThis,a={},o){let s={},c=await Rb(e,n,{global:i,extraRevivers:{...Hx(Tx(i,r,t,n,o)),...a},compressionStats:s});return await ex(s,`deserialize`),c}async function Px(e,t,n,r=[],i=globalThis,a=!1,o=!1,s=!1,c){if(a)return $_(l_(e,hx(i,r,t,n,o,c)));try{let a={},l=await Lb(e,n,{global:i,extraReducers:Vx(hx(i,r,t,n,o,c)),compression:s,compressionStats:a});return await ex(a,`serialize`),l}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step return value`,t);throw new h(n,{hint:r,cause:t})}}async function Fx(e,t,n,r=[],i=globalThis,a=!1){try{let o=l_(e,hx(i,r,t,n)),s=new TextEncoder().encode(o),c=gv(Q.DEVALUE_V1,s),l={},u=await Ex(await jv(c,a,l),n);return await ex(l,`serialize`),u}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`step error`,t);throw new h(n,{hint:r,cause:t})}}async function Ix(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);if(await ex(a,`deserialize`),!(o instanceof Uint8Array))return c_(o,{...wx(r),...i});let{format:s,payload:c}=vv(o);if(s===Q.DEVALUE_V1)return s_(new TextDecoder().decode(c),{...wx(r),...i});throw Error(`Unsupported serialization format: ${s}`)}async function Lx(e,t,n,r=globalThis,i=!1){try{let t=l_(e,mx(r)),a=new TextEncoder().encode(t),o=gv(Q.DEVALUE_V1,a),s={},c=await Ex(await jv(o,i,s),n);return await ex(s,`serialize`),c}catch(e){let t=$b(e),{message:n,hint:r}=Pb(`run error`,t);throw new h(n,{hint:r,cause:t})}}async function Rx(e,t,n,r=[],i=globalThis,a={}){let o={},s=await Mv(await Dx(e,n),o);if(await ex(o,`deserialize`),!(s instanceof Uint8Array))return c_(s,{...Cx(i,r,t,n),...a});let{format:c,payload:l}=vv(s);if(c===Q.DEVALUE_V1)return s_(new TextDecoder().decode(l),{...Cx(i,r,t,n),...a});throw Error(`Unsupported serialization format: ${c}`)}async function zx(e,t,n,r=globalThis,i={}){let a={},o=await Mv(await Dx(e,n),a);return await ex(a,`deserialize`),zb(o,{global:r,extraRevivers:{...Hx(wx(r)),...i}})}const Bx=[`ReadableStream`,`WritableStream`,`Request`,`Response`,`StepFunction`,`AbortController`,`AbortSignal`];function Vx(e){let t={};for(let n of Bx)n in e&&(t[n]=e[n]);return t}function Hx(e){let t={};for(let n of Bx)n in e&&(t[n]=e[n]);return t}const Ux=[{format:Q.ENCRYPTED,minVersion:`4.2.0-beta.64`},{format:Q.GZIP,minVersion:`5.0.0-beta.18`},{format:Q.ZSTD,minVersion:`5.0.0-beta.18`}],Wx=[{capability:`framedByteStreams`,minVersion:`5.0.0-beta.15`}],Gx=new Set([Q.DEVALUE_V1]);function Kx(e){if(!e||!f_.default.valid(e))return{supportedFormats:Gx,framedByteStreams:!1};let t=new Set(Gx);for(let{format:n,minVersion:r}of Ux)f_.default.gte(e,r)&&t.add(n);let n={supportedFormats:t,framedByteStreams:!1};for(let{capability:t,minVersion:r}of Wx)f_.default.gte(e,r)&&(n[t]=!0);return n}const qx=`5.0.0-beta.26`,Jx=/^[a-zA-Z0-9_\-./@]+$/;function Yx(e,t){if(!Jx.test(e))throw Error(`Invalid workflow name "${e}": must only contain alphanumeric characters, underscores, hyphens, dots, forward slashes, or at signs`);return`${ah(`workflow`,ih(t))}${e}`}const Xx=Ih();function Zx(e){return`__health_check__${e}`}function Qx(e){let t=fh.safeParse(e);if(t.success)return t.data}function $x(e){return`wrun_hc_${e}`}async function eS(e,t,n){let r=await T_(),i=Zx(e.correlationId),a=JSON.stringify({healthy:!0,endpoint:t,correlationId:e.correlationId,specVersion:n??5,workflowCoreVersion:qx,timestamp:Date.now()}),o=$x(e.correlationId);await r.streams.write(o,i,a),await r.streams.close(o,i)}async function tS(e,t){let n=[],r=!1,i=!1;for(;!r&&!i;){let a=e.read(),o=new Promise(e=>setTimeout(()=>{i=!0,e({done:!0,value:void 0})},t)),s=await Promise.race([a,o]);r=s.done,s.value&&n.push(s.value)}return{chunks:n,timedOut:i}}function nS(e){if(e.length===0)return null;let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;let i=new TextDecoder().decode(n),a;try{a=JSON.parse(i)}catch{return i.length>0?{healthy:!0}:null}if(typeof a!=`object`||!a||!(`healthy`in a)||typeof a.healthy!=`boolean`)return null;let o=a,s={healthy:o.healthy};return typeof o.specVersion==`number`&&(s.specVersion=o.specVersion),typeof o.workflowCoreVersion==`string`&&(s.workflowCoreVersion=o.workflowCoreVersion),s}async function rS(e,t,n){let r=n?.timeout??3e4,i=Xx(),a=Zx(i),o=`${ah(t,ih(n?.namespace))}health_check`,s=Date.now();try{for(await e.queue(o,{__healthCheck:!0,correlationId:i},{specVersion:1,deploymentId:n?.deploymentId});Date.now()-s<r;)try{let t=(await e.streams.get($x(i),a)).getReader(),{chunks:n,timedOut:r}=await tS(t,500);if(r){try{t.cancel()}catch{}await new Promise(e=>setTimeout(e,100));continue}let o=nS(n);if(o)return{...o,latencyMs:Date.now()-s};await new Promise(e=>setTimeout(e,100))}catch{await new Promise(e=>setTimeout(e,100))}return{healthy:!1,error:`Health check timed out after ${r}ms`}}catch(e){return{healthy:!1,error:e instanceof Error?e.message:String(e)}}}function iS(e,t){return new d(`Event pagination ${t} for workflow run "${e}".`,{code:u.WORLD_CONTRACT_ERROR})}function aS(e,t,n){if(t){if(n.has(t))throw iS(e,`did not advance`);n.add(t)}}function oS(e,t,n){for(let r of n)t.has(r.eventId)||(t.add(r.eventId),e.push(r))}function sS(e,t,n,r){if(t){if(n===null)throw iS(e,`returned more pages without a cursor`);if(r.has(n))throw iS(e,`repeated a cursor`)}}function cS(e,t,n){return t!==null&&!n&&d.is(e)&&e.status===400}async function lS(e,t){let n=t!==void 0;return vb(n?`workflow.loadNewEvents`:`workflow.loadEvents`,async r=>{r?.setAttributes({...Jv(e)});let i=[],a=new Set,o=new Set,s=t??null,c=!0,l=0,u=!1,d=await T_(),f=Date.now();for(;c;){let t=Date.now(),r=s;aS(e,r,o);let f;try{f=await d.events.list({runId:e,pagination:{sortOrder:`asc`,cursor:r??void 0}})}catch(t){if(cS(t,r,u)){Ab.warn(`Event cursor was rejected; retrying with a full event reload.`,{workflowRunId:e}),i.length=0,a.clear(),o.clear(),s=null,u=!0;continue}throw t}oS(i,a,f.data),c=f.hasMore,sS(e,c,f.cursor,o),s=f.cursor??s,l++,Ab.debug(`Loaded event page`,{workflowRunId:e,incremental:n,page:l,pageEvents:f.data.length,totalEvents:i.length,hasMore:c,pageMs:Date.now()-t})}return Ab.debug(`Event load complete`,{workflowRunId:e,incremental:n,totalEvents:i.length,pagesLoaded:l,totalMs:Date.now()-f}),r?.setAttributes({...Zv(i.length),...Ky(l)}),{events:i,cursor:s}})}const uS={"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, OPTIONS, GET, HEAD`,"Access-Control-Allow-Headers":`Content-Type`};function dS(e,t){return async n=>{let r=new URL(n.url);return r.searchParams.has(`__health`)?n.method===`OPTIONS`?new Response(null,{status:204,headers:uS}):new Response(JSON.stringify({healthy:!0,endpoint:r.pathname,specVersion:t??5,workflowCoreVersion:qx}),{status:200,headers:{"Content-Type":`application/json`,...uS}}):await e(n)}}async function fS(e,...t){let n=t[0];await vb(`queue.publish`,{attributes:{...ky(`vercel-queue`),...Ay(n),...My(`publish`),...nb(`vercel-queue`),...rb(`vercel-queue`),...ib(`vqs`),...ab(`publish`)},kind:await Sb(`PRODUCER`)},async n=>{let{messageId:r}=await e.queue(...t);r&&n?.setAttributes(jy(r))})}function pS(e){if(e.requestedAt)try{return Ny(Date.now()-e.requestedAt.getTime())}catch{return}}function mS(e,t){let n;return()=>(n||=(async()=>{let n=await e.getEncryptionKeyForRun?.(t);return n?await p_(n):void 0})(),n)}function hS(t){import(`./functions-CnVBREsg.js`).then(t=>e(t.default,1)).then(({waitUntil:e})=>{e(t)})}function gS(e,t){hS(e.catch(e=>{if(!(e?.name===`AbortError`||e?.name===`ResponseAborted`))try{t(e)}catch{}}))}async function _S(e){let t=e();return hS(t.catch(()=>{})),t}function vS(e,t={}){if(typeof e!=`object`||!e||Array.isArray(e))throw new g(`experimental_setAttributes requires a plain object, got ${e===null?`null`:Array.isArray(e)?`array`:typeof e}`);let n=Object.entries(e).map(([e,t])=>({key:e,value:t===void 0?null:t}));if(n.length===0)return n;let r=t.allowReservedAttributes===!0;try{Am(n,{allowReservedAttributes:r})}catch(e){throw e instanceof Em?new g(e.message):e}return n}export{sb as $,Nf as $n,Wv as $t,jx as A,xh as An,Qv as At,kb as B,oh as Bn,uy as Bt,Cx as C,Uh as Cn,Sy as Ct,Ix as D,Ih as Dn,by as Dt,Nx as E,Ah as En,Oy as Et,Hb as F,sh as Fn,sy as Ft,lb as G,Nm as Gn,Yv as Gt,fb as H,eh as Hn,py as Ht,Gb as I,ph as In,Kv as It,pb as J,jm as Jn,ty as Jt,ub as K,q as Kn,Xv as Kt,Ub as L,nh as Ln,qv as Lt,Yb as M,gh as Mn,iy as Mt,Kb as N,_h as Nn,ry as Nt,zx as O,Ch as On,yy as Ot,qb as P,mh as Pn,Zv as Pt,Py as Q,am as Qn,Gv as Qt,Vb as R,uh as Rn,$v as Rt,px as S,Wh as Sn,my as St,Rx as T,Vh as Tn,Dy as Tt,db as U,$m as Un,ly as Ut,jb as V,ih as Vn,dy as Vt,Sb as W,Pm as Wn,Jv as Wt,hb as X,wm as Xn,ny as Xt,vb as Y,Am as Yn,ey as Yt,Eb as Z,bm as Zn,cy as Zt,Mx as _,T_ as _n,Te as _r,wy as _t,Yx as a,N_ as an,R as ar,Hy as at,Ox as b,y_ as bn,hy as bt,lS as c,L_ as cn,Oe as cr,Ay as ct,fS as d,M_ as dn,je as dr,ky as dt,Q as en,Uf as er,ob as et,dS as f,k_ as fn,Me as fr,qy as ft,Lx as g,E_ as gn,Ce as gr,gy as gt,cx as h,D_ as hn,we as hr,xy as ht,pS as i,z_ as in,H as ir,Fy as it,Xb as j,yh as jn,ay as jt,kx as k,bh as kn,_y as kt,mS as l,B_ as ln,Ae as lr,jy as lt,Kx as m,O_ as mn,De as mr,Yy as mt,gS as n,K_ as nn,B as nr,Ly as nt,eS as o,P_ as on,Yf as or,Wy as ot,qx as p,j_ as pn,Ee as pr,Jy as pt,Tb as q,Em as qn,oy as qt,_S as r,q_ as rn,V as rr,Iy as rt,rS as s,R_ as sn,ed as sr,Uy as st,vS as t,G_ as tn,bf as tr,Gy as tt,Qx as u,A_ as un,ke as ur,My as ut,Fx as v,g_ as vn,Cy as vt,tx as w,Bh as wn,Ey as wt,Ax as x,p_ as xn,vy as xt,Px as y,x_ as yn,Ty as yt,Ab as z,ah as zn,fy as zt};
|
package/dist/src/compiled/_chunks/workflow/{resume-hook-CUCPW67D.js → resume-hook-C15uJ2ik.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./chunk-BHKSVoKr.js";import{n as t,o as n,w as r}from"./dist-Dxrjttr2.js";import{E as i,It as a,Wt as o,Y as s,_n as c,a as l,en as u,it as d,kn as f,ln as p,m,n as h,nt as g,q as _,r as v,rt as y,xn as b,y as x,z as S}from"./attribute-changes-
|
|
1
|
+
import{r as e}from"./chunk-BHKSVoKr.js";import{n as t,o as n,w as r}from"./dist-Dxrjttr2.js";import{E as i,It as a,Wt as o,Y as s,_n as c,a as l,en as u,it as d,kn as f,ln as p,m,n as h,nt as g,q as _,r as v,rt as y,xn as b,y as x,z as S}from"./attribute-changes-zAifvEhb.js";var C=e({getHookByToken:()=>T,resumeHook:()=>E,resumeWebhook:()=>D});async function w(e){let t=await c(),n=await t.hooks.getByToken(e),r=await t.runs.get(n.runId),a=await t.getEncryptionKeyForRun?.(r),o=a?await b(a):void 0;return n.metadata!==void 0&&(n.metadata=await i(n.metadata,n.runId,o)),{hook:n,run:r,encryptionKey:o}}async function T(e){let{hook:t}=await w(e);return t}async function E(e,t,n){return await v(()=>s(`hook.resume`,async r=>{let i=await c();try{let s,c,p;if(typeof e==`string`){let t=await w(e);s=t.hook,c=t.run,p=n??t.encryptionKey}else if(s=e,c=await i.runs.get(s.runId),n)p=n;else{let e=await i.getEncryptionKeyForRun?.(c);p=e?await b(e):void 0}r?.setAttributes({...d(s.token),...y(s.hookId),...o(s.runId)});let g=c.executionContext?.workflowCoreVersion,v=m(typeof g==`string`?g:void 0);v.supportedFormats.has(u.ENCRYPTED)||(p=void 0);let C=(c.specVersion??0)>=5&&v.supportedFormats.has(u.GZIP),T=[],E=f(s.specVersion),D=await x(t,s.runId,p,T,globalThis,E,v.framedByteStreams,C);h(Promise.all(T),e=>{e!==void 0&&S.warn(`Background flush of hook payload ops failed`,{workflowRunId:s.runId,hookId:s.hookId,error:e instanceof Error?e.message:String(e)})}),await i.events.create(s.runId,{eventType:`hook_received`,specVersion:5,correlationId:s.hookId,eventData:{...E?{}:{token:s.token},payload:D}},{v1Compat:E}),r?.setAttributes({...a(c.workflowName)});let O=await _(c.executionContext?.traceCarrier);return O&&r?.addLink?.(O),await i.queue(l(c.workflowName),{runId:s.runId,traceCarrier:c.executionContext?.traceCarrier??void 0},{deploymentId:c.deploymentId,specVersion:c.specVersion??1}),s}catch(t){throw r?.setAttributes({...d(typeof e==`string`?e:e.token),...g(!1)}),t}}))}async function D(e,i){let{hook:a,encryptionKey:o}=await w(e);if(a.isWebhook===!1)throw new n(e);let s,c;if(a.metadata&&typeof a.metadata==`object`&&`respondWith`in a.metadata)if(a.metadata.respondWith===`manual`){let{readable:e,writable:t}=new TransformStream;c=e,i[p]=t}else if(a.metadata.respondWith instanceof Response)s=a.metadata.respondWith;else throw new r(`Invalid \`respondWith\` value: ${a.metadata.respondWith}`,{slug:t.WEBHOOK_INVALID_RESPOND_WITH_VALUE});else s=new Response(null,{status:202});if(await E(a,i,o),c){let e=c.getReader(),t=await e.read();t.value&&(s=t.value),e.cancel()}if(!s)throw new r(`Workflow run did not send a response`,{slug:t.WEBHOOK_RESPONSE_NOT_SENT});return s}export{C as i,E as n,D as r,T as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as e}from"./dist-FLIfyJ4Y.js";import{C as t,E as n,S as r,T as i,b as a,d as o,m as s,p as c,r as l,s as u,t as d,w as f,x as p,y as m}from"./dist-Dxrjttr2.js";import{A as h,At as g,C as _,Dn as v,Gt as ee,It as y,J as b,L as x,Lt as S,Q as C,T as w,Wt as T,Y as E,_n as D,a as O,b as k,en as A,gn as j,hn as M,k as N,kn as P,m as F,n as I,p as L,r as R,s as z,t as B,xn as V,z as H}from"./attribute-changes-zAifvEhb.js";const U=new Set([`PARSE_ERROR`,`SCHEMA_VALIDATION`,n.WORLD_CONTRACT_ERROR]),W=new Set([`TRANSPORT`,`TIMEOUT`]),G=[f.is,c.is,m.is,o.is];function K(e){if(!i.is(e)||e.status!==void 0)return!1;let t=`cause`in e?e.cause:void 0;return e.code!==void 0&&U.has(e.code)||e.message.startsWith(`Failed to parse response body for `)||e.message.startsWith(`Schema validation failed for `)||typeof t==`object`&&!!t&&`name`in t&&t.name===`ZodError`}function q(e){return s.is(e)?!0:i.is(e)?e.status!==void 0&&e.status>=500?!0:e.code!==void 0&&W.has(e.code):!1}function J(e){if(u.is(e))return n.REPLAY_DIVERGENCE;if(d.is(e))return n.CORRUPTED_EVENT_LOG;if(K(e)||q(e))return n.WORLD_CONTRACT_ERROR;for(let t of G)if(t(e))return n.RUNTIME_ERROR;return n.USER_ERROR}const Y=v();let X=!1;async function Z(t,n,r){"use step";return await R(()=>{let i=t?.workflowId;if(!i)throw new f(`'start' received an invalid workflow function. Ensure the Workflow SDK is configured correctly and the function includes a 'use workflow' directive.`,{slug:`start-invalid-workflow-function`});return E(`workflow.start ${e(i)}`,async e=>{e?.setAttributes({...y(i),...S(`start`)});let t=[],a=r??{};Array.isArray(n)?t=n:typeof n==`object`&&(a=n),e?.setAttributes({...g(t.length)});let o=a?.world??await D(),s=await o.getDeploymentId(),c=a.deploymentId??s;c===`latest`&&(o.resolveLatestDeploymentId?c=await o.resolveLatestDeploymentId():(X||(X=!0,H.warn(`deploymentId: 'latest' has no effect in this world and was ignored. It is only supported by worlds with atomic deployments, such as Vercel. The run will target the current deployment.`,{currentDeploymentId:s})),c=s));let u,d;if(c===s)u=!0,d=!0;else if(typeof o.streams?.get!=`function`)u=!1,d=!1;else{let e=F((await z(o,`workflow`,{deploymentId:c,timeout:2e3}).catch(()=>void 0))?.workflowCoreVersion);u=e.framedByteStreams,d=e.supportedFormats.has(A.GZIP)}let p=[],m=`wrun_${Y()}`,h=await b(),_=a.specVersion??o.specVersion??2,v=P(_),x=a.allowReservedAttributes===!0,w;if(a.attributes&&Object.keys(a.attributes).length>0){if(_<4)throw new f(`Initial workflow attributes require a World that supports spec version 4 or later.`);for(let[e,t]of Object.entries(a.attributes))if(typeof t!=`string`)throw new f(`Initial workflow attribute ${JSON.stringify(e)} must be a string value.`);let e=B(a.attributes,{allowReservedAttributes:x});w=Object.fromEntries(e.map(({key:e,value:t})=>[e,t]))}let E=w?{attributes:w,...x?{allowReservedAttributes:!0}:{}}:{},j=await o.getEncryptionKeyForRun?.(m,{...a,deploymentId:c}),M=j?await V(j):void 0,N=await k(t,m,M,p,globalThis,v,u,d&&_>=5),R={traceCarrier:h,workflowCoreVersion:L,features:{encryption:!!M}},[U,W]=await Promise.allSettled([o.events.create(m,{eventType:`run_created`,specVersion:_,eventData:{deploymentId:c,workflowName:i,input:N,executionContext:R,...E}},{v1Compat:v}),o.queue(O(i),{runId:m,traceCarrier:h,..._>=3?{runInput:{input:N,deploymentId:c,workflowName:i,specVersion:_,executionContext:R,...E}}:{}},{deploymentId:c,specVersion:_})]);if(W.status===`rejected`)throw W.reason;let G=!1;if(U.status===`rejected`){let e=U.reason;if(!l.is(e))if(q(e))G=!0,H.warn(`Run creation event failed, but the run was accepted via the queue. The run_created event will be re-tried async by the runtime.`,{workflowRunId:m,error:e.message});else throw e}else{let e=U.value;if(!e.run)throw new f(`Missing 'run' in server response for 'run_created' event`);if(!v&&e.run.runId!==m)throw new f(`Server returned different runId than requested: expected ${m}, got ${e.run.runId}`)}return I(Promise.all(p),e=>{H.warn(`Background flush of workflow argument streams failed`,{workflowRunId:m,error:e instanceof Error?e.message:String(e)})}),e?.setAttributes({...T(m),...C(c),...U.status===`fulfilled`&&U.value.run?ee(U.value.run.status):{}}),new $(m,{resilientStart:G})})})}const te=e=>Array.isArray(e)?e:[e];async function ne(e,t,n={}){try{let r=await e.runs.get(t,{resolveData:`all`}),i=await e.getEncryptionKeyForRun?.(r),a=i?await V(i):void 0,o=te(await N(r.input,t,a,globalThis)),s=n.specVersion??r.specVersion??1,c=n.deploymentId??r.deploymentId;return(await Z({workflowId:r.workflowName},o,{deploymentId:c,world:e,specVersion:s})).runId}catch(e){throw Error(`Failed to recreate run from ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function re(e,t){try{let n=(await e.runs.get(t,{resolveData:`none`})).specVersion??1,r=P(n),i={eventType:`run_cancelled`,specVersion:n};await e.events.create(t,i,{v1Compat:r})}catch(e){throw Error(`Failed to cancel run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function ie(e,t){try{let n=await e.runs.get(t,{resolveData:`none`});await e.queue(O(n.workflowName),{runId:t},{deploymentId:n.deploymentId,specVersion:n.specVersion??1})}catch(e){throw Error(`Failed to re-enqueue run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Q(e,t,n){try{let r=await e.runs.get(t,{resolveData:`none`}),i=P(r.specVersion),a=[],o=null;do{let n=await e.events.list({runId:t,pagination:{limit:1e3,...o?{cursor:o}:{}},resolveData:`none`});a.push(...n.data),o=n.hasMore?n.cursor:null}while(o);let s=a.filter(e=>e.eventType===`wait_created`),c=new Set(a.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),u=s.filter(e=>!c.has(e.correlationId));if(n?.correlationIds&&n.correlationIds.length>0){let e=new Set(n.correlationIds);u=u.filter(t=>t.correlationId&&e.has(t.correlationId))}let d=[],f=0;for(let n of u){if(!n.correlationId)continue;let a=i?{eventType:`wait_completed`,correlationId:n.correlationId}:{eventType:`wait_completed`,correlationId:n.correlationId,specVersion:r.specVersion,eventData:{resumeAt:n.eventData.resumeAt}};try{await e.events.create(t,a,{v1Compat:i}),f++}catch(e){l.is(e)?f++:d.push(e instanceof Error?e:Error(String(e)))}}if(f>0&&await e.queue(O(r.workflowName),{runId:t},{deploymentId:r.deploymentId,specVersion:r.specVersion??1}),d.length>0)throw AggregateError(d,`Failed to complete ${d.length}/${u.length} pending wait(s) for run ${t}`);return{stoppedCount:f}}catch(e){throw e instanceof AggregateError?e:Error(`Failed to wake up run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function ae(e,t,n,r){try{return await e.streams.get(t,n,r?.startIndex)}catch(e){throw Error(`Failed to read stream ${n}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function oe(e,t){try{return await e.streams.list(t)}catch(e){throw Error(`Failed to list streams for run ${t}: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}var $=class e{static[j](e){return{runId:e.runId,resilientStart:e.#r}}static[M](t){return new e(t.runId,{resilientStart:t.resilientStart})}runId;#e;get#t(){return this.#e||=D(),this.#e}#n=null;#r=!1;constructor(e,t){this.runId=e,this.#r=t?.resilientStart??!1}#i(){return this.#n||=(async()=>{let e=await this.#t,t=await e.runs.get(this.runId),n=await e.getEncryptionKeyForRun?.(t);return n?await V(n):void 0})(),this.#n}#a(){return()=>this.#i()}async wakeUp(e){"use step";return Q(await this.#t,this.runId,e)}async cancel(){"use step";await(await this.#t).events.create(this.runId,{eventType:`run_cancelled`,specVersion:5})}get exists(){"use step";return this.#t.then(e=>e.runs.get(this.runId,{resolveData:`none`}).then(()=>!0).catch(e=>{if(t.is(e))return!1;throw e}))}get status(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.status))}get returnValue(){"use step";return this.#o()}get workflowName(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.workflowName))}get createdAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.createdAt))}get startedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.startedAt))}get completedAt(){"use step";return this.#t.then(e=>e.runs.get(this.runId).then(e=>e.completedAt))}get readable(){return this.getReadable()}getReadable(e={}){"use step";let{ops:t=[],global:n=globalThis,startIndex:r,namespace:i}=e,a=x(this.runId,i),o=this.#a(),s=_(n,t,this.runId,o).ReadableStream({name:a,startIndex:r}),c=this.#t,l=this.runId;return Object.assign(s,{getTailIndex:async()=>(await(await c).streams.getInfo(l,a)).tailIndex})}async#o(){let e=await this.#t,n=0,i=this.#r?3:0,o=[1e3,3e3,6e3];for(;;)try{let t=await e.runs.get(this.runId);if(t.status===`completed`){let e=await this.#i();return await h(t.output,this.runId,e)}if(t.status===`cancelled`)throw new a(this.runId);if(t.status===`failed`){let e=await this.#i(),n;try{n=await w(t.error,this.runId,e)}catch{n=Error(`Failed to hydrate workflow run error`)}throw new p(this.runId,n,{errorCode:t.errorCode})}throw new r(this.runId,t.status)}catch(e){if(r.is(e)){await new Promise(e=>setTimeout(e,1e3));continue}if(t.is(e)&&n<i){let e=o[n];n++,await new Promise(t=>setTimeout(t,e));continue}throw e}}};function se(e){return new $(e)}export{ae as a,Q as c,q as d,K as f,oe as i,Z as l,se as n,ne as o,re as r,ie as s,$ as t,J as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pn as e,ur as t}from"./attribute-changes-
|
|
1
|
+
import{pn as e,ur as t}from"./attribute-changes-zAifvEhb.js";async function n(r){let i=globalThis[e];return i||t(`sleep()`,`https://workflow-sdk.dev/docs/api-reference/workflow/sleep`,n),i(r)}export{n as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChildToken}from"#harness/runtime-actions.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChildToken}from"#harness/runtime-actions.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),f=getPendingRuntimeActionBatch(s.state);if(f===void 0||f.actions.length===0)return{results:[],sessionState:e.sessionState};let p=await deserializeContext(e.serializedContext),m=p.require(BundleKey),h=hydrateDurableSession({compactionOverrides:{thresholdPercent:m.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:m.turnAgent}),g=p.require(ChannelKey),_=p.get(AuthKey)??null,v=p.get(CapabilitiesKey),y=p.get(ChannelInstrumentationKey),b=p.get(InitiatorAuthKey)??null,x=e.parentWritable.getWriter(),S=buildAdapterContext(g,p),C=h,w=[];try{for(let r of f.actions){let i,a,o,s;switch(r.kind){case`subagent-call`:{let t=m.subagentRegistry.subagentsByNodeId.get(r.nodeId),n=t?.definition.kind===`subagent`?{description:t.definition.description,type:`local`}:{type:`runtime`},o=createWorkflowRuntime({compiledArtifactsSource:m.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:c,runInput:l}=buildSubagentRunInput({action:r,auth:_,batchEvent:f.event,capabilities:v,channelMetadata:y,initiatorAuth:b,parentContinuationToken:e.parentContinuationToken,session:h,source:n}),u=await o.run(l);C=recordPendingSubagentChildToken({callId:r.callId,childContinuationToken:c,session:C}),i=u.sessionId,a=r.name,s=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:m.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,callbackBaseUrl:e.callbackBaseUrl,callbackToken:e.parentContinuationToken,remote:n,session:h})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),w.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}a=r.name,o={url:n.url},s=r.remoteAgentName;break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let d=await callAdapterEventHandler(g,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:o,sequence:f.event.sequence,sessionId:h.sessionId,toolName:s,turnId:f.event.turnId,workflowId:workflowEntryReference.workflowId}),S);await x.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(d)))}}finally{x.releaseLock()}return{results:w,sessionState:C===h?e.sessionState:createDurableSessionState({session:C})}}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}export{dispatchRuntimeActionsStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveCallbackRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER}from"#protocol/message.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{
|
|
1
|
+
import{createEveCallbackRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER}from"#protocol/message.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{formatSubagentInput}from"#execution/subagent-invocation.js";async function startRemoteAgentSession(n){let r=n.callbackToken??n.session.continuationToken;if(!r)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!n.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let i=await resolveRemoteAgentRequestHeaders(n.remote),a=await fetch(createRemoteAgentSessionUrl(n.remote),{body:JSON.stringify({callback:{callId:n.action.callId,subagentName:n.action.remoteAgentName,token:r,url:createWorkflowCallbackUrl(n.callbackBaseUrl,createEveCallbackRoutePath(r))},message:formatRemoteAgentCallInputMessage({action:n.action,remote:n.remote}),mode:`task`,outputSchema:n.action.input.outputSchema??n.remote.outputSchema}),headers:{"content-type":`application/json`,...i},method:`POST`});if(!a.ok)throw Error(`Remote agent "${n.action.remoteAgentName}" create-session request failed with HTTP ${a.status}.`);let o=a.headers.get(EVE_SESSION_ID_HEADER);if(o!==null&&o.length>0)return o;try{let e=await a.json();if(typeof e.sessionId==`string`&&e.sessionId.length>0)return e.sessionId}catch{}throw Error(`Remote agent "${n.action.remoteAgentName}" create-session response did not include a session id.`)}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}function createRemoteAgentSessionUrl(e){return new URL(e.path,`${trimTrailingSlash(e.url)}/`).toString()}async function resolveRemoteAgentRequestHeaders(e){let t={};return e.headers!==void 0&&Object.assign(t,typeof e.headers==`function`?await e.headers():e.headers),e.auth!==void 0&&Object.assign(t,(await e.auth()).headers),t}function formatRemoteAgentCallInputMessage(e){let t=typeof e.action.input.message==`string`?e.action.input.message:``;return formatSubagentInput({description:e.remote.description,message:t,name:e.action.remoteAgentName,type:`remote`}).message}function trimTrailingSlash(e){return e.endsWith(`/`)?e.slice(0,-1):e}export{resolveRemoteAgentForAction,startRemoteAgentSession};
|
|
@@ -6,11 +6,26 @@ import type { StepInput } from "#harness/types.js";
|
|
|
6
6
|
export interface FormattedSubagentInvocation extends StepInput {
|
|
7
7
|
readonly message: string;
|
|
8
8
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
type RuntimeSubagentInputFormatRequest = {
|
|
10
|
+
readonly message: string;
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly type: "runtime";
|
|
13
|
+
};
|
|
14
|
+
type LocalSubagentInputFormatRequest = {
|
|
13
15
|
readonly description: string;
|
|
14
16
|
readonly message: string;
|
|
15
17
|
readonly name: string;
|
|
16
|
-
|
|
18
|
+
readonly type: "local";
|
|
19
|
+
};
|
|
20
|
+
type RemoteSubagentInputFormatRequest = {
|
|
21
|
+
readonly description: string;
|
|
22
|
+
readonly message: string;
|
|
23
|
+
readonly name: string;
|
|
24
|
+
readonly type: "remote";
|
|
25
|
+
};
|
|
26
|
+
type SubagentInputFormatRequest = RuntimeSubagentInputFormatRequest | LocalSubagentInputFormatRequest | RemoteSubagentInputFormatRequest;
|
|
27
|
+
/**
|
|
28
|
+
* Formats the stable delegated input handed to one child agent invocation.
|
|
29
|
+
*/
|
|
30
|
+
export declare function formatSubagentInput(input: SubagentInputFormatRequest): FormattedSubagentInvocation;
|
|
31
|
+
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
2
|
-
`)}}export{
|
|
1
|
+
const formatSubagentInputByType={runtime(e){return formatSubagentPrompt({descriptionLines:[],message:e.message,name:e.name})},local(e){return formatSubagentPrompt({descriptionLines:formatDescriptionLines(e.description),message:e.message,name:e.name})},remote(e){return formatSubagentPrompt({descriptionLines:formatDescriptionLines(e.description),message:e.message,name:e.name})}};function formatSubagentInput(t){switch(t.type){case`runtime`:return formatSubagentInputByType.runtime(t);case`local`:return formatSubagentInputByType.local(t);case`remote`:return formatSubagentInputByType.remote(t);default:return t}}function formatSubagentPrompt(e){return{message:[`You are the subagent "${e.name}".`,...e.descriptionLines,``,`The caller delegated the following task to you. Complete it and return the final result directly.`,``,`Caller message:`,e.message].join(`
|
|
2
|
+
`)}}function formatDescriptionLines(e){return e.trim().length>0?[`Description: ${e}`]:[]}export{formatSubagentInput};
|
|
@@ -8,6 +8,12 @@ interface BatchEventMetadata {
|
|
|
8
8
|
readonly sequence: number;
|
|
9
9
|
readonly turnId: string;
|
|
10
10
|
}
|
|
11
|
+
export type SubagentInputSource = {
|
|
12
|
+
readonly description: string;
|
|
13
|
+
readonly type: "local";
|
|
14
|
+
} | {
|
|
15
|
+
readonly type: "runtime";
|
|
16
|
+
};
|
|
11
17
|
/**
|
|
12
18
|
* Result of {@link buildSubagentRunInput}.
|
|
13
19
|
*
|
|
@@ -37,5 +43,6 @@ export declare function buildSubagentRunInput(input: {
|
|
|
37
43
|
/** Hook token owned by the workflow currently waiting for this child. */
|
|
38
44
|
readonly parentContinuationToken?: string;
|
|
39
45
|
readonly session: HarnessSession;
|
|
46
|
+
readonly source: SubagentInputSource;
|
|
40
47
|
}): SubagentRunInputBuild;
|
|
41
48
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{
|
|
1
|
+
import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{formatSubagentInput}from"#execution/subagent-invocation.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l,source:u}=n,d=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),f=l.rootSessionId??l.sessionId;return{childContinuationToken:d,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:n.parentContinuationToken??l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:d,initiatorAuth:c,input:{message:formatSubagentCallInputMessage({action:r,source:u}),outputSchema:r.input.outputSchema},mode:`task`,parent:{callId:r.callId,rootSessionId:f,sessionId:l.sessionId,turn:{id:a.turnId,sequence:a.sequence}}}}}function formatSubagentCallInputMessage(e){let{message:t}=e.action.input;switch(e.source.type){case`local`:return formatSubagentInput({description:e.source.description,message:t,name:e.action.subagentName,type:`local`}).message;case`runtime`:return formatSubagentInput({message:t,name:e.action.subagentName,type:`runtime`}).message;default:return e.source}}export{buildSubagentRunInput};
|
|
@@ -171,7 +171,7 @@ export interface ToolLoopHarnessConfig {
|
|
|
171
171
|
* Exposes the `Workflow` orchestration tool — an isolated JavaScript sandbox
|
|
172
172
|
* whose only callable operations are this agent's subagents and remote
|
|
173
173
|
* agents. Resolved by the runtime from the agent's `workflowEnabled` flag
|
|
174
|
-
*
|
|
174
|
+
* in the compiled manifest.
|
|
175
175
|
* Defaults to `false`.
|
|
176
176
|
*/
|
|
177
177
|
readonly workflow?: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.17.1`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectString}from"#internal/authored-module.js";import{isDynamicSentinel}from"#shared/dynamic-tool-definition.js";import{normalizeJsonSchemaDefinition}from"#internal/json-schema.js";import{isDisabledToolSentinel
|
|
1
|
+
import{expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectString}from"#internal/authored-module.js";import{isDynamicSentinel}from"#shared/dynamic-tool-definition.js";import{normalizeJsonSchemaDefinition}from"#internal/json-schema.js";import{isDisabledToolSentinel}from"#public/definitions/tool.js";function isEnableWorkflowToolSentinel(e){return typeof e==`object`&&!!e&&e.kind===`eve:enable-workflow-tool`}function normalizeToolDefinition(t,n){if(isDynamicSentinel(t))return{kind:`dynamic-tool`,eventNames:Object.keys(t.events)};if(isDisabledToolSentinel(t))return{kind:`disabled`};if(isEnableWorkflowToolSentinel(t))return{kind:`enable-workflow`};let r=expectObjectRecord(t,n);expectOnlyKnownKeys(r,[`auth`,`description`,`execute`,`inputSchema`,`approval`,`outputSchema`,`toModelOutput`],n);let i=r.inputSchema===void 0?null:normalizeJsonSchemaDefinition(r.inputSchema),a=r.outputSchema===void 0?void 0:normalizeJsonSchemaDefinition(r.outputSchema,`output`),o={description:expectString(r.description,n),execute:expectFunction(r.execute,n),inputSchema:i};return a!==void 0&&(o.outputSchema=a),r.approval!==void 0&&expectFunction(r.approval,n),r.toModelOutput!==void 0&&expectFunction(r.toModelOutput,n),r.auth!==void 0&&expectFunction(expectObjectRecord(r.auth,n).getToken,n),{kind:`tool`,definition:o}}export{normalizeToolDefinition};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function encodeBasicCredentials(username: string, password: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function encodeBasicCredentials(e,t){let n=new TextEncoder().encode(`${e}:${t}`),r=Array.from(n,e=>String.fromCodePoint(e)).join(``);return btoa(r)}export{encodeBasicCredentials};
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* exposing a third-party SDK through eve public surfaces.
|
|
6
6
|
*/
|
|
7
7
|
import { type JsonObject } from "#shared/json.js";
|
|
8
|
+
import { type TelegramChatType } from "#public/channels/telegram/inbound.js";
|
|
8
9
|
/** Telegram bot token, materialized directly or from an async secret provider. */
|
|
9
10
|
export type TelegramBotToken = string | (() => string | Promise<string>);
|
|
10
11
|
/** Fetch implementation override for tests or non-standard runtimes. */
|
|
@@ -39,6 +40,8 @@ export interface TelegramMessageResult {
|
|
|
39
40
|
readonly id: string;
|
|
40
41
|
/** Telegram chat id associated with the message, when Telegram returned one. */
|
|
41
42
|
readonly chatId?: string;
|
|
43
|
+
/** Recognized Telegram chat type associated with the message, when returned. */
|
|
44
|
+
readonly chatType?: TelegramChatType;
|
|
42
45
|
/** Telegram's raw JSON response. */
|
|
43
46
|
readonly raw: unknown;
|
|
44
47
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";const TELEGRAM_MESSAGE_TEXT_MAX_LENGTH=4096;function telegramContinuationToken(e){let t=e.messageThreadId===void 0?``:String(e.messageThreadId),n=e.conversationId===void 0?``:String(e.conversationId);return`${String(e.chatId)}:${t}:${n}`}async function resolveTelegramBotToken(e){let t=e??process.env.TELEGRAM_BOT_TOKEN;if(!t)throw Error(`TELEGRAM_BOT_TOKEN is required.`);return typeof t==`function`?await t():t}async function callTelegramApi(e){let n=e.fetch??fetch,r=await resolveTelegramBotToken(e.botToken),i={headers:{"content-type":`application/json; charset=utf-8`},method:`POST`};e.body!==void 0&&(i.body=JSON.stringify(parseJsonObject(e.body)));let a=await n(`${e.apiBaseUrl??`https://api.telegram.org`}/bot${r}/${encodeURIComponent(e.method)}`,i);return{body:await parseResponseBody(a),ok:a.ok,status:a.status}}async function sendTelegramMessage(e){let t=await callTelegramApi({apiBaseUrl:e.apiBaseUrl,body:normalizeTelegramMessageBody(e.body,e.chatId),botToken:e.credentials?.botToken,fetch:e.fetch,method:`sendMessage`});if(!t.ok)throw Error(`Telegram sendMessage failed with HTTP ${t.status}.`);return toTelegramMessageResult(t.body)}async function sendTelegramChatAction(e){return callTelegramApi({apiBaseUrl:e.apiBaseUrl,body:parseJsonObject({action:e.action,chat_id:e.chatId,message_thread_id:e.messageThreadId}),botToken:e.credentials?.botToken,fetch:e.fetch,method:`sendChatAction`})}async function answerTelegramCallbackQuery(e){return callTelegramApi({apiBaseUrl:e.apiBaseUrl,body:parseJsonObject({callback_query_id:e.callbackQueryId,show_alert:e.showAlert,text:e.text}),botToken:e.credentials?.botToken,fetch:e.fetch,method:`answerCallbackQuery`})}async function editTelegramMessageReplyMarkup(e){return callTelegramApi({apiBaseUrl:e.apiBaseUrl,body:parseJsonObject({chat_id:e.chatId,message_id:Number(e.messageId),reply_markup:e.replyMarkup}),botToken:e.credentials?.botToken,fetch:e.fetch,method:`editMessageReplyMarkup`})}async function getTelegramFile(t){let n=await callTelegramApi({apiBaseUrl:t.apiBaseUrl,body:{file_id:t.fileId},botToken:t.credentials?.botToken,fetch:t.fetch,method:`getFile`});if(!n.ok)throw Error(`Telegram getFile failed with HTTP ${n.status}.`);let r=isObject(n.body)?n.body:{},i=isObject(r.result)?r.result:{};if(typeof i.file_path!=`string`||i.file_path.length===0)throw Error(`Telegram getFile response did not include result.file_path.`);return{filePath:i.file_path,raw:n.body}}async function downloadTelegramFile(e){let t=e.fetch??fetch,n=await resolveTelegramBotToken(e.credentials?.botToken);return t(`${e.fileBaseUrl??e.apiBaseUrl??`https://api.telegram.org`}/file/bot${n}/${e.filePath}`)}function splitTelegramMessageText(e){if(e.length<=4096)return[e];let t=[],
|
|
2
|
-
`,TELEGRAM_MESSAGE_TEXT_MAX_LENGTH);e<=0&&(e=
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";import{parseTelegramChatType}from"#public/channels/telegram/inbound.js";const TELEGRAM_MESSAGE_TEXT_MAX_LENGTH=4096;function telegramContinuationToken(e){let t=e.messageThreadId===void 0?``:String(e.messageThreadId),n=e.conversationId===void 0?``:String(e.conversationId);return`${String(e.chatId)}:${t}:${n}`}async function resolveTelegramBotToken(e){let t=e??process.env.TELEGRAM_BOT_TOKEN;if(!t)throw Error(`TELEGRAM_BOT_TOKEN is required.`);return typeof t==`function`?await t():t}async function callTelegramApi(e){let n=e.fetch??fetch,r=await resolveTelegramBotToken(e.botToken),i={headers:{"content-type":`application/json; charset=utf-8`},method:`POST`};e.body!==void 0&&(i.body=JSON.stringify(parseJsonObject(e.body)));let a=await n(`${e.apiBaseUrl??`https://api.telegram.org`}/bot${r}/${encodeURIComponent(e.method)}`,i);return{body:await parseResponseBody(a),ok:a.ok,status:a.status}}async function sendTelegramMessage(e){let t=await callTelegramApi({apiBaseUrl:e.apiBaseUrl,body:normalizeTelegramMessageBody(e.body,e.chatId),botToken:e.credentials?.botToken,fetch:e.fetch,method:`sendMessage`});if(!t.ok)throw Error(`Telegram sendMessage failed with HTTP ${t.status}.`);return toTelegramMessageResult(t.body)}async function sendTelegramChatAction(e){return callTelegramApi({apiBaseUrl:e.apiBaseUrl,body:parseJsonObject({action:e.action,chat_id:e.chatId,message_thread_id:e.messageThreadId}),botToken:e.credentials?.botToken,fetch:e.fetch,method:`sendChatAction`})}async function answerTelegramCallbackQuery(e){return callTelegramApi({apiBaseUrl:e.apiBaseUrl,body:parseJsonObject({callback_query_id:e.callbackQueryId,show_alert:e.showAlert,text:e.text}),botToken:e.credentials?.botToken,fetch:e.fetch,method:`answerCallbackQuery`})}async function editTelegramMessageReplyMarkup(e){return callTelegramApi({apiBaseUrl:e.apiBaseUrl,body:parseJsonObject({chat_id:e.chatId,message_id:Number(e.messageId),reply_markup:e.replyMarkup}),botToken:e.credentials?.botToken,fetch:e.fetch,method:`editMessageReplyMarkup`})}async function getTelegramFile(t){let n=await callTelegramApi({apiBaseUrl:t.apiBaseUrl,body:{file_id:t.fileId},botToken:t.credentials?.botToken,fetch:t.fetch,method:`getFile`});if(!n.ok)throw Error(`Telegram getFile failed with HTTP ${n.status}.`);let r=isObject(n.body)?n.body:{},i=isObject(r.result)?r.result:{};if(typeof i.file_path!=`string`||i.file_path.length===0)throw Error(`Telegram getFile response did not include result.file_path.`);return{filePath:i.file_path,raw:n.body}}async function downloadTelegramFile(e){let t=e.fetch??fetch,n=await resolveTelegramBotToken(e.credentials?.botToken);return t(`${e.fileBaseUrl??e.apiBaseUrl??`https://api.telegram.org`}/file/bot${n}/${e.filePath}`)}function splitTelegramMessageText(e){if(e.length<=4096)return[e];let t=[],n=e;for(;n.length>TELEGRAM_MESSAGE_TEXT_MAX_LENGTH;){let e=n.lastIndexOf(`
|
|
2
|
+
`,TELEGRAM_MESSAGE_TEXT_MAX_LENGTH);e<=0&&(e=n.lastIndexOf(` `,TELEGRAM_MESSAGE_TEXT_MAX_LENGTH)),e<=0&&(e=TELEGRAM_MESSAGE_TEXT_MAX_LENGTH),t.push(n.slice(0,e).trimEnd()),n=n.slice(e).trimStart()}return t.push(n),t}function normalizeTelegramMessageBody(e,n){return parseJsonObject({...e,chat_id:n})}function toTelegramMessageResult(t){let r=isObject(t)?t:{},i=isObject(r.result)?r.result:{},a=isObject(i.chat)?i.chat:{};return{chatId:typeof a.id==`number`||typeof a.id==`string`?String(a.id):void 0,chatType:parseTelegramChatType(a.type)??void 0,id:typeof i.message_id==`number`||typeof i.message_id==`string`?String(i.message_id):``,raw:t}}async function parseResponseBody(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}export{TELEGRAM_MESSAGE_TEXT_MAX_LENGTH,answerTelegramCallbackQuery,callTelegramApi,downloadTelegramFile,editTelegramMessageReplyMarkup,getTelegramFile,resolveTelegramBotToken,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken};
|
|
@@ -100,3 +100,5 @@ export declare function parseTelegramUpdate(value: unknown): TelegramUpdate | nu
|
|
|
100
100
|
* user identity fields.
|
|
101
101
|
*/
|
|
102
102
|
export declare function formatTelegramContextBlock(context: TelegramInboundContext): string;
|
|
103
|
+
/** Parses the Telegram chat types eve recognizes from inbound and send responses. */
|
|
104
|
+
export declare function parseTelegramChatType(value: unknown): TelegramChatType | null;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{isNonEmptyString,isObject}from"#shared/guards.js";function parseTelegramUpdate(e){if(!isObject(e))return null;let n=parseTelegramMessage(e.message);if(n!==null)return{kind:`message`,message:n};let r=parseTelegramCallbackQuery(e.callback_query);return r===null?null:{callbackQuery:r,kind:`callback_query`}}function formatTelegramContextBlock(e){return[`<telegram_context>`,`response_medium: telegram`,`response_instructions: Reply for Telegram in concise plain text. Avoid tables, long code fences, and formatting that depends on Markdown rendering.`,`chat_id: ${e.chatId}`,`chat_type: ${e.chatType}`,...e.chatTitle?[`chat_title: ${e.chatTitle}`]:[],`message_id: ${e.messageId}`,...e.messageThreadId===void 0?[]:[`message_thread_id: ${e.messageThreadId}`],...e.userId?[`user_id: ${e.userId}`]:[],...e.username?[`username: ${e.username}`]:[],...e.botUsername?[`bot_username: ${e.botUsername}`]:[],`</telegram_context>`].join(`
|
|
2
|
-
`)}function parseTelegramMessage(e){if(!isObject(e))return null;let n=parseTelegramChat(e.chat),r=numberLikeToString(e.message_id);return!n||!r?null:{attachments:parseAttachments(e),caption:typeof e.caption==`string`?e.caption:``,chat:n,from:parseTelegramUser(e.from),messageId:r,messageThreadId:typeof e.message_thread_id==`number`?e.message_thread_id:void 0,raw:e,replyToMessage:parseMessageReference(e.reply_to_message),text:typeof e.text==`string`?e.text:``}}function parseTelegramCallbackQuery(n){if(!isObject(n)||!isNonEmptyString(n.id))return null;let r=parseTelegramUser(n.from);return r?{data:typeof n.data==`string`?n.data:void 0,from:r,id:n.id,message:parseMessageReference(n.message),raw:n}:null}function parseMessageReference(e){if(!isObject(e))return;let n=parseTelegramChat(e.chat),r=numberLikeToString(e.message_id);if(!(!n||!r))return{chat:n,from:parseTelegramUser(e.from),messageId:r,messageThreadId:typeof e.message_thread_id==`number`?e.message_thread_id:void 0}}function parseTelegramChat(e){if(!isObject(e))return null;let n=numberLikeToString(e.id),r=
|
|
2
|
+
`)}function parseTelegramMessage(e){if(!isObject(e))return null;let n=parseTelegramChat(e.chat),r=numberLikeToString(e.message_id);return!n||!r?null:{attachments:parseAttachments(e),caption:typeof e.caption==`string`?e.caption:``,chat:n,from:parseTelegramUser(e.from),messageId:r,messageThreadId:typeof e.message_thread_id==`number`?e.message_thread_id:void 0,raw:e,replyToMessage:parseMessageReference(e.reply_to_message),text:typeof e.text==`string`?e.text:``}}function parseTelegramCallbackQuery(n){if(!isObject(n)||!isNonEmptyString(n.id))return null;let r=parseTelegramUser(n.from);return r?{data:typeof n.data==`string`?n.data:void 0,from:r,id:n.id,message:parseMessageReference(n.message),raw:n}:null}function parseMessageReference(e){if(!isObject(e))return;let n=parseTelegramChat(e.chat),r=numberLikeToString(e.message_id);if(!(!n||!r))return{chat:n,from:parseTelegramUser(e.from),messageId:r,messageThreadId:typeof e.message_thread_id==`number`?e.message_thread_id:void 0}}function parseTelegramChat(e){if(!isObject(e))return null;let n=numberLikeToString(e.id),r=parseTelegramChatType(e.type);return!n||!r?null:{id:n,title:typeof e.title==`string`?e.title:void 0,type:r,username:typeof e.username==`string`?e.username:void 0}}function parseTelegramUser(e){if(!isObject(e))return;let n=numberLikeToString(e.id);if(n)return{firstName:typeof e.first_name==`string`?e.first_name:void 0,id:n,isBot:e.is_bot===!0,languageCode:typeof e.language_code==`string`?e.language_code:void 0,lastName:typeof e.last_name==`string`?e.last_name:void 0,username:typeof e.username==`string`?e.username:void 0}}function parseAttachments(e){let t=[],n=parseLargestPhoto(e.photo);n!==null&&t.push(n);let r=parseDocument(e.document);return r!==null&&t.push(r),t}function parseLargestPhoto(e){if(!Array.isArray(e)||e.length===0)return null;let n=e.filter(isObject).map(e=>({fileId:typeof e.file_id==`string`?e.file_id:``,fileUniqueId:typeof e.file_unique_id==`string`?e.file_unique_id:void 0,height:typeof e.height==`number`?e.height:void 0,size:typeof e.file_size==`number`?e.file_size:void 0,width:typeof e.width==`number`?e.width:void 0})).filter(e=>e.fileId.length>0).sort((e,t)=>scorePhoto(t)-scorePhoto(e))[0];return n?{fileId:n.fileId,fileName:`photo.jpg`,fileUniqueId:n.fileUniqueId,height:n.height,kind:`photo`,mediaType:`image/jpeg`,size:n.size,width:n.width}:null}function parseDocument(e){return!isObject(e)||typeof e.file_id!=`string`?null:{fileId:e.file_id,fileName:typeof e.file_name==`string`?e.file_name:void 0,fileUniqueId:typeof e.file_unique_id==`string`?e.file_unique_id:void 0,kind:`document`,mediaType:typeof e.mime_type==`string`?e.mime_type:void 0,size:typeof e.file_size==`number`?e.file_size:void 0}}function scorePhoto(e){return e.size===void 0?(e.width??0)*(e.height??0):e.size}function parseTelegramChatType(e){return e===`channel`||e===`group`||e===`private`||e===`supergroup`?e:null}function numberLikeToString(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e==`number`&&Number.isFinite(e))return String(e)}export{formatTelegramContextBlock,parseTelegramChatType,parseTelegramUpdate};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TELEGRAM_MESSAGE_TEXT_MAX_LENGTH,answerTelegramCallbackQuery,callTelegramApi,downloadTelegramFile,editTelegramMessageReplyMarkup,getTelegramFile,resolveTelegramBotToken,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken}from"#public/channels/telegram/api.js";import{TELEGRAM_CALLBACK_RESPONSE_PREFIX,TELEGRAM_HITL_CALLBACK_PREFIX,TELEGRAM_REPLY_RESPONSE_PREFIX,isTelegramSyntheticResponse,registerTelegramFreeformPrompt,renderTelegramInputRequest,resolveTelegramInputResponses,telegramCallbackInputResponse,telegramReplyInputResponse}from"#public/channels/telegram/hitl.js";import{telegramChannel}from"#public/channels/telegram/telegramChannel.js";import{
|
|
1
|
+
import{formatTelegramContextBlock,parseTelegramUpdate}from"#public/channels/telegram/inbound.js";import{TELEGRAM_MESSAGE_TEXT_MAX_LENGTH,answerTelegramCallbackQuery,callTelegramApi,downloadTelegramFile,editTelegramMessageReplyMarkup,getTelegramFile,resolveTelegramBotToken,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken}from"#public/channels/telegram/api.js";import{TELEGRAM_CALLBACK_RESPONSE_PREFIX,TELEGRAM_HITL_CALLBACK_PREFIX,TELEGRAM_REPLY_RESPONSE_PREFIX,isTelegramSyntheticResponse,registerTelegramFreeformPrompt,renderTelegramInputRequest,resolveTelegramInputResponses,telegramCallbackInputResponse,telegramReplyInputResponse}from"#public/channels/telegram/hitl.js";import{telegramChannel}from"#public/channels/telegram/telegramChannel.js";import{TELEGRAM_FILE_URL_PROTOCOL,buildTelegramTurnMessage,collectTelegramFileParts,createTelegramFetchFile,createTelegramFileUrl}from"#public/channels/telegram/attachments.js";import{defaultTelegramAuth}from"#public/channels/telegram/defaults.js";import{resolveTelegramWebhookSecretToken,verifyTelegramRequest}from"#public/channels/telegram/verify.js";export{TELEGRAM_CALLBACK_RESPONSE_PREFIX,TELEGRAM_FILE_URL_PROTOCOL,TELEGRAM_HITL_CALLBACK_PREFIX,TELEGRAM_MESSAGE_TEXT_MAX_LENGTH,TELEGRAM_REPLY_RESPONSE_PREFIX,answerTelegramCallbackQuery,buildTelegramTurnMessage,callTelegramApi,collectTelegramFileParts,createTelegramFetchFile,createTelegramFileUrl,defaultTelegramAuth,downloadTelegramFile,editTelegramMessageReplyMarkup,formatTelegramContextBlock,getTelegramFile,isTelegramSyntheticResponse,parseTelegramUpdate,registerTelegramFreeformPrompt,renderTelegramInputRequest,resolveTelegramBotToken,resolveTelegramInputResponses,resolveTelegramWebhookSecretToken,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramCallbackInputResponse,telegramChannel,telegramContinuationToken,telegramReplyInputResponse,verifyTelegramRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{isCompiledChannel}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/defineChannel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{answerTelegramCallbackQuery,callTelegramApi,editTelegramMessageReplyMarkup,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken}from"#public/channels/telegram/api.js";import{TELEGRAM_HITL_CALLBACK_PREFIX,isTelegramSyntheticResponse,resolveTelegramInputResponses,telegramCallbackInputResponse,telegramReplyInputResponse}from"#public/channels/telegram/hitl.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{isCompiledChannel}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/defineChannel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{formatTelegramContextBlock,parseTelegramUpdate}from"#public/channels/telegram/inbound.js";import{answerTelegramCallbackQuery,callTelegramApi,editTelegramMessageReplyMarkup,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken}from"#public/channels/telegram/api.js";import{TELEGRAM_HITL_CALLBACK_PREFIX,isTelegramSyntheticResponse,resolveTelegramInputResponses,telegramCallbackInputResponse,telegramReplyInputResponse}from"#public/channels/telegram/hitl.js";import{buildTelegramTurnMessage,collectTelegramFileParts,createTelegramFetchFile}from"#public/channels/telegram/attachments.js";import{defaultEvents,defaultOnMessage}from"#public/channels/telegram/defaults.js";import{verifyTelegramRequest}from"#public/channels/telegram/verify.js";const log=createLogger(`telegram.channel`);function telegramChannel(e={}){let t=mergeUploadPolicy(e.uploadPolicy),n=e.onMessage??defaultOnMessage,r={...defaultEvents,...e.events},c=defineChannel({kindHint:`telegram`,state:initialTelegramState(e.botUsername),metadata:e=>({chatId:e.chatId,chatType:e.chatType,triggeringUserId:e.triggeringUserId??null}),fetchFile:createTelegramFetchFile({api:e.api,credentials:e.credentials,policy:t}),context(t,n){return rebuildTelegramContext(t,n,e)},routes:[POST(e.route??`/eve/v1/telegram`,async(r,{send:a,waitUntil:o})=>{let s=await verifyInbound(r,e.credentials);if(s===null)return new Response(`unauthorized`,{status:401});let c;try{c=parseJsonObject(JSON.parse(s))}catch(e){return log.warn(`inbound Telegram body is not valid JSON`,{error:e}),new Response(`ok`)}let u=parseTelegramUpdate(c);return u===null?new Response(`ok`):u.kind===`message`?(o(dispatchMessage({config:e,message:u.message,onMessage:n,send:a,uploadPolicy:t})),new Response(`ok`)):(o(dispatchCallbackQuery({config:e,query:u.callbackQuery,send:a})),new Response(`ok`))})],async receive(t,{send:n}){let r=t.target,i=readChatId(r.chatId);if(i===void 0)throw Error(`telegramChannel().receive requires target.chatId.`);let a=typeof r.messageThreadId==`number`?r.messageThreadId:void 0,o=readOptionalString(r.conversationId),s=r.initialMessage;if(s!==void 0&&o!==void 0)throw Error("telegramChannel().receive: `conversationId` and `initialMessage` are mutually exclusive.");let c={...initialTelegramState(e.botUsername),chatId:i,conversationId:o??null,messageThreadId:a??null};return s!==void 0&&await buildTelegramHandle({config:e,state:c}).sendMessage(s),n(t.message,{auth:t.auth,continuationToken:continuationTokenFromState(c),state:c})},events:r});return attachTelegramDeliver(c),c}function rebuildTelegramContext(e,t,n){return{state:e,telegram:buildTelegramHandle({config:n,session:t,state:e})}}function buildTelegramHandle(e){let n=e.config.api,r=e.state,i=e.config.credentials;function anchor(t){let n=r.chatType??t.chatType??null;r.chatType===null&&t.chatType!==void 0&&(r.chatType=t.chatType),!(!t.id||!shouldAnchorTelegramConversation(n))&&(r.conversationId=t.id,r.chatId&&e.session?.setContinuationToken(telegramContinuationToken({chatId:r.chatId,conversationId:t.id,messageThreadId:r.messageThreadId??void 0})))}async function sendOne(e){let t=r.chatId??``;if(!t)throw Error(`telegramChannel: missing chat id for outbound message.`);let a=await sendTelegramMessage({apiBaseUrl:n?.apiBaseUrl,body:{...e,message_thread_id:e.message_thread_id??r.messageThreadId??void 0},credentials:i,fetch:n?.fetch,fileBaseUrl:n?.fileBaseUrl,chatId:t});return anchor(a),a}return{botUsername:r.botUsername??e.config.botUsername,chatId:r.chatId??``,chatType:r.chatType??void 0,conversationId:r.conversationId??void 0,messageThreadId:r.messageThreadId??void 0,answerCallbackQuery(e){return answerTelegramCallbackQuery({apiBaseUrl:n?.apiBaseUrl,callbackQueryId:e.callbackQueryId,credentials:i,fetch:n?.fetch,showAlert:e.showAlert,text:e.text})},editMessageReplyMarkup(e){let t=r.chatId??``;if(!t)throw Error(`telegramChannel: missing chat id for reply-markup edit.`);return editTelegramMessageReplyMarkup({apiBaseUrl:n?.apiBaseUrl,chatId:t,credentials:i,fetch:n?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup})},post(e){return postTelegramMessage(e,sendOne)},request(e,t){return callTelegramApi({apiBaseUrl:n?.apiBaseUrl,body:t,botToken:i?.botToken,fetch:n?.fetch,method:e})},sendMessage(e){return postTelegramMessage(e,sendOne)},async startTyping(e=`typing`){let a=r.chatId??``;if(a)try{await sendTelegramChatAction({action:e,apiBaseUrl:n?.apiBaseUrl,chatId:a,credentials:i,fetch:n?.fetch,messageThreadId:r.messageThreadId??void 0})}catch(e){logError(log,`Telegram typing indicator failed — swallowed`,e,{chatId:a})}}}}function shouldAnchorTelegramConversation(e){return e===`group`||e===`supergroup`}async function postTelegramMessage(e,t){let n=typeof e==`string`?{text:e}:e,r=splitTelegramMessageText(n.text),i;for(let[e,a]of r.entries()){let r=await t(e===0?{...n,text:a}:{text:a});i===void 0&&(i=r)}return i??{id:``,raw:null}}async function verifyInbound(e,t){try{return await verifyTelegramRequest(e,{secretToken:t?.webhookVerifier?void 0:t?.webhookSecretToken,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`telegram inbound verification failed`,{error:e}),null}}async function dispatchMessage(e){if(e.message.from?.isBot===!0)return;let t=stateFromMessage(e.message,e.config),n={telegram:buildTelegramHandle({config:e.config,state:t})},r;try{r=await e.onMessage(n,e.message)}catch(e){log.error(`message handler failed`,{error:e});return}if(r==null)return;let i=collectTelegramFileParts(e.message.attachments,e.uploadPolicy),a=buildTelegramTurnMessage(e.message,i),o=formatTelegramContextBlock({botUsername:e.config.botUsername,chatId:e.message.chat.id,chatTitle:e.message.chat.title,chatType:e.message.chat.type,messageId:e.message.messageId,messageThreadId:e.message.messageThreadId,userId:e.message.from?.id,username:e.message.from?.username}),s=r.context??[],l=e.message.text||e.message.caption,u=e.message.replyToMessage?.from?.isBot===!0&&l.trim().length>0?[telegramReplyInputResponse({messageId:e.message.replyToMessage.messageId,text:l})]:void 0;try{await e.send({inputResponses:u,message:a,context:[o,...s]},{auth:r.auth,continuationToken:continuationTokenFromState(t),state:t})}catch(e){log.error(`message delivery failed`,{error:e})}}async function dispatchCallbackQuery(e){let t=stateFromCallbackQuery(e.query,e.config),n={telegram:buildTelegramHandle({config:e.config,state:t})};if(e.query.data?.startsWith(TELEGRAM_HITL_CALLBACK_PREFIX)===!0){try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:`Answer received.`})}catch(e){log.warn(`Telegram callback-query acknowledgement failed`,{error:e})}if(!e.query.message||!t.chatId)return;try{await e.send({inputResponses:[telegramCallbackInputResponse(e.query.data)]},{auth:null,continuationToken:continuationTokenFromState(t),state:t})}catch(e){log.error(`callback query delivery failed`,{error:e})}return}if(e.config.onCallbackQuery!==void 0){try{await e.config.onCallbackQuery(n,e.query)}catch(e){log.error(`custom callback-query handler failed`,{error:e})}return}try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:`Unsupported action.`})}catch(e){log.warn(`Telegram unsupported callback-query acknowledgement failed`,{error:e})}}function attachTelegramDeliver(e){if(!isCompiledChannel(e))return;let t=e.adapter;t.deliver=(e,t)=>{let n=e.inputResponses??[];if(n.some(isTelegramSyntheticResponse)){let r=resolveTelegramInputResponses(t.state,n);return r.length>0?{inputResponses:r,context:e.context}:e.message===void 0?void 0:{message:e.message,context:e.context}}return defaultDeliverResult(e)}}function stateFromMessage(e,t){let n=e.chat.type===`private`;return{...initialTelegramState(t.botUsername),chatId:e.chat.id,chatType:e.chat.type,conversationId:n?null:conversationIdForMessage(e),messageThreadId:e.messageThreadId??null,triggeringUserId:e.from?.id??null}}function stateFromCallbackQuery(e,t){let n=e.message;if(!n)return{...initialTelegramState(t.botUsername),triggeringUserId:e.from.id};let r=n.chat.type===`private`;return{...initialTelegramState(t.botUsername),chatId:n.chat.id,chatType:n.chat.type,conversationId:r?null:n.messageId,messageThreadId:n.messageThreadId??null,triggeringUserId:e.from.id}}function conversationIdForMessage(e){return e.replyToMessage?.from?.isBot===!0?e.replyToMessage.messageId:e.messageId}function continuationTokenFromState(e){return telegramContinuationToken({chatId:e.chatId??``,conversationId:e.chatType===`private`?void 0:e.conversationId??void 0,messageThreadId:e.messageThreadId??void 0})}function initialTelegramState(e){return{botUsername:e??null,chatId:null,chatType:null,conversationId:null,hitlCallbacks:{},messageThreadId:null,nextHitlCallbackId:0,pendingFreeformReplies:{},triggeringUserId:null}}function readChatId(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e==`number`&&Number.isFinite(e))return String(e)}function readOptionalString(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e==`number`&&Number.isFinite(e))return String(e)}export{telegramChannel};
|