@onereach/step-create-chat-completion 0.0.7-rc.57 → 0.0.7-rc.59
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/dist/index.d.mts +709 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -11
- package/dist/index.d.ts +0 -691
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/schemas/data-in.ts","../src/threads/base-types.ts","../src/utils/thread-utilities.ts","../src/threads/base-child-types.ts","../src/threads/cancel/cancel-context-types.ts","../src/step-types.ts","../src/threads/base.ts","../src/threads/cancel/cancel-context.ts","../src/threads/request/request-context-types.ts","../src/threads/tools/tools-context-types.ts","../src/threads/content/abstract-content-context-types.ts","../src/threads/content/abstract-content-context.ts","../src/threads/content/simple/simple-content-context-types.ts","../src/threads/content/simple/simple-content-context.ts","../src/threads/content/stream/stream-content-context-types.ts","../src/threads/content/stream/stream-content-context-worker-types.ts","../src/threads/content/stream/stream-content-context-worker.ts","../src/threads/content/stream/stream-content-context.ts","../src/threads/history/history-context-types.ts","../src/threads/history/history-context.ts","../src/threads/request/request-context.ts","../src/threads/tools/tools-context-worker-types.ts","../src/threads/tools/tools-context-worker.ts","../src/threads/tools/tools-context.ts","../src/step.ts","../src/index.ts"],"mappings":";;;;;;;;;cAuEa,YAAA,EAAY,CAAA,CAAA,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAsJb,MAAA,GAAS,CAAA,CAAE,KAAA,QAAa,YAAA;;;UCzNnB,UAAA,SAAmB,MAAA;EAClC,MAAA,EAAQ,MAAA;AAAA;;;KCoGE,kBAAA;EACV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;;;;SAWiB,oBAAA,WAA+B,oBAAA,CAAA,CAAsB,MAAA,EAAQ,OAAA,CAAQ,CAAA,IAAK,OAAA;EAAA,OAOhF,WAAA,CAAY,MAAA,EAAQ,OAAA,GAAU,SAAA;EAOrC,OAAA,CAAA;EAQA,UAAA,CAAA;EAKA,UAAA,CAAW,KAAA,EAAO,yBAAA;EAmBlB,sBAAA,CAAA;EAOA,iBAAA,CAAkB,KAAA,EAAO,YAAA,CAAa,wBAAA,EAA0B,MAAA,CAAO,GAAA;;;;YAmCpE,qBAAA,CAAsB,QAAA,EAAU,uCAAA;EAAA,UAShC,iBAAA,CAAkB,UAAA,UAAoB,MAAA;EAAA,UAatC,wBAAA,CAAA;EAAA,cAgBI,QAAA,CAAA,GAAY,gCAAA;AAAA;;;cClKf,wBAAA,SAAiC,QAAA,CAAS,oBAAA;EAE9C,OAAA,CAAA;EAcM,UAAA,CAAA,GAAc,OAAA;EAiBd,mBAAA,CAAoB,KAAA,EAAO,YAAA,CAAa,oBAAA,EAAsB,MAAA,CAAO,GAAA,IAAO,OAAA;EAgD5E,mBAAA,CAAoB,KAAA,EAAO,YAAA,CAAa,oBAAA,EAAsB,MAAA,CAAO,GAAA,IAAO,OAAA;EAmB5E,QAAA,CAAA,GAAY,OAAA;EAAA,QAIX,aAAA;;;;;;;;;;UAyDA,SAAA;EAAA,QAYN,UAAA;EAAA,QAMA,sBAAA;EAAA,YAWI,cAAA,CAAA;AAAA;;;cCtMD,MAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ze=Object.defineProperty;var l=(n,e)=>Ze(n,"name",{value:e,configurable:!0});import{install as Ot}from"source-map-support";import{ACTION as Ye}from"@onereach/flow-sdk/types/index.js";import be from"@onereach/flow-sdk/errors/timeout.js";import{z as xe}from"zod/v4-mini";import we from"@onereach/flow-sdk/errors/base.js";var p={UNKNOWN:"UNKNOWN",STEP_LOGIC_ISSUE:"STEP_LOGIC_ISSUE",AUTH:"AUTH",TIMEOUT:"TIMEOUT",VALIDATION:"VALIDATION",INVALID_REQUEST:"INVALID_REQUEST",RATE_LIMITED:"RATE_LIMITED",LLM_FINISH_LENGTH:"LLM_FINISH_LENGTH",SERVER_ERROR:"SERVER_ERROR",UNSUPPORTED:"UNSUPPORTED"},h=class extends we{static{l(this,"CreateChatCompletionStepError")}},oe=class extends we{static{l(this,"AbortRequestError")}};var Xe=[h,be];function x(n,e={}){let{preserveErrors:t=Xe,unknownMessage:r="Unknown error",unknownCode:i=p.UNKNOWN}=e;if(t?.some(o=>n instanceof o))return n;if(n instanceof xe.core.$ZodError)return new h(xe.prettifyError(n),n,{code:p.VALIDATION});if(typeof n=="string")return new h(n,{code:p.UNKNOWN});if(n instanceof Error){if(n.message.includes("Request timed out"))return new be("Timeout",n,{code:p.TIMEOUT});let o=n?.response?.data?.error?.message;return o!=null?new h(o,n,{code:p.SERVER_ERROR}):new h(r,n,{code:i})}return new h(r,{code:i,data:n})}l(x,"errorFilter");function re(n,e){function t(r,i,o,a){let c=n(r,i,o,a);if(typeof c=="function"){let f=a.value,w=c;if(f?.name!=null)try{Object.defineProperty(w,"name",{value:f.name})}catch{}return a.value=w,a}return c??a}return l(t,"runApply"),l(function(i,o,a){if(i!==null&&typeof i=="object"&&(typeof o=="string"||typeof o=="symbol")&&a!==null&&typeof a=="object")return t(e,i,o,a);{let c=i??e;return(f,w,m)=>t(c,f,w,m)}},"decoratorOrFactory")}l(re,"createMethodDecoratorWithOptionalArguments");var et={allowHandleError:!1,useErrorFilter:!0},u=re((n,e,t,r)=>{let i=r.value;if(!(!i||typeof i!="function"))return function(...o){try{let a=i.apply(this,o);return a instanceof Promise?a.catch(c=>_e.call(this,n,c,t)):a}catch(a){return _e.call(this,n,a,t)}}},et);function _e(n,e,t){let r=t.toString();this.log.DEBUG?.(`Error in method '${r}'`,e);let i=n.useErrorFilter?x(e):e;if(i instanceof Error)if(n.allowHandleError){this.thread.enqueue({name:Ye.error,error:i});return}else{this.end(i);return}throw i}l(_e,"errorHandler");function ve({thread:n,...e}){let t=ue({thread:n,...e}),r=n.process;if(r.cache[t]!=null)throw new Error(`AbortController for key '${t}' already exists`);return r.cache[t]=new AbortController}l(ve,"createAbortController");function Re({thread:n,...e}){let t=ue({thread:n,...e});return n.process.cache[t]}l(Re,"getAbortController");function z({thread:n,...e}){let t=ue({thread:n,...e});delete n.process.cache[t]}l(z,"deleteAbortController");function ue({thread:n,prefix:e,stepId:t=n.currentStepId}){return`${e?`${e}:`:""}abrt_ctrl:${t}`}l(ue,"getAbortControllerKey");import{ACTION as Se}from"@onereach/flow-sdk/types/index.js";async function k(n,{id:e,state:t,local:r,...i},{force:o}={}){let a=n.process.getThread(e);if(n.log.DEBUG?.(`runThread: thread with id '${e}'`,i),a==null)return await n.thread.runThread({...i,id:e,state:t,local:{...r,parent:n.thread.id,active:!0}});if(!o&&!a.ended&&a.local.active)throw new Error(`Thread with id '${e}' has not ended yet, cannot start it again`);if(t==null)throw new Error(`Thread with id '${e}' must have a state to run`);return a.local.active=!0,await a.enqueueAndRun({name:Se.goto,state:{...t,active:!0}})}l(k,"runChildThread");function Ie(n,e){let t=n.process.getThread(e);return!!(t!=null&&t.local.active&&!t.ended)}l(Ie,"isThreadBusy");function tt(n,e=n.id){let t=[];for(let r in n.process.threads){let i=n.process.threads[r];i?.local.parent===e&&t.push(i)}return t}l(tt,"listChildThreads");async function J(n,e,{result:t,stopChildThreads:r}={}){let i=n.process.getThread(e);n.log.DEBUG?.(`stopThread: thread with id '${e}'`),i&&(r&&await he(i,t),i.local.active&&(i.local.active=!1,!i.ended&&await i.enqueueAndRun({name:Se.ending,result:t})))}l(J,"stopThread");async function he(n,e,t={}){let i=tt(n).map(async c=>await J(n,c.id,{stopChildThreads:!0,result:e})),o=await Promise.allSettled(i);if(t.throw??!0){let c=o.find(f=>f.status==="rejected");if(c)throw c.reason}return o}l(he,"endChildThreads");import it from"@onereach/flow-sdk/step.js";var nt={},M=re((n,e,t,r)=>{let i=r.value;if(!(!i||typeof i!="function"))return function(...o){try{let a=i.apply(this,o);return a instanceof Promise?a.catch(c=>{let f=t.toString();throw this.log.DEBUG?.(`Error in method '${f}'`,c),x(c)}):a}catch(a){let c=t.toString();throw this.log.DEBUG?.(`Error in method '${c}'`,a),x(a)}}},nt);import{en as ot}from"zod/v4/locales";import{z as s}from"zod/v4-mini";s.config(ot());var y=s.string().check(s.trim(),s.refine(n=>!["undefined","null"].includes(n),{error:"Unexpected undefined or null merge-field value"})),Oe=s.discriminatedUnion("role",[s.object({role:s.literal("system"),content:y}),s.object({role:s.literal("user"),content:y,name:s.optional(y.check(s.minLength(1),s.maxLength(64)))}),s.object({role:s.literal("assistant"),content:s.nullable(y),tool_calls:s.optional(s.array(s.object({id:y.check(s.minLength(1)),type:s.literal("function"),function:s.object({name:y.check(s.minLength(1)),arguments:y.check(s.minLength(1))})})))}),s.object({role:s.literal("tool"),content:y,name:s.optional(y.check(s.minLength(1),s.maxLength(64))),tool_call_id:y.check(s.minLength(1))})]),rt=s.object({type:s.literal("object"),properties:s.record(s.string().check(s.minLength(1),s.maxLength(64)),s.object({type:s.enum(["string","number","boolean","array","object"]),description:s.optional(s.string().check(s.maxLength(1e3))),items:s.optional(s.object({type:s.enum(["string","number","boolean","object"]),description:s.optional(s.string().check(s.maxLength(1e3)))}))}))}),ke=s.object({provider:y.check(s.minLength(1)),model:y.check(s.minLength(1)),accountKey:U(y),typeOfStep:s.enum(["chat","completion"]),systemMessage:s.optional(y),userMessage:s.optional(y),switchAssistantsMessage:s._default(s.boolean(),!1),assistantsFirstMessage:s.optional(y),temperature:U(s.coerce.number().check(s.gte(0),s.lte(2))),topP:U(s.coerce.number().check(s.gte(0),s.lte(1))),maxTokens:U(s.coerce.number().check(s.int(),s.gte(1))),presencePenalty:U(s.coerce.number().check(s.gte(-2),s.lte(2))),frequencyPenalty:U(s.coerce.number().check(s.gte(-2),s.lte(2))),n:U(s.coerce.number().check(s.int(),s.gte(1),s.lte(128))),stop:s.optional(s.array(s.object({token:s.string().check(s.minLength(1),s.maxLength(64))})).check(s.maxLength(4))),reasoningEffort:U(s.enum(["none","low","medium","high"])),streamResponse:s._default(s.boolean(),!1),streamSettings:s.optional(s.object({maxBufferLength:s.coerce.number().check(s.overwrite(n=>n===0?50:n),s.int(),s.gte(1),s.lte(32768)),debounceDuration:s.coerce.number().check(s.int(),s.gte(0),s.lte(1e4))})),customHistory:s._default(s.boolean(),!1),historyLength:U(s.coerce.number().check(s.int(),s.gte(1),s.lte(100))),historyMode:s.optional(s.enum(["mergefield","codeHistory"])),historyMergefield:s.optional(s.array(Oe)),historyCode:s.optional(s.array(Oe)),functionsList:s.array(s.object({name:y.check(s.minLength(1),s.maxLength(64)),description:s.optional(y.check(s.maxLength(1e3))),parameters:s.optional(s.pipe(rt,s.transform(n=>(n.required=Object.keys(n.properties),n.additionalProperties=!1,n)))),strict:s.boolean()})),useState:s.optional(s.boolean()),stateSettings:s.optional(s.object({stateFunction:s.function()})),processError:s.boolean(),processTimeout:s.boolean(),timeoutDuration:y.check(s.trim(),s.minLength(1))}).check(s.refine(n=>!n.streamResponse||n.provider==="openai",{error:"Streaming is only supported for OpenAI provider"}),s.refine(n=>!n.streamResponse||n.streamSettings!==void 0,{error:'Missing "Stream settings" for response streaming mode'}),s.refine(n=>n.typeOfStep!=="chat"||n.customHistory||!n.switchAssistantsMessage||n.assistantsFirstMessage!==void 0,{error:`Missing "Assistant's first message" value`}),s.refine(n=>n.customHistory||n.userMessage!==void 0,{error:'Missing "User message" value'}),s.refine(n=>n.typeOfStep!=="chat"||!n.customHistory||n.historyMode!==void 0,{error:'Missing "History mode" value'}),s.refine(n=>n.typeOfStep!=="chat"||!n.customHistory||n.historyMode!=="mergefield"||n.historyMergefield!==void 0,{error:'Missing "History" data via merge-field'}),s.refine(n=>n.typeOfStep!=="chat"||!n.customHistory||n.historyMode!=="mergefield"||n.historyMergefield?.find?.(e=>e.role==="user"),{error:'Missing at least one message with role "user" message in "History" data via merge-field'}),s.refine(n=>n.typeOfStep!=="chat"||!n.customHistory||n.historyMode!=="codeHistory"||n.historyCode!==void 0,{error:'Missing "History" data as code'}),s.refine(n=>n.typeOfStep!=="chat"||!n.customHistory||n.historyMode!=="codeHistory"||n.historyCode?.find?.(e=>e.role==="user"),{error:'Missing at least one message with role "user" message in "History" data via code'}),s.refine(n=>!n.useState||n.stateSettings!=null,{error:"Missing state settings"}));function U(n){return s.pipe(s.union([s.undefined(),s.literal(""),n]),s.transform(e=>e===""?void 0:e))}l(U,"optionalStringValue");function st(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(st,"_ts_decorate");function fe(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(fe,"_ts_metadata");var C=class extends it{static{l(this,"BaseStep")}async resolveDataIn(){let e=await super.resolveDataIn();return ke.parse(e)}};st([M,fe("design:type",Function),fe("design:paramtypes",[]),fe("design:returntype",Promise)],C.prototype,"resolveDataIn",null);var I="llm_cmp";var je="cncl_ctrl",se={cancel:"st_cancel"},Ae={cancel:"cnl_cancel"};function me(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(me,"_ts_decorate");function D(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(D,"_ts_metadata");var j=class n extends C{static{l(this,"CancelContext")}static class=je;static async start(e){await k(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class},background:!0},{force:!0})}static async stop(e){await J(e,this.getThreadId(e.step.id))}static getThreadId(e){return`${I}_${this.class}_${e}`}runStep(){this.triggers.local({name:Ae.cancel},this.onCancel).otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ${n.name} thread`)}onCancel(){this.log.DEBUG?.("Canceling LLM request");let e=this.local.parent,t=this.process.getThread(e);if(!t||t.ended)return this.end();let r=Re({thread:this.thread});r?r.abort(new oe("Request cancelled")):this.process.enqueueAndRun({name:se.cancel,thread:e})}};me([u,D("design:type",Function),D("design:paramtypes",[]),D("design:returntype",void 0)],j.prototype,"runStep",null);me([u,D("design:type",Function),D("design:paramtypes",[]),D("design:returntype",void 0)],j.prototype,"initialize",null);me([u,D("design:type",Function),D("design:paramtypes",[]),D("design:returntype",void 0)],j.prototype,"onCancel",null);import{ACTION as Be}from"@onereach/flow-sdk/types/index.js";import{setImmediate as yt}from"timers/promises";import{clear as Ct,Memoize as Et}from"typescript-memoize";import{clear as ft,Memoize as De}from"typescript-memoize";var Pe="hst_ctrl",B={appendToHistory:"hst_append",prepareHistory:"hst_prepare",adjustOnCancel:"hst_cncl"};function Q(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(Q,"_ts_decorate");function b(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(b,"_ts_metadata");var g=class n extends C{static{l(this,"HistoryContext")}static class=Pe;static async start(e){let t=this.getThreadId(e.step.id);e.process.getThread(t)==null&&await e.process.runThread({id:t,background:!0,state:{step:e.step.id,class:this.class,messages:[]}})}static async prepareHistory(e){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:B.prepareHistory})}static async appendToHistory(e,t){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:B.appendToHistory,params:{message:t}})}static async adjustOnCancel(e){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:B.adjustOnCancel})}static getHistory(e){return e.process.getSafeThread(this.getThreadId(e.step.id)).state.messages}static getThreadId(e){return`${I}_${this.class}_${e}`}runStep(){this.triggers.local(B.prepareHistory,this.onPrepareHistory).local(B.appendToHistory,this.onAppendToHistory).local(B.adjustOnCancel,this.onAdjustOnCancel).otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ${n.name} thread`)}onAdjustOnCancel(){let e;for(;(e=this.state.messages.at(-1))&&!(["system","user"].includes(e.role)||e.role==="assistant"&&e.tool_calls==null);){let t=this.state.messages.pop();this.log.DEBUG?.("Removed message from history",t)}}onPrepareHistory(){this.log.DEBUG?.("Preparing history");let{customHistory:e,historyLength:t,systemMessage:r,typeOfStep:i,userMessage:o,historyMode:a,historyMergefield:c,historyCode:f,assistantsFirstMessage:w}=this.data;if(i==="completion"){this.state.messages=[{role:"user",content:o}];return}if(e){this.state.messages=a==="mergefield"?c:f;return}let m=this.state.messages;if(m.length===0&&w!=null&&w.length>0&&m.push({role:"assistant",content:w}),m.at(-1)?.role!=="tool"&&m.push({role:"user",content:o}),!m.some(N=>N.role==="tool")&&t!=null&&t>0&&(m=m.slice(-1*t)),r!=null&&r.length>0){let N={role:"system",content:r};m[0]?.role==="system"?m[0]=N:m.unshift(N)}this.state.messages=m}onAppendToHistory(e){this.log.DEBUG?.("Appending message to history",e.params);let{message:t}=e.params,r=Array.isArray(t)?t:[t];this.state.messages.push(...r)}};Q([u,b("design:type",Function),b("design:paramtypes",[]),b("design:returntype",void 0)],g.prototype,"runStep",null);Q([u,b("design:type",Function),b("design:paramtypes",[]),b("design:returntype",void 0)],g.prototype,"initialize",null);Q([u,b("design:type",Function),b("design:paramtypes",[]),b("design:returntype",void 0)],g.prototype,"onAdjustOnCancel",null);Q([u,b("design:type",Function),b("design:paramtypes",[]),b("design:returntype",void 0)],g.prototype,"onPrepareHistory",null);Q([u,b("design:type",Function),b("design:paramtypes",[typeof HistoryContextEventAppendToHistory>"u"?Object:HistoryContextEventAppendToHistory]),b("design:returntype",void 0)],g.prototype,"onAppendToHistory",null);import{BasicThreadService as at}from"@onereach/flow-sdk/services/basic.js";import{setImmediate as lt}from"timers/promises";var ie={handleContent:"hnd_cnt"};var W=class extends at{static{l(this,"AbstractResponseHandler")}async handleContentByParentThread(e){await lt(),await this.thread.process.enqueueAndRun({thread:this.thread.local.parent,name:ie.handleContent,params:{content:e}})}};var ae=class extends W{static{l(this,"SimpleResponseHandler")}async handle(e){this.log.DEBUG?.("Start processing response from LLM"),await this.handleContentByParentThread(e),z({thread:this.thread})}};var le=class extends W{static{l(this,"StreamResponseHandler")}async handle(e){this.log.DEBUG?.("Start processing stream of chunks from LLM");for await(let t of e)await this.handleContentByParentThread(t);z({thread:this.thread})}};function Le({thread:n,isStreaming:e}){return e?new le(n):new ae(n)}l(Le,"responseHandlerFactory");var Me="rqst_ctx";import pt from"openai";import ut from"timestring";import{Memoize as ht}from"typescript-memoize";import{z as de}from"zod/v4-mini";import{BasicThreadService as ct}from"@onereach/flow-sdk/services/basic.js";var ce=class extends ct{static{l(this,"ThreadServiceWithData")}data;constructor(e,t){super(e),this.data=t}};function dt(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(dt,"_ts_decorate");function Ue(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(Ue,"_ts_metadata");var $=class extends ce{static{l(this,"OpenAIRequestService")}async makeOpenAiRequest(e,t){let{model:r,temperature:i,topP:o,maxTokens:a,frequencyPenalty:c,presencePenalty:f,n:w,streamResponse:m,reasoningEffort:ne}=this.data,N={messages:structuredClone(e),model:r,temperature:i,top_p:o,max_tokens:a,frequency_penalty:c,presence_penalty:f,stop:this.stopSequences,n:w,reasoning_effort:ne,stream:m,tools:this.tools};this.log.DEBUG?.("LLM request",N);try{let q=await this.openAiClient.chat.completions.create(N,{signal:t});return m||this.log.DEBUG?.("LLM response",q),q}catch(q){throw q instanceof Error?new h("Chat completion request failed",q,{code:p.SERVER_ERROR,data:N}):q}}get tools(){let{functionsList:e}=this.data;if(!(!Array.isArray(e)||e.length===0))return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:!t.parameters||Object.keys(t.parameters).length===0?void 0:t.parameters,strict:t.strict}}))}get openAiClient(){let{provider:e,accountKey:t}=this.data,r={baseURL:`${this.config.env.OPENAI_API_URL}/${e}`,apiKey:"",defaultHeaders:{Authorization:this.config.authorization,"x-or-session-id":this.session.get(["reporting","sessionId"]),...t?{"x-or-account-token-name":t}:void 0},timeout:this.timeoutMs};return this.log.DEBUG?.("OpenAI client options",r),new pt(r)}get stopSequences(){return(this.data.stop??[]).map(t=>t.token).filter(t=>t.length>0)}get timeoutMs(){let e=ut(this.data.timeoutDuration,"ms");return de.number().check(de.int(),de.gte(1e3),de.lte(6e5)).parse(e)}};dt([ht(),Ue("design:type",Number),Ue("design:paramtypes",[])],$.prototype,"timeoutMs",null);function ge(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(ge,"_ts_decorate");function G(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(G,"_ts_metadata");var Fe=["requestInit"],_=class extends C{static{l(this,"RequestContext")}static class=Me;static async start(e){return await k(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class},background:!0})}static getThreadId(e){return`${I}_${this.class}_${e}`}async runStep(){ft(Fe);let e=ve({thread:this.thread});try{let t=await this.openAiService.makeOpenAiRequest(await this.getHistory(),e.signal);await this.responseHandler.handle(t),this.complete()}catch(t){if(e?.signal.aborted)return this.cancel();throw t}finally{z({thread:this.thread})}}cancel(){this.end({status:"cancel"})}complete(){this.end({status:"ok"})}async getHistory(){let e=g.getHistory(this.thread);if(!this.data.useState)return e;let t=[...e],i={role:"assistant",content:await this.data.stateSettings?.stateFunction()};return e.at(-1)?.role==="user"?t.splice(-1,0,i):t.push(i),t}get openAiService(){return new $(this.thread,this.data)}get responseHandler(){let e=this.data.streamResponse;return Le({thread:this.thread,isStreaming:e})}};ge([u,G("design:type",Function),G("design:paramtypes",[]),G("design:returntype",Promise)],_.prototype,"runStep",null);ge([De(),G("design:type",typeof $>"u"?Object:$),G("design:paramtypes",[])],_.prototype,"openAiService",null);ge([De({tags:Fe}),G("design:type",typeof AbstractResponseHandler>"u"?Object:AbstractResponseHandler),G("design:paramtypes",[])],_.prototype,"responseHandler",null);import{ACTION as gt}from"@onereach/flow-sdk/types/index.js";var Ne="tl_ctrl",Z={callTool:"tl_run_call",lastToolCallReceived:"tl_rsp_end"};var He="tl_wrk";function mt(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(mt,"_ts_decorate");function ye(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(ye,"_ts_metadata");var P=class extends C{static{l(this,"ToolsContextWorker")}static class=He;static async start(e,t){let r=JSON.parse(t.function?.arguments);await k(e,{id:this.getThreadId(t),state:{step:e.step.id,class:this.class},local:{toolCall:t,parsedArguments:r,parent:e.id,active:!0}})}static getThreadId(e){return`${I}_${this.class}_${e.id}`}runStep(){let{toolCall:e,parsedArguments:t}=this.local;this.log.DEBUG?.("Initializing tool worker thread",e),this.exitStep(this.getExitName(),{function:{name:e.function.name,arguments:t}})}getExitName(){return"function"}};mt([M,ye("design:type",Function),ye("design:paramtypes",[]),ye("design:returntype",void 0)],P.prototype,"runStep",null);function X(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(X,"_ts_decorate");function v(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(v,"_ts_metadata");var E=class n extends C{static{l(this,"ToolsContext")}static class=Ne;static async start(e){let t=this.getThreadId(e.step.id);await k(e,{id:t,state:{step:e.step.id,class:this.class,tasks:{},expectMoreTasks:!0},background:!0})}static async callTool(e,t){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:Z.callTool,params:{toolCall:t}})}static async lastToolCallReceived(e){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:Z.lastToolCallReceived})}static getThreadId(e){return`${I}_${this.class}_${e}`}runStep(){this.triggers.local(Z.callTool,this.onCallTool).local(Z.lastToolCallReceived,this.onLastToolCallReceived).otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ${n.name} thread`)}onCallTool(e){let{toolCall:t}=e.params;if(t.type!=="function")throw new h("Only function tools are supported at the moment",{code:p.UNSUPPORTED});this.state.tasks[t.id]={call:t,status:"pending"},this.startToolWorkerThread(t)}onLastToolCallReceived(){this.log.DEBUG?.("No more tool calls expected",this.state.tasks),this.state.expectMoreTasks=!1,this.tryEndToolsContextThread()}onWorkerThreadEnd(e){this.log.DEBUG?.("Tool caller worker thread has ended",e);let{result:t}=e.params.thread;if(t==null)throw new h(`${P.name} thread ended unexpectedly`,{code:p.STEP_LOGIC_ISSUE});if(t instanceof Error)throw x(t,{unknownMessage:`${P.name} thread ended with an error`,unknownCode:p.STEP_LOGIC_ISSUE});t.status!=="cancel"&&(this.log.DEBUG?.("Tool worker thread completed successfully",{toolCallId:t.toolCallId,result:t.data}),this.setToolCallResult(t.toolCallId,t.data),this.tryEndToolsContextThread())}startToolWorkerThread(e){this.triggers.hook({name:gt.end,thread:P.getThreadId(e)},this.onWorkerThreadEnd),P.start(this.thread,e)}setToolCallResult(e,t){let r=this.state.tasks[e];if(r==null)throw new h(`Unknown tool call with id '${e}'`,{code:p.STEP_LOGIC_ISSUE});r.status="completed",r.result=t}tryEndToolsContextThread(){this.state.expectMoreTasks||Object.values(this.state.tasks).some(t=>t.status==="pending")||(this.log.DEBUG?.("All tool calls completed or failed",this.state.tasks),this.end({status:"ok",messages:this.messages}))}get messages(){return Object.values(this.state.tasks).map(e=>({role:"tool",tool_call_id:e.call.id,content:JSON.stringify(e.result)}))}};X([u,v("design:type",Function),v("design:paramtypes",[]),v("design:returntype",void 0)],E.prototype,"runStep",null);X([u,v("design:type",Function),v("design:paramtypes",[]),v("design:returntype",void 0)],E.prototype,"initialize",null);X([u,v("design:type",Function),v("design:paramtypes",[typeof ToolsContextEventCallTool>"u"?Object:ToolsContextEventCallTool]),v("design:returntype",void 0)],E.prototype,"onCallTool",null);X([u,v("design:type",Function),v("design:paramtypes",[]),v("design:returntype",void 0)],E.prototype,"onLastToolCallReceived",null);X([u,v("design:type",Function),v("design:paramtypes",[typeof IActionEvent>"u"?Object:IActionEvent]),v("design:returntype",void 0)],E.prototype,"onWorkerThreadEnd",null);function Y(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(Y,"_ts_decorate");function R(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(R,"_ts_metadata");var $e=["toolsInit"],L=class extends C{static{l(this,"AbstractContentContext")}static get class(){throw new Error('Define "class" static field')}static getInitialState(){throw new Error('Define "getInitialState" static method')}runStep(){Ct($e),this.triggers.local(ie.handleContent,this.onHandleContent).hook({name:Be.end,thread:_.getThreadId(this.thread.step.id)},this.onRequestContextEnd).otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ${this.constructor.name} thread`),_.start(this.thread)}async onRequestContextEnd(e){let{result:t}=e.params.thread;if(this.log.DEBUG?.(`${_.name} thread ended with result`,t),t==null)throw new h(`${_.name} thread ended unexpectedly`,{code:p.STEP_LOGIC_ISSUE});if(t instanceof Error)throw x(t,{unknownMessage:`${_.name} thread ended with an error`,unknownCode:p.STEP_LOGIC_ISSUE});if(t.status==="cancel")return this.cancel();if(t.status!=="ok")throw new h(`Unexpected end of the ${_.name} thread`,{code:p.STEP_LOGIC_ISSUE,data:e.params.result});this.state.requestComplete=!0,await this.onAllContentReceived(),this.state.toolsReady!=null&&(await yt(),await E.lastToolCallReceived(this.thread)),await this.tryToComplete()}async onToolsContextEnd(e){let{result:t}=e.params.thread;if(this.log.DEBUG?.(`${E.name} thread ended`,t),t==null)throw new h(`${E.name} thread ended unexpectedly`,{code:p.STEP_LOGIC_ISSUE});if(t instanceof Error)throw x(t,{unknownMessage:`${E.name} thread ended with an error`,unknownCode:p.STEP_LOGIC_ISSUE});if(t.status==="cancel")return;let{status:r,messages:i}=t;if(r!=="ok"||!Array.isArray(i))throw new h(`Unexpected end of the ${E.name} thread`,{code:p.STEP_LOGIC_ISSUE,data:e.params.result});this.state.toolsResults=i,this.state.toolsReady=!0,await this.tryToComplete()}async callFunction(e){this.state.toolsReady=!1,await this.initToolsContextThread(),await E.callTool(this.thread,e)}handleMultipleChoices(){let{chatCompletion:e}=this.state,t=e?.choices??[];t?.length>1&&this.log.WARN?.("Multiple choices received from LLM, but only the first one will be processed",{choices:t.length})}async initToolsContextThread(){this.triggers.hook({name:Be.end,thread:E.getThreadId(this.thread.step.id)},this.onToolsContextEnd),await E.start(this.thread)}cancel(){this.end({status:"cancel"})}complete(){let{chatCompletion:e}=this.state;if(e==null)throw new h("Missing chat completion content to return value",{code:p.STEP_LOGIC_ISSUE});this.end({status:"ok",chatCompletion:e,toolsResults:this.state.toolsResults??[]})}};Y([u,R("design:type",Function),R("design:paramtypes",[]),R("design:returntype",Object)],L.prototype,"runStep",null);Y([u,R("design:type",Function),R("design:paramtypes",[]),R("design:returntype",void 0)],L.prototype,"initialize",null);Y([u,R("design:type",Function),R("design:paramtypes",[typeof IActionEvent>"u"?Object:IActionEvent]),R("design:returntype",Promise)],L.prototype,"onRequestContextEnd",null);Y([u,R("design:type",Function),R("design:paramtypes",[typeof IActionEvent>"u"?Object:IActionEvent]),R("design:returntype",Promise)],L.prototype,"onToolsContextEnd",null);Y([Et({tags:$e}),R("design:type",Function),R("design:paramtypes",[]),R("design:returntype",Promise)],L.prototype,"initToolsContextThread",null);function Ge(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(Ge,"_ts_decorate");function K(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(K,"_ts_metadata");var F=class extends L{static{l(this,"SimpleContentContext")}static class="cnt_cxt_smp";static getInitialState(){return{requestComplete:!1}}async onHandleContent(e){let{content:t}=e.params;this.state.chatCompletion=t;let r=t.choices[0]?.message.tool_calls;if(r!=null)for(let i of r)await this.callFunction(i)}onAllContentReceived(){this.handleMultipleChoices()}tryToComplete(){let{requestComplete:e,toolsReady:t}=this.state;!e||t===!1||this.complete()}};Ge([u,K("design:type",Function),K("design:paramtypes",[typeof SimpleContentContextHandleContentEvent>"u"?Object:SimpleContentContextHandleContentEvent]),K("design:returntype",Promise)],F.prototype,"onHandleContent",null);Ge([u,K("design:type",Function),K("design:paramtypes",[]),K("design:returntype",void 0)],F.prototype,"onAllContentReceived",null);var qe="str_wrk",ze={chunk:"chunk"};function Tt(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(Tt,"_ts_decorate");function Ce(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(Ce,"_ts_metadata");var A=class extends C{static{l(this,"StreamContentContextWorker")}static class=qe;static async start(e,t){await k(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class,event:t}})}static isBusy(e){return Ie(e,this.getThreadId(e.step.id))}static getThreadId(e){return`${I}_${this.class}_${e}`}runStep(){if(!("event"in this.state)||this.state.event==null)throw new h("Stream worker thread state must contain an event to process",{code:p.STEP_LOGIC_ISSUE});let e=this.state.event;this.log.DEBUG?.("Executing stream worker thread",e),this.exitStep(ze.chunk,{chunk:e})}};Tt([M,Ce("design:type",Function),Ce("design:paramtypes",[]),Ce("design:returntype",void 0)],A.prototype,"runStep",null);import{ACTION as wt}from"@onereach/flow-sdk/types/index.js";import{clear as xt,Memoize as Ve}from"typescript-memoize";import{z as d}from"zod/v4-mini";var We=d.looseObject({name:d.string(),params:d.looseObject({content:d.looseObject({id:d.string(),object:d.literal("chat.completion.chunk"),created:d.number(),model:d.string(),service_tier:d.nullish(d.enum(["default","auto","flex","scale","priority"])),choices:d.array(d.looseObject({index:d.number().check(d.int(),d.gte(0)),delta:d.looseObject({role:d.optional(d.enum(["developer","system","user","assistant","tool"])),content:d.nullish(d.string()),refusal:d.nullish(d.string()),tool_calls:d.optional(d.array(d.looseObject({index:d.number().check(d.int(),d.gte(0)),id:d.optional(d.string()),type:d.optional(d.literal("function")),function:d.looseObject({name:d.optional(d.string()),arguments:d.optional(d.string())})})))}),logprobs:d.nullish(d.any()),finish_reason:d.nullable(d.enum(["stop","length","tool_calls","content_filter"]))})),logprobs:d.nullish(d.looseObject({content:d.nullable(d.array(d.looseObject({}))),refusal:d.nullable(d.array(d.looseObject({})))})),usage:d.nullish(d.looseObject({prompt_tokens:d.number(),completion_tokens:d.number(),total_tokens:d.number(),completion_tokens_details:d.optional(d.looseObject({accepted_prediction_tokens:d.optional(d.number()),audio_tokens:d.optional(d.number()),reasoning_tokens:d.optional(d.number()),rejected_prediction_tokens:d.optional(d.number())})),prompt_tokens_details:d.optional(d.looseObject({audio_tokens:d.optional(d.number()),cached_tokens:d.optional(d.number())}))}))})})});var pe=class{static{l(this,"StreamReducerService")}_result;_onToolCall;constructor(e,t){this._result=e,this._onToolCall=t}reduceChunk(e){if(Object.keys(this._result).length===0){let{choices:t,...r}=e;Object.assign(this._result,r),this._result.object!=null&&(this._result.object="chat.completion")}e.usage&&(this._result.usage=e.usage);for(let t of e.choices){let r=this._result.choices?.[t.index];if(!r){let{delta:i,...o}=t;r=o,this._result.choices??=[],this._result.choices[t.index]=r}if(t.finish_reason!=null&&(r.finish_reason=t.finish_reason),t.logprobs!=null&&(r.logprobs=t.logprobs),t.delta?.content!==void 0){let{content:i,...o}=t.delta;r.message??=o,i===null?r.message.content??=null:(r.message.content??="",r.message.content+=i)}if(t.delta?.tool_calls!=null){let{tool_calls:i,...o}=t.delta;r.message??=o,r.message.tool_calls??=[];for(let a of t.delta.tool_calls){let c=a.index;if(r.message.tool_calls[c]==null)r.message.tool_calls[c]=structuredClone(a);else{let f=r.message.tool_calls[c];if(!("function"in f)||f.function==null)continue;f.function.arguments+=a.function?.arguments??""}t.index===0&&this.tryParseToolCall(r.message.tool_calls[c])}}}}tryParseToolCall(e){try{if(!("function"in e)||e.function==null)return;let t=JSON.parse(e.function.arguments);this._onToolCall(e,t)}catch{}}};var Ke="cnt_cxt_str";function V(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(V,"_ts_decorate");function T(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(T,"_ts_metadata");var Ee=["streamInit"],O=class n extends L{static{l(this,"StreamContentContext")}static class=Ke;static getInitialState(){return{class:n.class,requestComplete:!1,workerComplete:!1,partialChatCompletion:{},events:[],lastChunkReceived:!1,index:-1}}async runStep(){await super.runStep(),xt(Ee),this.triggers.hook({name:wt.end,thread:A.getThreadId(this.thread.step.id)},this.onWorkerThreadEnd)}onWorkerThreadEnd(e){let{result:t}=e.params.thread;if(this.log.DEBUG?.(`${A.name} thread finished processing chunk`,t),t instanceof Error)throw x(t,{unknownMessage:`${A.name} thread ended with an error`});t?.status!=="cancel"&&this.tryRunWorker()}onHandleContent(e){let r=We.parse(e).params.content;new pe(this.state.partialChatCompletion,this.onToolCall.bind(this)).reduceChunk(r);for(let o of r.choices){if(o.index>0)continue;let a=o.delta?.content;a!=null&&a.length>0&&(this.addContentToQueue(a),this.scheduleNextContentEvent())}}onAllContentReceived(){this.log.DEBUG?.("All LLM response chunks were received. No more response chunks expected"),this.state.chatCompletion=this.state.partialChatCompletion,this.handleMultipleChoices(),this.state.events.push({lastChunkReceived:!0}),this.state.lastChunkReceived=!0,this.tryRunWorker()}onToolCall(e){this.log.DEBUG?.("Tool call received",e),this.callFunction(e)}scheduleNextContentEvent(){let e=this.state.events[0];e==null||!this.isEventReady(e)||"lastChunkReceived"in e||this.tryRunWorker()}addContentToQueue(e){let t=this.state.events.at(-1);if(t!=null){if("lastChunkReceived"in t){this.log.WARN?.("A new chunk received after the `lastChunkReceived` event. Ignoring it.");return}if(t.content.length<this.maxChunkContentLength){let r=`${t.content}${e}`;t.content=r.slice(0,this.maxChunkContentLength),e=r.slice(this.maxChunkContentLength)}}for(;e;){this.state.index+=1;let r={content:e.slice(0,this.maxChunkContentLength),index:this.state.index,ts:Date.now()};this.log.DEBUG?.("Add new event into the queue",r),this.state.events.push(r),e=e.slice(this.maxChunkContentLength)}}tryRunWorker(){if(A.isBusy(this.thread)){this.log.DEBUG?.("Skip event processing. Worker thread is busy");return}let e=this.getEventToProcess();if(e!=null){if("lastChunkReceived"in e){this.log.DEBUG?.(`Stopping ${n.name} thread. All response content chunks were processed and no new chunks are coming`),this.state.workerComplete=!0,this.tryToComplete();return}this.log.DEBUG?.("Notify stream worker thread about response chunk to process",e),A.start(this.thread,e)}}isEventReady(e){if(e==null)return!1;if("lastChunkReceived"in e)return!0;if(e.content==null)return!1;let t=Date.now()-e.ts;return this.state.lastChunkReceived||t>=this.debounceDuration||e.content.length>=this.maxChunkContentLength}getEventToProcess(){let e=this.state.events[0];if(e!=null&&this.isEventReady(e))return"lastChunkReceived"in e||this.state.events.shift(),e}tryToComplete(){let{chatCompletion:e,toolsReady:t,requestComplete:r,workerComplete:i}=this.state;if(!i||!r||t===!1||e==null)return;if(e.choices?.[0]?.message==null)throw new h("Missing completion message in chat completion result",{code:p.STEP_LOGIC_ISSUE});this.complete()}get maxChunkContentLength(){return this.data.streamSettings?.maxBufferLength??100}get debounceDuration(){return this.data.streamSettings?.debounceDuration??200}};V([u,T("design:type",Function),T("design:paramtypes",[]),T("design:returntype",Promise)],O.prototype,"runStep",null);V([u,T("design:type",Function),T("design:paramtypes",[typeof IActionEvent>"u"?Object:IActionEvent]),T("design:returntype",void 0)],O.prototype,"onWorkerThreadEnd",null);V([u,T("design:type",Function),T("design:paramtypes",[typeof StreamContentContextHandleContentEvent>"u"?Object:StreamContentContextHandleContentEvent]),T("design:returntype",void 0)],O.prototype,"onHandleContent",null);V([u,T("design:type",Function),T("design:paramtypes",[]),T("design:returntype",void 0)],O.prototype,"onAllContentReceived",null);V([Ve({tags:Ee}),T("design:type",Number),T("design:paramtypes",[])],O.prototype,"maxChunkContentLength",null);V([Ve({tags:Ee}),T("design:type",Number),T("design:paramtypes",[])],O.prototype,"debounceDuration",null);import{ACTION as Qe}from"@onereach/flow-sdk/types/index.js";import{Memoize as _t}from"typescript-memoize";function bt(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(bt,"_ts_decorate");function Te(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(Te,"_ts_metadata");var ee=class n{static{l(this,"ContentContextUtilities")}static factory(e){let t=e?O:F;return new n(t)}Constructor;constructor(e){this.Constructor=e}async start(e){let t=this.Constructor.getInitialState();await k(e,{id:this.getThreadId(e.step.id),state:{...t,requestComplete:!1,step:e.step.id,class:this.Constructor.class},background:!0})}async cancel(e){await J(e,this.getThreadId(e.step.id),{result:{status:"cancel"},stopChildThreads:!0})}getThreadId(e){return`${I}_${this.Constructor.class}_${e}`}};bt([_t(),Te("design:type",Function),Te("design:paramtypes",[Boolean]),Te("design:returntype",Object)],ee,"factory",null);import{readFile as vt}from"fs/promises";import{createRequire as Rt}from"module";var St=Rt(import.meta.url);async function Je(n){if(typeof n!="string"||!/^\d+\.\d+\.\d+$/.test(n))throw new Error(`Invalid minimum version format: ${n}`);let e=St.resolve("@onereach/flow-sdk/package.json");if(!e)throw new Error("Could not find package.json for @onereach/flow-sdk");let t=await vt(e,"utf8"),{version:r}=JSON.parse(t),{groups:i}=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)/.exec(r)||{};if(!i)throw new Error(`Invalid Flow SDK version format: ${r}`);let o=Number.parseInt(i.major??"0",10),a=Number.parseInt(i.minor??"0",10),c=Number.parseInt(i.patch??"0",10);if(o==null||a==null||c==null||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(c))throw new Error(`Invalid version format: ${r}`);let[f,w,m]=n.split(".").map(ne=>Number.parseInt(ne,10));if(f==null||w==null||m==null||Number.isNaN(f)||Number.isNaN(w)||Number.isNaN(m))throw new Error(`Invalid minimum version format: ${n}`);if(o<f||o===f&&a<w||o===f&&a===w&&c<m)throw new Error(`Flow SDK version '${r}' is lower than required minimum version '${n}' for the step`)}l(Je,"validateFlowSdkVersion");function te(n,e,t,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,e,t,r);else for(var c=n.length-1;c>=0;c--)(a=n[c])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o}l(te,"_ts_decorate");function S(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}l(S,"_ts_metadata");var It="8.0.72",H=class extends C{static{l(this,"CreateChatCompletionStep")}runStep(){this.triggers.hook({name:Qe.end,thread:this.contentContext.getThreadId(this.thread.step.id)},this.onContentContextEnd),this.triggers.hook({name:Qe.end,thread:g.getThreadId(this.thread.step.id)},this.onHistoryContextEnd),this.triggers.local(se.cancel,this.onCancel),this.triggers.otherwise(this.initialize)}async initialize(){await Je(It),this.validateMergeFieldType(),this.resetState(),this.state.cancelled=!1,await Promise.all([g.start(this.thread),j.start(this.thread)]),await g.prepareHistory(this.thread),await this.contentContext.start(this.thread)}async onContentContextEnd(e){try{let{result:t}=e.params.thread;if(this.log.DEBUG?.("ContentContext thread ended with result",t),t==null)throw new h("ContentContext thread ended unexpectedly",{code:p.STEP_LOGIC_ISSUE});if(t instanceof Error)throw x(t,{unknownMessage:"ContentContext thread ended with an error",unknownCode:p.STEP_LOGIC_ISSUE});if(t.status==="cancel"){await this.resetStep();return}let{status:r,chatCompletion:i,toolsResults:o}=t;if(r!=="ok"||i==null||o==null)throw new h("Unexpected end of the ContentContext thread",{code:p.STEP_LOGIC_ISSUE,data:e.params.result});this.log.DEBUG?.("Create Chat Completion result",i),this.state.contentReady=!0,this.state.chatCompletion=i,this.state.toolsResults=o,await this.tryToExitStep()}catch(t){throw await this.resetStep().catch(()=>{}),t}}async onHistoryContextEnd(e){try{let{result:t}=e.params.thread;if(this.log.DEBUG?.(`${g.name} thread ended with result`,t),t instanceof Error)throw x(t,{unknownMessage:`${g.name} thread ended with an error`,unknownCode:p.STEP_LOGIC_ISSUE})}catch(t){throw await j.stop(this.thread).catch(()=>{}),t}}async onCancel(){await this.resetStep()}async tryToExitStep(){let{cancelled:e,contentReady:t,chatCompletion:r,toolsResults:i}=this.state;if(e){this.resetState();return}if(!t)return;if(r==null)throw new h("Missing chat completion result, but request is marked as processed",{code:p.STEP_LOGIC_ISSUE});let o=r.choices?.[0]?.message;if(o==null)throw new h("Missing completion message in chat completion result",{code:p.STEP_LOGIC_ISSUE});await Promise.all([g.appendToHistory(this.thread,[o,...i]),j.stop(this.thread)]);let a=r.choices[0]?.finish_reason;if(a==="length")throw new h("Reached limit of tokens for LLM completion response",{code:p.LLM_FINISH_LENGTH});if(a==="tool_calls"){this.thread.jumpTo(this.currentStepId);return}this.log.DEBUG?.("Exiting step with collected data",r),this.exitStep("next",r)}async resetStep(){this.resetState(),this.state.cancelled=!0;let t=(await Promise.allSettled([he(this.thread,{status:"cancel"}),g.adjustOnCancel(this.thread)])).find(r=>r.status==="rejected");if(t)throw t.reason}resetState(){this.state.contentReady=!1,this.state.chatCompletion=void 0,this.state.toolsResults=[]}validateMergeFieldType(){let{functionsList:e}=this.data;if(!(!Array.isArray(e)||e.length===0)&&(this.dataOut==null||this.getMergeField(this.dataOut).type!=="thread"))throw new h('Merge-field type has to be "Thread" if you are using functions',{code:p.VALIDATION})}get contentContext(){let e=this.data.streamResponse;return ee.factory(e)}};te([M,S("design:type",Function),S("design:paramtypes",[]),S("design:returntype",void 0)],H.prototype,"runStep",null);te([M,S("design:type",Function),S("design:paramtypes",[]),S("design:returntype",Promise)],H.prototype,"initialize",null);te([u({allowHandleError:!0}),S("design:type",Function),S("design:paramtypes",[typeof IActionEvent>"u"?Object:IActionEvent]),S("design:returntype",Promise)],H.prototype,"onContentContextEnd",null);te([u({allowHandleError:!0}),S("design:type",Function),S("design:paramtypes",[typeof IActionEvent>"u"?Object:IActionEvent]),S("design:returntype",Promise)],H.prototype,"onHistoryContextEnd",null);te([M,S("design:type",Function),S("design:paramtypes",[]),S("design:returntype",Promise)],H.prototype,"onCancel",null);Ot();var Xr={[g.class]:g,[_.class]:_,[E.class]:E,[P.class]:P,[F.class]:F,[O.class]:O,[A.class]:A,[j.class]:j};export{Xr as states,H as step};
|
|
1
|
+
import{createRequire as e}from"node:module";import{install as t}from"source-map-support";import{ACTION as n}from"@onereach/flow-sdk/types/index.js";import r from"@onereach/flow-sdk/errors/timeout.js";import*as i from"zod/mini";import a from"@onereach/flow-sdk/errors/base.js";import o from"@onereach/flow-sdk/step.js";import{setImmediate as s}from"node:timers/promises";import{Memoize as c,clear as l}from"typescript-memoize";import{BasicThreadService as u}from"@onereach/flow-sdk/services/basic.js";import d from"openai";import ee from"timestring";import{readFile as te}from"node:fs/promises";const f={UNKNOWN:`UNKNOWN`,STEP_LOGIC_ISSUE:`STEP_LOGIC_ISSUE`,AUTH:`AUTH`,TIMEOUT:`TIMEOUT`,VALIDATION:`VALIDATION`,INVALID_REQUEST:`INVALID_REQUEST`,RATE_LIMITED:`RATE_LIMITED`,LLM_FINISH_LENGTH:`LLM_FINISH_LENGTH`,SERVER_ERROR:`SERVER_ERROR`,UNSUPPORTED:`UNSUPPORTED`};var p=class extends a{},ne=class extends a{};i.config(i.locales.en());const re=[p,r];function m(e,t={}){let{preserveErrors:n=re,unknownMessage:a=`Unknown error`,unknownCode:o=f.UNKNOWN}=t;if(n?.some(t=>e instanceof t))return e;if(e instanceof i.core.$ZodError)return new p(i.prettifyError(e),e,{code:f.VALIDATION});if(typeof e==`string`)return new p(e,{code:f.UNKNOWN});if(e instanceof Error){if(e.message.includes(`Request timed out`))return new r(`Timeout`,e,{code:f.TIMEOUT});let t=e?.response?.data?.error?.message;return t==null?new p(a,e,{code:o}):new p(t,e,{code:f.SERVER_ERROR})}return new p(a,{code:o,data:e})}function h(e,t){function n(t,n,r,i){let a=e(t,n,r,i);if(typeof a==`function`){let e=i.value,t=a;if(e?.name!=null)try{Object.defineProperty(t,`name`,{value:e.name})}catch{}return i.value=t,i}return a??i}return function(e,r,i){if(typeof e==`object`&&e&&(typeof r==`string`||typeof r==`symbol`)&&typeof i==`object`&&i)return n(t,e,r,i);{let r=e??t;return(e,t,i)=>n(r,e,t,i)}}}const g=h((e,t,n,r)=>{let i=r.value;if(!(!i||typeof i!=`function`))return function(...t){try{let r=i.apply(this,t);return r instanceof Promise?r.catch(t=>_.call(this,e,t,n)):r}catch(t){return _.call(this,e,t,n)}}},{allowHandleError:!1,useErrorFilter:!0});function _(e,t,r){let i=r.toString();this.log.DEBUG?.(`Error in method '${i}'`,t);let a=e.useErrorFilter?m(t):t;if(a instanceof Error)if(e.allowHandleError){this.thread.enqueue({name:n.error,error:a});return}else{this.end(a);return}throw a}function ie({thread:e,...t}){let n=b({thread:e,...t}),r=e.process;if(r.cache[n]!=null)throw Error(`AbortController for key '${n}' already exists`);return r.cache[n]=new AbortController}function v({thread:e,...t}){let n=b({thread:e,...t});return e.process.cache[n]}function y({thread:e,...t}){let n=b({thread:e,...t});delete e.process.cache[n]}function b({thread:e,prefix:t,stepId:n=e.currentStepId}){return`${t?`${t}:`:``}abrt_ctrl:${n}`}async function x(e,{id:t,state:r,local:i,...a},{force:o}={}){let s=e.process.getThread(t);if(e.log.DEBUG?.(`runThread: thread with id '${t}'`,a),s==null)return await e.thread.runThread({...a,id:t,state:r,local:{...i,parent:e.thread.id,active:!0}});if(!o&&!s.ended&&s.local.active)throw Error(`Thread with id '${t}' has not ended yet, cannot start it again`);if(r==null)throw Error(`Thread with id '${t}' must have a state to run`);return s.local.active=!0,await s.enqueueAndRun({name:n.goto,state:{...r,active:!0}})}function ae(e,t){let n=e.process.getThread(t);return!!(n!=null&&n.local.active&&!n.ended)}function oe(e,t=e.id){let n=[];for(let r in e.process.threads){let i=e.process.threads[r];i?.local.parent===t&&n.push(i)}return n}async function S(e,t,{result:r,stopChildThreads:i}={}){let a=e.process.getThread(t);e.log.DEBUG?.(`stopThread: thread with id '${t}'`),a&&(i&&await C(a,r),a.local.active&&(a.local.active=!1,!a.ended&&await a.enqueueAndRun({name:n.ending,result:r})))}async function C(e,t,n={}){let r=oe(e).map(async n=>await S(e,n.id,{stopChildThreads:!0,result:t})),i=await Promise.allSettled(r);if(n.throw??!0){let e=i.find(e=>e.status===`rejected`);if(e)throw e.reason}return i}const w=h((e,t,n,r)=>{let i=r.value;if(!(!i||typeof i!=`function`))return function(...e){try{let t=i.apply(this,e);return t instanceof Promise?t.catch(e=>{let t=n.toString();throw this.log.DEBUG?.(`Error in method '${t}'`,e),m(e)}):t}catch(e){let t=n.toString();throw this.log.DEBUG?.(`Error in method '${t}'`,e),m(e)}}},{});i.config(i.locales.en());const T=i.string().check(i.trim(),i.refine(e=>![`undefined`,`null`].includes(e),{error:`Unexpected undefined or null merge-field value`})),E=i.discriminatedUnion(`role`,[i.object({role:i.literal(`system`),content:T}),i.object({role:i.literal(`user`),content:T,name:i.optional(T.check(i.minLength(1),i.maxLength(64)))}),i.object({role:i.literal(`assistant`),content:i.nullable(T),tool_calls:i.optional(i.array(i.object({id:T.check(i.minLength(1)),type:i.literal(`function`),function:i.object({name:T.check(i.minLength(1)),arguments:T.check(i.minLength(1))})})))}),i.object({role:i.literal(`tool`),content:T,name:i.optional(T.check(i.minLength(1),i.maxLength(64))),tool_call_id:T.check(i.minLength(1))})]),se=i.object({type:i.literal(`object`),properties:i.record(i.string().check(i.minLength(1),i.maxLength(64)),i.object({type:i.enum([`string`,`number`,`boolean`,`array`,`object`]),description:i.optional(i.string().check(i.maxLength(1e3))),items:i.optional(i.object({type:i.enum([`string`,`number`,`boolean`,`object`]),description:i.optional(i.string().check(i.maxLength(1e3)))}))}))}),ce=i.object({provider:T.check(i.minLength(1)),model:T.check(i.minLength(1)),accountKey:D(T),typeOfStep:i.enum([`chat`,`completion`]),systemMessage:i.optional(T),userMessage:i.optional(T),switchAssistantsMessage:i._default(i.boolean(),!1),assistantsFirstMessage:i.optional(T),temperature:D(i.coerce.number().check(i.gte(0),i.lte(2))),topP:D(i.coerce.number().check(i.gte(0),i.lte(1))),maxTokens:D(i.coerce.number().check(i.int(),i.gte(1))),presencePenalty:D(i.coerce.number().check(i.gte(-2),i.lte(2))),frequencyPenalty:D(i.coerce.number().check(i.gte(-2),i.lte(2))),n:D(i.coerce.number().check(i.int(),i.gte(1),i.lte(128))),stop:i.optional(i.array(i.object({token:i.string().check(i.minLength(1),i.maxLength(64))})).check(i.maxLength(4))),reasoningEffort:D(i.enum([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`])),streamResponse:i._default(i.boolean(),!1),streamSettings:i.optional(i.object({maxBufferLength:i.coerce.number().check(i.overwrite(e=>e===0?50:e),i.int(),i.gte(1),i.lte(32768)),debounceDuration:i.coerce.number().check(i.int(),i.gte(0),i.lte(1e4))})),customHistory:i._default(i.boolean(),!1),historyLength:D(i.coerce.number().check(i.int(),i.gte(1),i.lte(100))),historyMode:i.optional(i.enum([`mergefield`,`codeHistory`])),historyMergefield:i.optional(i.array(E)),historyCode:i.optional(i.array(E)),functionsList:i.array(i.object({name:T.check(i.minLength(1),i.maxLength(64)),description:i.optional(T.check(i.maxLength(1e3))),parameters:i.optional(i.pipe(se,i.transform(e=>(e.required=Object.keys(e.properties),e.additionalProperties=!1,e)))),strict:i.boolean()})),useState:i.optional(i.boolean()),stateSettings:i.optional(i.object({stateFunction:i.function()})),processError:i.boolean(),processTimeout:i.boolean(),timeoutDuration:T.check(i.trim(),i.minLength(1))}).check(i.refine(e=>!e.streamResponse||e.provider===`openai`,{error:`Streaming is only supported for OpenAI provider`}),i.refine(e=>!e.streamResponse||e.streamSettings!==void 0,{error:`Missing "Stream settings" for response streaming mode`}),i.refine(e=>e.typeOfStep!==`chat`||e.customHistory||!e.switchAssistantsMessage||e.assistantsFirstMessage!==void 0,{error:`Missing "Assistant's first message" value`}),i.refine(e=>e.customHistory||e.userMessage!==void 0,{error:`Missing "User message" value`}),i.refine(e=>e.typeOfStep!==`chat`||!e.customHistory||e.historyMode!==void 0,{error:`Missing "History mode" value`}),i.refine(e=>e.typeOfStep!==`chat`||!e.customHistory||e.historyMode!==`mergefield`||e.historyMergefield!==void 0,{error:`Missing "History" data via merge-field`}),i.refine(e=>e.typeOfStep!==`chat`||!e.customHistory||e.historyMode!==`mergefield`||e.historyMergefield?.find?.(e=>e.role===`user`),{error:`Missing at least one message with role "user" message in "History" data via merge-field`}),i.refine(e=>e.typeOfStep!==`chat`||!e.customHistory||e.historyMode!==`codeHistory`||e.historyCode!==void 0,{error:`Missing "History" data as code`}),i.refine(e=>e.typeOfStep!==`chat`||!e.customHistory||e.historyMode!==`codeHistory`||e.historyCode?.find?.(e=>e.role===`user`),{error:`Missing at least one message with role "user" message in "History" data via code`}),i.refine(e=>!e.useState||e.stateSettings!=null,{error:`Missing state settings`}));function D(e){return i.optional(i.pipe(i.union([i.undefined(),i.literal(``),e]),i.transform(e=>e===``?void 0:e)))}function O(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function k(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var A=class extends o{async resolveDataIn(){let e=await super.resolveDataIn();return ce.parse(e)}};k([w,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Promise)],A.prototype,`resolveDataIn`,null);const j=`llm_cmp`,M={cancel:`st_cancel`},le={cancel:`cnl_cancel`};var N=class e extends A{static class=`cncl_ctrl`;static async start(e){await x(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class},background:!0},{force:!0})}static async stop(e){await S(e,this.getThreadId(e.step.id))}static getThreadId(e){return`${j}_${this.class}_${e}`}runStep(){this.triggers.local({name:le.cancel},this.onCancel).otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ${e.name} thread`)}onCancel(){this.log.DEBUG?.(`Canceling LLM request`);let e=this.local.parent,t=this.process.getThread(e);if(!t||t.ended)return this.end();let n=v({thread:this.thread});n?n.abort(new ne(`Request cancelled`)):this.process.enqueueAndRun({name:M.cancel,thread:e})}};k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],N.prototype,`runStep`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],N.prototype,`initialize`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],N.prototype,`onCancel`,null);const P={appendToHistory:`hst_append`,prepareHistory:`hst_prepare`,adjustOnCancel:`hst_cncl`};var F=class e extends A{static class=`hst_ctrl`;static async start(e){let t=this.getThreadId(e.step.id);e.process.getThread(t)??await e.process.runThread({id:t,background:!0,state:{step:e.step.id,class:this.class,messages:[]}})}static async prepareHistory(e){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:P.prepareHistory})}static async appendToHistory(e,t){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:P.appendToHistory,params:{message:t}})}static async adjustOnCancel(e){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:P.adjustOnCancel})}static getHistory(e){return e.process.getSafeThread(this.getThreadId(e.step.id)).state.messages}static getThreadId(e){return`${j}_${this.class}_${e}`}runStep(){this.triggers.local(P.prepareHistory,this.onPrepareHistory).local(P.appendToHistory,this.onAppendToHistory).local(P.adjustOnCancel,this.onAdjustOnCancel).otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ${e.name} thread`)}onAdjustOnCancel(){let e;for(;(e=this.state.messages.at(-1))&&!([`system`,`user`].includes(e.role)||e.role===`assistant`&&e.tool_calls==null);){let e=this.state.messages.pop();this.log.DEBUG?.(`Removed message from history`,e)}}onPrepareHistory(){this.log.DEBUG?.(`Preparing history`);let{customHistory:e,historyLength:t,systemMessage:n,typeOfStep:r,userMessage:i,historyMode:a,historyMergefield:o,historyCode:s,assistantsFirstMessage:c}=this.data;if(r===`completion`){this.state.messages=[{role:`user`,content:i}];return}if(e){this.state.messages=a===`mergefield`?o:s;return}let l=this.state.messages;if(l.length===0&&c!=null&&c.length>0&&l.push({role:`assistant`,content:c}),l.at(-1)?.role!==`tool`&&l.push({role:`user`,content:i}),!l.some(e=>e.role===`tool`)&&t!=null&&t>0&&(l=l.slice(-1*t)),n!=null&&n.length>0){let e={role:`system`,content:n};l[0]?.role===`system`?l[0]=e:l.unshift(e)}this.state.messages=l}onAppendToHistory(e){this.log.DEBUG?.(`Appending message to history`,e.params);let{message:t}=e.params,n=Array.isArray(t)?t:[t];this.state.messages.push(...n)}};k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],F.prototype,`runStep`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],F.prototype,`initialize`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],F.prototype,`onAdjustOnCancel`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],F.prototype,`onPrepareHistory`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,void 0)],F.prototype,`onAppendToHistory`,null);const I={handleContent:`hnd_cnt`};var L=class extends u{async handleContentByParentThread(e){await s(),await this.thread.process.enqueueAndRun({thread:this.thread.local.parent,name:I.handleContent,params:{content:e}})}},ue=class extends L{async handle(e){this.log.DEBUG?.(`Start processing response from LLM`),await this.handleContentByParentThread(e),y({thread:this.thread})}},de=class extends L{async handle(e){this.log.DEBUG?.(`Start processing stream of chunks from LLM`);for await(let t of e)await this.handleContentByParentThread(t);y({thread:this.thread})}};function fe({thread:e,isStreaming:t}){return t?new de(e):new ue(e)}var pe=class extends u{data;constructor(e,t){super(e),this.data=t}};i.config(i.locales.en());var R=class extends pe{async makeOpenAiRequest(e,t){let{model:n,temperature:r,topP:i,maxTokens:a,frequencyPenalty:o,presencePenalty:s,n:c,streamResponse:l,reasoningEffort:u}=this.data,d={messages:structuredClone(e),model:n,temperature:r,top_p:i,max_tokens:a,frequency_penalty:o,presence_penalty:s,stop:this.stopSequences,n:c,reasoning_effort:u,stream:l,tools:this.tools};this.log.DEBUG?.(`LLM request`,d);try{let e=await this.openAiClient.chat.completions.create(d,{signal:t});return l||this.log.DEBUG?.(`LLM response`,e),e}catch(e){throw e instanceof Error?new p(`Chat completion request failed`,e,{code:f.SERVER_ERROR,data:d}):e}}get tools(){let{functionsList:e}=this.data;if(!(!Array.isArray(e)||e.length===0))return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:!e.parameters||Object.keys(e.parameters).length===0?void 0:e.parameters,strict:e.strict}}))}get openAiClient(){let{provider:e,accountKey:t}=this.data,n={baseURL:`${this.config.env.OPENAI_API_URL}/${e}`,apiKey:`_fake_key_`,defaultHeaders:{Authorization:this.config.authorization,"x-or-session-id":this.session.get([`reporting`,`sessionId`]),...t?{"x-or-account-token-name":t}:void 0},timeout:this.timeoutMs};return this.log.DEBUG?.(`OpenAI client options`,n),new d(n)}get stopSequences(){return(this.data.stop??[]).map(e=>e.token).filter(e=>e.length>0)}get timeoutMs(){let e=ee(this.data.timeoutDuration,`ms`);return i.number().check(i.int(),i.gte(1e3),i.lte(6e5)).parse(e)}};k([c(),O(`design:type`,Number),O(`design:paramtypes`,[])],R.prototype,`timeoutMs`,null);var z;const B=[`requestInit`];var V=class extends A{static class=`rqst_ctx`;static async start(e){return await x(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class},background:!0})}static getThreadId(e){return`${j}_${this.class}_${e}`}async runStep(){l(B);let e=ie({thread:this.thread});try{let t=await this.openAiService.makeOpenAiRequest(await this.getHistory(),e.signal);await this.responseHandler.handle(t),this.complete()}catch(t){if(e?.signal.aborted)return this.cancel();throw t}finally{y({thread:this.thread})}}cancel(){this.end({status:`cancel`})}complete(){this.end({status:`ok`})}async getHistory(){let e=F.getHistory(this.thread);if(!this.data.useState)return e;let t=[...e],n={role:`assistant`,content:await this.data.stateSettings?.stateFunction()};return e.at(-1)?.role===`user`?t.splice(-1,0,n):t.push(n),t}get openAiService(){return new R(this.thread,this.data)}get responseHandler(){let e=this.data.streamResponse;return fe({thread:this.thread,isStreaming:e})}};k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Promise)],V.prototype,`runStep`,null),k([c(),O(`design:type`,typeof(z=R!==void 0&&R)==`function`?z:Object),O(`design:paramtypes`,[])],V.prototype,`openAiService`,null),k([c({tags:B}),O(`design:type`,Object),O(`design:paramtypes`,[])],V.prototype,`responseHandler`,null);const H={callTool:`tl_run_call`,lastToolCallReceived:`tl_rsp_end`};var U=class extends A{static class=`tl_wrk`;static async start(e,t){let n=JSON.parse(t.function?.arguments);await x(e,{id:this.getThreadId(t),state:{step:e.step.id,class:this.class},local:{toolCall:t,parsedArguments:n,parent:e.id,active:!0}})}static getThreadId(e){return`${j}_${this.class}_${e.id}`}runStep(){let{toolCall:e,parsedArguments:t}=this.local;this.log.DEBUG?.(`Initializing tool worker thread`,e),this.exitStep(this.getExitName(),{function:{name:e.function.name,arguments:t}})}getExitName(){return`function`}};k([w,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],U.prototype,`runStep`,null);var W=class e extends A{static class=`tl_ctrl`;static async start(e){await x(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class,tasks:{},expectMoreTasks:!0},background:!0})}static async callTool(e,t){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:H.callTool,params:{toolCall:t}})}static async lastToolCallReceived(e){await e.process.enqueueAndRun({thread:this.getThreadId(e.step.id),name:H.lastToolCallReceived})}static getThreadId(e){return`${j}_${this.class}_${e}`}runStep(){this.triggers.local(H.callTool,this.onCallTool).local(H.lastToolCallReceived,this.onLastToolCallReceived).otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ${e.name} thread`)}onCallTool(e){let{toolCall:t}=e.params;if(t.type!==`function`)throw new p(`Only function tools are supported at the moment`,{code:f.UNSUPPORTED});this.state.tasks[t.id]={call:t,status:`pending`},this.startToolWorkerThread(t)}onLastToolCallReceived(){this.log.DEBUG?.(`No more tool calls expected`,this.state.tasks),this.state.expectMoreTasks=!1,this.tryEndToolsContextThread()}onWorkerThreadEnd(e){this.log.DEBUG?.(`Tool caller worker thread has ended`,e);let{result:t}=e.params.thread;if(t==null)throw new p(`${U.name} thread ended unexpectedly`,{code:f.STEP_LOGIC_ISSUE});if(t instanceof Error)throw m(t,{unknownMessage:`${U.name} thread ended with an error`,unknownCode:f.STEP_LOGIC_ISSUE});t.status!==`cancel`&&(this.log.DEBUG?.(`Tool worker thread completed successfully`,{toolCallId:t.toolCallId,result:t.data}),this.setToolCallResult(t.toolCallId,t.data),this.tryEndToolsContextThread())}startToolWorkerThread(e){this.triggers.hook({name:n.end,thread:U.getThreadId(e)},this.onWorkerThreadEnd),U.start(this.thread,e)}setToolCallResult(e,t){let n=this.state.tasks[e];if(n==null)throw new p(`Unknown tool call with id '${e}'`,{code:f.STEP_LOGIC_ISSUE});n.status=`completed`,n.result=t}tryEndToolsContextThread(){this.state.expectMoreTasks||Object.values(this.state.tasks).some(e=>e.status===`pending`)||(this.log.DEBUG?.(`All tool calls completed or failed`,this.state.tasks),this.end({status:`ok`,messages:this.messages}))}get messages(){return Object.values(this.state.tasks).map(e=>({role:`tool`,tool_call_id:e.call.id,content:JSON.stringify(e.result)}))}};k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],W.prototype,`runStep`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],W.prototype,`initialize`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,void 0)],W.prototype,`onCallTool`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],W.prototype,`onLastToolCallReceived`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,void 0)],W.prototype,`onWorkerThreadEnd`,null);const G=[`toolsInit`];var K=class extends A{static get class(){throw Error(`Define "class" static field`)}static getInitialState(){throw Error(`Define "getInitialState" static method`)}runStep(){l(G),this.triggers.local(I.handleContent,this.onHandleContent).hook({name:n.end,thread:V.getThreadId(this.thread.step.id)},this.onRequestContextEnd).otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ${this.constructor.name} thread`),V.start(this.thread)}async onRequestContextEnd(e){let{result:t}=e.params.thread;if(this.log.DEBUG?.(`${V.name} thread ended with result`,t),t==null)throw new p(`${V.name} thread ended unexpectedly`,{code:f.STEP_LOGIC_ISSUE});if(t instanceof Error)throw m(t,{unknownMessage:`${V.name} thread ended with an error`,unknownCode:f.STEP_LOGIC_ISSUE});if(t.status===`cancel`)return this.cancel();if(t.status!==`ok`)throw new p(`Unexpected end of the ${V.name} thread`,{code:f.STEP_LOGIC_ISSUE,data:e.params.result});this.state.requestComplete=!0,await this.onAllContentReceived(),this.state.toolsReady!=null&&(await s(),await W.lastToolCallReceived(this.thread)),await this.tryToComplete()}async onToolsContextEnd(e){let{result:t}=e.params.thread;if(this.log.DEBUG?.(`${W.name} thread ended`,t),t==null)throw new p(`${W.name} thread ended unexpectedly`,{code:f.STEP_LOGIC_ISSUE});if(t instanceof Error)throw m(t,{unknownMessage:`${W.name} thread ended with an error`,unknownCode:f.STEP_LOGIC_ISSUE});if(t.status===`cancel`)return;let{status:n,messages:r}=t;if(n!==`ok`||!Array.isArray(r))throw new p(`Unexpected end of the ${W.name} thread`,{code:f.STEP_LOGIC_ISSUE,data:e.params.result});this.state.toolsResults=r,this.state.toolsReady=!0,await this.tryToComplete()}async callFunction(e){this.state.toolsReady=!1,await this.initToolsContextThread(),await W.callTool(this.thread,e)}handleMultipleChoices(){let{chatCompletion:e}=this.state,t=e?.choices??[];t?.length>1&&this.log.WARN?.(`Multiple choices received from LLM, but only the first one will be processed`,{choices:t.length})}async initToolsContextThread(){this.triggers.hook({name:n.end,thread:W.getThreadId(this.thread.step.id)},this.onToolsContextEnd),await W.start(this.thread)}cancel(){this.end({status:`cancel`})}complete(){let{chatCompletion:e}=this.state;if(e==null)throw new p(`Missing chat completion content to return value`,{code:f.STEP_LOGIC_ISSUE});this.end({status:`ok`,chatCompletion:e,toolsResults:this.state.toolsResults??[]})}};k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Object)],K.prototype,`runStep`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],K.prototype,`initialize`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,Promise)],K.prototype,`onRequestContextEnd`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,Promise)],K.prototype,`onToolsContextEnd`,null),k([c({tags:G}),O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Promise)],K.prototype,`initToolsContextThread`,null);var q=class extends K{static class=`cnt_cxt_smp`;static getInitialState(){return{requestComplete:!1}}async onHandleContent(e){let{content:t}=e.params;this.state.chatCompletion=t;let n=t.choices[0]?.message.tool_calls;if(n!=null)for(let e of n)await this.callFunction(e)}onAllContentReceived(){this.handleMultipleChoices()}tryToComplete(){let{requestComplete:e,toolsReady:t}=this.state;!e||t===!1||this.complete()}};k([g,O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,Promise)],q.prototype,`onHandleContent`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],q.prototype,`onAllContentReceived`,null);const me={chunk:`chunk`};var J=class extends A{static class=`str_wrk`;static async start(e,t){await x(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class,event:t}})}static isBusy(e){return ae(e,this.getThreadId(e.step.id))}static getThreadId(e){return`${j}_${this.class}_${e}`}runStep(){if(!(`event`in this.state)||this.state.event==null)throw new p(`Stream worker thread state must contain an event to process`,{code:f.STEP_LOGIC_ISSUE});let e=this.state.event;this.log.DEBUG?.(`Executing stream worker thread`,e),this.exitStep(me.chunk,{chunk:e})}};k([w,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],J.prototype,`runStep`,null),i.config(i.locales.en());const he=i.looseObject({name:i.string(),params:i.looseObject({content:i.looseObject({id:i.string(),object:i.literal(`chat.completion.chunk`),created:i.number(),model:i.string(),service_tier:i.nullish(i.enum([`default`,`auto`,`flex`,`scale`,`priority`])),choices:i.array(i.looseObject({index:i.number().check(i.int(),i.gte(0)),delta:i.looseObject({role:i.optional(i.enum([`developer`,`system`,`user`,`assistant`,`tool`])),content:i.nullish(i.string()),refusal:i.nullish(i.string()),tool_calls:i.optional(i.array(i.looseObject({index:i.number().check(i.int(),i.gte(0)),id:i.optional(i.string()),type:i.optional(i.literal(`function`)),function:i.looseObject({name:i.optional(i.string()),arguments:i.optional(i.string())})})))}),logprobs:i.nullish(i.any()),finish_reason:i.nullable(i.enum([`stop`,`length`,`tool_calls`,`content_filter`]))})),logprobs:i.nullish(i.looseObject({content:i.nullable(i.array(i.looseObject({}))),refusal:i.nullable(i.array(i.looseObject({})))})),usage:i.nullish(i.looseObject({prompt_tokens:i.number(),completion_tokens:i.number(),total_tokens:i.number(),completion_tokens_details:i.optional(i.looseObject({accepted_prediction_tokens:i.optional(i.number()),audio_tokens:i.optional(i.number()),reasoning_tokens:i.optional(i.number()),rejected_prediction_tokens:i.optional(i.number())})),prompt_tokens_details:i.optional(i.looseObject({audio_tokens:i.optional(i.number()),cached_tokens:i.optional(i.number())}))}))})})});var ge=class{_result;_onToolCall;constructor(e,t){this._result=e,this._onToolCall=t}reduceChunk(e){if(Object.keys(this._result).length===0){let{choices:t,...n}=e;Object.assign(this._result,n),this._result.object!=null&&(this._result.object=`chat.completion`)}e.usage&&(this._result.usage=e.usage);for(let t of e.choices){let e=this._result.choices?.[t.index];if(!e){let{delta:n,...r}=t;e=r,this._result.choices??=[],this._result.choices[t.index]=e}if(t.finish_reason!=null&&(e.finish_reason=t.finish_reason),t.logprobs!=null&&(e.logprobs=t.logprobs),t.delta?.content!==void 0){let{content:n,...r}=t.delta;e.message??=r,n===null?e.message.content??=null:(e.message.content??=``,e.message.content+=n)}if(t.delta?.tool_calls!=null){let{tool_calls:n,...r}=t.delta;e.message??=r,e.message.tool_calls??=[];for(let n of t.delta.tool_calls){let r=n.index;if(e.message.tool_calls[r]==null)e.message.tool_calls[r]=structuredClone(n);else{let t=e.message.tool_calls[r];if(!(`function`in t)||t.function==null)continue;t.function.arguments+=n.function?.arguments??``}t.index===0&&this.tryParseToolCall(e.message.tool_calls[r])}}}}tryParseToolCall(e){try{if(!(`function`in e)||e.function==null)return;let t=JSON.parse(e.function.arguments);this._onToolCall(e,t)}catch{}}};const Y=[`streamInit`];var X=class e extends K{static class=`cnt_cxt_str`;static getInitialState(){return{class:e.class,requestComplete:!1,workerComplete:!1,partialChatCompletion:{},events:[],lastChunkReceived:!1,index:-1}}async runStep(){await super.runStep(),l(Y),this.triggers.hook({name:n.end,thread:J.getThreadId(this.thread.step.id)},this.onWorkerThreadEnd)}onWorkerThreadEnd(e){let{result:t}=e.params.thread;if(this.log.DEBUG?.(`${J.name} thread finished processing chunk`,t),t instanceof Error)throw m(t,{unknownMessage:`${J.name} thread ended with an error`});t?.status!==`cancel`&&this.tryRunWorker()}onHandleContent(e){let t=he.parse(e).params.content;new ge(this.state.partialChatCompletion,this.onToolCall.bind(this)).reduceChunk(t);for(let e of t.choices){if(e.index>0)continue;let t=e.delta?.content;t!=null&&t.length>0&&(this.addContentToQueue(t),this.scheduleNextContentEvent())}}onAllContentReceived(){this.log.DEBUG?.(`All LLM response chunks were received. No more response chunks expected`),this.state.chatCompletion=this.state.partialChatCompletion,this.handleMultipleChoices(),this.state.events.push({lastChunkReceived:!0}),this.state.lastChunkReceived=!0,this.tryRunWorker()}onToolCall(e){this.log.DEBUG?.(`Tool call received`,e),this.callFunction(e)}scheduleNextContentEvent(){let e=this.state.events[0];e==null||!this.isEventReady(e)||`lastChunkReceived`in e||this.tryRunWorker()}addContentToQueue(e){let t=this.state.events.at(-1);if(t!=null){if(`lastChunkReceived`in t){this.log.WARN?.("A new chunk received after the `lastChunkReceived` event. Ignoring it.");return}if(t.content.length<this.maxChunkContentLength){let n=`${t.content}${e}`;t.content=n.slice(0,this.maxChunkContentLength),e=n.slice(this.maxChunkContentLength)}}for(;e;){this.state.index+=1;let t={content:e.slice(0,this.maxChunkContentLength),index:this.state.index,ts:Date.now()};this.log.DEBUG?.(`Add new event into the queue`,t),this.state.events.push(t),e=e.slice(this.maxChunkContentLength)}}tryRunWorker(){if(J.isBusy(this.thread)){this.log.DEBUG?.(`Skip event processing. Worker thread is busy`);return}let t=this.getEventToProcess();if(t!=null){if(`lastChunkReceived`in t){this.log.DEBUG?.(`Stopping ${e.name} thread. All response content chunks were processed and no new chunks are coming`),this.state.workerComplete=!0,this.tryToComplete();return}this.log.DEBUG?.(`Notify stream worker thread about response chunk to process`,t),J.start(this.thread,t)}}isEventReady(e){if(e==null)return!1;if(`lastChunkReceived`in e)return!0;if(e.content==null)return!1;let t=Date.now()-e.ts;return this.state.lastChunkReceived||t>=this.debounceDuration||e.content.length>=this.maxChunkContentLength}getEventToProcess(){let e=this.state.events[0];if(e!=null&&this.isEventReady(e))return`lastChunkReceived`in e||this.state.events.shift(),e}tryToComplete(){let{chatCompletion:e,toolsReady:t,requestComplete:n,workerComplete:r}=this.state;if(!(!r||!n||t===!1||e==null)){if(e.choices?.[0]?.message==null)throw new p(`Missing completion message in chat completion result`,{code:f.STEP_LOGIC_ISSUE});this.complete()}}get maxChunkContentLength(){return this.data.streamSettings?.maxBufferLength??100}get debounceDuration(){return this.data.streamSettings?.debounceDuration??200}};k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Promise)],X.prototype,`runStep`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,void 0)],X.prototype,`onWorkerThreadEnd`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,void 0)],X.prototype,`onHandleContent`,null),k([g,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],X.prototype,`onAllContentReceived`,null),k([c({tags:Y}),O(`design:type`,Number),O(`design:paramtypes`,[])],X.prototype,`maxChunkContentLength`,null),k([c({tags:Y}),O(`design:type`,Number),O(`design:paramtypes`,[])],X.prototype,`debounceDuration`,null);var Z,Q=class e{static factory(t){return new e(t?X:q)}Constructor;constructor(e){this.Constructor=e}async start(e){let t=this.Constructor.getInitialState();await x(e,{id:this.getThreadId(e.step.id),state:{...t,requestComplete:!1,step:e.step.id,class:this.Constructor.class},background:!0})}async cancel(e){await S(e,this.getThreadId(e.step.id),{result:{status:`cancel`},stopChildThreads:!0})}getThreadId(e){return`${j}_${this.Constructor.class}_${e}`}};k([c(),O(`design:type`,Function),O(`design:paramtypes`,[Boolean]),O(`design:returntype`,typeof(Z=Q!==void 0&&Q)==`function`?Z:Object)],Q,`factory`,null);const _e=e(import.meta.url);async function ve(e){if(typeof e!=`string`||!/^\d+\.\d+\.\d+$/.test(e))throw Error(`Invalid minimum version format: ${e}`);let t=_e.resolve(`@onereach/flow-sdk/package.json`);if(!t)throw Error(`Could not find package.json for @onereach/flow-sdk`);let n=await te(t,`utf8`),{version:r}=JSON.parse(n),{groups:i}=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)/.exec(r)||{};if(!i)throw Error(`Invalid Flow SDK version format: ${r}`);let a=Number.parseInt(i.major??`0`,10),o=Number.parseInt(i.minor??`0`,10),s=Number.parseInt(i.patch??`0`,10);if(a==null||o==null||s==null||Number.isNaN(a)||Number.isNaN(o)||Number.isNaN(s))throw Error(`Invalid version format: ${r}`);let[c,l,u]=e.split(`.`).map(e=>Number.parseInt(e,10));if(c==null||l==null||u==null||Number.isNaN(c)||Number.isNaN(l)||Number.isNaN(u))throw Error(`Invalid minimum version format: ${e}`);if(a<c||a===c&&o<l||a===c&&o===l&&s<u)throw Error(`Flow SDK version '${r}' is lower than required minimum version '${e}' for the step`)}var $=class extends A{runStep(){this.triggers.hook({name:n.end,thread:this.contentContext.getThreadId(this.thread.step.id)},this.onContentContextEnd),this.triggers.hook({name:n.end,thread:F.getThreadId(this.thread.step.id)},this.onHistoryContextEnd),this.triggers.local(M.cancel,this.onCancel),this.triggers.otherwise(this.initialize)}async initialize(){await ve(`8.0.72`),this.validateMergeFieldType(),this.resetState(),this.state.cancelled=!1,await Promise.all([F.start(this.thread),N.start(this.thread)]),await F.prepareHistory(this.thread),await this.contentContext.start(this.thread)}async onContentContextEnd(e){try{let{result:t}=e.params.thread;if(this.log.DEBUG?.(`ContentContext thread ended with result`,t),t==null)throw new p(`ContentContext thread ended unexpectedly`,{code:f.STEP_LOGIC_ISSUE});if(t instanceof Error)throw m(t,{unknownMessage:`ContentContext thread ended with an error`,unknownCode:f.STEP_LOGIC_ISSUE});if(t.status===`cancel`){await this.resetStep();return}let{status:n,chatCompletion:r,toolsResults:i}=t;if(n!==`ok`||r==null||i==null)throw new p(`Unexpected end of the ContentContext thread`,{code:f.STEP_LOGIC_ISSUE,data:e.params.result});this.log.DEBUG?.(`Create Chat Completion result`,r),this.state.contentReady=!0,this.state.chatCompletion=r,this.state.toolsResults=i,await this.tryToExitStep()}catch(e){throw await this.resetStep().catch(()=>{}),e}}async onHistoryContextEnd(e){try{let{result:t}=e.params.thread;if(this.log.DEBUG?.(`${F.name} thread ended with result`,t),t instanceof Error)throw m(t,{unknownMessage:`${F.name} thread ended with an error`,unknownCode:f.STEP_LOGIC_ISSUE})}catch(e){throw await N.stop(this.thread).catch(()=>{}),e}}async onCancel(){await this.resetStep()}async tryToExitStep(){let{cancelled:e,contentReady:t,chatCompletion:n,toolsResults:r}=this.state;if(e){this.resetState();return}if(!t)return;if(n==null)throw new p(`Missing chat completion result, but request is marked as processed`,{code:f.STEP_LOGIC_ISSUE});let i=n.choices?.[0]?.message;if(i==null)throw new p(`Missing completion message in chat completion result`,{code:f.STEP_LOGIC_ISSUE});await Promise.all([F.appendToHistory(this.thread,[i,...r]),N.stop(this.thread)]);let a=n.choices[0]?.finish_reason;if(a===`length`)throw new p(`Reached limit of tokens for LLM completion response`,{code:f.LLM_FINISH_LENGTH});if(a===`tool_calls`){this.thread.jumpTo(this.currentStepId);return}this.log.DEBUG?.(`Exiting step with collected data`,n),this.exitStep(`next`,n)}async resetStep(){this.resetState(),this.state.cancelled=!0;let e=(await Promise.allSettled([C(this.thread,{status:`cancel`}),F.adjustOnCancel(this.thread)])).find(e=>e.status===`rejected`);if(e)throw e.reason}resetState(){this.state.contentReady=!1,this.state.chatCompletion=void 0,this.state.toolsResults=[]}validateMergeFieldType(){let{functionsList:e}=this.data;if(!(!Array.isArray(e)||e.length===0)&&(this.dataOut==null||this.getMergeField(this.dataOut).type!==`thread`))throw new p(`Merge-field type has to be "Thread" if you are using functions`,{code:f.VALIDATION})}get contentContext(){let e=this.data.streamResponse;return Q.factory(e)}};k([w,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,void 0)],$.prototype,`runStep`,null),k([w,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Promise)],$.prototype,`initialize`,null),k([g({allowHandleError:!0}),O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,Promise)],$.prototype,`onContentContextEnd`,null),k([g({allowHandleError:!0}),O(`design:type`,Function),O(`design:paramtypes`,[Object]),O(`design:returntype`,Promise)],$.prototype,`onHistoryContextEnd`,null),k([w,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Promise)],$.prototype,`onCancel`,null),t();const ye={[F.class]:F,[V.class]:V,[W.class]:W,[U.class]:U,[q.class]:q,[X.class]:X,[J.class]:J,[N.class]:N};export{ye as states,$ as step};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|