@cascaide-ts/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2026 Cascaide
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _toolkit = require('@reduxjs/toolkit');var it={context:{},activeNodes:{},history:[],errors:{}},b= exports.workflowSlice =_toolkit.createSlice.call(void 0, {name:"workflow",initialState:it,reducers:{updateContext:{reducer:(e,n)=>{Object.entries(n.payload).forEach(([o,t])=>{if(e.context[o]||(e.context[o]=[]),typeof t=="object"&&t!==null&&!Array.isArray(t)&&"index"in t){let s=t.index;e.context[o][s]=t}else e.context[o].push(t)})},prepare:(e,n)=>({payload:e,meta:n||{}})},addActiveNode:{reducer:(e,n)=>{let{nodeId:o,nodeName:t,parentTriggerId:s,contextData:i}=n.payload,{origin:a,functionId:d,cascadeId:c}=n.meta;e.activeNodes[o]={nodeName:t,parentTriggerId:s,processed:!1,initialContext:i,origin:a,functionId:d,cascadeId:c||_optionalChain([i, 'optionalAccess', _2 => _2.cascadeId])},e.errors[o]&&delete e.errors[o]},prepare:(e,n)=>{let o=_optionalChain([n, 'optionalAccess', _3 => _3.cascadeId])||_optionalChain([e, 'access', _4 => _4.contextData, 'optionalAccess', _5 => _5.cascadeId]);return{payload:e,meta:{...n,cascadeId:o}}}},removeActiveNode:{reducer:(e,n)=>{let{nodeId:o}=n.payload;e.activeNodes[o]&&(e.history.push({nodeId:o,nodeName:e.activeNodes[o].nodeName,timestamp:Date.now()}),delete e.activeNodes[o])},prepare:(e,n)=>({payload:e,meta:n||{}})},setError:{reducer:(e,n)=>{let{nodeId:o,error:t}=n.payload;e.errors[o]=t},prepare:(e,n)=>({payload:e,meta:n||{}})},markNodeProcessed:(e,n)=>{let{nodeId:o}=n.payload;e.activeNodes[o]&&(e.activeNodes[o].processed=!0)},streamChunkReceived:(e,n)=>{let{cascadeId:o,contentChunk:t,toolChunk:s,reasoningChunk:i,thoughtSignature:a}=n.payload;if(!t&&!s&&!i&&!a)return;let d=e.context[o];if(!d||d.length===0)return;let u=d[d.length-1].history,r=u[u.length-1];if(!(!r||r.role!=="assistant")&&(i&&(r.reasoning_content===void 0&&(r.reasoning_content=""),r.reasoning_content+=i),a&&(r.thought_signature=a),t&&(r.content+=t),s)){r.tool_calls||(r.tool_calls=[]);let l=_nullishCoalesce(s.index, () => (0));r.tool_calls[l]||(r.tool_calls[l]={id:"",type:"function",function:{name:"",arguments:""}});let f=r.tool_calls[l];s.id&&(f.id=s.id),s.thought_signature&&(f.thought_signature=s.thought_signature),_optionalChain([s, 'access', _6 => _6.function, 'optionalAccess', _7 => _7.name])&&(f.function.name=s.function.name),_optionalChain([s, 'access', _8 => _8.function, 'optionalAccess', _9 => _9.arguments])&&(f.function.arguments+=s.function.arguments)}},hydrateContext:(e,n)=>{Object.entries(n.payload).forEach(([o,t])=>{e.context[o]=t})}}}),{updateContext:I,addActiveNode:w,removeActiveNode:S,setError:N,markNodeProcessed:Dt,streamChunkReceived:G,hydrateContext:O}=b.actions,z=b.reducer;var L=process.env.NODE_ENV==="development",Y= exports.createClientHydrationMiddleware =e=>n=>o=>async t=>{if(w.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta;if(a&&i>0&&s==="client"){let c=n.getState().workflow.context[a];if(!c||c.length===0){L&&console.log(`[CLIENT HYDRATION] \u{1F9CA} Cold start for ${a}`);try{let u=await fetch(e.hydrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cascadeId:a,functionId:i})});if(!u.ok)throw new Error(`Hydration API failed: ${u.status}`);let r=await u.json();r&&Object.keys(r).length>0&&(n.dispatch(O(r)),L&&console.log("[CLIENT HYDRATION] \u2705 State hydrated via Dispatch"))}catch(u){L&&console.error("[CLIENT HYDRATION] \u274C Hydration failed:",u)}}}}return o(t)};var E=process.env.NODE_ENV==="development";async function P(e,n=3,o=100){for(let t=1;t<=n;t++)try{return await e()}catch(s){if(t===n)return E&&console.error(`[CLIENT MW] \u274C All ${n} retry attempts failed:`,s),null;let i=o*Math.pow(2,t-1);E&&console.warn(`[CLIENT MW] \u26A0\uFE0F Attempt ${t} failed, retrying in ${i}ms...`),await new Promise(a=>setTimeout(a,i))}return null}var B=e=>n=>o=>async t=>{if(w.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,{nodeId:d,nodeName:c,contextData:u}=t.payload;if(!a||s)return o(t);let r=_nullishCoalesce(i, () => (0)),l=await P(async()=>{let y=await fetch(e.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"claim",nodeInstanceId:d,cascadeId:a,userId:u.userId,nodeName:c,functionId:r,inputContext:u,location:"client"})});if(!y.ok)throw new Error(`Persistence sync failed: ${y.status}`);return await y.json()});if(!l){E&&console.error(`[CLIENT MW] \u274C Failed to claim node ${d} after retries`);return}let f=l.functionId;E&&console.log(`[CLIENT MW] \u2705 Node ${d} bound to FnId: ${f}`);let p={...t,meta:{...t.meta,origin:"client",functionId:f,cascadeId:a}};return o(p)}if(S.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,d=typeof t.payload=="string"?t.payload:t.payload.nodeId,c=t.payload.hasSpawns,u=t.payload.fullOutput,r=n.getState(),l=r.workflow.activeNodes[d],f=a||_optionalChain([l, 'optionalAccess', _10 => _10.cascadeId]),p=_nullishCoalesce(_nullishCoalesce(i, () => (_optionalChain([l, 'optionalAccess', _11 => _11.functionId]))), () => (0));if(!f||s)return o(t);let y=u||r.workflow.context[f];if(!await P(async()=>{let x=await fetch(e.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"finalize",nodeInstanceId:d,cascadeId:f,fullOutput:y,hasSpawns:c})});if(!x.ok)throw new Error(`Persistence sync failed: ${x.status}`);return await x.json()})){E&&console.error(`[CLIENT MW] \u274C Failed to finalize node ${d} after retries`);return}return o({...t,meta:{...t.meta,origin:"client",functionId:p,cascadeId:f}})}if(N.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,{nodeId:d,error:c}=t.payload,r=n.getState().workflow.activeNodes[d],l=a||_optionalChain([r, 'optionalAccess', _12 => _12.cascadeId]);if(!l||s)return o(t);if(!await P(async()=>{let p=await fetch(e.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"error",nodeInstanceId:d,cascadeId:l,error:c})});if(!p.ok)throw new Error(`Persistence sync failed: ${p.status}`);return await p.json()})){E&&console.error(`[CLIENT MW] \u274C Failed to mark node ${d} as failed after retries`);return}return o({...t,meta:{...t.meta,origin:"client",cascadeId:l}})}if(I.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,d=t.payload,c=a,u=_nullishCoalesce(i, () => (0));if(!c||s||(E&&console.log("[CLIENT MW] \u{1F504} Persisting context:",JSON.stringify(d,null,2)),_optionalChain([d, 'access', _13 => _13[c], 'optionalAccess', _14 => _14.status])==="streaming"))return o(t);if(!await P(async()=>{let l=await fetch(e.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"context",cascadeId:c,functionId:u,updates:d})});if(!l.ok)throw new Error(`Persistence sync failed: ${l.status}`);return await l.json()})){E&&console.error(`[CLIENT MW] \u274C Failed to record context for cascade ${c} after retries`);return}return o({...t,meta:{...t.meta,origin:"client",functionId:u,cascadeId:c}})}return o(t)};var j=_toolkit.createListenerMiddleware.call(void 0, ),ct=j.startListening,q=`
2
+ __END_STREAM_METADATA__
3
+ `,Q=e=>{ct({actionCreator:w,effect:async(n,o)=>{let{nodeId:t,nodeName:s,contextData:i}=n.payload,{functionId:a}=n.meta,d=e.workflowGraph[s],c=e.isLite;if(!d||d.isUINode)return;let u=c?_nullishCoalesce(_optionalChain([i, 'optionalAccess', _15 => _15.history, 'optionalAccess', _16 => _16.slice, 'call', _17 => _17(-1)]), () => ([])):[..._nullishCoalesce(_optionalChain([i, 'optionalAccess', _18 => _18.history]), () => ([]))];_optionalChain([i, 'optionalAccess', _19 => _19.sentFromClient])&&await o.dispatch(I({[_optionalChain([i, 'optionalAccess', _20 => _20.cascadeId])]:{history:u,status:"completed"}},{functionId:a,cascadeId:_optionalChain([i, 'optionalAccess', _21 => _21.cascadeId])}));try{let r=await fetch(e.actionRelayEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},signal:o.signal,body:JSON.stringify(n)});if(!r.ok||!r.body)throw new Error(await r.text()||"Action relay failed");let l=_optionalChain([i, 'optionalAccess', _22 => _22.cascadeId]);await dt(r.body,l,t,o,n,c)}catch(r){if(r.name==="AbortError")return;await o.dispatch(N({nodeId:t,error:r.message})),await o.dispatch(S({nodeId:t,hasSpawns:!1}))}}})};async function dt(e,n,o,t,s,i){let a=e.getReader(),d=new TextDecoder,c="",u=!1;try{for(;;){let{done:r,value:l}=await a.read();if(r)break;if(c+=d.decode(l,{stream:!0}),!u){let f=c.indexOf(q);if(f!==-1){let p=c.substring(0,f),y=c.substring(f+q.length);if(K(p,n,t),y.trim())try{let g=JSON.parse(y.trim());await lt(g,o,t,s,i)}catch(g){console.error("Metadata parse error",g)}u=!0;break}c=await K(c,n,t)}}}finally{a.releaseLock()}}async function K(e,n,o){let t=e.split(`
4
+ `),s=t.pop()||"";for(let i of t)if(!(!i.trim()||i.startsWith(":")))try{let a=JSON.parse(i);a.type==="init"?await o.dispatch(I({[a.cascadeId]:{history:[{role:"assistant",content:""}],status:"streaming"}})):a.type==="sync"?await o.dispatch(I({[a.cascadeId]:{history:[a.history],status:"completed"}})):o.dispatch(G({cascadeId:n,contentChunk:a.contentChunk||a.chunk,toolChunk:a.toolChunk||a.tool_call,reasoningChunk:a.reasoningChunk}))}catch(a){console.error("Chunk parse error",a)}return s}async function lt(e,n,o,t,s){let i=_nullishCoalesce(_optionalChain([t, 'access', _23 => _23.meta, 'optionalAccess', _24 => _24.functionId]), () => (0)),a=_nullishCoalesce(_optionalChain([t, 'access', _25 => _25.meta, 'optionalAccess', _26 => _26.origin]), () => ("server")),d=_optionalChain([t, 'access', _27 => _27.payload, 'access', _28 => _28.contextData, 'optionalAccess', _29 => _29.cascadeId]),c=e.spawns?Object.entries(e.spawns):[],u=c.length>0;u&&c.forEach(async([r,l],f)=>{let p=s?o.getState().workflow.context[d]:l;await o.dispatch(w({nodeId:`${r}_${Date.now()}_${f}`,nodeName:r,parentTriggerId:n,contextData:{...p,userId:_optionalChain([p, 'optionalAccess', _30 => _30.userId])||_optionalChain([t, 'access', _31 => _31.payload, 'access', _32 => _32.contextData, 'optionalAccess', _33 => _33.userId])}},{functionId:i+1+f,cascadeId:d,origin:a}))}),await o.dispatch(S({nodeId:n,hasSpawns:u,fullOutput:e.updates},{functionId:void 0,cascadeId:d,origin:a}))}var pt=_toolkit.combineReducers.call(void 0, {workflow:b.reducer}),Ut= exports.createClientStore =(e,n,o,t,s=[])=>{Q({workflowGraph:e,actionRelayEndpoint:n,isLite:!o});let a=[];return o&&a.push(B({persistenceEndpoint:o}),Y({hydrationEndpoint:t})),a.push(...s),a.push(j.middleware),_toolkit.configureStore.call(void 0, {reducer:pt,middleware:d=>d({serializableCheck:!1}).concat(a),devTools:process.env.NODE_ENV!=="production"})};var D=process.env.NODE_ENV==="development";async function $(e,n=3,o=100){for(let t=1;t<=n;t++)try{return await e()}catch(s){if(t===n)return D&&console.error(`[SERVER MW] \u274C All ${n} retry attempts failed:`,s),null;let i=o*Math.pow(2,t-1);D&&console.warn(`[SERVER MW] \u26A0\uFE0F Attempt ${t} failed, retrying in ${i}ms...`),await new Promise(a=>setTimeout(a,i))}return null}var X=e=>n=>o=>async t=>{if(w.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,{nodeId:d,nodeName:c,contextData:u}=t.payload;if(!a||s)return o(t);let r=_nullishCoalesce(i, () => (0)),l=await $(async()=>await e.claimNodeExecution({nodeInstanceId:d,cascadeId:a,userId:u.userId,nodeName:c,functionId:r,inputContext:u,location:"server"}));if(!l){D&&console.error(`[SERVER MW] \u274C Failed to claim node ${d} after retries`);return}D&&console.log(`[SERVER MW] \u2705 Claimed node ${d} with FnId: ${l.functionId}`);let f={...t,meta:{...t.meta,origin:"server",functionId:l.functionId,cascadeId:a}};return o(f)}if(S.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,d=typeof t.payload=="string"?t.payload:t.payload.nodeId,c=_nullishCoalesce(t.payload.hasSpawns, () => (!1)),u=t.payload.fullOutput,r=n.getState(),l=r.workflow.activeNodes[d],f=a||_optionalChain([l, 'optionalAccess', _34 => _34.cascadeId]),p=_nullishCoalesce(_nullishCoalesce(i, () => (_optionalChain([l, 'optionalAccess', _35 => _35.functionId]))), () => (0));if(!f||s)return o(t);let y=u||r.workflow.context[f];if(!await $(async()=>await e.finalizeNodeExecution({nodeInstanceId:d,cascadeId:f,fullOutput:y,hasSpawns:c}))){D&&console.error(`[SERVER MW] \u274C Failed to finalize node ${d} after retries`);return}let x={...t,meta:{...t.meta,origin:"server",functionId:p,cascadeId:f}};return o(x)}if(N.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,{nodeId:d,error:c}=t.payload,r=n.getState().workflow.activeNodes[d],l=a||_optionalChain([r, 'optionalAccess', _36 => _36.cascadeId]),f=_nullishCoalesce(_nullishCoalesce(i, () => (_optionalChain([r, 'optionalAccess', _37 => _37.functionId]))), () => (0));if(!l||s)return o(t);if(!await $(async()=>await e.markExecutionFailed(d,l,c))){D&&console.error(`[SERVER MW] \u274C Failed to mark node ${d} as failed after retries`);return}let y={...t,meta:{...t.meta,origin:"server",functionId:f,cascadeId:l}};return o(y)}if(I.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,d=t.payload,c=a,u=_nullishCoalesce(i, () => (0));if(!c||s)return o(t);let r=d[c];if(r&&r.status==="streaming")return o(t);if(!await $(async()=>await e.recordContextEvents({cascadeId:c,functionId:u,updates:d}))){D&&console.error(`[SERVER MW] \u274C Failed to record context for cascade ${c} after retries`);return}let f={...t,meta:{...t.meta,origin:"server",functionId:u,cascadeId:c}};return o(f)}return o(t)};var F=process.env.NODE_ENV==="development",Z= exports.createServerHydrationMiddleware =e=>n=>o=>async t=>{if(w.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta;if(a&&i>0&&s){let c=n.getState().workflow.context[a];if(!c||c.length===0){F&&console.log(`[SERVER HYDRATION] \u{1F9CA} Cold start for ${a}`);try{let u=await e.hydrateCascadeContext(a,i+1);u&&Object.keys(u).length>0&&(await n.dispatch(O(u)),F&&console.log("[SERVER HYDRATION] \u2705 State hydrated via Dispatch"))}catch(u){F&&console.error("[SERVER HYDRATION] \u274C Hydration failed:",u)}}}}return o(t)};var ee=(e,n=[])=>{let o=_toolkit.createListenerMiddleware.call(void 0, ),t=[];return e&&t.push(X(e),Z(e)),t.push(...n),t.push(o.middleware),{store:_toolkit.configureStore.call(void 0, {reducer:{workflow:z},middleware:i=>i({serializableCheck:!1}).concat(t),devTools:process.env.NODE_ENV!=="production"}),serverListener:o}};var tt={extractDelta(e){let n=_optionalChain([e, 'access', _38 => _38.choices, 'optionalAccess', _39 => _39[0], 'optionalAccess', _40 => _40.delta]);if(!n)return{};let o={};if(n.content&&(o.contentChunk=n.content),n.tool_calls){let t=n.tool_calls[0];o.toolChunk={index:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _41 => _41.index]), () => (0)),id:_optionalChain([t, 'optionalAccess', _42 => _42.id]),function:{name:_optionalChain([t, 'optionalAccess', _43 => _43.function, 'optionalAccess', _44 => _44.name]),arguments:_optionalChain([t, 'optionalAccess', _45 => _45.function, 'optionalAccess', _46 => _46.arguments])}}}return o}},gt={isReasoningModel:!0,extractDelta(e){let n=_optionalChain([e, 'access', _47 => _47.choices, 'optionalAccess', _48 => _48[0], 'optionalAccess', _49 => _49.delta]);if(!n)return{};let o={};if(n.reasoning_content&&(o.reasoningChunk=n.reasoning_content),n.content&&(o.contentChunk=n.content),n.tool_calls){let t=n.tool_calls[0];o.toolChunk={index:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _50 => _50.index]), () => (0)),id:_optionalChain([t, 'optionalAccess', _51 => _51.id]),function:{name:_optionalChain([t, 'optionalAccess', _52 => _52.function, 'optionalAccess', _53 => _53.name]),arguments:_optionalChain([t, 'optionalAccess', _54 => _54.function, 'optionalAccess', _55 => _55.arguments])}}}return o}},yt={extractDelta(e){let n={};return e.type==="content_block_delta"&&(_optionalChain([e, 'access', _56 => _56.delta, 'optionalAccess', _57 => _57.type])==="text_delta"&&(n.contentChunk=e.delta.text),_optionalChain([e, 'access', _58 => _58.delta, 'optionalAccess', _59 => _59.type])==="input_json_delta"&&(n.toolChunk={index:_nullishCoalesce(e.index, () => (0)),function:{arguments:e.delta.partial_json}})),e.type==="content_block_start"&&_optionalChain([e, 'access', _60 => _60.content_block, 'optionalAccess', _61 => _61.type])==="tool_use"&&(n.toolChunk={index:_nullishCoalesce(e.index, () => (0)),id:e.content_block.id,function:{name:e.content_block.name,arguments:""}}),n}},wt={isReasoningModel:!0,extractDelta(e){let n={};return e.type==="content_block_delta"&&(_optionalChain([e, 'access', _62 => _62.delta, 'optionalAccess', _63 => _63.type])==="text_delta"&&(e.content_block_type==="thinking"?n.reasoningChunk=e.delta.text:n.contentChunk=e.delta.text),_optionalChain([e, 'access', _64 => _64.delta, 'optionalAccess', _65 => _65.type])==="input_json_delta"&&(n.toolChunk={index:_nullishCoalesce(e.index, () => (0)),function:{arguments:e.delta.partial_json}})),e.type==="content_block_start"&&(_optionalChain([e, 'access', _66 => _66.content_block, 'optionalAccess', _67 => _67.type])==="thinking"&&(n.reasoningChunk=""),_optionalChain([e, 'access', _68 => _68.content_block, 'optionalAccess', _69 => _69.type])==="tool_use"&&(n.toolChunk={index:_nullishCoalesce(e.index, () => (0)),id:e.content_block.id,function:{name:e.content_block.name,arguments:""}})),n}},It={extractDelta(e){let n={},o=_optionalChain([e, 'access', _70 => _70.candidates, 'optionalAccess', _71 => _71[0]]);if(!o)return n;let t=_optionalChain([o, 'access', _72 => _72.content, 'optionalAccess', _73 => _73.parts, 'optionalAccess', _74 => _74[0]]);return _optionalChain([t, 'optionalAccess', _75 => _75.text])&&(n.contentChunk=t.text),_optionalChain([t, 'optionalAccess', _76 => _76.functionCall])&&(n.toolChunk={index:0,id:t.functionCall.name,function:{name:t.functionCall.name,arguments:JSON.stringify(t.functionCall.args)}}),n}},V=new Map,Ct={isReasoningModel:!0,extractDelta(e){let n={},o=e.responseId||"unknown_id",t=_optionalChain([e, 'access', _77 => _77.candidates, 'optionalAccess', _78 => _78[0]]);if(!t)return n;let s=_optionalChain([t, 'access', _79 => _79.content, 'optionalAccess', _80 => _80.parts])||[],i=V.get(o)||0;return s.forEach(a=>{if(_optionalChain([a, 'optionalAccess', _81 => _81.thought])===!0&&_optionalChain([a, 'optionalAccess', _82 => _82.text])&&(n.reasoningChunk=(n.reasoningChunk||"")+a.text),_optionalChain([a, 'optionalAccess', _83 => _83.thoughtSignature])&&(n.thoughtSignature=a.thoughtSignature),_optionalChain([a, 'optionalAccess', _84 => _84.functionCall])){let d=`call_${a.functionCall.name}_${o}_${i}`;n.toolChunk={index:i,id:d,thought_signature:a.thoughtSignature,function:{name:a.functionCall.name,arguments:JSON.stringify(a.functionCall.args)}},i++}_optionalChain([a, 'optionalAccess', _85 => _85.text])&&_optionalChain([a, 'optionalAccess', _86 => _86.thought])!==!0&&(n.contentChunk=(n.contentChunk||"")+a.text)}),V.set(o,i),_optionalChain([t, 'optionalAccess', _87 => _87.finishReason])&&(n.finishReason=t.finishReason,V.delete(o)),n}},St={extractDelta(e){return tt.extractDelta(e)}},kt={isReasoningModel:!0,extractDelta(e){let n=_optionalChain([e, 'access', _88 => _88.choices, 'optionalAccess', _89 => _89[0], 'optionalAccess', _90 => _90.delta]);if(!n)return{};let o={};if(n.content){let t=n.content;t.includes("<think>")?o.reasoningChunk=t.replace("<think>",""):t.includes("</think>")?o.reasoningChunk=t.replace("</think>",""):o.contentChunk=t}if(n.tool_calls){let t=n.tool_calls[0];o.toolChunk={index:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _91 => _91.index]), () => (0)),id:_optionalChain([t, 'optionalAccess', _92 => _92.id]),function:{name:_optionalChain([t, 'optionalAccess', _93 => _93.function, 'optionalAccess', _94 => _94.name]),arguments:_optionalChain([t, 'optionalAccess', _95 => _95.function, 'optionalAccess', _96 => _96.arguments])}}}return o}},H={openai:tt,"openai-reasoning":gt,anthropic:yt,"anthropic-reasoning":wt,gemini:It,"gemini-reasoning":Ct,deepseek:St,"deepseek-reasoning":kt};var et=process.env.NODE_ENV==="development",k=(...e)=>{et&&console.log(...e)},xt=(...e)=>{et&&console.error(...e)};function ie(e,n,o,t,s){let i=`
5
+ __END_STREAM_METADATA__
6
+ `,{writer:a,encoder:d,send:c}=o;e.startListening({actionCreator:w,effect:async(u,r)=>{t.chainDepth.current++;let{nodeId:l,nodeName:f,contextData:p}=u.payload,{functionId:y}=_nullishCoalesce(u.meta, () => (0)),g=n.workflowGraph[f];if(k(`
7
+ [Node ${t.chainDepth.current}] \u{1F680} Starting: ${f}`),!g||g.isUINode){k(`[Node ${t.chainDepth.current}] \u{1F5A5}\uFE0F UI Node detected. Handing off to client listener.`),await a.write(d.encode(i+JSON.stringify({spawns:{[f]:p}}))),t.activeNodeCount.current--,t.activeNodeCount.current===0&&await a.close();return}let x=_optionalChain([p, 'access', _97 => _97.cascadeId, 'optionalAccess', _98 => _98.startsWith, 'call', _99 => _99("call")]);try{y==0&&await r.dispatch(I({[_optionalChain([p, 'optionalAccess', _100 => _100.cascadeId])]:{history:[..._optionalChain([p, 'optionalAccess', _101 => _101.history])],status:"completed"}},{origin:"server"}));let M=structuredClone(p),T={};if(g.prep){let _=r.getState().workflow.context,A=await g.prep(_,M)}let h=T.cascadeId||p.cascadeId,v=_nullishCoalesce(_optionalChain([u, 'access', _102 => _102.meta, 'optionalAccess', _103 => _103.functionId]), () => (0)),m=null;if(g.isStreaming){k(`[Node ${t.chainDepth.current}] \u{1F30A} Executing Streaming Node...`);let _=await g.exec(T),A=await Nt(_,h,c);m=await g.post({assistantMessage:A,cascadeId:h,history:structuredClone(T.history),userId:p.userId})}else{k(`[Node ${t.chainDepth.current}] \u26A1 Executing Standard Node...`);let _=await g.exec(T);m=await g.post(_)}if(m){let _=Date.now()-s,A=n.maxExecutionTime-_,W=m.spawns?Object.keys(m.spawns):[];if(W.length)if(A>n.safeBuffer){k(`[Node ${t.chainDepth.current}] \u2705 Internally Spawning: ${W.join(", ")} (${Math.round(A/1e3)}s remaining)`);let R=m.updates[h];if(m.updates){await r.dispatch(I(m.updates,{functionId:v,cascadeId:h}));let C=_nullishCoalesce(_optionalChain([m, 'access', _104 => _104.uiUpdates, 'optionalAccess', _105 => _105[h]]), () => (_optionalChain([m, 'access', _106 => _106.updates, 'optionalAccess', _107 => _107[h]])));C&&!g.isStreaming&&(k(`[Node ${t.chainDepth.current}] \u{1F504} Syncing context chunk to client UI.`),await c({type:"sync",cascadeId:h,...C}))}x||(t.activeNodeCount.current+=W.length),Object.entries(m.spawns).forEach(async([C,at],U)=>{await r.dispatch(w({nodeId:`${C}_${Date.now()}_${U}`,nodeName:C,parentTriggerId:l,contextData:at||{}},{functionId:v+1+U,cascadeId:h}))}),await r.dispatch(S({nodeId:l,hasSpawns:!0,fullOutput:R},{functionId:v,cascadeId:h}))}else{k(`[Node ${t.chainDepth.current}] \u23F3 Time Buffer Reached. Handing off to client to checkpoint.`);let R=m.updates[h];if(m.updates){await r.dispatch(I(m.updates,{functionId:v,cascadeId:h}));let C=_nullishCoalesce(_optionalChain([m, 'access', _108 => _108.uiUpdates, 'optionalAccess', _109 => _109[h]]), () => (_optionalChain([m, 'access', _110 => _110.updates, 'optionalAccess', _111 => _111[h]])));C&&!g.isStreaming&&(k(`[Node ${t.chainDepth.current}] \u{1F504} Syncing context chunk to client UI.`),await c({type:"sync",cascadeId:h,...C}))}await r.dispatch(S({nodeId:l,hasSpawns:!0,fullOutput:R},{functionId:v,cascadeId:h})),await a.write(d.encode(i+JSON.stringify(m)))}else{k(`[Node ${t.chainDepth.current}] \u{1F3C1} Chain Terminal. Dispatching completion.`);let R=m.updates[h];if(m.updates){await r.dispatch(I(m.updates,{functionId:v,cascadeId:h}));let C=_nullishCoalesce(_optionalChain([m, 'access', _112 => _112.uiUpdates, 'optionalAccess', _113 => _113[h]]), () => (_optionalChain([m, 'access', _114 => _114.updates, 'optionalAccess', _115 => _115[h]])));C&&!g.isStreaming&&(k(`[Node ${t.chainDepth.current}] \u{1F504} Syncing context chunk to client UI.`),await c({type:"sync",cascadeId:h,...C}))}await r.dispatch(S({nodeId:l,hasSpawns:!1,fullOutput:R},{functionId:v,cascadeId:h})),x||await a.write(d.encode(i+JSON.stringify(m)))}}}catch(M){xt(`[Node ${t.chainDepth.current}] \u274C Execution Error:`,M.message),await r.dispatch(N({nodeId:l,error:M.message},{functionId:_optionalChain([u, 'access', _116 => _116.meta, 'optionalAccess', _117 => _117.functionId]),cascadeId:_optionalChain([p, 'optionalAccess', _118 => _118.cascadeId])})),await a.write(d.encode(i+JSON.stringify({error:M.message})))}finally{x||t.activeNodeCount.current--,t.activeNodeCount.current===0&&(k(`[Server] \u{1F4EA} Stream closing. Total Nodes: ${t.chainDepth.current} | Total Time: ${Date.now()-s}ms
8
+ `),await a.close())}}})}async function Nt(e,n,o){let{stream:t,provider:s,isReasoning:i=!1}=e,a=i?`${s}-reasoning`:s,d=H[a]||H[s];await o({type:"init",cascadeId:n});let c={role:"assistant",content:"",...d.isReasoningModel&&{reasoning_content:""}};for await(let u of t){let r=d.extractDelta(u);if(!r.contentChunk&&!r.toolChunk&&!r.reasoningChunk&&!r.thoughtSignature)continue;let l={cascadeId:n};if(r.reasoningChunk&&(c.reasoning_content+=r.reasoningChunk,l.reasoningChunk=r.reasoningChunk),r.thoughtSignature&&(c.thought_signature=r.thoughtSignature,l.thoughtSignature=r.thoughtSignature),r.contentChunk&&(c.content+=r.contentChunk,l.contentChunk=r.contentChunk),r.finishReason&&(c.finishReason=r.finishReason,l.finishReason=r.finishReason),r.toolChunk){l.toolChunk=r.toolChunk,c.tool_calls||(c.tool_calls=[]);let f=r.toolChunk.index;c.tool_calls[f]||(c.tool_calls[f]={id:"",type:"function",function:{name:"",arguments:""},thought_signature:r.toolChunk.thought_signature,executed:!1});let p=c.tool_calls[f];r.toolChunk.id&&(p.id=r.toolChunk.id),r.toolChunk.thought_signature&&(p.thought_signature=r.toolChunk.thought_signature),_optionalChain([r, 'access', _119 => _119.toolChunk, 'access', _120 => _120.function, 'optionalAccess', _121 => _121.name])&&(p.function.name=r.toolChunk.function.name),_optionalChain([r, 'access', _122 => _122.toolChunk, 'access', _123 => _123.function, 'optionalAccess', _124 => _124.arguments])&&(p.function.arguments+=r.toolChunk.function.arguments)}await o(l)}return c}var _reselect = require('reselect');var Et=e=>e.workflow.activeNodes,nt=e=>e.workflow.context,ot=(e,n)=>n,de= exports.makeSelectCascadeState =()=>_reselect.createSelector.call(void 0, [nt,ot],(e,n)=>{let o=e[n];if(!o||o.length===0)return;let t=o[o.length-1].status,s=o.flatMap(i=>i.history||[]);return{status:t,history:s}}),le= exports.makeSelectCascadeNodes =()=>_reselect.createSelector.call(void 0, [Et,ot],(e,n)=>(console.log(`Reselect: Re-calculating nodes for cascade ${n}`),Object.entries(e).filter(([o,t])=>_optionalChain([t, 'access', _125 => _125.initialContext, 'optionalAccess', _126 => _126.cascadeId])===n).map(([o,t])=>({nodeId:o,nodeName:t.nodeName,parentTriggerId:t.parentTriggerId,initialContext:t.initialContext,processed:t.processed})))),ue= exports.selectAllCascadeIds =_reselect.createSelector.call(void 0, [nt],e=>(console.log("Reselect: Re-calculating all cascade IDs"),Object.keys(e).filter(n=>n.startsWith("cascade_"))));exports.addActiveNode = w; exports.createClientHydrationMiddleware = Y; exports.createClientPersistenceMiddleware = B; exports.createClientStore = Ut; exports.createServerHydrationMiddleware = Z; exports.createServerPersistenceMiddleware = X; exports.createServerStore = ee; exports.handleProviderStream = Nt; exports.hydrateContext = O; exports.makeSelectCascadeNodes = le; exports.makeSelectCascadeState = de; exports.markNodeProcessed = Dt; exports.removeActiveNode = S; exports.selectAllCascadeIds = ue; exports.setError = N; exports.setupServerWorkflowListener = ie; exports.streamChunkReceived = G; exports.updateContext = I; exports.workflowSlice = b;
@@ -0,0 +1,406 @@
1
+ import * as _reduxjs_toolkit from '@reduxjs/toolkit';
2
+ import { configureStore, Middleware, PayloadAction } from '@reduxjs/toolkit';
3
+ import * as reselect from 'reselect';
4
+
5
+ type WorkflowStep = {
6
+ history: any;
7
+ status: string;
8
+ [extraKeys: string]: any;
9
+ };
10
+ type WorkflowContext = {
11
+ [cascadeId: string]: WorkflowStep[];
12
+ };
13
+ type ActionMeta = {
14
+ origin?: 'client' | 'server';
15
+ functionId?: number;
16
+ cascadeId?: string;
17
+ userId?: string;
18
+ };
19
+ type ActiveNode = {
20
+ nodeName: string;
21
+ parentTriggerId?: string;
22
+ processed?: boolean;
23
+ initialContext?: any;
24
+ origin?: 'client' | 'server';
25
+ functionId?: number;
26
+ cascadeId?: string;
27
+ };
28
+ type StreamChunk = {
29
+ contentChunk?: string;
30
+ toolChunk?: any;
31
+ cascadeId: string;
32
+ reasoningChunk?: string;
33
+ thoughtSignature?: string;
34
+ };
35
+ type NodeHistoryRecord = {
36
+ nodeId: string;
37
+ nodeName: string;
38
+ timestamp: number;
39
+ };
40
+ interface WorkflowState {
41
+ context: WorkflowContext;
42
+ activeNodes: {
43
+ [nodeId: string]: ActiveNode;
44
+ };
45
+ history: NodeHistoryRecord[];
46
+ errors: {
47
+ [nodeId: string]: string;
48
+ };
49
+ }
50
+ interface ClaimRequest {
51
+ nodeInstanceId: string;
52
+ cascadeId: string;
53
+ userId: string;
54
+ nodeName: string;
55
+ functionId: number;
56
+ inputContext: any;
57
+ location: 'client' | 'server';
58
+ }
59
+ interface ClaimResponse {
60
+ status: string;
61
+ functionId: number;
62
+ }
63
+ interface NodeDefinition {
64
+ name: string;
65
+ isUINode: boolean;
66
+ env: string;
67
+ }
68
+ type Updates = {
69
+ [cascadeId: string]: WorkflowStep;
70
+ };
71
+ type SpawnContext<T = Record<string, any>> = {
72
+ cascadeId: string;
73
+ history: any;
74
+ userId: string;
75
+ } & T;
76
+ type PostResult = {
77
+ updates: Updates;
78
+ uiUpdates?: Updates;
79
+ spawns?: Record<string, SpawnContext>;
80
+ };
81
+ type ClientWorkflowGraph = Record<string, NodeDefinition>;
82
+ interface ServerNodeDefinition<TPrep = any, TExec = any> extends NodeDefinition {
83
+ prep: (cascadeContext: WorkflowContext, initialContext: any) => Promise<TPrep>;
84
+ exec: (prepOutput: TPrep) => Promise<TExec>;
85
+ post: (execOutput: TExec) => Promise<PostResult>;
86
+ isStreaming: boolean;
87
+ }
88
+ type ServerWorkflowGraph = Record<string, ServerNodeDefinition<any, any>>;
89
+ type StreamEventType = 'init' | 'sync' | 'chunk';
90
+ type ProviderType = 'openai' | 'anthropic' | 'gemini' | 'deepseek';
91
+ interface StreamAdapter {
92
+ extractDelta(chunk: any): StreamDelta;
93
+ isReasoningModel?: boolean;
94
+ }
95
+ interface StreamDelta {
96
+ contentChunk?: string;
97
+ toolChunk?: {
98
+ index: number;
99
+ id?: string;
100
+ thought_signature?: string;
101
+ function?: {
102
+ name?: string;
103
+ arguments?: string;
104
+ };
105
+ };
106
+ reasoningChunk?: string;
107
+ finishReason?: string;
108
+ thoughtSignature?: string;
109
+ }
110
+ interface StreamConfig {
111
+ stream: AsyncIterable<any>;
112
+ provider: ProviderType;
113
+ isReasoning?: boolean;
114
+ }
115
+
116
+ declare const rootReducer: _reduxjs_toolkit.Reducer<{
117
+ workflow: WorkflowState;
118
+ }, _reduxjs_toolkit.UnknownAction, Partial<{
119
+ workflow: WorkflowState;
120
+ }>>;
121
+ type RootState = ReturnType<typeof rootReducer>;
122
+ type AppDispatch = ReturnType<typeof configureStore>['dispatch'];
123
+ declare const createClientStore: (workflowGraph: ClientWorkflowGraph, actionRelayEndpoint: string, persistenceEndpoint?: string, hydrationEndpoint?: string, extraMiddlewares?: Middleware[]) => _reduxjs_toolkit.EnhancedStore<{
124
+ workflow: WorkflowState;
125
+ }, _reduxjs_toolkit.UnknownAction, _reduxjs_toolkit.Tuple<[_reduxjs_toolkit.StoreEnhancer<{
126
+ dispatch: _reduxjs_toolkit.ThunkDispatch<{
127
+ workflow: WorkflowState;
128
+ }, undefined, _reduxjs_toolkit.UnknownAction>;
129
+ }>, _reduxjs_toolkit.StoreEnhancer]>>;
130
+
131
+ interface CascadePersistence {
132
+ claimNodeExecution(params: ClaimRequest): Promise<ClaimResponse>;
133
+ finalizeNodeExecution(params: {
134
+ nodeInstanceId: string;
135
+ cascadeId: string;
136
+ fullOutput: any;
137
+ hasSpawns: boolean;
138
+ }): Promise<{
139
+ status: string;
140
+ }>;
141
+ markExecutionFailed(nodeInstanceId: string, cascadeId: string, error: string): Promise<{
142
+ status: string;
143
+ }>;
144
+ recordContextEvents(params: {
145
+ cascadeId: string;
146
+ functionId: number;
147
+ updates: {
148
+ [key: string]: any;
149
+ };
150
+ }): Promise<{
151
+ status: string;
152
+ }>;
153
+ hydrateCascadeContext(cascadeId: string, upToFunctionId: number): Promise<WorkflowContext>;
154
+ forkCascade(params: {
155
+ sourceCascadeId: string;
156
+ newCascadeId: string;
157
+ upToFunctionId: number;
158
+ }): Promise<{
159
+ newCascadeId: string;
160
+ status: string;
161
+ }>;
162
+ }
163
+
164
+ declare const createServerStore: (persistor?: CascadePersistence, extraMiddlewares?: Middleware[]) => {
165
+ store: _reduxjs_toolkit.EnhancedStore<{
166
+ workflow: WorkflowState;
167
+ }, _reduxjs_toolkit.UnknownAction, _reduxjs_toolkit.Tuple<[_reduxjs_toolkit.StoreEnhancer<{
168
+ dispatch: _reduxjs_toolkit.ThunkDispatch<{
169
+ workflow: WorkflowState;
170
+ }, undefined, _reduxjs_toolkit.UnknownAction>;
171
+ }>, _reduxjs_toolkit.StoreEnhancer]>>;
172
+ serverListener: _reduxjs_toolkit.ListenerMiddlewareInstance<unknown, _reduxjs_toolkit.ThunkDispatch<unknown, unknown, _reduxjs_toolkit.UnknownAction>, unknown>;
173
+ };
174
+
175
+ type addActiveNodePayload = {
176
+ nodeId: string;
177
+ nodeName: string;
178
+ parentTriggerId?: string;
179
+ contextData?: any;
180
+ };
181
+ type updateContextPayload = {
182
+ [cascadeId: string]: WorkflowStep;
183
+ };
184
+ type removeActiveNodePayload = {
185
+ nodeId: string;
186
+ hasSpawns: boolean;
187
+ fullOutput?: any;
188
+ };
189
+ type setErrorPayload = {
190
+ nodeId: string;
191
+ error: string;
192
+ };
193
+ type markNodeProcessedPayload = {
194
+ nodeId: string;
195
+ };
196
+ declare const workflowSlice: _reduxjs_toolkit.Slice<WorkflowState, {
197
+ updateContext: {
198
+ reducer: (state: WorkflowState, action: PayloadAction<updateContextPayload, string, ActionMeta>) => void;
199
+ prepare: (payload: {
200
+ [key: string]: any;
201
+ }, meta?: ActionMeta) => {
202
+ payload: {
203
+ [key: string]: any;
204
+ };
205
+ meta: ActionMeta;
206
+ };
207
+ };
208
+ addActiveNode: {
209
+ reducer: (state: WorkflowState, action: PayloadAction<addActiveNodePayload, string, ActionMeta>) => void;
210
+ prepare: (payload: addActiveNodePayload, meta?: ActionMeta) => {
211
+ payload: addActiveNodePayload;
212
+ meta: {
213
+ cascadeId: any;
214
+ origin?: "client" | "server";
215
+ functionId?: number;
216
+ userId?: string;
217
+ };
218
+ };
219
+ };
220
+ removeActiveNode: {
221
+ reducer: (state: WorkflowState, action: PayloadAction<removeActiveNodePayload, string, ActionMeta>) => void;
222
+ prepare: (payload: removeActiveNodePayload, meta?: ActionMeta) => {
223
+ payload: removeActiveNodePayload;
224
+ meta: ActionMeta;
225
+ };
226
+ };
227
+ setError: {
228
+ reducer: (state: WorkflowState, action: PayloadAction<setErrorPayload, string, ActionMeta>) => void;
229
+ prepare: (payload: setErrorPayload, meta?: ActionMeta) => {
230
+ payload: setErrorPayload;
231
+ meta: ActionMeta;
232
+ };
233
+ };
234
+ markNodeProcessed: (state: WorkflowState, action: PayloadAction<markNodeProcessedPayload>) => void;
235
+ streamChunkReceived: (state: WorkflowState, action: PayloadAction<StreamChunk>) => void;
236
+ hydrateContext: (state: WorkflowState, action: PayloadAction<WorkflowContext>) => void;
237
+ }, "workflow", "workflow", _reduxjs_toolkit.SliceSelectors<WorkflowState>>;
238
+ declare const updateContext: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
239
+ [key: string]: any;
240
+ }, meta?: ActionMeta], {
241
+ [key: string]: any;
242
+ }, "workflow/updateContext", never, ActionMeta>;
243
+ declare const addActiveNode: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: addActiveNodePayload, meta?: ActionMeta], addActiveNodePayload, "workflow/addActiveNode", never, {
244
+ cascadeId: any;
245
+ origin?: "client" | "server";
246
+ functionId?: number;
247
+ userId?: string;
248
+ }>;
249
+ declare const removeActiveNode: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: removeActiveNodePayload, meta?: ActionMeta], removeActiveNodePayload, "workflow/removeActiveNode", never, ActionMeta>;
250
+ declare const setError: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: setErrorPayload, meta?: ActionMeta], setErrorPayload, "workflow/setError", never, ActionMeta>;
251
+ declare const markNodeProcessed: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<markNodeProcessedPayload, "workflow/markNodeProcessed">;
252
+ declare const streamChunkReceived: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<StreamChunk, "workflow/streamChunkReceived">;
253
+ declare const hydrateContext: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<WorkflowContext, "workflow/hydrateContext">;
254
+
255
+ declare const createServerPersistenceMiddleware: (persistor: CascadePersistence) => Middleware;
256
+
257
+ declare function setupServerWorkflowListener(serverListener: any, config: {
258
+ workflowGraph: ServerWorkflowGraph;
259
+ maxExecutionTime: number;
260
+ safeBuffer: number;
261
+ }, streamControl: {
262
+ writer: WritableStreamDefaultWriter;
263
+ encoder: TextEncoder;
264
+ send: (data: any) => Promise<void>;
265
+ }, counters: {
266
+ activeNodeCount: {
267
+ current: number;
268
+ };
269
+ chainDepth: {
270
+ current: number;
271
+ };
272
+ }, startTime: number): void;
273
+ declare function handleProviderStream(config: StreamConfig, cascadeId: string, send: (data: any) => Promise<void>): Promise<any>;
274
+
275
+ declare const createServerHydrationMiddleware: (persistor: CascadePersistence) => Middleware;
276
+
277
+ interface ClientPersistenceConfig {
278
+ persistenceEndpoint: string;
279
+ }
280
+ declare const createClientPersistenceMiddleware: (config: ClientPersistenceConfig) => Middleware;
281
+
282
+ interface ClientHydrationConfig {
283
+ hydrationEndpoint: string;
284
+ }
285
+ declare const createClientHydrationMiddleware: (config: ClientHydrationConfig) => Middleware;
286
+
287
+ declare const makeSelectCascadeState: () => ((state: {
288
+ workflow: WorkflowState;
289
+ }, cascadeId: string) => {
290
+ status: string;
291
+ history: any[];
292
+ }) & {
293
+ clearCache: () => void;
294
+ resultsCount: () => number;
295
+ resetResultsCount: () => void;
296
+ } & {
297
+ resultFunc: (resultFuncArgs_0: WorkflowContext, resultFuncArgs_1: string) => {
298
+ status: string;
299
+ history: any[];
300
+ };
301
+ memoizedResultFunc: ((resultFuncArgs_0: WorkflowContext, resultFuncArgs_1: string) => {
302
+ status: string;
303
+ history: any[];
304
+ }) & {
305
+ clearCache: () => void;
306
+ resultsCount: () => number;
307
+ resetResultsCount: () => void;
308
+ };
309
+ lastResult: () => {
310
+ status: string;
311
+ history: any[];
312
+ };
313
+ dependencies: [(state: RootState) => WorkflowContext, (_state: RootState, cascadeId: string) => string];
314
+ recomputations: () => number;
315
+ resetRecomputations: () => void;
316
+ dependencyRecomputations: () => number;
317
+ resetDependencyRecomputations: () => void;
318
+ } & {
319
+ memoize: typeof reselect.weakMapMemoize;
320
+ argsMemoize: typeof reselect.weakMapMemoize;
321
+ };
322
+ /**
323
+ * Creates a memoized selector to get all active nodes for a specific cascade.
324
+ * This is a "factory function" because it needs the `cascadeId` to work.
325
+ */
326
+ declare const makeSelectCascadeNodes: () => ((state: {
327
+ workflow: WorkflowState;
328
+ }, cascadeId: string) => {
329
+ nodeId: string;
330
+ nodeName: string;
331
+ parentTriggerId: string;
332
+ initialContext: any;
333
+ processed: boolean;
334
+ }[]) & {
335
+ clearCache: () => void;
336
+ resultsCount: () => number;
337
+ resetResultsCount: () => void;
338
+ } & {
339
+ resultFunc: (resultFuncArgs_0: {
340
+ [nodeId: string]: ActiveNode;
341
+ }, resultFuncArgs_1: string) => {
342
+ nodeId: string;
343
+ nodeName: string;
344
+ parentTriggerId: string;
345
+ initialContext: any;
346
+ processed: boolean;
347
+ }[];
348
+ memoizedResultFunc: ((resultFuncArgs_0: {
349
+ [nodeId: string]: ActiveNode;
350
+ }, resultFuncArgs_1: string) => {
351
+ nodeId: string;
352
+ nodeName: string;
353
+ parentTriggerId: string;
354
+ initialContext: any;
355
+ processed: boolean;
356
+ }[]) & {
357
+ clearCache: () => void;
358
+ resultsCount: () => number;
359
+ resetResultsCount: () => void;
360
+ };
361
+ lastResult: () => {
362
+ nodeId: string;
363
+ nodeName: string;
364
+ parentTriggerId: string;
365
+ initialContext: any;
366
+ processed: boolean;
367
+ }[];
368
+ dependencies: [(state: RootState) => {
369
+ [nodeId: string]: ActiveNode;
370
+ }, (_state: RootState, cascadeId: string) => string];
371
+ recomputations: () => number;
372
+ resetRecomputations: () => void;
373
+ dependencyRecomputations: () => number;
374
+ resetDependencyRecomputations: () => void;
375
+ } & {
376
+ memoize: typeof reselect.weakMapMemoize;
377
+ argsMemoize: typeof reselect.weakMapMemoize;
378
+ };
379
+ /**
380
+ * Memoized selector to get all cascade IDs.
381
+ */
382
+ declare const selectAllCascadeIds: ((state: {
383
+ workflow: WorkflowState;
384
+ }) => string[]) & {
385
+ clearCache: () => void;
386
+ resultsCount: () => number;
387
+ resetResultsCount: () => void;
388
+ } & {
389
+ resultFunc: (resultFuncArgs_0: WorkflowContext) => string[];
390
+ memoizedResultFunc: ((resultFuncArgs_0: WorkflowContext) => string[]) & {
391
+ clearCache: () => void;
392
+ resultsCount: () => number;
393
+ resetResultsCount: () => void;
394
+ };
395
+ lastResult: () => string[];
396
+ dependencies: [(state: RootState) => WorkflowContext];
397
+ recomputations: () => number;
398
+ resetRecomputations: () => void;
399
+ dependencyRecomputations: () => number;
400
+ resetDependencyRecomputations: () => void;
401
+ } & {
402
+ memoize: typeof reselect.weakMapMemoize;
403
+ argsMemoize: typeof reselect.weakMapMemoize;
404
+ };
405
+
406
+ export { type ActionMeta, type ActiveNode, type AppDispatch, type CascadePersistence, type ClaimRequest, type ClaimResponse, type ClientHydrationConfig, type ClientPersistenceConfig, type ClientWorkflowGraph, type NodeDefinition, type NodeHistoryRecord, type PostResult, type ProviderType, type RootState, type ServerNodeDefinition, type ServerWorkflowGraph, type SpawnContext, type StreamAdapter, type StreamChunk, type StreamConfig, type StreamDelta, type StreamEventType, type Updates, type WorkflowContext, type WorkflowState, type WorkflowStep, addActiveNode, type addActiveNodePayload, createClientHydrationMiddleware, createClientPersistenceMiddleware, createClientStore, createServerHydrationMiddleware, createServerPersistenceMiddleware, createServerStore, handleProviderStream, hydrateContext, makeSelectCascadeNodes, makeSelectCascadeState, markNodeProcessed, type markNodeProcessedPayload, removeActiveNode, type removeActiveNodePayload, selectAllCascadeIds, setError, type setErrorPayload, setupServerWorkflowListener, streamChunkReceived, updateContext, type updateContextPayload, workflowSlice };
@@ -0,0 +1,406 @@
1
+ import * as _reduxjs_toolkit from '@reduxjs/toolkit';
2
+ import { configureStore, Middleware, PayloadAction } from '@reduxjs/toolkit';
3
+ import * as reselect from 'reselect';
4
+
5
+ type WorkflowStep = {
6
+ history: any;
7
+ status: string;
8
+ [extraKeys: string]: any;
9
+ };
10
+ type WorkflowContext = {
11
+ [cascadeId: string]: WorkflowStep[];
12
+ };
13
+ type ActionMeta = {
14
+ origin?: 'client' | 'server';
15
+ functionId?: number;
16
+ cascadeId?: string;
17
+ userId?: string;
18
+ };
19
+ type ActiveNode = {
20
+ nodeName: string;
21
+ parentTriggerId?: string;
22
+ processed?: boolean;
23
+ initialContext?: any;
24
+ origin?: 'client' | 'server';
25
+ functionId?: number;
26
+ cascadeId?: string;
27
+ };
28
+ type StreamChunk = {
29
+ contentChunk?: string;
30
+ toolChunk?: any;
31
+ cascadeId: string;
32
+ reasoningChunk?: string;
33
+ thoughtSignature?: string;
34
+ };
35
+ type NodeHistoryRecord = {
36
+ nodeId: string;
37
+ nodeName: string;
38
+ timestamp: number;
39
+ };
40
+ interface WorkflowState {
41
+ context: WorkflowContext;
42
+ activeNodes: {
43
+ [nodeId: string]: ActiveNode;
44
+ };
45
+ history: NodeHistoryRecord[];
46
+ errors: {
47
+ [nodeId: string]: string;
48
+ };
49
+ }
50
+ interface ClaimRequest {
51
+ nodeInstanceId: string;
52
+ cascadeId: string;
53
+ userId: string;
54
+ nodeName: string;
55
+ functionId: number;
56
+ inputContext: any;
57
+ location: 'client' | 'server';
58
+ }
59
+ interface ClaimResponse {
60
+ status: string;
61
+ functionId: number;
62
+ }
63
+ interface NodeDefinition {
64
+ name: string;
65
+ isUINode: boolean;
66
+ env: string;
67
+ }
68
+ type Updates = {
69
+ [cascadeId: string]: WorkflowStep;
70
+ };
71
+ type SpawnContext<T = Record<string, any>> = {
72
+ cascadeId: string;
73
+ history: any;
74
+ userId: string;
75
+ } & T;
76
+ type PostResult = {
77
+ updates: Updates;
78
+ uiUpdates?: Updates;
79
+ spawns?: Record<string, SpawnContext>;
80
+ };
81
+ type ClientWorkflowGraph = Record<string, NodeDefinition>;
82
+ interface ServerNodeDefinition<TPrep = any, TExec = any> extends NodeDefinition {
83
+ prep: (cascadeContext: WorkflowContext, initialContext: any) => Promise<TPrep>;
84
+ exec: (prepOutput: TPrep) => Promise<TExec>;
85
+ post: (execOutput: TExec) => Promise<PostResult>;
86
+ isStreaming: boolean;
87
+ }
88
+ type ServerWorkflowGraph = Record<string, ServerNodeDefinition<any, any>>;
89
+ type StreamEventType = 'init' | 'sync' | 'chunk';
90
+ type ProviderType = 'openai' | 'anthropic' | 'gemini' | 'deepseek';
91
+ interface StreamAdapter {
92
+ extractDelta(chunk: any): StreamDelta;
93
+ isReasoningModel?: boolean;
94
+ }
95
+ interface StreamDelta {
96
+ contentChunk?: string;
97
+ toolChunk?: {
98
+ index: number;
99
+ id?: string;
100
+ thought_signature?: string;
101
+ function?: {
102
+ name?: string;
103
+ arguments?: string;
104
+ };
105
+ };
106
+ reasoningChunk?: string;
107
+ finishReason?: string;
108
+ thoughtSignature?: string;
109
+ }
110
+ interface StreamConfig {
111
+ stream: AsyncIterable<any>;
112
+ provider: ProviderType;
113
+ isReasoning?: boolean;
114
+ }
115
+
116
+ declare const rootReducer: _reduxjs_toolkit.Reducer<{
117
+ workflow: WorkflowState;
118
+ }, _reduxjs_toolkit.UnknownAction, Partial<{
119
+ workflow: WorkflowState;
120
+ }>>;
121
+ type RootState = ReturnType<typeof rootReducer>;
122
+ type AppDispatch = ReturnType<typeof configureStore>['dispatch'];
123
+ declare const createClientStore: (workflowGraph: ClientWorkflowGraph, actionRelayEndpoint: string, persistenceEndpoint?: string, hydrationEndpoint?: string, extraMiddlewares?: Middleware[]) => _reduxjs_toolkit.EnhancedStore<{
124
+ workflow: WorkflowState;
125
+ }, _reduxjs_toolkit.UnknownAction, _reduxjs_toolkit.Tuple<[_reduxjs_toolkit.StoreEnhancer<{
126
+ dispatch: _reduxjs_toolkit.ThunkDispatch<{
127
+ workflow: WorkflowState;
128
+ }, undefined, _reduxjs_toolkit.UnknownAction>;
129
+ }>, _reduxjs_toolkit.StoreEnhancer]>>;
130
+
131
+ interface CascadePersistence {
132
+ claimNodeExecution(params: ClaimRequest): Promise<ClaimResponse>;
133
+ finalizeNodeExecution(params: {
134
+ nodeInstanceId: string;
135
+ cascadeId: string;
136
+ fullOutput: any;
137
+ hasSpawns: boolean;
138
+ }): Promise<{
139
+ status: string;
140
+ }>;
141
+ markExecutionFailed(nodeInstanceId: string, cascadeId: string, error: string): Promise<{
142
+ status: string;
143
+ }>;
144
+ recordContextEvents(params: {
145
+ cascadeId: string;
146
+ functionId: number;
147
+ updates: {
148
+ [key: string]: any;
149
+ };
150
+ }): Promise<{
151
+ status: string;
152
+ }>;
153
+ hydrateCascadeContext(cascadeId: string, upToFunctionId: number): Promise<WorkflowContext>;
154
+ forkCascade(params: {
155
+ sourceCascadeId: string;
156
+ newCascadeId: string;
157
+ upToFunctionId: number;
158
+ }): Promise<{
159
+ newCascadeId: string;
160
+ status: string;
161
+ }>;
162
+ }
163
+
164
+ declare const createServerStore: (persistor?: CascadePersistence, extraMiddlewares?: Middleware[]) => {
165
+ store: _reduxjs_toolkit.EnhancedStore<{
166
+ workflow: WorkflowState;
167
+ }, _reduxjs_toolkit.UnknownAction, _reduxjs_toolkit.Tuple<[_reduxjs_toolkit.StoreEnhancer<{
168
+ dispatch: _reduxjs_toolkit.ThunkDispatch<{
169
+ workflow: WorkflowState;
170
+ }, undefined, _reduxjs_toolkit.UnknownAction>;
171
+ }>, _reduxjs_toolkit.StoreEnhancer]>>;
172
+ serverListener: _reduxjs_toolkit.ListenerMiddlewareInstance<unknown, _reduxjs_toolkit.ThunkDispatch<unknown, unknown, _reduxjs_toolkit.UnknownAction>, unknown>;
173
+ };
174
+
175
+ type addActiveNodePayload = {
176
+ nodeId: string;
177
+ nodeName: string;
178
+ parentTriggerId?: string;
179
+ contextData?: any;
180
+ };
181
+ type updateContextPayload = {
182
+ [cascadeId: string]: WorkflowStep;
183
+ };
184
+ type removeActiveNodePayload = {
185
+ nodeId: string;
186
+ hasSpawns: boolean;
187
+ fullOutput?: any;
188
+ };
189
+ type setErrorPayload = {
190
+ nodeId: string;
191
+ error: string;
192
+ };
193
+ type markNodeProcessedPayload = {
194
+ nodeId: string;
195
+ };
196
+ declare const workflowSlice: _reduxjs_toolkit.Slice<WorkflowState, {
197
+ updateContext: {
198
+ reducer: (state: WorkflowState, action: PayloadAction<updateContextPayload, string, ActionMeta>) => void;
199
+ prepare: (payload: {
200
+ [key: string]: any;
201
+ }, meta?: ActionMeta) => {
202
+ payload: {
203
+ [key: string]: any;
204
+ };
205
+ meta: ActionMeta;
206
+ };
207
+ };
208
+ addActiveNode: {
209
+ reducer: (state: WorkflowState, action: PayloadAction<addActiveNodePayload, string, ActionMeta>) => void;
210
+ prepare: (payload: addActiveNodePayload, meta?: ActionMeta) => {
211
+ payload: addActiveNodePayload;
212
+ meta: {
213
+ cascadeId: any;
214
+ origin?: "client" | "server";
215
+ functionId?: number;
216
+ userId?: string;
217
+ };
218
+ };
219
+ };
220
+ removeActiveNode: {
221
+ reducer: (state: WorkflowState, action: PayloadAction<removeActiveNodePayload, string, ActionMeta>) => void;
222
+ prepare: (payload: removeActiveNodePayload, meta?: ActionMeta) => {
223
+ payload: removeActiveNodePayload;
224
+ meta: ActionMeta;
225
+ };
226
+ };
227
+ setError: {
228
+ reducer: (state: WorkflowState, action: PayloadAction<setErrorPayload, string, ActionMeta>) => void;
229
+ prepare: (payload: setErrorPayload, meta?: ActionMeta) => {
230
+ payload: setErrorPayload;
231
+ meta: ActionMeta;
232
+ };
233
+ };
234
+ markNodeProcessed: (state: WorkflowState, action: PayloadAction<markNodeProcessedPayload>) => void;
235
+ streamChunkReceived: (state: WorkflowState, action: PayloadAction<StreamChunk>) => void;
236
+ hydrateContext: (state: WorkflowState, action: PayloadAction<WorkflowContext>) => void;
237
+ }, "workflow", "workflow", _reduxjs_toolkit.SliceSelectors<WorkflowState>>;
238
+ declare const updateContext: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
239
+ [key: string]: any;
240
+ }, meta?: ActionMeta], {
241
+ [key: string]: any;
242
+ }, "workflow/updateContext", never, ActionMeta>;
243
+ declare const addActiveNode: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: addActiveNodePayload, meta?: ActionMeta], addActiveNodePayload, "workflow/addActiveNode", never, {
244
+ cascadeId: any;
245
+ origin?: "client" | "server";
246
+ functionId?: number;
247
+ userId?: string;
248
+ }>;
249
+ declare const removeActiveNode: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: removeActiveNodePayload, meta?: ActionMeta], removeActiveNodePayload, "workflow/removeActiveNode", never, ActionMeta>;
250
+ declare const setError: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: setErrorPayload, meta?: ActionMeta], setErrorPayload, "workflow/setError", never, ActionMeta>;
251
+ declare const markNodeProcessed: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<markNodeProcessedPayload, "workflow/markNodeProcessed">;
252
+ declare const streamChunkReceived: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<StreamChunk, "workflow/streamChunkReceived">;
253
+ declare const hydrateContext: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<WorkflowContext, "workflow/hydrateContext">;
254
+
255
+ declare const createServerPersistenceMiddleware: (persistor: CascadePersistence) => Middleware;
256
+
257
+ declare function setupServerWorkflowListener(serverListener: any, config: {
258
+ workflowGraph: ServerWorkflowGraph;
259
+ maxExecutionTime: number;
260
+ safeBuffer: number;
261
+ }, streamControl: {
262
+ writer: WritableStreamDefaultWriter;
263
+ encoder: TextEncoder;
264
+ send: (data: any) => Promise<void>;
265
+ }, counters: {
266
+ activeNodeCount: {
267
+ current: number;
268
+ };
269
+ chainDepth: {
270
+ current: number;
271
+ };
272
+ }, startTime: number): void;
273
+ declare function handleProviderStream(config: StreamConfig, cascadeId: string, send: (data: any) => Promise<void>): Promise<any>;
274
+
275
+ declare const createServerHydrationMiddleware: (persistor: CascadePersistence) => Middleware;
276
+
277
+ interface ClientPersistenceConfig {
278
+ persistenceEndpoint: string;
279
+ }
280
+ declare const createClientPersistenceMiddleware: (config: ClientPersistenceConfig) => Middleware;
281
+
282
+ interface ClientHydrationConfig {
283
+ hydrationEndpoint: string;
284
+ }
285
+ declare const createClientHydrationMiddleware: (config: ClientHydrationConfig) => Middleware;
286
+
287
+ declare const makeSelectCascadeState: () => ((state: {
288
+ workflow: WorkflowState;
289
+ }, cascadeId: string) => {
290
+ status: string;
291
+ history: any[];
292
+ }) & {
293
+ clearCache: () => void;
294
+ resultsCount: () => number;
295
+ resetResultsCount: () => void;
296
+ } & {
297
+ resultFunc: (resultFuncArgs_0: WorkflowContext, resultFuncArgs_1: string) => {
298
+ status: string;
299
+ history: any[];
300
+ };
301
+ memoizedResultFunc: ((resultFuncArgs_0: WorkflowContext, resultFuncArgs_1: string) => {
302
+ status: string;
303
+ history: any[];
304
+ }) & {
305
+ clearCache: () => void;
306
+ resultsCount: () => number;
307
+ resetResultsCount: () => void;
308
+ };
309
+ lastResult: () => {
310
+ status: string;
311
+ history: any[];
312
+ };
313
+ dependencies: [(state: RootState) => WorkflowContext, (_state: RootState, cascadeId: string) => string];
314
+ recomputations: () => number;
315
+ resetRecomputations: () => void;
316
+ dependencyRecomputations: () => number;
317
+ resetDependencyRecomputations: () => void;
318
+ } & {
319
+ memoize: typeof reselect.weakMapMemoize;
320
+ argsMemoize: typeof reselect.weakMapMemoize;
321
+ };
322
+ /**
323
+ * Creates a memoized selector to get all active nodes for a specific cascade.
324
+ * This is a "factory function" because it needs the `cascadeId` to work.
325
+ */
326
+ declare const makeSelectCascadeNodes: () => ((state: {
327
+ workflow: WorkflowState;
328
+ }, cascadeId: string) => {
329
+ nodeId: string;
330
+ nodeName: string;
331
+ parentTriggerId: string;
332
+ initialContext: any;
333
+ processed: boolean;
334
+ }[]) & {
335
+ clearCache: () => void;
336
+ resultsCount: () => number;
337
+ resetResultsCount: () => void;
338
+ } & {
339
+ resultFunc: (resultFuncArgs_0: {
340
+ [nodeId: string]: ActiveNode;
341
+ }, resultFuncArgs_1: string) => {
342
+ nodeId: string;
343
+ nodeName: string;
344
+ parentTriggerId: string;
345
+ initialContext: any;
346
+ processed: boolean;
347
+ }[];
348
+ memoizedResultFunc: ((resultFuncArgs_0: {
349
+ [nodeId: string]: ActiveNode;
350
+ }, resultFuncArgs_1: string) => {
351
+ nodeId: string;
352
+ nodeName: string;
353
+ parentTriggerId: string;
354
+ initialContext: any;
355
+ processed: boolean;
356
+ }[]) & {
357
+ clearCache: () => void;
358
+ resultsCount: () => number;
359
+ resetResultsCount: () => void;
360
+ };
361
+ lastResult: () => {
362
+ nodeId: string;
363
+ nodeName: string;
364
+ parentTriggerId: string;
365
+ initialContext: any;
366
+ processed: boolean;
367
+ }[];
368
+ dependencies: [(state: RootState) => {
369
+ [nodeId: string]: ActiveNode;
370
+ }, (_state: RootState, cascadeId: string) => string];
371
+ recomputations: () => number;
372
+ resetRecomputations: () => void;
373
+ dependencyRecomputations: () => number;
374
+ resetDependencyRecomputations: () => void;
375
+ } & {
376
+ memoize: typeof reselect.weakMapMemoize;
377
+ argsMemoize: typeof reselect.weakMapMemoize;
378
+ };
379
+ /**
380
+ * Memoized selector to get all cascade IDs.
381
+ */
382
+ declare const selectAllCascadeIds: ((state: {
383
+ workflow: WorkflowState;
384
+ }) => string[]) & {
385
+ clearCache: () => void;
386
+ resultsCount: () => number;
387
+ resetResultsCount: () => void;
388
+ } & {
389
+ resultFunc: (resultFuncArgs_0: WorkflowContext) => string[];
390
+ memoizedResultFunc: ((resultFuncArgs_0: WorkflowContext) => string[]) & {
391
+ clearCache: () => void;
392
+ resultsCount: () => number;
393
+ resetResultsCount: () => void;
394
+ };
395
+ lastResult: () => string[];
396
+ dependencies: [(state: RootState) => WorkflowContext];
397
+ recomputations: () => number;
398
+ resetRecomputations: () => void;
399
+ dependencyRecomputations: () => number;
400
+ resetDependencyRecomputations: () => void;
401
+ } & {
402
+ memoize: typeof reselect.weakMapMemoize;
403
+ argsMemoize: typeof reselect.weakMapMemoize;
404
+ };
405
+
406
+ export { type ActionMeta, type ActiveNode, type AppDispatch, type CascadePersistence, type ClaimRequest, type ClaimResponse, type ClientHydrationConfig, type ClientPersistenceConfig, type ClientWorkflowGraph, type NodeDefinition, type NodeHistoryRecord, type PostResult, type ProviderType, type RootState, type ServerNodeDefinition, type ServerWorkflowGraph, type SpawnContext, type StreamAdapter, type StreamChunk, type StreamConfig, type StreamDelta, type StreamEventType, type Updates, type WorkflowContext, type WorkflowState, type WorkflowStep, addActiveNode, type addActiveNodePayload, createClientHydrationMiddleware, createClientPersistenceMiddleware, createClientStore, createServerHydrationMiddleware, createServerPersistenceMiddleware, createServerStore, handleProviderStream, hydrateContext, makeSelectCascadeNodes, makeSelectCascadeState, markNodeProcessed, type markNodeProcessedPayload, removeActiveNode, type removeActiveNodePayload, selectAllCascadeIds, setError, type setErrorPayload, setupServerWorkflowListener, streamChunkReceived, updateContext, type updateContextPayload, workflowSlice };
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ import{configureStore as ut,combineReducers as ft}from"@reduxjs/toolkit";import{createSlice as rt}from"@reduxjs/toolkit";var it={context:{},activeNodes:{},history:[],errors:{}},b=rt({name:"workflow",initialState:it,reducers:{updateContext:{reducer:(e,n)=>{Object.entries(n.payload).forEach(([o,t])=>{if(e.context[o]||(e.context[o]=[]),typeof t=="object"&&t!==null&&!Array.isArray(t)&&"index"in t){let s=t.index;e.context[o][s]=t}else e.context[o].push(t)})},prepare:(e,n)=>({payload:e,meta:n||{}})},addActiveNode:{reducer:(e,n)=>{let{nodeId:o,nodeName:t,parentTriggerId:s,contextData:i}=n.payload,{origin:a,functionId:d,cascadeId:c}=n.meta;e.activeNodes[o]={nodeName:t,parentTriggerId:s,processed:!1,initialContext:i,origin:a,functionId:d,cascadeId:c||i?.cascadeId},e.errors[o]&&delete e.errors[o]},prepare:(e,n)=>{let o=n?.cascadeId||e.contextData?.cascadeId;return{payload:e,meta:{...n,cascadeId:o}}}},removeActiveNode:{reducer:(e,n)=>{let{nodeId:o}=n.payload;e.activeNodes[o]&&(e.history.push({nodeId:o,nodeName:e.activeNodes[o].nodeName,timestamp:Date.now()}),delete e.activeNodes[o])},prepare:(e,n)=>({payload:e,meta:n||{}})},setError:{reducer:(e,n)=>{let{nodeId:o,error:t}=n.payload;e.errors[o]=t},prepare:(e,n)=>({payload:e,meta:n||{}})},markNodeProcessed:(e,n)=>{let{nodeId:o}=n.payload;e.activeNodes[o]&&(e.activeNodes[o].processed=!0)},streamChunkReceived:(e,n)=>{let{cascadeId:o,contentChunk:t,toolChunk:s,reasoningChunk:i,thoughtSignature:a}=n.payload;if(!t&&!s&&!i&&!a)return;let d=e.context[o];if(!d||d.length===0)return;let u=d[d.length-1].history,r=u[u.length-1];if(!(!r||r.role!=="assistant")&&(i&&(r.reasoning_content===void 0&&(r.reasoning_content=""),r.reasoning_content+=i),a&&(r.thought_signature=a),t&&(r.content+=t),s)){r.tool_calls||(r.tool_calls=[]);let l=s.index??0;r.tool_calls[l]||(r.tool_calls[l]={id:"",type:"function",function:{name:"",arguments:""}});let f=r.tool_calls[l];s.id&&(f.id=s.id),s.thought_signature&&(f.thought_signature=s.thought_signature),s.function?.name&&(f.function.name=s.function.name),s.function?.arguments&&(f.function.arguments+=s.function.arguments)}},hydrateContext:(e,n)=>{Object.entries(n.payload).forEach(([o,t])=>{e.context[o]=t})}}}),{updateContext:I,addActiveNode:w,removeActiveNode:S,setError:N,markNodeProcessed:Dt,streamChunkReceived:G,hydrateContext:O}=b.actions,z=b.reducer;var L=process.env.NODE_ENV==="development",Y=e=>n=>o=>async t=>{if(w.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta;if(a&&i>0&&s==="client"){let c=n.getState().workflow.context[a];if(!c||c.length===0){L&&console.log(`[CLIENT HYDRATION] \u{1F9CA} Cold start for ${a}`);try{let u=await fetch(e.hydrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cascadeId:a,functionId:i})});if(!u.ok)throw new Error(`Hydration API failed: ${u.status}`);let r=await u.json();r&&Object.keys(r).length>0&&(n.dispatch(O(r)),L&&console.log("[CLIENT HYDRATION] \u2705 State hydrated via Dispatch"))}catch(u){L&&console.error("[CLIENT HYDRATION] \u274C Hydration failed:",u)}}}}return o(t)};var E=process.env.NODE_ENV==="development";async function P(e,n=3,o=100){for(let t=1;t<=n;t++)try{return await e()}catch(s){if(t===n)return E&&console.error(`[CLIENT MW] \u274C All ${n} retry attempts failed:`,s),null;let i=o*Math.pow(2,t-1);E&&console.warn(`[CLIENT MW] \u26A0\uFE0F Attempt ${t} failed, retrying in ${i}ms...`),await new Promise(a=>setTimeout(a,i))}return null}var B=e=>n=>o=>async t=>{if(w.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,{nodeId:d,nodeName:c,contextData:u}=t.payload;if(!a||s)return o(t);let r=i??0,l=await P(async()=>{let y=await fetch(e.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"claim",nodeInstanceId:d,cascadeId:a,userId:u.userId,nodeName:c,functionId:r,inputContext:u,location:"client"})});if(!y.ok)throw new Error(`Persistence sync failed: ${y.status}`);return await y.json()});if(!l){E&&console.error(`[CLIENT MW] \u274C Failed to claim node ${d} after retries`);return}let f=l.functionId;E&&console.log(`[CLIENT MW] \u2705 Node ${d} bound to FnId: ${f}`);let p={...t,meta:{...t.meta,origin:"client",functionId:f,cascadeId:a}};return o(p)}if(S.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,d=typeof t.payload=="string"?t.payload:t.payload.nodeId,c=t.payload.hasSpawns,u=t.payload.fullOutput,r=n.getState(),l=r.workflow.activeNodes[d],f=a||l?.cascadeId,p=i??l?.functionId??0;if(!f||s)return o(t);let y=u||r.workflow.context[f];if(!await P(async()=>{let x=await fetch(e.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"finalize",nodeInstanceId:d,cascadeId:f,fullOutput:y,hasSpawns:c})});if(!x.ok)throw new Error(`Persistence sync failed: ${x.status}`);return await x.json()})){E&&console.error(`[CLIENT MW] \u274C Failed to finalize node ${d} after retries`);return}return o({...t,meta:{...t.meta,origin:"client",functionId:p,cascadeId:f}})}if(N.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,{nodeId:d,error:c}=t.payload,r=n.getState().workflow.activeNodes[d],l=a||r?.cascadeId;if(!l||s)return o(t);if(!await P(async()=>{let p=await fetch(e.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"error",nodeInstanceId:d,cascadeId:l,error:c})});if(!p.ok)throw new Error(`Persistence sync failed: ${p.status}`);return await p.json()})){E&&console.error(`[CLIENT MW] \u274C Failed to mark node ${d} as failed after retries`);return}return o({...t,meta:{...t.meta,origin:"client",cascadeId:l}})}if(I.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,d=t.payload,c=a,u=i??0;if(!c||s||(E&&console.log("[CLIENT MW] \u{1F504} Persisting context:",JSON.stringify(d,null,2)),d[c]?.status==="streaming"))return o(t);if(!await P(async()=>{let l=await fetch(e.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"context",cascadeId:c,functionId:u,updates:d})});if(!l.ok)throw new Error(`Persistence sync failed: ${l.status}`);return await l.json()})){E&&console.error(`[CLIENT MW] \u274C Failed to record context for cascade ${c} after retries`);return}return o({...t,meta:{...t.meta,origin:"client",functionId:u,cascadeId:c}})}return o(t)};import{createListenerMiddleware as st}from"@reduxjs/toolkit";var j=st(),ct=j.startListening,q=`
2
+ __END_STREAM_METADATA__
3
+ `,Q=e=>{ct({actionCreator:w,effect:async(n,o)=>{let{nodeId:t,nodeName:s,contextData:i}=n.payload,{functionId:a}=n.meta,d=e.workflowGraph[s],c=e.isLite;if(!d||d.isUINode)return;let u=c?i?.history?.slice(-1)??[]:[...i?.history??[]];i?.sentFromClient&&await o.dispatch(I({[i?.cascadeId]:{history:u,status:"completed"}},{functionId:a,cascadeId:i?.cascadeId}));try{let r=await fetch(e.actionRelayEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},signal:o.signal,body:JSON.stringify(n)});if(!r.ok||!r.body)throw new Error(await r.text()||"Action relay failed");let l=i?.cascadeId;await dt(r.body,l,t,o,n,c)}catch(r){if(r.name==="AbortError")return;await o.dispatch(N({nodeId:t,error:r.message})),await o.dispatch(S({nodeId:t,hasSpawns:!1}))}}})};async function dt(e,n,o,t,s,i){let a=e.getReader(),d=new TextDecoder,c="",u=!1;try{for(;;){let{done:r,value:l}=await a.read();if(r)break;if(c+=d.decode(l,{stream:!0}),!u){let f=c.indexOf(q);if(f!==-1){let p=c.substring(0,f),y=c.substring(f+q.length);if(K(p,n,t),y.trim())try{let g=JSON.parse(y.trim());await lt(g,o,t,s,i)}catch(g){console.error("Metadata parse error",g)}u=!0;break}c=await K(c,n,t)}}}finally{a.releaseLock()}}async function K(e,n,o){let t=e.split(`
4
+ `),s=t.pop()||"";for(let i of t)if(!(!i.trim()||i.startsWith(":")))try{let a=JSON.parse(i);a.type==="init"?await o.dispatch(I({[a.cascadeId]:{history:[{role:"assistant",content:""}],status:"streaming"}})):a.type==="sync"?await o.dispatch(I({[a.cascadeId]:{history:[a.history],status:"completed"}})):o.dispatch(G({cascadeId:n,contentChunk:a.contentChunk||a.chunk,toolChunk:a.toolChunk||a.tool_call,reasoningChunk:a.reasoningChunk}))}catch(a){console.error("Chunk parse error",a)}return s}async function lt(e,n,o,t,s){let i=t.meta?.functionId??0,a=t.meta?.origin??"server",d=t.payload.contextData?.cascadeId,c=e.spawns?Object.entries(e.spawns):[],u=c.length>0;u&&c.forEach(async([r,l],f)=>{let p=s?o.getState().workflow.context[d]:l;await o.dispatch(w({nodeId:`${r}_${Date.now()}_${f}`,nodeName:r,parentTriggerId:n,contextData:{...p,userId:p?.userId||t.payload.contextData?.userId}},{functionId:i+1+f,cascadeId:d,origin:a}))}),await o.dispatch(S({nodeId:n,hasSpawns:u,fullOutput:e.updates},{functionId:void 0,cascadeId:d,origin:a}))}var pt=ft({workflow:b.reducer}),Ut=(e,n,o,t,s=[])=>{Q({workflowGraph:e,actionRelayEndpoint:n,isLite:!o});let a=[];return o&&a.push(B({persistenceEndpoint:o}),Y({hydrationEndpoint:t})),a.push(...s),a.push(j.middleware),ut({reducer:pt,middleware:d=>d({serializableCheck:!1}).concat(a),devTools:process.env.NODE_ENV!=="production"})};import{configureStore as mt,createListenerMiddleware as ht}from"@reduxjs/toolkit";var D=process.env.NODE_ENV==="development";async function $(e,n=3,o=100){for(let t=1;t<=n;t++)try{return await e()}catch(s){if(t===n)return D&&console.error(`[SERVER MW] \u274C All ${n} retry attempts failed:`,s),null;let i=o*Math.pow(2,t-1);D&&console.warn(`[SERVER MW] \u26A0\uFE0F Attempt ${t} failed, retrying in ${i}ms...`),await new Promise(a=>setTimeout(a,i))}return null}var X=e=>n=>o=>async t=>{if(w.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,{nodeId:d,nodeName:c,contextData:u}=t.payload;if(!a||s)return o(t);let r=i??0,l=await $(async()=>await e.claimNodeExecution({nodeInstanceId:d,cascadeId:a,userId:u.userId,nodeName:c,functionId:r,inputContext:u,location:"server"}));if(!l){D&&console.error(`[SERVER MW] \u274C Failed to claim node ${d} after retries`);return}D&&console.log(`[SERVER MW] \u2705 Claimed node ${d} with FnId: ${l.functionId}`);let f={...t,meta:{...t.meta,origin:"server",functionId:l.functionId,cascadeId:a}};return o(f)}if(S.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,d=typeof t.payload=="string"?t.payload:t.payload.nodeId,c=t.payload.hasSpawns??!1,u=t.payload.fullOutput,r=n.getState(),l=r.workflow.activeNodes[d],f=a||l?.cascadeId,p=i??l?.functionId??0;if(!f||s)return o(t);let y=u||r.workflow.context[f];if(!await $(async()=>await e.finalizeNodeExecution({nodeInstanceId:d,cascadeId:f,fullOutput:y,hasSpawns:c}))){D&&console.error(`[SERVER MW] \u274C Failed to finalize node ${d} after retries`);return}let x={...t,meta:{...t.meta,origin:"server",functionId:p,cascadeId:f}};return o(x)}if(N.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,{nodeId:d,error:c}=t.payload,r=n.getState().workflow.activeNodes[d],l=a||r?.cascadeId,f=i??r?.functionId??0;if(!l||s)return o(t);if(!await $(async()=>await e.markExecutionFailed(d,l,c))){D&&console.error(`[SERVER MW] \u274C Failed to mark node ${d} as failed after retries`);return}let y={...t,meta:{...t.meta,origin:"server",functionId:f,cascadeId:l}};return o(y)}if(I.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta,d=t.payload,c=a,u=i??0;if(!c||s)return o(t);let r=d[c];if(r&&r.status==="streaming")return o(t);if(!await $(async()=>await e.recordContextEvents({cascadeId:c,functionId:u,updates:d}))){D&&console.error(`[SERVER MW] \u274C Failed to record context for cascade ${c} after retries`);return}let f={...t,meta:{...t.meta,origin:"server",functionId:u,cascadeId:c}};return o(f)}return o(t)};var F=process.env.NODE_ENV==="development",Z=e=>n=>o=>async t=>{if(w.match(t)){let{origin:s,functionId:i,cascadeId:a}=t.meta;if(a&&i>0&&s){let c=n.getState().workflow.context[a];if(!c||c.length===0){F&&console.log(`[SERVER HYDRATION] \u{1F9CA} Cold start for ${a}`);try{let u=await e.hydrateCascadeContext(a,i+1);u&&Object.keys(u).length>0&&(await n.dispatch(O(u)),F&&console.log("[SERVER HYDRATION] \u2705 State hydrated via Dispatch"))}catch(u){F&&console.error("[SERVER HYDRATION] \u274C Hydration failed:",u)}}}}return o(t)};var ee=(e,n=[])=>{let o=ht(),t=[];return e&&t.push(X(e),Z(e)),t.push(...n),t.push(o.middleware),{store:mt({reducer:{workflow:z},middleware:i=>i({serializableCheck:!1}).concat(t),devTools:process.env.NODE_ENV!=="production"}),serverListener:o}};var tt={extractDelta(e){let n=e.choices?.[0]?.delta;if(!n)return{};let o={};if(n.content&&(o.contentChunk=n.content),n.tool_calls){let t=n.tool_calls[0];o.toolChunk={index:t?.index??0,id:t?.id,function:{name:t?.function?.name,arguments:t?.function?.arguments}}}return o}},gt={isReasoningModel:!0,extractDelta(e){let n=e.choices?.[0]?.delta;if(!n)return{};let o={};if(n.reasoning_content&&(o.reasoningChunk=n.reasoning_content),n.content&&(o.contentChunk=n.content),n.tool_calls){let t=n.tool_calls[0];o.toolChunk={index:t?.index??0,id:t?.id,function:{name:t?.function?.name,arguments:t?.function?.arguments}}}return o}},yt={extractDelta(e){let n={};return e.type==="content_block_delta"&&(e.delta?.type==="text_delta"&&(n.contentChunk=e.delta.text),e.delta?.type==="input_json_delta"&&(n.toolChunk={index:e.index??0,function:{arguments:e.delta.partial_json}})),e.type==="content_block_start"&&e.content_block?.type==="tool_use"&&(n.toolChunk={index:e.index??0,id:e.content_block.id,function:{name:e.content_block.name,arguments:""}}),n}},wt={isReasoningModel:!0,extractDelta(e){let n={};return e.type==="content_block_delta"&&(e.delta?.type==="text_delta"&&(e.content_block_type==="thinking"?n.reasoningChunk=e.delta.text:n.contentChunk=e.delta.text),e.delta?.type==="input_json_delta"&&(n.toolChunk={index:e.index??0,function:{arguments:e.delta.partial_json}})),e.type==="content_block_start"&&(e.content_block?.type==="thinking"&&(n.reasoningChunk=""),e.content_block?.type==="tool_use"&&(n.toolChunk={index:e.index??0,id:e.content_block.id,function:{name:e.content_block.name,arguments:""}})),n}},It={extractDelta(e){let n={},o=e.candidates?.[0];if(!o)return n;let t=o.content?.parts?.[0];return t?.text&&(n.contentChunk=t.text),t?.functionCall&&(n.toolChunk={index:0,id:t.functionCall.name,function:{name:t.functionCall.name,arguments:JSON.stringify(t.functionCall.args)}}),n}},V=new Map,Ct={isReasoningModel:!0,extractDelta(e){let n={},o=e.responseId||"unknown_id",t=e.candidates?.[0];if(!t)return n;let s=t.content?.parts||[],i=V.get(o)||0;return s.forEach(a=>{if(a?.thought===!0&&a?.text&&(n.reasoningChunk=(n.reasoningChunk||"")+a.text),a?.thoughtSignature&&(n.thoughtSignature=a.thoughtSignature),a?.functionCall){let d=`call_${a.functionCall.name}_${o}_${i}`;n.toolChunk={index:i,id:d,thought_signature:a.thoughtSignature,function:{name:a.functionCall.name,arguments:JSON.stringify(a.functionCall.args)}},i++}a?.text&&a?.thought!==!0&&(n.contentChunk=(n.contentChunk||"")+a.text)}),V.set(o,i),t?.finishReason&&(n.finishReason=t.finishReason,V.delete(o)),n}},St={extractDelta(e){return tt.extractDelta(e)}},kt={isReasoningModel:!0,extractDelta(e){let n=e.choices?.[0]?.delta;if(!n)return{};let o={};if(n.content){let t=n.content;t.includes("<think>")?o.reasoningChunk=t.replace("<think>",""):t.includes("</think>")?o.reasoningChunk=t.replace("</think>",""):o.contentChunk=t}if(n.tool_calls){let t=n.tool_calls[0];o.toolChunk={index:t?.index??0,id:t?.id,function:{name:t?.function?.name,arguments:t?.function?.arguments}}}return o}},H={openai:tt,"openai-reasoning":gt,anthropic:yt,"anthropic-reasoning":wt,gemini:It,"gemini-reasoning":Ct,deepseek:St,"deepseek-reasoning":kt};var et=process.env.NODE_ENV==="development",k=(...e)=>{et&&console.log(...e)},xt=(...e)=>{et&&console.error(...e)};function ie(e,n,o,t,s){let i=`
5
+ __END_STREAM_METADATA__
6
+ `,{writer:a,encoder:d,send:c}=o;e.startListening({actionCreator:w,effect:async(u,r)=>{t.chainDepth.current++;let{nodeId:l,nodeName:f,contextData:p}=u.payload,{functionId:y}=u.meta??0,g=n.workflowGraph[f];if(k(`
7
+ [Node ${t.chainDepth.current}] \u{1F680} Starting: ${f}`),!g||g.isUINode){k(`[Node ${t.chainDepth.current}] \u{1F5A5}\uFE0F UI Node detected. Handing off to client listener.`),await a.write(d.encode(i+JSON.stringify({spawns:{[f]:p}}))),t.activeNodeCount.current--,t.activeNodeCount.current===0&&await a.close();return}let x=p.cascadeId?.startsWith("call");try{y==0&&await r.dispatch(I({[p?.cascadeId]:{history:[...p?.history],status:"completed"}},{origin:"server"}));let M=structuredClone(p),T={};if(g.prep){let _=r.getState().workflow.context,A=await g.prep(_,M)}let h=T.cascadeId||p.cascadeId,v=u.meta?.functionId??0,m=null;if(g.isStreaming){k(`[Node ${t.chainDepth.current}] \u{1F30A} Executing Streaming Node...`);let _=await g.exec(T),A=await Nt(_,h,c);m=await g.post({assistantMessage:A,cascadeId:h,history:structuredClone(T.history),userId:p.userId})}else{k(`[Node ${t.chainDepth.current}] \u26A1 Executing Standard Node...`);let _=await g.exec(T);m=await g.post(_)}if(m){let _=Date.now()-s,A=n.maxExecutionTime-_,W=m.spawns?Object.keys(m.spawns):[];if(W.length)if(A>n.safeBuffer){k(`[Node ${t.chainDepth.current}] \u2705 Internally Spawning: ${W.join(", ")} (${Math.round(A/1e3)}s remaining)`);let R=m.updates[h];if(m.updates){await r.dispatch(I(m.updates,{functionId:v,cascadeId:h}));let C=m.uiUpdates?.[h]??m.updates?.[h];C&&!g.isStreaming&&(k(`[Node ${t.chainDepth.current}] \u{1F504} Syncing context chunk to client UI.`),await c({type:"sync",cascadeId:h,...C}))}x||(t.activeNodeCount.current+=W.length),Object.entries(m.spawns).forEach(async([C,at],U)=>{await r.dispatch(w({nodeId:`${C}_${Date.now()}_${U}`,nodeName:C,parentTriggerId:l,contextData:at||{}},{functionId:v+1+U,cascadeId:h}))}),await r.dispatch(S({nodeId:l,hasSpawns:!0,fullOutput:R},{functionId:v,cascadeId:h}))}else{k(`[Node ${t.chainDepth.current}] \u23F3 Time Buffer Reached. Handing off to client to checkpoint.`);let R=m.updates[h];if(m.updates){await r.dispatch(I(m.updates,{functionId:v,cascadeId:h}));let C=m.uiUpdates?.[h]??m.updates?.[h];C&&!g.isStreaming&&(k(`[Node ${t.chainDepth.current}] \u{1F504} Syncing context chunk to client UI.`),await c({type:"sync",cascadeId:h,...C}))}await r.dispatch(S({nodeId:l,hasSpawns:!0,fullOutput:R},{functionId:v,cascadeId:h})),await a.write(d.encode(i+JSON.stringify(m)))}else{k(`[Node ${t.chainDepth.current}] \u{1F3C1} Chain Terminal. Dispatching completion.`);let R=m.updates[h];if(m.updates){await r.dispatch(I(m.updates,{functionId:v,cascadeId:h}));let C=m.uiUpdates?.[h]??m.updates?.[h];C&&!g.isStreaming&&(k(`[Node ${t.chainDepth.current}] \u{1F504} Syncing context chunk to client UI.`),await c({type:"sync",cascadeId:h,...C}))}await r.dispatch(S({nodeId:l,hasSpawns:!1,fullOutput:R},{functionId:v,cascadeId:h})),x||await a.write(d.encode(i+JSON.stringify(m)))}}}catch(M){xt(`[Node ${t.chainDepth.current}] \u274C Execution Error:`,M.message),await r.dispatch(N({nodeId:l,error:M.message},{functionId:u.meta?.functionId,cascadeId:p?.cascadeId})),await a.write(d.encode(i+JSON.stringify({error:M.message})))}finally{x||t.activeNodeCount.current--,t.activeNodeCount.current===0&&(k(`[Server] \u{1F4EA} Stream closing. Total Nodes: ${t.chainDepth.current} | Total Time: ${Date.now()-s}ms
8
+ `),await a.close())}}})}async function Nt(e,n,o){let{stream:t,provider:s,isReasoning:i=!1}=e,a=i?`${s}-reasoning`:s,d=H[a]||H[s];await o({type:"init",cascadeId:n});let c={role:"assistant",content:"",...d.isReasoningModel&&{reasoning_content:""}};for await(let u of t){let r=d.extractDelta(u);if(!r.contentChunk&&!r.toolChunk&&!r.reasoningChunk&&!r.thoughtSignature)continue;let l={cascadeId:n};if(r.reasoningChunk&&(c.reasoning_content+=r.reasoningChunk,l.reasoningChunk=r.reasoningChunk),r.thoughtSignature&&(c.thought_signature=r.thoughtSignature,l.thoughtSignature=r.thoughtSignature),r.contentChunk&&(c.content+=r.contentChunk,l.contentChunk=r.contentChunk),r.finishReason&&(c.finishReason=r.finishReason,l.finishReason=r.finishReason),r.toolChunk){l.toolChunk=r.toolChunk,c.tool_calls||(c.tool_calls=[]);let f=r.toolChunk.index;c.tool_calls[f]||(c.tool_calls[f]={id:"",type:"function",function:{name:"",arguments:""},thought_signature:r.toolChunk.thought_signature,executed:!1});let p=c.tool_calls[f];r.toolChunk.id&&(p.id=r.toolChunk.id),r.toolChunk.thought_signature&&(p.thought_signature=r.toolChunk.thought_signature),r.toolChunk.function?.name&&(p.function.name=r.toolChunk.function.name),r.toolChunk.function?.arguments&&(p.function.arguments+=r.toolChunk.function.arguments)}await o(l)}return c}import{createSelector as J}from"reselect";var Et=e=>e.workflow.activeNodes,nt=e=>e.workflow.context,ot=(e,n)=>n,de=()=>J([nt,ot],(e,n)=>{let o=e[n];if(!o||o.length===0)return;let t=o[o.length-1].status,s=o.flatMap(i=>i.history||[]);return{status:t,history:s}}),le=()=>J([Et,ot],(e,n)=>(console.log(`Reselect: Re-calculating nodes for cascade ${n}`),Object.entries(e).filter(([o,t])=>t.initialContext?.cascadeId===n).map(([o,t])=>({nodeId:o,nodeName:t.nodeName,parentTriggerId:t.parentTriggerId,initialContext:t.initialContext,processed:t.processed})))),ue=J([nt],e=>(console.log("Reselect: Re-calculating all cascade IDs"),Object.keys(e).filter(n=>n.startsWith("cascade_"))));export{w as addActiveNode,Y as createClientHydrationMiddleware,B as createClientPersistenceMiddleware,Ut as createClientStore,Z as createServerHydrationMiddleware,X as createServerPersistenceMiddleware,ee as createServerStore,Nt as handleProviderStream,O as hydrateContext,le as makeSelectCascadeNodes,de as makeSelectCascadeState,Dt as markNodeProcessed,S as removeActiveNode,ue as selectAllCascadeIds,N as setError,ie as setupServerWorkflowListener,G as streamChunkReceived,I as updateContext,b as workflowSlice};
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@cascaide-ts/core",
3
+ "version": "0.1.0",
4
+ "files": [
5
+ "dist"
6
+ ],
7
+ "type": "module",
8
+ "main": "./dist/index.cjs",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.cjs"
16
+ }
17
+ },
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "sideEffects": false,
22
+ "peerDependencies": {
23
+ "@reduxjs/toolkit": "^2.0.0",
24
+ "reselect": "^5.0.0"
25
+ },
26
+ "devDependencies": {
27
+ "@reduxjs/toolkit": "^2.0.0",
28
+ "reselect": "^5.0.0",
29
+ "tsup": "^8.5.1",
30
+ "typescript": "^5.0.0"
31
+ },
32
+ "scripts": {
33
+ "build": "tsup",
34
+ "dev": "tsup --watch"
35
+ }
36
+ }