@cascaide-ts/core 0.1.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +38 -0
- package/dist/index.cjs +5 -6
- package/dist/index.d.cts +195 -71
- package/dist/index.d.ts +195 -71
- package/dist/index.js +5 -6
- package/package.json +14 -4
package/LICENSE
CHANGED
package/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# @cascaide-ts/core
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
The core engine that powers Cascaide applications.
|
|
5
|
+
|
|
6
|
+
Cascaide is a fullstack agent runtime and AI orchestration framework in typescript designed to run anywhere JS/TS can. It was originally built for web applications but works equally well for headless/CLI AI agents and workflows in javascript runtimes.
|
|
7
|
+
|
|
8
|
+
What it really is is a distributed, observable, durable graph executor. The first split just happens to be client/server, hence full stack.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
`@cascaide-ts/core` is the package all other packages depend on. You will be using it with other packages like `@cascaide-ts/react` to build your full stack AI applications.
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @cascaide-ts/core
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
In your codebase itself, you will be mostly using `core` for the types.
|
|
19
|
+
|
|
20
|
+
| Package | Role |
|
|
21
|
+
|---|---|
|
|
22
|
+
| [`@cascaide-ts/helpers`](https://github.com/Airavat-Research/cascaide-ts/tree/master/packages/helpers) | Agent factories (`createReactAgent`, `createSupervisorAgent`, …) and LLM utilities |
|
|
23
|
+
| [`@cascaide-ts/react`](https://github.com/Airavat-Research/cascaide-ts/tree/master/packages/react) | Client-side runtime: `WorkflowProvider`, `WorkflowRenderer`, hooks |
|
|
24
|
+
| [`@cascaide-ts/postgres-js`](https://github.com/Airavat-Research/cascaide-ts/tree/master/packages/postgres-js) | Postgres `Persistor` for durable cascades |
|
|
25
|
+
| [`@cascaide-ts/server-next`](https://github.com/Airavat-Research/cascaide-ts/tree/master/packages/server-next) | Next.js adapter |
|
|
26
|
+
| [`@cascaide-ts/server-hono`](https://github.com/Airavat-Research/cascaide-ts/tree/master/packages/server-hono) | Hono adapter |
|
|
27
|
+
| [`@cascaide-ts/server-fastify`](https://github.com/Airavat-Research/cascaide-ts/tree/master/packages/server-fastify) | Fastify adapter |
|
|
28
|
+
| [`@cascaide-ts/server-express`](https://github.com/Airavat-Research/cascaide-ts/tree/master/packages/server-express) | Express adapter |
|
|
29
|
+
| [`@cascaide-ts/cli`](https://github.com/Airavat-Research/cascaide-ts/tree/master/packages/cli) | `npx create-cascaide-app` — scaffold a working app in one command |
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## Additional Resources
|
|
35
|
+
|
|
36
|
+
[Introduction](https://www.cascaide-ts.com/docs/introduction)
|
|
37
|
+
[Quickstart](https://www.cascaide-ts.com/docs/QuickStart/overview)
|
|
38
|
+
[Basic Concepts](https://www.cascaide-ts.com/docs/Learn/basic_concepts)
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
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
|
|
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 we={context:{},activeNodes:{},history:[],errors:{}},K= exports.workflowSlice =_toolkit.createSlice.call(void 0, {name:"workflow",initialState:we,reducers:{updateContext:{reducer:(n,a)=>{Object.entries(a.payload).forEach(([t,e])=>{if(n.context[t]||(n.context[t]=[]),typeof e=="object"&&e!==null&&!Array.isArray(e)&&"index"in e){let r=e.index;n.context[t][r]=e}else n.context[t].push(e)})},prepare:(n,a)=>({payload:n,meta:a||{}})},addActiveNode:{reducer:(n,a)=>{let{nodeId:t,nodeName:e,parentTriggerId:r,contextData:o}=a.payload,{origin:s,functionId:i,cascadeId:c}=a.meta;n.activeNodes[t]={nodeName:e,parentTriggerId:r,processed:!1,initialContext:o,origin:s,functionId:i,cascadeId:c||_optionalChain([o, 'optionalAccess', _2 => _2.cascadeId])},n.errors[t]&&delete n.errors[t]},prepare:(n,a)=>{let t=_optionalChain([a, 'optionalAccess', _3 => _3.cascadeId])||_optionalChain([n, 'access', _4 => _4.contextData, 'optionalAccess', _5 => _5.cascadeId]);return{payload:n,meta:{...a,cascadeId:t}}}},removeActiveNode:{reducer:(n,a)=>{let{nodeId:t}=a.payload;n.activeNodes[t]&&(n.history.push({nodeId:t,nodeName:n.activeNodes[t].nodeName,timestamp:Date.now()}),delete n.activeNodes[t])},prepare:(n,a)=>({payload:n,meta:a||{}})},setError:{reducer:(n,a)=>{let{nodeId:t,error:e}=a.payload;n.errors[t]=e},prepare:(n,a)=>({payload:n,meta:a||{}})},markNodeProcessed:(n,a)=>{let{nodeId:t}=a.payload;n.activeNodes[t]&&(n.activeNodes[t].processed=!0)},streamChunkReceived:(n,a)=>{let{cascadeId:t,identity:e,value:r}=a.payload;if(!e||r===void 0)return;let o=n.context[t];if(!o||o.length===0)return;let i=o[o.length-1].history,c=i[i.length-1];!c||c.role!=="assistant"||(typeof c[e]=="string"?c[e]+=r:c[e]=r)},hydrateContext:(n,a)=>{Object.entries(a.payload).forEach(([t,e])=>{n.context[t]=e})},forkAndHydrate:{reducer:()=>{},prepare:n=>({payload:n})}}}),{updateContext:S,addActiveNode:I,removeActiveNode:N,setError:R,markNodeProcessed:We,streamChunkReceived:X,hydrateContext:W,forkAndHydrate:j}=K.actions,ee=K.reducer;var _uuid = require('uuid');var B=_toolkit.createListenerMiddleware.call(void 0, ),he=B.startListening,te=`
|
|
2
2
|
__END_STREAM_METADATA__
|
|
3
|
-
`,
|
|
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=`
|
|
3
|
+
`,re=n=>{he({actionCreator:I,effect:async(a,t)=>{let{nodeId:e,nodeName:r,contextData:o}=a.payload,{functionId:s}=a.meta,i=n.workflowGraph[r],c=n.isLite;if(!(!i||i.isUINode)){if(_optionalChain([o, 'optionalAccess', _6 => _6.sentFromClient])&&!_optionalChain([o, 'optionalAccess', _7 => _7.handledTimeout])){let{cascadeId:d,userId:f,history:l,sentFromClient:u,...m}=o,p=c?_nullishCoalesce(_optionalChain([l, 'optionalAccess', _8 => _8.slice, 'call', _9 => _9(-1)]), () => ([])):[..._nullishCoalesce(l, () => ([]))];await t.dispatch(S({[d]:{...m,history:p,status:"completed"}},{functionId:s,cascadeId:d}))}try{let d=await fetch(n.actionRelayEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},signal:t.signal,body:JSON.stringify(a)});if(!d.ok||!d.body)throw new Error(await d.text()||"Action relay failed");let f=_optionalChain([o, 'optionalAccess', _10 => _10.cascadeId]);await Ie(d.body,f,e,t,a,c)}catch(d){if(d.name==="AbortError")return;await t.dispatch(R({nodeId:e,error:d.message})),await t.dispatch(N({nodeId:e,hasSpawns:!1}))}}}})};async function Ie(n,a,t,e,r,o){let s=n.getReader(),i=new TextDecoder,c="",d=!1;try{for(;;){let{done:f,value:l}=await s.read();if(f)break;if(c+=i.decode(l,{stream:!0}),!d){let u=c.indexOf(te);if(u!==-1){let m=c.substring(0,u),p=c.substring(u+te.length);if(await ae(m,a,e),p.trim())try{let h=JSON.parse(p.trim());await Ce(h,t,e,r,o)}catch(h){console.error("Metadata parse error",h)}d=!0;break}c=await ae(c,a,e)}}}finally{s.releaseLock()}}async function ae(n,a,t){let e=n.split(`
|
|
4
|
+
`),r=e.pop()||"";for(let o of e)if(!(!o.trim()||o.startsWith(":")))try{let s=JSON.parse(o);s.type==="init"?await t.dispatch(S({[s.cascadeId]:{history:[{role:"assistant"}],status:"streaming"}})):s.type==="sync"?await t.dispatch(S({[s.cascadeId]:{history:s.history,status:"completed"}})):s.type==="ui_spawn"?await t.dispatch(I({nodeId:`${s.nodeName}_${_uuid.v7.call(void 0, )}`,nodeName:s.nodeName,contextData:s.contextData})):await t.dispatch(X({cascadeId:s.cascadeId,identity:s.identity,value:s.value}))}catch(s){console.error("Chunk parse error",s)}return r}async function Ce(n,a,t,e,r){let o=_nullishCoalesce(_optionalChain([e, 'access', _11 => _11.meta, 'optionalAccess', _12 => _12.functionId]), () => (0)),s=_nullishCoalesce(_optionalChain([e, 'access', _13 => _13.meta, 'optionalAccess', _14 => _14.origin]), () => ("server")),i=_optionalChain([e, 'access', _15 => _15.payload, 'access', _16 => _16.contextData, 'optionalAccess', _17 => _17.cascadeId]),c=l=>{if(!r)return l;let u=t.getState().workflow.context[i],m=Object.keys(u||{}),p=Object.fromEntries(Object.entries(l||{}).filter(([y])=>!m.includes(y))),h=u.flatMap(y=>y.history||[]);return{...p,history:h,sentFromClient:!0,handledTimeout:!0}},d=n.spawns?Object.entries(n.spawns):[],f=d.length>0;f&&d.forEach(async([l,u],m)=>{let p=c(u);await t.dispatch(I({nodeId:`${l}_${_uuid.v7.call(void 0, )}_${m}`,nodeName:l,parentTriggerId:a,contextData:{...p,cascadeId:i,userId:_optionalChain([p, 'optionalAccess', _18 => _18.userId])||_optionalChain([e, 'access', _19 => _19.payload, 'access', _20 => _20.contextData, 'optionalAccess', _21 => _21.userId])}},{functionId:r?0:o+1+m,cascadeId:i,origin:s}))}),await t.dispatch(N({nodeId:a,hasSpawns:f,fullOutput:n.updates},{functionId:void 0,cascadeId:i,origin:s}))}var ve=_toolkit.combineReducers.call(void 0, {workflow:K.reducer}),Ze= exports.createClientStore =(n,a,t,e=[])=>{re({workflowGraph:n,actionRelayEndpoint:a,isLite:!t});let o=[];return t&&o.push(oe({persistenceEndpoint:t}),se({persistenceEndpoint:t})),o.push(...e),o.push(B.middleware),_toolkit.configureStore.call(void 0, {reducer:ve,middleware:s=>s({serializableCheck:!1}).concat(o),devTools:process.env.NODE_ENV!=="production"})};var D=process.env.NODE_ENV==="development";async function Y(n,a=3,t=100){for(let e=1;e<=a;e++)try{return await n()}catch(r){if(e===a)return D&&console.error(`[SERVER MW] \u274C All ${a} retry attempts failed:`,r),null;let o=t*Math.pow(2,e-1);D&&console.warn(`[SERVER MW] \u26A0\uFE0F Attempt ${e} failed, retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o))}return null}var ie=n=>a=>t=>async e=>{if(I.match(e)){let{origin:r,functionId:o,cascadeId:s,userId:i}=e.meta,{nodeId:c,nodeName:d,contextData:f}=e.payload;if(!s||r)return t(e);let l=_nullishCoalesce(o, () => (0)),u=await Y(async()=>await n.claimNodeExecution({nodeInstanceId:c,cascadeId:s,userId:i||f.userId,nodeName:d,functionId:l,inputContext:f,location:"server"}));if(!u){D&&console.error(`[SERVER MW] \u274C Failed to claim node ${c} after retries`);return}D&&console.log(`[SERVER MW] \u2705 Claimed node ${c} with FnId: ${u.functionId}`);let m={...e,meta:{...e.meta,origin:"server",functionId:u.functionId,cascadeId:s}};return t(m)}if(N.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,i=typeof e.payload=="string"?e.payload:e.payload.nodeId,c=_nullishCoalesce(e.payload.hasSpawns, () => (!1)),d=e.payload.fullOutput,f=a.getState(),l=f.workflow.activeNodes[i],u=s||_optionalChain([l, 'optionalAccess', _22 => _22.cascadeId]),m=_nullishCoalesce(_nullishCoalesce(o, () => (_optionalChain([l, 'optionalAccess', _23 => _23.functionId]))), () => (0));if(!u||r)return t(e);let p=d||f.workflow.context[u];if(!await Y(async()=>await n.finalizeNodeExecution({nodeInstanceId:i,cascadeId:u,fullOutput:p,hasSpawns:c}))){D&&console.error(`[SERVER MW] \u274C Failed to finalize node ${i} after retries`);return}let y={...e,meta:{...e.meta,origin:"server",functionId:m,cascadeId:u}};return t(y)}if(R.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,{nodeId:i,error:c}=e.payload,f=a.getState().workflow.activeNodes[i],l=s||_optionalChain([f, 'optionalAccess', _24 => _24.cascadeId]),u=_nullishCoalesce(_nullishCoalesce(o, () => (_optionalChain([f, 'optionalAccess', _25 => _25.functionId]))), () => (0));if(!l||r)return t(e);if(!await Y(async()=>await n.markExecutionFailed(i,l,c))){D&&console.error(`[SERVER MW] \u274C Failed to mark node ${i} as failed after retries`);return}let p={...e,meta:{...e.meta,origin:"server",functionId:u,cascadeId:l}};return t(p)}if(S.match(e)){let{origin:r,functionId:o,cascadeId:s,uiUpdates:i}=e.meta,c=e.payload,d=s,f=_nullishCoalesce(o, () => (0));if(!d||r)return t(e);let l=c[d];if(l&&l.status==="streaming")return t(e);if(!await Y(async()=>await n.recordContextEvents({cascadeId:d,functionId:f,updates:c,uiUpdates:i}))){D&&console.error(`[SERVER MW] \u274C Failed to record context for cascade ${d} after retries`);return}let m={...e,meta:{...e.meta,origin:"server",functionId:f,cascadeId:d}};return t(m)}return t(e)};var T=process.env.NODE_ENV==="development";async function ce(n,a=3,t=100){for(let e=1;e<=a;e++)try{return await n()}catch(r){if(e===a)return T&&console.error(`[SERVER HYDRATION] \u274C All ${a} attempts failed:`,r),null;let o=t*Math.pow(2,e-1);T&&console.warn(`[SERVER HYDRATION] \u26A0\uFE0F Attempt ${e} failed, retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o))}return null}var de=n=>a=>t=>async e=>{if(I.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta;if(s&&o>0&&r){let c=a.getState().workflow.context[s];if(!c||Object.keys(c).length===0){T&&console.log(`[SERVER HYDRATION] \u{1F9CA} Cold start for ${s}`);let d=await ce(async()=>await n.hydrateCascadeContext(s,o+1));if(!d){let f=`[SERVER HYDRATION] \u{1F6D1} Critical: Hydration failed for ${s}. Terminating action.`;throw T&&console.error(f),new Error("Server-side hydration failed: persistence unreachable.")}Object.keys(d).length>0&&(await a.dispatch(W(d)),T&&console.log("[SERVER HYDRATION] \u2705 State restored successfully"))}}}if(j.match(e)){let{sourceCascadeId:r,newCascadeId:o,upToFunctionId:s}=e.payload;T&&console.log(`[SERVER FORK] \u{1F374} Forking ${r} \u2192 ${o} at fn ${s}`);let i=await ce(async()=>await n.forkCascadeWithContext({sourceCascadeId:r,newCascadeId:o,upToFunctionId:s}));if(!i){let c=`[SERVER FORK] \u{1F6D1} Critical: Fork failed for ${r}. Terminating action.`;throw T&&console.error(c),new Error("Server-side fork failed: persistence unreachable.")}i.context&&Object.keys(i.context).length>0?(await a.dispatch(W(i.context)),T&&console.log(`[SERVER FORK] \u2705 Fork complete, context hydrated for ${o}`)):T&&console.log(`[SERVER FORK] \u2705 Fork complete, no context to hydrate for ${o}`)}return t(e)};var ct=(n,a=[])=>{let t=_toolkit.createListenerMiddleware.call(void 0, ),e=[];return n&&e.push(ie(n),de(n)),e.push(...a),e.push(t.middleware),{store:_toolkit.configureStore.call(void 0, {reducer:{workflow:ee},middleware:o=>o({serializableCheck:!1}).concat(e),devTools:process.env.NODE_ENV!=="production"}),serverListener:t}};async function lt(n,a,t){switch(a){case"claim":return await n.claimNodeExecution(t);case"finalize":return await n.finalizeNodeExecution(t);case"error":return await n.markExecutionFailed(t.nodeInstanceId,t.cascadeId,t.error);case"context":return await n.recordContextEvents(t);case"hydrate":return await n.hydrateCascadeContext(t.cascadeId,t.functionId,t.ui);case"forkAndHydrate":return await n.forkCascadeWithContext({sourceCascadeId:t.sourceCascadeId,newCascadeId:t.newCascadeId,upToFunctionId:t.upToFunctionId});default:throw new Error("Invalid action")}}var Ee=()=>{let n=!1;return a=>{if(a.type==="content_block_start"){let t=()=>(n=!0,{identity:"role",value:"assistant",silent:!0});if(_optionalChain([a, 'access', _26 => _26.content_block, 'optionalAccess', _27 => _27.type])==="thinking")return[...n?[]:[t()],{identity:"thinking",value:""}];if(_optionalChain([a, 'access', _28 => _28.content_block, 'optionalAccess', _29 => _29.type])==="text")return[...n?[]:[t()],{identity:"content",value:""}];if(_optionalChain([a, 'access', _30 => _30.content_block, 'optionalAccess', _31 => _31.type])==="tool_use")return[...n?[]:[t()],{identity:"tool_calls",value:[],buffer:!0,accumulate:(e=[],r)=>(e.push({id:a.content_block.id,name:a.content_block.name,args:{}}),e)}]}if(a.type==="content_block_delta"){if(_optionalChain([a, 'access', _32 => _32.delta, 'optionalAccess', _33 => _33.type])==="text_delta")return{identity:"content",value:a.delta.text};if(_optionalChain([a, 'access', _34 => _34.delta, 'optionalAccess', _35 => _35.type])==="thinking_delta")return{identity:"thinking",value:a.delta.thinking};if(_optionalChain([a, 'access', _36 => _36.delta, 'optionalAccess', _37 => _37.type])==="signature_delta")return{identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(t={},e)=>({...t,anthropic:{..._nullishCoalesce(t.anthropic, () => ({})),signature:a.delta.signature}})};if(_optionalChain([a, 'access', _38 => _38.delta, 'optionalAccess', _39 => _39.type])==="input_json_delta")return{identity:"tool_calls",value:a.delta.partial_json,buffer:!0,accumulate:(t=[],e)=>{let r=t[t.length-1];return r&&(r._rawArgs=(_nullishCoalesce(r._rawArgs, () => ("")))+e),t}}}return a.type==="content_block_stop"?{identity:"tool_calls",value:null,buffer:!0,accumulate:(t=[],e)=>{let r=t[t.length-1];if(r&&r._rawArgs!==void 0){try{r.args=JSON.parse(r._rawArgs||"{}")}catch (e2){r.args={}}delete r._rawArgs}return t}}:null}},_e=()=>{let n=!1;return a=>{let t=_optionalChain([a, 'access', _40 => _40.choices, 'optionalAccess', _41 => _41[0], 'optionalAccess', _42 => _42.delta]);if(!t)return null;let e=[];if(n||(n=!0,e.push({identity:"role",value:"assistant",silent:!0})),t.reasoning_content&&e.push({identity:"thinking",value:t.reasoning_content}),t.content&&e.push({identity:"content",value:t.content}),t.tool_calls){let r=t.tool_calls[0],o=_nullishCoalesce(r.index, () => (0));e.push({identity:"tool_calls",value:r,buffer:!0,accumulate:(s=[],i)=>(s[o]||(s[o]={id:"",name:"",args:{}}),i.id&&(s[o].id=i.id),_optionalChain([i, 'access', _43 => _43.function, 'optionalAccess', _44 => _44.name])&&(s[o].name+=i.function.name),_optionalChain([i, 'access', _45 => _45.function, 'optionalAccess', _46 => _46.arguments])&&(s[o]._rawArgs=(_nullishCoalesce(s[o]._rawArgs, () => ("")))+i.function.arguments),s)})}return _optionalChain([a, 'access', _47 => _47.choices, 'optionalAccess', _48 => _48[0], 'optionalAccess', _49 => _49.finish_reason])==="tool_calls"&&e.push({identity:"tool_calls",value:null,buffer:!0,accumulate:(r=[],o)=>r.map(s=>{if(s._rawArgs!==void 0){try{s.args=JSON.parse(s._rawArgs||"{}")}catch (e3){s.args={}}delete s._rawArgs}return s})}),e.length===0?null:e.length===1?e[0]:e}},Me=()=>{let n=!1,a=[];return t=>{let e=_nullishCoalesce(_optionalChain([t, 'access', _50 => _50.candidates, 'optionalAccess', _51 => _51[0], 'optionalAccess', _52 => _52.content, 'optionalAccess', _53 => _53.parts]), () => ([]));if(!e.length)return null;let r=[];n||(n=!0,r.push({identity:"role",value:"assistant",silent:!0}));for(let o of e)if(o.thought===!0&&o.text){let s=a.find(i=>i.thought===!0);s?(s.text+=o.text,o.thoughtSignature&&(s.thoughtSignature=o.thoughtSignature)):a.push({...o}),r.push({identity:"thinking",value:o.text}),o.thoughtSignature&&r.push({identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(i={},c)=>({...i,gemini:{..._nullishCoalesce(i.gemini, () => ({})),thoughtSignature:o.thoughtSignature,parts:[...a]}})})}else if(o.text&&o.thought!==!0){let s=a.find(i=>i.text!==void 0&&!i.thought&&!i.functionCall);s?s.text+=o.text:a.push({text:o.text}),r.push({identity:"content",value:o.text}),r.push({identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(i={},c)=>({...i,gemini:{..._nullishCoalesce(i.gemini, () => ({})),parts:[...a]}})})}else o.functionCall&&(a.push({...o}),r.push({identity:"tool_calls",value:null,buffer:!0,accumulate:(s=[],i)=>a.filter(c=>c.functionCall).map(c=>({id:_nullishCoalesce(c.functionCall.id, () => (c.functionCall.name)),name:c.functionCall.name,args:_nullishCoalesce(c.functionCall.args, () => ({}))}))}),r.push({identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(s={},i)=>({...s,gemini:{..._nullishCoalesce(s.gemini, () => ({})),parts:[...a]}})}));return r.length===0?null:r.length===1?r[0]:r}},Te=()=>{let n=[];return a=>{if(a.type==="response.output_item.added"){let t=a.item;if(!t)return null;if(t.type==="reasoning")return n.push({id:t.id,type:"reasoning",summary:[{type:"summary_text",text:""}]}),$("openai_responses",n);if(t.type==="message")return n.push({id:t.id,type:"message",role:"assistant",content:[{type:"output_text",text:""}]}),[{identity:"role",value:"assistant",silent:!0},$("openai_responses",n)];if(t.type==="function_call")return n.push({id:t.id,type:"function_call",call_id:t.call_id,name:t.name,arguments:""}),$("openai_responses",n)}if(a.type==="response.reasoning_summary_text.delta"){let t=n.find(e=>e.id===a.item_id&&e.type==="reasoning");return t&&(t.summary[0].text+=a.delta),[$("openai_responses",n),{identity:"thinking",value:a.delta}]}if(a.type==="response.output_text.delta"){let t=n.find(e=>e.id===a.item_id&&e.type==="message");return t&&(t.content[0].text+=a.delta),[$("openai_responses",n),{identity:"content",value:a.delta}]}if(a.type==="response.function_call_arguments.delta"){let t=n.find(e=>e.id===a.item_id&&e.type==="function_call");return t&&(t.arguments+=a.delta),$("openai_responses",n)}if(a.type==="response.function_call_arguments.done"){let t=n.find(r=>r.id===a.item_id&&r.type==="function_call");t&&(t.arguments=_nullishCoalesce(a.arguments, () => ("{}")));let e=n.filter(r=>r.type==="function_call").map(r=>({id:r.call_id,name:r.name,args:(()=>{try{return JSON.parse(r.arguments||"{}")}catch (e4){return{}}})()}));return[$("openai_responses",n),{identity:"tool_calls",value:e,buffer:!0,accumulate:(r,o)=>o}]}return null}};function $(n,a){return{identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(t={},e)=>({...t,[n]:{output:[...a]}})}}var q={anthropic:Ee,openai:_e,"gemini-genai":Me,"openai-responses":Te};var _reselect = require('reselect');var be=n=>n.workflow.activeNodes,le=n=>n.workflow.context,ue=(n,a)=>a,V= exports.makeSelectCascadeState =()=>_reselect.createSelector.call(void 0, [le,ue],(n,a)=>{let t=n[a];if(!t||t.length===0)return;let e=t[t.length-1].status,r={};return t.forEach(o=>{let{status:s,...i}=o;Object.entries(i).forEach(([c,d])=>{d!=null&&(r[c]||(r[c]=[]),Array.isArray(d)?r[c].push(...d):r[c].push(d))})}),{...r,status:e}}),J= exports.makeSelectCascadeNodes =()=>_reselect.createSelector.call(void 0, [be,ue],(n,a)=>Object.entries(n).filter(([t,e])=>_optionalChain([e, 'access', _54 => _54.initialContext, 'optionalAccess', _55 => _55.cascadeId])===a).map(([t,e])=>({nodeId:t,nodeName:e.nodeName,parentTriggerId:e.parentTriggerId,initialContext:e.initialContext,processed:e.processed}))),mt= exports.selectAllCascadeIds =_reselect.createSelector.call(void 0, [le],n=>Object.keys(n));function fe(n){return{updateContext:async a=>{await n.dispatch(S(a))},spawn:async a=>{let t=[];for(let[e,r]of Object.entries(a)){let o=`${e}_${_uuid.v7.call(void 0, )}`;await n.dispatch(I({nodeId:o,nodeName:e,contextData:r},{cascadeId:r.cascadeId,userId:r.userId,functionId:0})),r.cascadeId&&t.push(r.cascadeId)}t.length!==0&&await n.condition((e,r)=>t.every(o=>{let s=J()(r,o),i=V()(r,o);return s.length===0&&i!==void 0}))},fork:async(a,t,e)=>{try{return await n.dispatch(j({sourceCascadeId:e,newCascadeId:a,upToFunctionId:t})),{status:"SUCCESS"}}catch (e5){return{status:"FAILED"}}},waitUntil:async a=>{await n.condition((t,e)=>a(e))},getCascadeState:a=>V()(n.getState(),a),getCascadeNodes:a=>J()(n.getState(),a),isComplete:a=>{let t=n.getState();return J()(t,a).length===0&&V()(t,a)!==void 0},exists:a=>{let t=n.getState();return V()(t,a)!==void 0||J()(t,a).length>0},getState:()=>n.getState()}}var pe=process.env.NODE_ENV==="development",k=(...n)=>{pe&&console.log(...n)},Re=(...n)=>{pe&&console.error(...n)};function kt(n,a,t,e,r,o){let s=`
|
|
5
5
|
__END_STREAM_METADATA__
|
|
6
|
-
`,{
|
|
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;
|
|
6
|
+
`,{writeRaw:i,close:c,send:d}=t;n.startListening({actionCreator:I,effect:async(f,l)=>{let{nodeId:u,nodeName:m,contextData:p}=f.payload,{functionId:h=0}=_nullishCoalesce(f.meta, () => ({})),y=a.workflowGraph[m],O=p.userId,G=fe(l);k(`
|
|
7
|
+
[Node ] \u{1F680} Starting: ${m}`);let C=_optionalChain([p, 'access', _56 => _56.cascadeId, 'optionalAccess', _57 => _57.startsWith, 'call', _58 => _58("call")]);if(!y||y.isUINode){k("[Node ] \u{1F5A5}\uFE0F UI Node detected. Handing off to client listener."),await d({type:"ui_spawn",nodeName:m,contextData:p}),await l.dispatch(N({nodeId:u,hasSpawns:!1},{origin:"server"}));let E=_optionalChain([l, 'access', _59 => _59.getState, 'call', _60 => _60(), 'access', _61 => _61.workflow, 'optionalAccess', _62 => _62.activeNodes])||{},g=Object.keys(E);k("[Server] Active node keys remaining:",g),g.length===0&&(k(`[Server] \u{1F3C1} State reached Zero. Closing stream. Triggered by completion of: ${m}`),await c());return}try{if(h==0){let{cascadeId:v,userId:L,history:U,sentFromClient:F,..._}=p;await l.dispatch(S({[_optionalChain([p, 'optionalAccess', _63 => _63.cascadeId])]:{..._,history:[..._optionalChain([p, 'optionalAccess', _64 => _64.history])],status:"completed"}},{origin:"server"})),p.sentFromClient||await d({type:"sync",cascadeId:p.cascadeId,history:[..._optionalChain([p, 'optionalAccess', _65 => _65.history])],status:"completed"})}let x=structuredClone(p),E={};if(y.prep){let v=l.getState().workflow.context;E=await y.prep(v,x)}let g=E.cascadeId||p.cascadeId,M=_nullishCoalesce(_optionalChain([f, 'access', _66 => _66.meta, 'optionalAccess', _67 => _67.functionId]), () => (0)),w=null;if(y.isStreaming){k("[Node ] \u{1F30A} Executing Streaming Node...");let v=await y.exec(E,G),{canonical:L,uiMessage:U}=await Ae(v,g,d,o);w=await y.post({assistantMessage:L,uiAssistantMessage:U,cascadeId:g,history:structuredClone(E.history),userId:p.userId})}else{k("[Node ] \u26A1 Executing Standard Node...");let v=await y.exec(E,G);w=await y.post(v)}if(w){let v=Date.now()-r,L=a.maxExecutionTime-v,U=w.spawns?Object.keys(w.spawns):[];if(U.length)if(L>a.safeBuffer){k(`[Node ] \u2705 Internally Spawning: ${U.join(", ")} (${Math.round(L/1e3)}s remaining)`);let F=w.updates[g];if(w.updates){await l.dispatch(S(w.updates,{functionId:M,cascadeId:g,uiUpdates:w.uiUpdates}));let P=_nullishCoalesce(_optionalChain([w, 'access', _68 => _68.uiUpdates, 'optionalAccess', _69 => _69[g]]), () => (_optionalChain([w, 'access', _70 => _70.updates, 'optionalAccess', _71 => _71[g]])));P&&!y.isStreaming&&(k("[Node ] \u{1F504} Syncing context chunk to client UI."),await d({type:"sync",cascadeId:g,...P}))}let _=Object.entries(w.spawns);_.every(([P])=>!a.workflowGraph[P]||a.workflowGraph[P].isUINode)?await i(s+JSON.stringify(w)):_.forEach(async([P,H],Q)=>{await l.dispatch(I({nodeId:`${P}_${_uuid.v7.call(void 0, )}_${Q}`,nodeName:P,parentTriggerId:u,contextData:_optionalChain([H, 'optionalAccess', _72 => _72.userId])?H:{...H,userId:O}},{functionId:M+1+Q,cascadeId:_optionalChain([H, 'optionalAccess', _73 => _73.cascadeId]),userId:_optionalChain([H, 'optionalAccess', _74 => _74.userId])||O}))}),await l.dispatch(N({nodeId:u,hasSpawns:!0,fullOutput:F},{functionId:M,cascadeId:g}))}else{k("[Node ] \u23F3 Time Buffer Reached. Handing off to client to checkpoint.");let F=w.updates[g];if(w.updates){await l.dispatch(S(w.updates,{functionId:M,cascadeId:g,uiUpdates:w.uiUpdates}));let _=_nullishCoalesce(_optionalChain([w, 'access', _75 => _75.uiUpdates, 'optionalAccess', _76 => _76[g]]), () => (_optionalChain([w, 'access', _77 => _77.updates, 'optionalAccess', _78 => _78[g]])));_&&!y.isStreaming&&(k("[Node ] \u{1F504} Syncing context chunk to client UI."),await d({type:"sync",cascadeId:g,..._}))}await l.dispatch(N({nodeId:u,hasSpawns:!0,fullOutput:F},{functionId:M,cascadeId:g})),await i(s+JSON.stringify(w))}else{k("[Node ] \u{1F3C1} Chain Terminal. Dispatching completion.");let F=w.updates[g];if(w.updates){await l.dispatch(S(w.updates,{functionId:M,cascadeId:g,uiUpdates:w.uiUpdates}));let _=_nullishCoalesce(_optionalChain([w, 'access', _79 => _79.uiUpdates, 'optionalAccess', _80 => _80[g]]), () => (_optionalChain([w, 'access', _81 => _81.updates, 'optionalAccess', _82 => _82[g]])));_&&!y.isStreaming&&(k("[Node ] \u{1F504} Syncing context chunk to client UI."),await d({type:"sync",cascadeId:g,..._}))}await l.dispatch(N({nodeId:u,hasSpawns:!1,fullOutput:F},{functionId:M,cascadeId:g})),C||await i(s+JSON.stringify(w))}}}catch(x){Re("[Node ] \u274C Execution Error:",x.message),await l.dispatch(R({nodeId:u,error:x.message},{functionId:_optionalChain([f, 'access', _83 => _83.meta, 'optionalAccess', _84 => _84.functionId]),cascadeId:_optionalChain([p, 'optionalAccess', _85 => _85.cascadeId])})),await l.dispatch(N({nodeId:u,hasSpawns:!1,fullOutput:void 0},{functionId:_optionalChain([f, 'access', _86 => _86.meta, 'optionalAccess', _87 => _87.functionId]),cascadeId:_optionalChain([p, 'optionalAccess', _88 => _88.cascadeId]),origin:"server"})),await i(s+JSON.stringify({error:x.message}))}finally{let E=_optionalChain([l, 'access', _89 => _89.getState, 'call', _90 => _90(), 'access', _91 => _91.workflow, 'optionalAccess', _92 => _92.activeNodes])||{},g=Object.keys(E);k("[Server] Active node keys remaining:",g),g.length===0&&(k(`[Server] \u{1F3C1} State reached Zero. Closing stream. Triggered by completion of: ${m}`),await c())}}})}async function Ae(n,a,t,e){let{stream:r,provider:o,mapper:s,filter:i}=n,c=_nullishCoalesce(s, () => (q[o]));if(!c)throw new Error(`[handleProviderStream] No mapper found for provider "${o}". Pass a custom mapper via StreamConfig.mapper, or use one of the built-in providers: ${Object.keys(q).join(", ")}.`);let d=typeof c=="function"&&c.length===0?c():c,f=a.startsWith("_");f||await t({type:"init",cascadeId:a});let l={},u={},m=!1,p=new Set;for await(let h of r){let y=d(h);if(!y)continue;let O=Array.isArray(y)?y:[y];for(let G of O){let{identity:C,value:x,accumulate:E,buffer:g,silent:M}=G;if(E?l[C]=E(l[C],x):typeof l[C]=="string"&&typeof x=="string"?l[C]+=x:l[C]=x,!(M&&(!e||C==="role"))){if(g){p.add(C);continue}if(!f){let w=typeof x=="string"?x:l[C];if(i&&!e){let v=i(C,w);m=!0,v!==!1&&(await t({cascadeId:a,identity:C,value:v}),typeof v=="string"?u[C]=(_nullishCoalesce(u[C], () => ("")))+v:u[C]=v)}else await t({cascadeId:a,identity:C,value:w})}}}}if(!f)for(let h of p){if(l[h]===void 0)continue;let y=l[h];if(i&&!e){let O=i(h,y);m=!0,O!==!1&&(await t({cascadeId:a,identity:h,value:O}),u[h]=O)}else await t({cascadeId:a,identity:h,value:y})}return{canonical:l,...m?{uiMessage:u}:{}}}var A=process.env.NODE_ENV==="development";async function z(n,a=3,t=100){for(let e=1;e<=a;e++)try{return await n()}catch(r){if(e===a)return A&&console.error(`[CLIENT MW] \u274C All ${a} retry attempts failed:`,r),null;let o=t*Math.pow(2,e-1);A&&console.warn(`[CLIENT MW] \u26A0\uFE0F Attempt ${e} failed, retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o))}return null}var oe=n=>a=>t=>async e=>{if(I.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,{nodeId:i,nodeName:c,contextData:d}=e.payload;if(!s||r)return t(e);let f=_nullishCoalesce(o, () => (0)),l=await z(async()=>{let p=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"claim",nodeInstanceId:i,cascadeId:s,userId:d.userId,nodeName:c,functionId:f,inputContext:d,location:"client"})});if(!p.ok)throw new Error(`Persistence sync failed: ${p.status}`);return await p.json()});if(!l){A&&console.error(`[CLIENT MW] \u274C Failed to claim node ${i} after retries`);return}let u=l.functionId;A&&console.log(`[CLIENT MW] \u2705 Node ${i} bound to FnId: ${u}`);let m={...e,meta:{...e.meta,origin:"client",functionId:u,cascadeId:s}};return t(m)}if(N.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,i=typeof e.payload=="string"?e.payload:e.payload.nodeId,c=e.payload.hasSpawns,d=e.payload.fullOutput,f=a.getState(),l=f.workflow.activeNodes[i],u=s||_optionalChain([l, 'optionalAccess', _93 => _93.cascadeId]),m=_nullishCoalesce(_nullishCoalesce(o, () => (_optionalChain([l, 'optionalAccess', _94 => _94.functionId]))), () => (0));if(!u||r)return t(e);let p=d||f.workflow.context[u];if(!await z(async()=>{let y=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"finalize",nodeInstanceId:i,cascadeId:u,fullOutput:p,hasSpawns:c})});if(!y.ok)throw new Error(`Persistence sync failed: ${y.status}`);return await y.json()})){A&&console.error(`[CLIENT MW] \u274C Failed to finalize node ${i} after retries`);return}return t({...e,meta:{...e.meta,origin:"client",functionId:m,cascadeId:u}})}if(R.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,{nodeId:i,error:c}=e.payload,f=a.getState().workflow.activeNodes[i],l=s||_optionalChain([f, 'optionalAccess', _95 => _95.cascadeId]);if(!l||r)return t(e);if(!await z(async()=>{let m=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"error",nodeInstanceId:i,cascadeId:l,error:c})});if(!m.ok)throw new Error(`Persistence sync failed: ${m.status}`);return await m.json()})){A&&console.error(`[CLIENT MW] \u274C Failed to mark node ${i} as failed after retries`);return}return t({...e,meta:{...e.meta,origin:"client",cascadeId:l}})}if(S.match(e)){let{origin:r,functionId:o,cascadeId:s,uiUpdates:i}=e.meta,c=e.payload,d=s,f=_nullishCoalesce(o, () => (0));if(!d||r||(A&&console.log("[CLIENT MW] \u{1F504} Persisting context:",JSON.stringify(c,null,2)),_optionalChain([c, 'access', _96 => _96[d], 'optionalAccess', _97 => _97.status])==="streaming"))return t(e);if(!await z(async()=>{let u=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"context",cascadeId:d,functionId:f,updates:c,uiUpdates:i})});if(!u.ok)throw new Error(`Persistence sync failed: ${u.status}`);return await u.json()})){A&&console.error(`[CLIENT MW] \u274C Failed to record context for cascade ${d} after retries`);return}return t({...e,meta:{...e.meta,origin:"client",functionId:f,cascadeId:d}})}return t(e)};var b=process.env.NODE_ENV==="development";async function me(n,a=3,t=100){for(let e=1;e<=a;e++)try{return await n()}catch(r){if(e===a)return b&&console.error(`[HYDRATION] \u274C All ${a} attempts failed:`,r),null;let o=t*Math.pow(2,e-1);b&&console.warn(`[HYDRATION] \u26A0\uFE0F Attempt ${e} failed, retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o))}return null}var se=n=>a=>t=>async e=>{if(I.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta;if(s&&o>0&&r==="client"){let c=a.getState().workflow.context[s];if(!c||Object.keys(c).length===0){b&&console.log(`[HYDRATION] \u{1F9CA} Cold start for ${s}`);let d=await me(async()=>{let f=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"hydrate",cascadeId:s,functionId:o,ui:!0})});if(!f.ok)throw new Error(`Status ${f.status}`);return await f.json()});if(!d){let f=`[HYDRATION] Critical Failure: Could not hydrate cascade ${s}. Action terminated.`;throw b&&console.error(f),new Error("Hydration failed")}Object.keys(d).length>0&&(a.dispatch(W(d)),b&&console.log("[HYDRATION] \u2705 State restored successfully"))}}}if(j.match(e)){let{sourceCascadeId:r,newCascadeId:o,upToFunctionId:s}=e.payload;b&&console.log(`[FORK] \u{1F374} Forking ${r} \u2192 ${o} at fn ${s}`);let i=await me(async()=>{let c=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"forkAndHydrate",sourceCascadeId:r,newCascadeId:o,upToFunctionId:s})});if(!c.ok)throw new Error(`Fork failed with status ${c.status}`);return await c.json()});if(!i){let c=`[FORK] Critical Failure: Could not fork cascade ${r}. Action terminated.`;throw b&&console.error(c),new Error("Fork failed")}i.context&&Object.keys(i.context).length>0?(a.dispatch(W(i.context)),b&&console.log(`[FORK] \u2705 Fork complete, context hydrated for ${o}`)):b&&console.log(`[FORK] \u2705 Fork complete, no context to hydrate for ${o}`)}return t(e)};exports.addActiveNode = I; exports.createClientHydrationMiddleware = se; exports.createClientPersistenceMiddleware = oe; exports.createClientStore = Ze; exports.createServerHydrationMiddleware = de; exports.createServerPersistenceMiddleware = ie; exports.createServerStore = ct; exports.forkAndHydrate = j; exports.handlePersistenceAction = lt; exports.handleProviderStream = Ae; exports.hydrateContext = W; exports.makeSelectCascadeNodes = J; exports.makeSelectCascadeState = V; exports.markNodeProcessed = We; exports.removeActiveNode = N; exports.selectAllCascadeIds = mt; exports.setError = R; exports.setupServerWorkflowListener = kt; exports.streamChunkReceived = X; exports.updateContext = S; exports.workflowSlice = K;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,9 +1,24 @@
|
|
|
1
1
|
import * as _reduxjs_toolkit from '@reduxjs/toolkit';
|
|
2
|
-
import { configureStore, Middleware, PayloadAction } from '@reduxjs/toolkit';
|
|
2
|
+
import { configureStore, Middleware, ListenerEffectAPI, PayloadAction } from '@reduxjs/toolkit';
|
|
3
3
|
import * as reselect from 'reselect';
|
|
4
4
|
|
|
5
|
+
declare const rootReducer: _reduxjs_toolkit.Reducer<{
|
|
6
|
+
workflow: WorkflowState;
|
|
7
|
+
}, _reduxjs_toolkit.UnknownAction, Partial<{
|
|
8
|
+
workflow: WorkflowState;
|
|
9
|
+
}>>;
|
|
10
|
+
type RootState = ReturnType<typeof rootReducer>;
|
|
11
|
+
type AppDispatch = ReturnType<typeof configureStore>['dispatch'];
|
|
12
|
+
declare const createClientStore: (workflowGraph: ClientWorkflowGraph, actionRelayEndpoint: string, persistenceEndpoint?: string, extraMiddlewares?: Middleware[]) => _reduxjs_toolkit.EnhancedStore<{
|
|
13
|
+
workflow: WorkflowState;
|
|
14
|
+
}, _reduxjs_toolkit.UnknownAction, _reduxjs_toolkit.Tuple<[_reduxjs_toolkit.StoreEnhancer<{
|
|
15
|
+
dispatch: _reduxjs_toolkit.ThunkDispatch<{
|
|
16
|
+
workflow: WorkflowState;
|
|
17
|
+
}, undefined, _reduxjs_toolkit.UnknownAction>;
|
|
18
|
+
}>, _reduxjs_toolkit.StoreEnhancer]>>;
|
|
19
|
+
|
|
5
20
|
type WorkflowStep = {
|
|
6
|
-
history: any;
|
|
21
|
+
history: any[];
|
|
7
22
|
status: string;
|
|
8
23
|
[extraKeys: string]: any;
|
|
9
24
|
};
|
|
@@ -15,6 +30,7 @@ type ActionMeta = {
|
|
|
15
30
|
functionId?: number;
|
|
16
31
|
cascadeId?: string;
|
|
17
32
|
userId?: string;
|
|
33
|
+
uiUpdates?: Updates;
|
|
18
34
|
};
|
|
19
35
|
type ActiveNode = {
|
|
20
36
|
nodeName: string;
|
|
@@ -25,13 +41,6 @@ type ActiveNode = {
|
|
|
25
41
|
functionId?: number;
|
|
26
42
|
cascadeId?: string;
|
|
27
43
|
};
|
|
28
|
-
type StreamChunk = {
|
|
29
|
-
contentChunk?: string;
|
|
30
|
-
toolChunk?: any;
|
|
31
|
-
cascadeId: string;
|
|
32
|
-
reasoningChunk?: string;
|
|
33
|
-
thoughtSignature?: string;
|
|
34
|
-
};
|
|
35
44
|
type NodeHistoryRecord = {
|
|
36
45
|
nodeId: string;
|
|
37
46
|
nodeName: string;
|
|
@@ -63,70 +72,153 @@ interface ClaimResponse {
|
|
|
63
72
|
interface NodeDefinition {
|
|
64
73
|
name: string;
|
|
65
74
|
isUINode: boolean;
|
|
66
|
-
env:
|
|
75
|
+
env: 'client' | 'server';
|
|
67
76
|
}
|
|
68
77
|
type Updates = {
|
|
69
78
|
[cascadeId: string]: WorkflowStep;
|
|
70
79
|
};
|
|
71
80
|
type SpawnContext<T = Record<string, any>> = {
|
|
72
|
-
cascadeId
|
|
73
|
-
history: any;
|
|
74
|
-
userId
|
|
81
|
+
cascadeId?: string;
|
|
82
|
+
history: any[];
|
|
83
|
+
userId?: string;
|
|
75
84
|
} & T;
|
|
85
|
+
type Spawns = Record<string, SpawnContext>;
|
|
76
86
|
type PostResult = {
|
|
77
87
|
updates: Updates;
|
|
78
88
|
uiUpdates?: Updates;
|
|
79
89
|
spawns?: Record<string, SpawnContext>;
|
|
80
90
|
};
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
91
|
+
interface WorkflowHandlerConfig {
|
|
92
|
+
workflowGraph: ServerWorkflowGraph;
|
|
93
|
+
persistor?: CascadePersistence;
|
|
94
|
+
maxExecutionTime?: number;
|
|
95
|
+
safeBuffer?: number;
|
|
96
|
+
extraMiddlewares?: Middleware[];
|
|
87
97
|
}
|
|
88
|
-
type
|
|
98
|
+
type ClientWorkflowGraph = Record<string, NodeDefinition>;
|
|
89
99
|
type StreamEventType = 'init' | 'sync' | 'chunk';
|
|
90
|
-
type
|
|
91
|
-
interface
|
|
92
|
-
|
|
93
|
-
|
|
100
|
+
type ChunkMapper = (chunk: any) => ChunkDelta | ChunkDelta[] | null;
|
|
101
|
+
interface ChunkDelta {
|
|
102
|
+
identity: string;
|
|
103
|
+
value: any;
|
|
104
|
+
accumulate?: (current: any, incoming: any) => any;
|
|
105
|
+
buffer?: boolean;
|
|
106
|
+
silent?: boolean;
|
|
94
107
|
}
|
|
95
|
-
interface
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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;
|
|
108
|
+
interface StreamChunk {
|
|
109
|
+
cascadeId: string;
|
|
110
|
+
identity: string;
|
|
111
|
+
value: any;
|
|
109
112
|
}
|
|
113
|
+
type LLMProvider = 'anthropic' | 'openai-responses' | 'gemini-genai' | 'openai' | 'custom';
|
|
110
114
|
interface StreamConfig {
|
|
111
115
|
stream: AsyncIterable<any>;
|
|
112
|
-
provider:
|
|
113
|
-
|
|
116
|
+
provider: LLMProvider;
|
|
117
|
+
/**
|
|
118
|
+
* Custom mapper — overrides the built-in mapper for this provider.
|
|
119
|
+
* Use when you need to handle a provider variant or custom API shape.
|
|
120
|
+
*/
|
|
121
|
+
mapper?: ChunkMapper | (() => ChunkMapper);
|
|
122
|
+
/**
|
|
123
|
+
* Controls what gets sent to the frontend.
|
|
124
|
+
*
|
|
125
|
+
* Return false → suppress this identity (not sent, not in uiMessage)
|
|
126
|
+
* Return the value → pass through unchanged
|
|
127
|
+
* Return anything else → send this instead (replacement/redaction)
|
|
128
|
+
*
|
|
129
|
+
* When absent, everything non-silent is sent as-is and uiMessage is not
|
|
130
|
+
* populated (persistence middleware treats canonical as the UI source too).
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* // Suppress thinking from frontend
|
|
134
|
+
* filter: (identity, value) => identity === 'thinking' ? false : value
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* // Redact tool call args
|
|
138
|
+
* filter: (identity, value) => {
|
|
139
|
+
* if (identity === 'tool_calls') {
|
|
140
|
+
* return value.map((tc: any) => ({ ...tc, args: { _redacted: true } }));
|
|
141
|
+
* }
|
|
142
|
+
* return value;
|
|
143
|
+
* }
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* // Replace tool result with a UI indicator
|
|
147
|
+
* filter: (identity, value) => {
|
|
148
|
+
* if (identity === 'tool_calls') {
|
|
149
|
+
* return { type: 'tool_indicator', names: value.map((tc: any) => tc.name) };
|
|
150
|
+
* }
|
|
151
|
+
* return value;
|
|
152
|
+
* }
|
|
153
|
+
*/
|
|
154
|
+
filter?: StreamFilter;
|
|
114
155
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
156
|
+
type MapperFactory = () => ChunkMapper;
|
|
157
|
+
interface StreamResult {
|
|
158
|
+
/**
|
|
159
|
+
* Full assembled canonical message — all identities, no filtering.
|
|
160
|
+
* Always present. Written to cascade state as LLM history.
|
|
161
|
+
*/
|
|
162
|
+
canonical: Record<string, any>;
|
|
163
|
+
/**
|
|
164
|
+
* What was actually sent to the frontend — filtered/replaced values only.
|
|
165
|
+
* Only present when a filter was applied. When absent, canonical is the
|
|
166
|
+
* source of truth for UI as well (persistence middleware handles this).
|
|
167
|
+
*/
|
|
168
|
+
uiMessage?: Record<string, any>;
|
|
169
|
+
}
|
|
170
|
+
type StreamFilter = (identity: string, value: any) => any | false;
|
|
171
|
+
type ServerRootState = {
|
|
124
172
|
workflow: WorkflowState;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
173
|
+
};
|
|
174
|
+
type ServerStore = ReturnType<typeof createServerStore>['store'];
|
|
175
|
+
type ServerDispatch = ServerStore['dispatch'];
|
|
176
|
+
type ServerListenerApi = ListenerEffectAPI<ServerRootState, ServerDispatch>;
|
|
177
|
+
type CascadeController = {
|
|
178
|
+
updateContext: (updates: Updates) => void;
|
|
179
|
+
spawn: (spawns: Record<string, SpawnContext>) => Promise<void>;
|
|
180
|
+
fork: (newCascadeId: string, upToFunctionId: number, sourceCascadeId?: string) => Promise<{
|
|
181
|
+
status: 'SUCCESS' | 'FAILED';
|
|
182
|
+
}>;
|
|
183
|
+
waitUntil: (predicate: (state: ServerRootState) => boolean) => Promise<void>;
|
|
184
|
+
getCascadeState: (cascadeId: string) => CascadeStateResult | undefined;
|
|
185
|
+
getCascadeNodes: (cascadeId: string) => CascadeNode[];
|
|
186
|
+
isComplete: (cascadeId: string) => boolean;
|
|
187
|
+
exists: (cascadeId: string) => boolean;
|
|
188
|
+
getState: () => ServerRootState;
|
|
189
|
+
};
|
|
190
|
+
type CascadeNode = {
|
|
191
|
+
nodeId: string;
|
|
192
|
+
nodeName: string;
|
|
193
|
+
parentTriggerId?: string;
|
|
194
|
+
initialContext?: any;
|
|
195
|
+
processed?: boolean;
|
|
196
|
+
};
|
|
197
|
+
type CascadeStateResult = {
|
|
198
|
+
status: string;
|
|
199
|
+
history: any[];
|
|
200
|
+
[key: string]: any;
|
|
201
|
+
};
|
|
202
|
+
interface ServerNodeDefinition<TPrep = any, TExec = any> extends NodeDefinition {
|
|
203
|
+
isStreaming: false;
|
|
204
|
+
prep: (cascadeContext: WorkflowContext, initialContext: any) => Promise<TPrep>;
|
|
205
|
+
exec: (prepOutput: TPrep, controller?: CascadeController) => Promise<TExec>;
|
|
206
|
+
post: (execOutput: TExec) => Promise<PostResult>;
|
|
207
|
+
}
|
|
208
|
+
interface StreamingServerNodeDefinition<TPrep = any> extends NodeDefinition {
|
|
209
|
+
isStreaming: true;
|
|
210
|
+
prep: (cascadeContext: WorkflowContext, initialContext: any) => Promise<TPrep>;
|
|
211
|
+
exec: (prepOutput: TPrep, controller?: CascadeController) => Promise<StreamConfig>;
|
|
212
|
+
post: (execOutput: StreamingExecOutput) => Promise<PostResult>;
|
|
213
|
+
}
|
|
214
|
+
type StreamingExecOutput = {
|
|
215
|
+
assistantMessage: any;
|
|
216
|
+
uiAssistantMessage?: any;
|
|
217
|
+
cascadeId?: string;
|
|
218
|
+
history: any[];
|
|
219
|
+
userId?: string;
|
|
220
|
+
};
|
|
221
|
+
type ServerWorkflowGraph = Record<string, ServerNodeDefinition<any, any> | StreamingServerNodeDefinition<any>>;
|
|
130
222
|
|
|
131
223
|
interface CascadePersistence {
|
|
132
224
|
claimNodeExecution(params: ClaimRequest): Promise<ClaimResponse>;
|
|
@@ -147,19 +239,26 @@ interface CascadePersistence {
|
|
|
147
239
|
updates: {
|
|
148
240
|
[key: string]: any;
|
|
149
241
|
};
|
|
242
|
+
uiUpdates?: {
|
|
243
|
+
[key: string]: any;
|
|
244
|
+
};
|
|
150
245
|
}): Promise<{
|
|
151
246
|
status: string;
|
|
152
247
|
}>;
|
|
153
|
-
hydrateCascadeContext(cascadeId: string, upToFunctionId: number): Promise<WorkflowContext>;
|
|
154
|
-
|
|
248
|
+
hydrateCascadeContext(cascadeId: string, upToFunctionId: number, ui?: boolean): Promise<WorkflowContext>;
|
|
249
|
+
forkCascadeWithContext(params: {
|
|
155
250
|
sourceCascadeId: string;
|
|
156
251
|
newCascadeId: string;
|
|
157
252
|
upToFunctionId: number;
|
|
158
253
|
}): Promise<{
|
|
159
254
|
newCascadeId: string;
|
|
160
255
|
status: string;
|
|
256
|
+
context: WorkflowContext;
|
|
161
257
|
}>;
|
|
162
258
|
}
|
|
259
|
+
declare function handlePersistenceAction(persistor: CascadePersistence, action: string, body: any): Promise<{
|
|
260
|
+
status: string;
|
|
261
|
+
} | WorkflowContext>;
|
|
163
262
|
|
|
164
263
|
declare const createServerStore: (persistor?: CascadePersistence, extraMiddlewares?: Middleware[]) => {
|
|
165
264
|
store: _reduxjs_toolkit.EnhancedStore<{
|
|
@@ -214,6 +313,7 @@ declare const workflowSlice: _reduxjs_toolkit.Slice<WorkflowState, {
|
|
|
214
313
|
origin?: "client" | "server";
|
|
215
314
|
functionId?: number;
|
|
216
315
|
userId?: string;
|
|
316
|
+
uiUpdates?: Updates;
|
|
217
317
|
};
|
|
218
318
|
};
|
|
219
319
|
};
|
|
@@ -234,6 +334,20 @@ declare const workflowSlice: _reduxjs_toolkit.Slice<WorkflowState, {
|
|
|
234
334
|
markNodeProcessed: (state: WorkflowState, action: PayloadAction<markNodeProcessedPayload>) => void;
|
|
235
335
|
streamChunkReceived: (state: WorkflowState, action: PayloadAction<StreamChunk>) => void;
|
|
236
336
|
hydrateContext: (state: WorkflowState, action: PayloadAction<WorkflowContext>) => void;
|
|
337
|
+
forkAndHydrate: {
|
|
338
|
+
reducer: () => void;
|
|
339
|
+
prepare: (payload: {
|
|
340
|
+
sourceCascadeId: string;
|
|
341
|
+
newCascadeId: string;
|
|
342
|
+
upToFunctionId: number;
|
|
343
|
+
}) => {
|
|
344
|
+
payload: {
|
|
345
|
+
sourceCascadeId: string;
|
|
346
|
+
newCascadeId: string;
|
|
347
|
+
upToFunctionId: number;
|
|
348
|
+
};
|
|
349
|
+
};
|
|
350
|
+
};
|
|
237
351
|
}, "workflow", "workflow", _reduxjs_toolkit.SliceSelectors<WorkflowState>>;
|
|
238
352
|
declare const updateContext: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
|
|
239
353
|
[key: string]: any;
|
|
@@ -245,32 +359,41 @@ declare const addActiveNode: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[
|
|
|
245
359
|
origin?: "client" | "server";
|
|
246
360
|
functionId?: number;
|
|
247
361
|
userId?: string;
|
|
362
|
+
uiUpdates?: Updates;
|
|
248
363
|
}>;
|
|
249
364
|
declare const removeActiveNode: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: removeActiveNodePayload, meta?: ActionMeta], removeActiveNodePayload, "workflow/removeActiveNode", never, ActionMeta>;
|
|
250
365
|
declare const setError: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: setErrorPayload, meta?: ActionMeta], setErrorPayload, "workflow/setError", never, ActionMeta>;
|
|
251
366
|
declare const markNodeProcessed: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<markNodeProcessedPayload, "workflow/markNodeProcessed">;
|
|
252
367
|
declare const streamChunkReceived: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<StreamChunk, "workflow/streamChunkReceived">;
|
|
253
368
|
declare const hydrateContext: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<WorkflowContext, "workflow/hydrateContext">;
|
|
369
|
+
declare const forkAndHydrate: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
|
|
370
|
+
sourceCascadeId: string;
|
|
371
|
+
newCascadeId: string;
|
|
372
|
+
upToFunctionId: number;
|
|
373
|
+
}], {
|
|
374
|
+
sourceCascadeId: string;
|
|
375
|
+
newCascadeId: string;
|
|
376
|
+
upToFunctionId: number;
|
|
377
|
+
}, "workflow/forkAndHydrate", never, never>;
|
|
254
378
|
|
|
255
379
|
declare const createServerPersistenceMiddleware: (persistor: CascadePersistence) => Middleware;
|
|
256
380
|
|
|
381
|
+
interface StreamControl {
|
|
382
|
+
send: (data: any) => Promise<void>;
|
|
383
|
+
writeRaw: (data: string) => Promise<void>;
|
|
384
|
+
close: () => Promise<void>;
|
|
385
|
+
}
|
|
257
386
|
declare function setupServerWorkflowListener(serverListener: any, config: {
|
|
258
387
|
workflowGraph: ServerWorkflowGraph;
|
|
259
388
|
maxExecutionTime: number;
|
|
260
389
|
safeBuffer: number;
|
|
261
|
-
}, streamControl:
|
|
262
|
-
|
|
263
|
-
encoder: TextEncoder;
|
|
264
|
-
send: (data: any) => Promise<void>;
|
|
265
|
-
}, counters: {
|
|
266
|
-
activeNodeCount: {
|
|
267
|
-
current: number;
|
|
268
|
-
};
|
|
390
|
+
}, streamControl: StreamControl, // Aspect 1: Version 1's abstracted StreamControl
|
|
391
|
+
counters: {
|
|
269
392
|
chainDepth: {
|
|
270
393
|
current: number;
|
|
271
394
|
};
|
|
272
|
-
}, startTime: number): void;
|
|
273
|
-
declare function handleProviderStream(config: StreamConfig, cascadeId: string, send: (data: any) => Promise<void
|
|
395
|
+
}, startTime: number, isLite: boolean): void;
|
|
396
|
+
declare function handleProviderStream(config: StreamConfig, cascadeId: string, send: (data: any) => Promise<void>, isLite: boolean): Promise<StreamResult>;
|
|
274
397
|
|
|
275
398
|
declare const createServerHydrationMiddleware: (persistor: CascadePersistence) => Middleware;
|
|
276
399
|
|
|
@@ -280,13 +403,14 @@ interface ClientPersistenceConfig {
|
|
|
280
403
|
declare const createClientPersistenceMiddleware: (config: ClientPersistenceConfig) => Middleware;
|
|
281
404
|
|
|
282
405
|
interface ClientHydrationConfig {
|
|
283
|
-
|
|
406
|
+
persistenceEndpoint: string;
|
|
284
407
|
}
|
|
285
408
|
declare const createClientHydrationMiddleware: (config: ClientHydrationConfig) => Middleware;
|
|
286
409
|
|
|
287
410
|
declare const makeSelectCascadeState: () => ((state: {
|
|
288
411
|
workflow: WorkflowState;
|
|
289
412
|
}, cascadeId: string) => {
|
|
413
|
+
[key: string]: any;
|
|
290
414
|
status: string;
|
|
291
415
|
history: any[];
|
|
292
416
|
}) & {
|
|
@@ -295,10 +419,12 @@ declare const makeSelectCascadeState: () => ((state: {
|
|
|
295
419
|
resetResultsCount: () => void;
|
|
296
420
|
} & {
|
|
297
421
|
resultFunc: (resultFuncArgs_0: WorkflowContext, resultFuncArgs_1: string) => {
|
|
422
|
+
[key: string]: any;
|
|
298
423
|
status: string;
|
|
299
424
|
history: any[];
|
|
300
425
|
};
|
|
301
426
|
memoizedResultFunc: ((resultFuncArgs_0: WorkflowContext, resultFuncArgs_1: string) => {
|
|
427
|
+
[key: string]: any;
|
|
302
428
|
status: string;
|
|
303
429
|
history: any[];
|
|
304
430
|
}) & {
|
|
@@ -307,6 +433,7 @@ declare const makeSelectCascadeState: () => ((state: {
|
|
|
307
433
|
resetResultsCount: () => void;
|
|
308
434
|
};
|
|
309
435
|
lastResult: () => {
|
|
436
|
+
[key: string]: any;
|
|
310
437
|
status: string;
|
|
311
438
|
history: any[];
|
|
312
439
|
};
|
|
@@ -376,9 +503,6 @@ declare const makeSelectCascadeNodes: () => ((state: {
|
|
|
376
503
|
memoize: typeof reselect.weakMapMemoize;
|
|
377
504
|
argsMemoize: typeof reselect.weakMapMemoize;
|
|
378
505
|
};
|
|
379
|
-
/**
|
|
380
|
-
* Memoized selector to get all cascade IDs.
|
|
381
|
-
*/
|
|
382
506
|
declare const selectAllCascadeIds: ((state: {
|
|
383
507
|
workflow: WorkflowState;
|
|
384
508
|
}) => string[]) & {
|
|
@@ -403,4 +527,4 @@ declare const selectAllCascadeIds: ((state: {
|
|
|
403
527
|
argsMemoize: typeof reselect.weakMapMemoize;
|
|
404
528
|
};
|
|
405
529
|
|
|
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
|
|
530
|
+
export { type ActionMeta, type ActiveNode, type AppDispatch, type CascadeController, type CascadeNode, type CascadePersistence, type CascadeStateResult, type ChunkDelta, type ChunkMapper, type ClaimRequest, type ClaimResponse, type ClientHydrationConfig, type ClientPersistenceConfig, type ClientWorkflowGraph, type LLMProvider, type MapperFactory, type NodeDefinition, type NodeHistoryRecord, type PostResult, type RootState, type ServerDispatch, type ServerListenerApi, type ServerNodeDefinition, type ServerRootState, type ServerStore, type ServerWorkflowGraph, type SpawnContext, type Spawns, type StreamChunk, type StreamConfig, type StreamControl, type StreamEventType, type StreamFilter, type StreamResult, type StreamingExecOutput, type StreamingServerNodeDefinition, type Updates, type WorkflowContext, type WorkflowHandlerConfig, type WorkflowState, type WorkflowStep, addActiveNode, type addActiveNodePayload, createClientHydrationMiddleware, createClientPersistenceMiddleware, createClientStore, createServerHydrationMiddleware, createServerPersistenceMiddleware, createServerStore, forkAndHydrate, handlePersistenceAction, handleProviderStream, hydrateContext, makeSelectCascadeNodes, makeSelectCascadeState, markNodeProcessed, type markNodeProcessedPayload, removeActiveNode, type removeActiveNodePayload, selectAllCascadeIds, setError, type setErrorPayload, setupServerWorkflowListener, streamChunkReceived, updateContext, type updateContextPayload, workflowSlice };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,24 @@
|
|
|
1
1
|
import * as _reduxjs_toolkit from '@reduxjs/toolkit';
|
|
2
|
-
import { configureStore, Middleware, PayloadAction } from '@reduxjs/toolkit';
|
|
2
|
+
import { configureStore, Middleware, ListenerEffectAPI, PayloadAction } from '@reduxjs/toolkit';
|
|
3
3
|
import * as reselect from 'reselect';
|
|
4
4
|
|
|
5
|
+
declare const rootReducer: _reduxjs_toolkit.Reducer<{
|
|
6
|
+
workflow: WorkflowState;
|
|
7
|
+
}, _reduxjs_toolkit.UnknownAction, Partial<{
|
|
8
|
+
workflow: WorkflowState;
|
|
9
|
+
}>>;
|
|
10
|
+
type RootState = ReturnType<typeof rootReducer>;
|
|
11
|
+
type AppDispatch = ReturnType<typeof configureStore>['dispatch'];
|
|
12
|
+
declare const createClientStore: (workflowGraph: ClientWorkflowGraph, actionRelayEndpoint: string, persistenceEndpoint?: string, extraMiddlewares?: Middleware[]) => _reduxjs_toolkit.EnhancedStore<{
|
|
13
|
+
workflow: WorkflowState;
|
|
14
|
+
}, _reduxjs_toolkit.UnknownAction, _reduxjs_toolkit.Tuple<[_reduxjs_toolkit.StoreEnhancer<{
|
|
15
|
+
dispatch: _reduxjs_toolkit.ThunkDispatch<{
|
|
16
|
+
workflow: WorkflowState;
|
|
17
|
+
}, undefined, _reduxjs_toolkit.UnknownAction>;
|
|
18
|
+
}>, _reduxjs_toolkit.StoreEnhancer]>>;
|
|
19
|
+
|
|
5
20
|
type WorkflowStep = {
|
|
6
|
-
history: any;
|
|
21
|
+
history: any[];
|
|
7
22
|
status: string;
|
|
8
23
|
[extraKeys: string]: any;
|
|
9
24
|
};
|
|
@@ -15,6 +30,7 @@ type ActionMeta = {
|
|
|
15
30
|
functionId?: number;
|
|
16
31
|
cascadeId?: string;
|
|
17
32
|
userId?: string;
|
|
33
|
+
uiUpdates?: Updates;
|
|
18
34
|
};
|
|
19
35
|
type ActiveNode = {
|
|
20
36
|
nodeName: string;
|
|
@@ -25,13 +41,6 @@ type ActiveNode = {
|
|
|
25
41
|
functionId?: number;
|
|
26
42
|
cascadeId?: string;
|
|
27
43
|
};
|
|
28
|
-
type StreamChunk = {
|
|
29
|
-
contentChunk?: string;
|
|
30
|
-
toolChunk?: any;
|
|
31
|
-
cascadeId: string;
|
|
32
|
-
reasoningChunk?: string;
|
|
33
|
-
thoughtSignature?: string;
|
|
34
|
-
};
|
|
35
44
|
type NodeHistoryRecord = {
|
|
36
45
|
nodeId: string;
|
|
37
46
|
nodeName: string;
|
|
@@ -63,70 +72,153 @@ interface ClaimResponse {
|
|
|
63
72
|
interface NodeDefinition {
|
|
64
73
|
name: string;
|
|
65
74
|
isUINode: boolean;
|
|
66
|
-
env:
|
|
75
|
+
env: 'client' | 'server';
|
|
67
76
|
}
|
|
68
77
|
type Updates = {
|
|
69
78
|
[cascadeId: string]: WorkflowStep;
|
|
70
79
|
};
|
|
71
80
|
type SpawnContext<T = Record<string, any>> = {
|
|
72
|
-
cascadeId
|
|
73
|
-
history: any;
|
|
74
|
-
userId
|
|
81
|
+
cascadeId?: string;
|
|
82
|
+
history: any[];
|
|
83
|
+
userId?: string;
|
|
75
84
|
} & T;
|
|
85
|
+
type Spawns = Record<string, SpawnContext>;
|
|
76
86
|
type PostResult = {
|
|
77
87
|
updates: Updates;
|
|
78
88
|
uiUpdates?: Updates;
|
|
79
89
|
spawns?: Record<string, SpawnContext>;
|
|
80
90
|
};
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
91
|
+
interface WorkflowHandlerConfig {
|
|
92
|
+
workflowGraph: ServerWorkflowGraph;
|
|
93
|
+
persistor?: CascadePersistence;
|
|
94
|
+
maxExecutionTime?: number;
|
|
95
|
+
safeBuffer?: number;
|
|
96
|
+
extraMiddlewares?: Middleware[];
|
|
87
97
|
}
|
|
88
|
-
type
|
|
98
|
+
type ClientWorkflowGraph = Record<string, NodeDefinition>;
|
|
89
99
|
type StreamEventType = 'init' | 'sync' | 'chunk';
|
|
90
|
-
type
|
|
91
|
-
interface
|
|
92
|
-
|
|
93
|
-
|
|
100
|
+
type ChunkMapper = (chunk: any) => ChunkDelta | ChunkDelta[] | null;
|
|
101
|
+
interface ChunkDelta {
|
|
102
|
+
identity: string;
|
|
103
|
+
value: any;
|
|
104
|
+
accumulate?: (current: any, incoming: any) => any;
|
|
105
|
+
buffer?: boolean;
|
|
106
|
+
silent?: boolean;
|
|
94
107
|
}
|
|
95
|
-
interface
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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;
|
|
108
|
+
interface StreamChunk {
|
|
109
|
+
cascadeId: string;
|
|
110
|
+
identity: string;
|
|
111
|
+
value: any;
|
|
109
112
|
}
|
|
113
|
+
type LLMProvider = 'anthropic' | 'openai-responses' | 'gemini-genai' | 'openai' | 'custom';
|
|
110
114
|
interface StreamConfig {
|
|
111
115
|
stream: AsyncIterable<any>;
|
|
112
|
-
provider:
|
|
113
|
-
|
|
116
|
+
provider: LLMProvider;
|
|
117
|
+
/**
|
|
118
|
+
* Custom mapper — overrides the built-in mapper for this provider.
|
|
119
|
+
* Use when you need to handle a provider variant or custom API shape.
|
|
120
|
+
*/
|
|
121
|
+
mapper?: ChunkMapper | (() => ChunkMapper);
|
|
122
|
+
/**
|
|
123
|
+
* Controls what gets sent to the frontend.
|
|
124
|
+
*
|
|
125
|
+
* Return false → suppress this identity (not sent, not in uiMessage)
|
|
126
|
+
* Return the value → pass through unchanged
|
|
127
|
+
* Return anything else → send this instead (replacement/redaction)
|
|
128
|
+
*
|
|
129
|
+
* When absent, everything non-silent is sent as-is and uiMessage is not
|
|
130
|
+
* populated (persistence middleware treats canonical as the UI source too).
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* // Suppress thinking from frontend
|
|
134
|
+
* filter: (identity, value) => identity === 'thinking' ? false : value
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* // Redact tool call args
|
|
138
|
+
* filter: (identity, value) => {
|
|
139
|
+
* if (identity === 'tool_calls') {
|
|
140
|
+
* return value.map((tc: any) => ({ ...tc, args: { _redacted: true } }));
|
|
141
|
+
* }
|
|
142
|
+
* return value;
|
|
143
|
+
* }
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* // Replace tool result with a UI indicator
|
|
147
|
+
* filter: (identity, value) => {
|
|
148
|
+
* if (identity === 'tool_calls') {
|
|
149
|
+
* return { type: 'tool_indicator', names: value.map((tc: any) => tc.name) };
|
|
150
|
+
* }
|
|
151
|
+
* return value;
|
|
152
|
+
* }
|
|
153
|
+
*/
|
|
154
|
+
filter?: StreamFilter;
|
|
114
155
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
156
|
+
type MapperFactory = () => ChunkMapper;
|
|
157
|
+
interface StreamResult {
|
|
158
|
+
/**
|
|
159
|
+
* Full assembled canonical message — all identities, no filtering.
|
|
160
|
+
* Always present. Written to cascade state as LLM history.
|
|
161
|
+
*/
|
|
162
|
+
canonical: Record<string, any>;
|
|
163
|
+
/**
|
|
164
|
+
* What was actually sent to the frontend — filtered/replaced values only.
|
|
165
|
+
* Only present when a filter was applied. When absent, canonical is the
|
|
166
|
+
* source of truth for UI as well (persistence middleware handles this).
|
|
167
|
+
*/
|
|
168
|
+
uiMessage?: Record<string, any>;
|
|
169
|
+
}
|
|
170
|
+
type StreamFilter = (identity: string, value: any) => any | false;
|
|
171
|
+
type ServerRootState = {
|
|
124
172
|
workflow: WorkflowState;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
173
|
+
};
|
|
174
|
+
type ServerStore = ReturnType<typeof createServerStore>['store'];
|
|
175
|
+
type ServerDispatch = ServerStore['dispatch'];
|
|
176
|
+
type ServerListenerApi = ListenerEffectAPI<ServerRootState, ServerDispatch>;
|
|
177
|
+
type CascadeController = {
|
|
178
|
+
updateContext: (updates: Updates) => void;
|
|
179
|
+
spawn: (spawns: Record<string, SpawnContext>) => Promise<void>;
|
|
180
|
+
fork: (newCascadeId: string, upToFunctionId: number, sourceCascadeId?: string) => Promise<{
|
|
181
|
+
status: 'SUCCESS' | 'FAILED';
|
|
182
|
+
}>;
|
|
183
|
+
waitUntil: (predicate: (state: ServerRootState) => boolean) => Promise<void>;
|
|
184
|
+
getCascadeState: (cascadeId: string) => CascadeStateResult | undefined;
|
|
185
|
+
getCascadeNodes: (cascadeId: string) => CascadeNode[];
|
|
186
|
+
isComplete: (cascadeId: string) => boolean;
|
|
187
|
+
exists: (cascadeId: string) => boolean;
|
|
188
|
+
getState: () => ServerRootState;
|
|
189
|
+
};
|
|
190
|
+
type CascadeNode = {
|
|
191
|
+
nodeId: string;
|
|
192
|
+
nodeName: string;
|
|
193
|
+
parentTriggerId?: string;
|
|
194
|
+
initialContext?: any;
|
|
195
|
+
processed?: boolean;
|
|
196
|
+
};
|
|
197
|
+
type CascadeStateResult = {
|
|
198
|
+
status: string;
|
|
199
|
+
history: any[];
|
|
200
|
+
[key: string]: any;
|
|
201
|
+
};
|
|
202
|
+
interface ServerNodeDefinition<TPrep = any, TExec = any> extends NodeDefinition {
|
|
203
|
+
isStreaming: false;
|
|
204
|
+
prep: (cascadeContext: WorkflowContext, initialContext: any) => Promise<TPrep>;
|
|
205
|
+
exec: (prepOutput: TPrep, controller?: CascadeController) => Promise<TExec>;
|
|
206
|
+
post: (execOutput: TExec) => Promise<PostResult>;
|
|
207
|
+
}
|
|
208
|
+
interface StreamingServerNodeDefinition<TPrep = any> extends NodeDefinition {
|
|
209
|
+
isStreaming: true;
|
|
210
|
+
prep: (cascadeContext: WorkflowContext, initialContext: any) => Promise<TPrep>;
|
|
211
|
+
exec: (prepOutput: TPrep, controller?: CascadeController) => Promise<StreamConfig>;
|
|
212
|
+
post: (execOutput: StreamingExecOutput) => Promise<PostResult>;
|
|
213
|
+
}
|
|
214
|
+
type StreamingExecOutput = {
|
|
215
|
+
assistantMessage: any;
|
|
216
|
+
uiAssistantMessage?: any;
|
|
217
|
+
cascadeId?: string;
|
|
218
|
+
history: any[];
|
|
219
|
+
userId?: string;
|
|
220
|
+
};
|
|
221
|
+
type ServerWorkflowGraph = Record<string, ServerNodeDefinition<any, any> | StreamingServerNodeDefinition<any>>;
|
|
130
222
|
|
|
131
223
|
interface CascadePersistence {
|
|
132
224
|
claimNodeExecution(params: ClaimRequest): Promise<ClaimResponse>;
|
|
@@ -147,19 +239,26 @@ interface CascadePersistence {
|
|
|
147
239
|
updates: {
|
|
148
240
|
[key: string]: any;
|
|
149
241
|
};
|
|
242
|
+
uiUpdates?: {
|
|
243
|
+
[key: string]: any;
|
|
244
|
+
};
|
|
150
245
|
}): Promise<{
|
|
151
246
|
status: string;
|
|
152
247
|
}>;
|
|
153
|
-
hydrateCascadeContext(cascadeId: string, upToFunctionId: number): Promise<WorkflowContext>;
|
|
154
|
-
|
|
248
|
+
hydrateCascadeContext(cascadeId: string, upToFunctionId: number, ui?: boolean): Promise<WorkflowContext>;
|
|
249
|
+
forkCascadeWithContext(params: {
|
|
155
250
|
sourceCascadeId: string;
|
|
156
251
|
newCascadeId: string;
|
|
157
252
|
upToFunctionId: number;
|
|
158
253
|
}): Promise<{
|
|
159
254
|
newCascadeId: string;
|
|
160
255
|
status: string;
|
|
256
|
+
context: WorkflowContext;
|
|
161
257
|
}>;
|
|
162
258
|
}
|
|
259
|
+
declare function handlePersistenceAction(persistor: CascadePersistence, action: string, body: any): Promise<{
|
|
260
|
+
status: string;
|
|
261
|
+
} | WorkflowContext>;
|
|
163
262
|
|
|
164
263
|
declare const createServerStore: (persistor?: CascadePersistence, extraMiddlewares?: Middleware[]) => {
|
|
165
264
|
store: _reduxjs_toolkit.EnhancedStore<{
|
|
@@ -214,6 +313,7 @@ declare const workflowSlice: _reduxjs_toolkit.Slice<WorkflowState, {
|
|
|
214
313
|
origin?: "client" | "server";
|
|
215
314
|
functionId?: number;
|
|
216
315
|
userId?: string;
|
|
316
|
+
uiUpdates?: Updates;
|
|
217
317
|
};
|
|
218
318
|
};
|
|
219
319
|
};
|
|
@@ -234,6 +334,20 @@ declare const workflowSlice: _reduxjs_toolkit.Slice<WorkflowState, {
|
|
|
234
334
|
markNodeProcessed: (state: WorkflowState, action: PayloadAction<markNodeProcessedPayload>) => void;
|
|
235
335
|
streamChunkReceived: (state: WorkflowState, action: PayloadAction<StreamChunk>) => void;
|
|
236
336
|
hydrateContext: (state: WorkflowState, action: PayloadAction<WorkflowContext>) => void;
|
|
337
|
+
forkAndHydrate: {
|
|
338
|
+
reducer: () => void;
|
|
339
|
+
prepare: (payload: {
|
|
340
|
+
sourceCascadeId: string;
|
|
341
|
+
newCascadeId: string;
|
|
342
|
+
upToFunctionId: number;
|
|
343
|
+
}) => {
|
|
344
|
+
payload: {
|
|
345
|
+
sourceCascadeId: string;
|
|
346
|
+
newCascadeId: string;
|
|
347
|
+
upToFunctionId: number;
|
|
348
|
+
};
|
|
349
|
+
};
|
|
350
|
+
};
|
|
237
351
|
}, "workflow", "workflow", _reduxjs_toolkit.SliceSelectors<WorkflowState>>;
|
|
238
352
|
declare const updateContext: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
|
|
239
353
|
[key: string]: any;
|
|
@@ -245,32 +359,41 @@ declare const addActiveNode: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[
|
|
|
245
359
|
origin?: "client" | "server";
|
|
246
360
|
functionId?: number;
|
|
247
361
|
userId?: string;
|
|
362
|
+
uiUpdates?: Updates;
|
|
248
363
|
}>;
|
|
249
364
|
declare const removeActiveNode: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: removeActiveNodePayload, meta?: ActionMeta], removeActiveNodePayload, "workflow/removeActiveNode", never, ActionMeta>;
|
|
250
365
|
declare const setError: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: setErrorPayload, meta?: ActionMeta], setErrorPayload, "workflow/setError", never, ActionMeta>;
|
|
251
366
|
declare const markNodeProcessed: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<markNodeProcessedPayload, "workflow/markNodeProcessed">;
|
|
252
367
|
declare const streamChunkReceived: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<StreamChunk, "workflow/streamChunkReceived">;
|
|
253
368
|
declare const hydrateContext: _reduxjs_toolkit.ActionCreatorWithOptionalPayload<WorkflowContext, "workflow/hydrateContext">;
|
|
369
|
+
declare const forkAndHydrate: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
|
|
370
|
+
sourceCascadeId: string;
|
|
371
|
+
newCascadeId: string;
|
|
372
|
+
upToFunctionId: number;
|
|
373
|
+
}], {
|
|
374
|
+
sourceCascadeId: string;
|
|
375
|
+
newCascadeId: string;
|
|
376
|
+
upToFunctionId: number;
|
|
377
|
+
}, "workflow/forkAndHydrate", never, never>;
|
|
254
378
|
|
|
255
379
|
declare const createServerPersistenceMiddleware: (persistor: CascadePersistence) => Middleware;
|
|
256
380
|
|
|
381
|
+
interface StreamControl {
|
|
382
|
+
send: (data: any) => Promise<void>;
|
|
383
|
+
writeRaw: (data: string) => Promise<void>;
|
|
384
|
+
close: () => Promise<void>;
|
|
385
|
+
}
|
|
257
386
|
declare function setupServerWorkflowListener(serverListener: any, config: {
|
|
258
387
|
workflowGraph: ServerWorkflowGraph;
|
|
259
388
|
maxExecutionTime: number;
|
|
260
389
|
safeBuffer: number;
|
|
261
|
-
}, streamControl:
|
|
262
|
-
|
|
263
|
-
encoder: TextEncoder;
|
|
264
|
-
send: (data: any) => Promise<void>;
|
|
265
|
-
}, counters: {
|
|
266
|
-
activeNodeCount: {
|
|
267
|
-
current: number;
|
|
268
|
-
};
|
|
390
|
+
}, streamControl: StreamControl, // Aspect 1: Version 1's abstracted StreamControl
|
|
391
|
+
counters: {
|
|
269
392
|
chainDepth: {
|
|
270
393
|
current: number;
|
|
271
394
|
};
|
|
272
|
-
}, startTime: number): void;
|
|
273
|
-
declare function handleProviderStream(config: StreamConfig, cascadeId: string, send: (data: any) => Promise<void
|
|
395
|
+
}, startTime: number, isLite: boolean): void;
|
|
396
|
+
declare function handleProviderStream(config: StreamConfig, cascadeId: string, send: (data: any) => Promise<void>, isLite: boolean): Promise<StreamResult>;
|
|
274
397
|
|
|
275
398
|
declare const createServerHydrationMiddleware: (persistor: CascadePersistence) => Middleware;
|
|
276
399
|
|
|
@@ -280,13 +403,14 @@ interface ClientPersistenceConfig {
|
|
|
280
403
|
declare const createClientPersistenceMiddleware: (config: ClientPersistenceConfig) => Middleware;
|
|
281
404
|
|
|
282
405
|
interface ClientHydrationConfig {
|
|
283
|
-
|
|
406
|
+
persistenceEndpoint: string;
|
|
284
407
|
}
|
|
285
408
|
declare const createClientHydrationMiddleware: (config: ClientHydrationConfig) => Middleware;
|
|
286
409
|
|
|
287
410
|
declare const makeSelectCascadeState: () => ((state: {
|
|
288
411
|
workflow: WorkflowState;
|
|
289
412
|
}, cascadeId: string) => {
|
|
413
|
+
[key: string]: any;
|
|
290
414
|
status: string;
|
|
291
415
|
history: any[];
|
|
292
416
|
}) & {
|
|
@@ -295,10 +419,12 @@ declare const makeSelectCascadeState: () => ((state: {
|
|
|
295
419
|
resetResultsCount: () => void;
|
|
296
420
|
} & {
|
|
297
421
|
resultFunc: (resultFuncArgs_0: WorkflowContext, resultFuncArgs_1: string) => {
|
|
422
|
+
[key: string]: any;
|
|
298
423
|
status: string;
|
|
299
424
|
history: any[];
|
|
300
425
|
};
|
|
301
426
|
memoizedResultFunc: ((resultFuncArgs_0: WorkflowContext, resultFuncArgs_1: string) => {
|
|
427
|
+
[key: string]: any;
|
|
302
428
|
status: string;
|
|
303
429
|
history: any[];
|
|
304
430
|
}) & {
|
|
@@ -307,6 +433,7 @@ declare const makeSelectCascadeState: () => ((state: {
|
|
|
307
433
|
resetResultsCount: () => void;
|
|
308
434
|
};
|
|
309
435
|
lastResult: () => {
|
|
436
|
+
[key: string]: any;
|
|
310
437
|
status: string;
|
|
311
438
|
history: any[];
|
|
312
439
|
};
|
|
@@ -376,9 +503,6 @@ declare const makeSelectCascadeNodes: () => ((state: {
|
|
|
376
503
|
memoize: typeof reselect.weakMapMemoize;
|
|
377
504
|
argsMemoize: typeof reselect.weakMapMemoize;
|
|
378
505
|
};
|
|
379
|
-
/**
|
|
380
|
-
* Memoized selector to get all cascade IDs.
|
|
381
|
-
*/
|
|
382
506
|
declare const selectAllCascadeIds: ((state: {
|
|
383
507
|
workflow: WorkflowState;
|
|
384
508
|
}) => string[]) & {
|
|
@@ -403,4 +527,4 @@ declare const selectAllCascadeIds: ((state: {
|
|
|
403
527
|
argsMemoize: typeof reselect.weakMapMemoize;
|
|
404
528
|
};
|
|
405
529
|
|
|
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
|
|
530
|
+
export { type ActionMeta, type ActiveNode, type AppDispatch, type CascadeController, type CascadeNode, type CascadePersistence, type CascadeStateResult, type ChunkDelta, type ChunkMapper, type ClaimRequest, type ClaimResponse, type ClientHydrationConfig, type ClientPersistenceConfig, type ClientWorkflowGraph, type LLMProvider, type MapperFactory, type NodeDefinition, type NodeHistoryRecord, type PostResult, type RootState, type ServerDispatch, type ServerListenerApi, type ServerNodeDefinition, type ServerRootState, type ServerStore, type ServerWorkflowGraph, type SpawnContext, type Spawns, type StreamChunk, type StreamConfig, type StreamControl, type StreamEventType, type StreamFilter, type StreamResult, type StreamingExecOutput, type StreamingServerNodeDefinition, type Updates, type WorkflowContext, type WorkflowHandlerConfig, type WorkflowState, type WorkflowStep, addActiveNode, type addActiveNodePayload, createClientHydrationMiddleware, createClientPersistenceMiddleware, createClientStore, createServerHydrationMiddleware, createServerPersistenceMiddleware, createServerStore, forkAndHydrate, handlePersistenceAction, handleProviderStream, hydrateContext, makeSelectCascadeNodes, makeSelectCascadeState, markNodeProcessed, type markNodeProcessedPayload, removeActiveNode, type removeActiveNodePayload, selectAllCascadeIds, setError, type setErrorPayload, setupServerWorkflowListener, streamChunkReceived, updateContext, type updateContextPayload, workflowSlice };
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import{configureStore as
|
|
1
|
+
import{configureStore as Se,combineReducers as xe}from"@reduxjs/toolkit";import{createListenerMiddleware as ge}from"@reduxjs/toolkit";import{createSlice as ye}from"@reduxjs/toolkit";var we={context:{},activeNodes:{},history:[],errors:{}},K=ye({name:"workflow",initialState:we,reducers:{updateContext:{reducer:(n,a)=>{Object.entries(a.payload).forEach(([t,e])=>{if(n.context[t]||(n.context[t]=[]),typeof e=="object"&&e!==null&&!Array.isArray(e)&&"index"in e){let r=e.index;n.context[t][r]=e}else n.context[t].push(e)})},prepare:(n,a)=>({payload:n,meta:a||{}})},addActiveNode:{reducer:(n,a)=>{let{nodeId:t,nodeName:e,parentTriggerId:r,contextData:o}=a.payload,{origin:s,functionId:i,cascadeId:c}=a.meta;n.activeNodes[t]={nodeName:e,parentTriggerId:r,processed:!1,initialContext:o,origin:s,functionId:i,cascadeId:c||o?.cascadeId},n.errors[t]&&delete n.errors[t]},prepare:(n,a)=>{let t=a?.cascadeId||n.contextData?.cascadeId;return{payload:n,meta:{...a,cascadeId:t}}}},removeActiveNode:{reducer:(n,a)=>{let{nodeId:t}=a.payload;n.activeNodes[t]&&(n.history.push({nodeId:t,nodeName:n.activeNodes[t].nodeName,timestamp:Date.now()}),delete n.activeNodes[t])},prepare:(n,a)=>({payload:n,meta:a||{}})},setError:{reducer:(n,a)=>{let{nodeId:t,error:e}=a.payload;n.errors[t]=e},prepare:(n,a)=>({payload:n,meta:a||{}})},markNodeProcessed:(n,a)=>{let{nodeId:t}=a.payload;n.activeNodes[t]&&(n.activeNodes[t].processed=!0)},streamChunkReceived:(n,a)=>{let{cascadeId:t,identity:e,value:r}=a.payload;if(!e||r===void 0)return;let o=n.context[t];if(!o||o.length===0)return;let i=o[o.length-1].history,c=i[i.length-1];!c||c.role!=="assistant"||(typeof c[e]=="string"?c[e]+=r:c[e]=r)},hydrateContext:(n,a)=>{Object.entries(a.payload).forEach(([t,e])=>{n.context[t]=e})},forkAndHydrate:{reducer:()=>{},prepare:n=>({payload:n})}}}),{updateContext:S,addActiveNode:I,removeActiveNode:N,setError:R,markNodeProcessed:We,streamChunkReceived:X,hydrateContext:W,forkAndHydrate:j}=K.actions,ee=K.reducer;import{v7 as ne}from"uuid";var B=ge(),he=B.startListening,te=`
|
|
2
2
|
__END_STREAM_METADATA__
|
|
3
|
-
`,
|
|
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=`
|
|
3
|
+
`,re=n=>{he({actionCreator:I,effect:async(a,t)=>{let{nodeId:e,nodeName:r,contextData:o}=a.payload,{functionId:s}=a.meta,i=n.workflowGraph[r],c=n.isLite;if(!(!i||i.isUINode)){if(o?.sentFromClient&&!o?.handledTimeout){let{cascadeId:d,userId:f,history:l,sentFromClient:u,...m}=o,p=c?l?.slice(-1)??[]:[...l??[]];await t.dispatch(S({[d]:{...m,history:p,status:"completed"}},{functionId:s,cascadeId:d}))}try{let d=await fetch(n.actionRelayEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},signal:t.signal,body:JSON.stringify(a)});if(!d.ok||!d.body)throw new Error(await d.text()||"Action relay failed");let f=o?.cascadeId;await Ie(d.body,f,e,t,a,c)}catch(d){if(d.name==="AbortError")return;await t.dispatch(R({nodeId:e,error:d.message})),await t.dispatch(N({nodeId:e,hasSpawns:!1}))}}}})};async function Ie(n,a,t,e,r,o){let s=n.getReader(),i=new TextDecoder,c="",d=!1;try{for(;;){let{done:f,value:l}=await s.read();if(f)break;if(c+=i.decode(l,{stream:!0}),!d){let u=c.indexOf(te);if(u!==-1){let m=c.substring(0,u),p=c.substring(u+te.length);if(await ae(m,a,e),p.trim())try{let h=JSON.parse(p.trim());await Ce(h,t,e,r,o)}catch(h){console.error("Metadata parse error",h)}d=!0;break}c=await ae(c,a,e)}}}finally{s.releaseLock()}}async function ae(n,a,t){let e=n.split(`
|
|
4
|
+
`),r=e.pop()||"";for(let o of e)if(!(!o.trim()||o.startsWith(":")))try{let s=JSON.parse(o);s.type==="init"?await t.dispatch(S({[s.cascadeId]:{history:[{role:"assistant"}],status:"streaming"}})):s.type==="sync"?await t.dispatch(S({[s.cascadeId]:{history:s.history,status:"completed"}})):s.type==="ui_spawn"?await t.dispatch(I({nodeId:`${s.nodeName}_${ne()}`,nodeName:s.nodeName,contextData:s.contextData})):await t.dispatch(X({cascadeId:s.cascadeId,identity:s.identity,value:s.value}))}catch(s){console.error("Chunk parse error",s)}return r}async function Ce(n,a,t,e,r){let o=e.meta?.functionId??0,s=e.meta?.origin??"server",i=e.payload.contextData?.cascadeId,c=l=>{if(!r)return l;let u=t.getState().workflow.context[i],m=Object.keys(u||{}),p=Object.fromEntries(Object.entries(l||{}).filter(([y])=>!m.includes(y))),h=u.flatMap(y=>y.history||[]);return{...p,history:h,sentFromClient:!0,handledTimeout:!0}},d=n.spawns?Object.entries(n.spawns):[],f=d.length>0;f&&d.forEach(async([l,u],m)=>{let p=c(u);await t.dispatch(I({nodeId:`${l}_${ne()}_${m}`,nodeName:l,parentTriggerId:a,contextData:{...p,cascadeId:i,userId:p?.userId||e.payload.contextData?.userId}},{functionId:r?0:o+1+m,cascadeId:i,origin:s}))}),await t.dispatch(N({nodeId:a,hasSpawns:f,fullOutput:n.updates},{functionId:void 0,cascadeId:i,origin:s}))}var ve=xe({workflow:K.reducer}),Ze=(n,a,t,e=[])=>{re({workflowGraph:n,actionRelayEndpoint:a,isLite:!t});let o=[];return t&&o.push(oe({persistenceEndpoint:t}),se({persistenceEndpoint:t})),o.push(...e),o.push(B.middleware),Se({reducer:ve,middleware:s=>s({serializableCheck:!1}).concat(o),devTools:process.env.NODE_ENV!=="production"})};import{configureStore as ke,createListenerMiddleware as Ne}from"@reduxjs/toolkit";var D=process.env.NODE_ENV==="development";async function Y(n,a=3,t=100){for(let e=1;e<=a;e++)try{return await n()}catch(r){if(e===a)return D&&console.error(`[SERVER MW] \u274C All ${a} retry attempts failed:`,r),null;let o=t*Math.pow(2,e-1);D&&console.warn(`[SERVER MW] \u26A0\uFE0F Attempt ${e} failed, retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o))}return null}var ie=n=>a=>t=>async e=>{if(I.match(e)){let{origin:r,functionId:o,cascadeId:s,userId:i}=e.meta,{nodeId:c,nodeName:d,contextData:f}=e.payload;if(!s||r)return t(e);let l=o??0,u=await Y(async()=>await n.claimNodeExecution({nodeInstanceId:c,cascadeId:s,userId:i||f.userId,nodeName:d,functionId:l,inputContext:f,location:"server"}));if(!u){D&&console.error(`[SERVER MW] \u274C Failed to claim node ${c} after retries`);return}D&&console.log(`[SERVER MW] \u2705 Claimed node ${c} with FnId: ${u.functionId}`);let m={...e,meta:{...e.meta,origin:"server",functionId:u.functionId,cascadeId:s}};return t(m)}if(N.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,i=typeof e.payload=="string"?e.payload:e.payload.nodeId,c=e.payload.hasSpawns??!1,d=e.payload.fullOutput,f=a.getState(),l=f.workflow.activeNodes[i],u=s||l?.cascadeId,m=o??l?.functionId??0;if(!u||r)return t(e);let p=d||f.workflow.context[u];if(!await Y(async()=>await n.finalizeNodeExecution({nodeInstanceId:i,cascadeId:u,fullOutput:p,hasSpawns:c}))){D&&console.error(`[SERVER MW] \u274C Failed to finalize node ${i} after retries`);return}let y={...e,meta:{...e.meta,origin:"server",functionId:m,cascadeId:u}};return t(y)}if(R.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,{nodeId:i,error:c}=e.payload,f=a.getState().workflow.activeNodes[i],l=s||f?.cascadeId,u=o??f?.functionId??0;if(!l||r)return t(e);if(!await Y(async()=>await n.markExecutionFailed(i,l,c))){D&&console.error(`[SERVER MW] \u274C Failed to mark node ${i} as failed after retries`);return}let p={...e,meta:{...e.meta,origin:"server",functionId:u,cascadeId:l}};return t(p)}if(S.match(e)){let{origin:r,functionId:o,cascadeId:s,uiUpdates:i}=e.meta,c=e.payload,d=s,f=o??0;if(!d||r)return t(e);let l=c[d];if(l&&l.status==="streaming")return t(e);if(!await Y(async()=>await n.recordContextEvents({cascadeId:d,functionId:f,updates:c,uiUpdates:i}))){D&&console.error(`[SERVER MW] \u274C Failed to record context for cascade ${d} after retries`);return}let m={...e,meta:{...e.meta,origin:"server",functionId:f,cascadeId:d}};return t(m)}return t(e)};var T=process.env.NODE_ENV==="development";async function ce(n,a=3,t=100){for(let e=1;e<=a;e++)try{return await n()}catch(r){if(e===a)return T&&console.error(`[SERVER HYDRATION] \u274C All ${a} attempts failed:`,r),null;let o=t*Math.pow(2,e-1);T&&console.warn(`[SERVER HYDRATION] \u26A0\uFE0F Attempt ${e} failed, retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o))}return null}var de=n=>a=>t=>async e=>{if(I.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta;if(s&&o>0&&r){let c=a.getState().workflow.context[s];if(!c||Object.keys(c).length===0){T&&console.log(`[SERVER HYDRATION] \u{1F9CA} Cold start for ${s}`);let d=await ce(async()=>await n.hydrateCascadeContext(s,o+1));if(!d){let f=`[SERVER HYDRATION] \u{1F6D1} Critical: Hydration failed for ${s}. Terminating action.`;throw T&&console.error(f),new Error("Server-side hydration failed: persistence unreachable.")}Object.keys(d).length>0&&(await a.dispatch(W(d)),T&&console.log("[SERVER HYDRATION] \u2705 State restored successfully"))}}}if(j.match(e)){let{sourceCascadeId:r,newCascadeId:o,upToFunctionId:s}=e.payload;T&&console.log(`[SERVER FORK] \u{1F374} Forking ${r} \u2192 ${o} at fn ${s}`);let i=await ce(async()=>await n.forkCascadeWithContext({sourceCascadeId:r,newCascadeId:o,upToFunctionId:s}));if(!i){let c=`[SERVER FORK] \u{1F6D1} Critical: Fork failed for ${r}. Terminating action.`;throw T&&console.error(c),new Error("Server-side fork failed: persistence unreachable.")}i.context&&Object.keys(i.context).length>0?(await a.dispatch(W(i.context)),T&&console.log(`[SERVER FORK] \u2705 Fork complete, context hydrated for ${o}`)):T&&console.log(`[SERVER FORK] \u2705 Fork complete, no context to hydrate for ${o}`)}return t(e)};var ct=(n,a=[])=>{let t=Ne(),e=[];return n&&e.push(ie(n),de(n)),e.push(...a),e.push(t.middleware),{store:ke({reducer:{workflow:ee},middleware:o=>o({serializableCheck:!1}).concat(e),devTools:process.env.NODE_ENV!=="production"}),serverListener:t}};async function lt(n,a,t){switch(a){case"claim":return await n.claimNodeExecution(t);case"finalize":return await n.finalizeNodeExecution(t);case"error":return await n.markExecutionFailed(t.nodeInstanceId,t.cascadeId,t.error);case"context":return await n.recordContextEvents(t);case"hydrate":return await n.hydrateCascadeContext(t.cascadeId,t.functionId,t.ui);case"forkAndHydrate":return await n.forkCascadeWithContext({sourceCascadeId:t.sourceCascadeId,newCascadeId:t.newCascadeId,upToFunctionId:t.upToFunctionId});default:throw new Error("Invalid action")}}var Ee=()=>{let n=!1;return a=>{if(a.type==="content_block_start"){let t=()=>(n=!0,{identity:"role",value:"assistant",silent:!0});if(a.content_block?.type==="thinking")return[...n?[]:[t()],{identity:"thinking",value:""}];if(a.content_block?.type==="text")return[...n?[]:[t()],{identity:"content",value:""}];if(a.content_block?.type==="tool_use")return[...n?[]:[t()],{identity:"tool_calls",value:[],buffer:!0,accumulate:(e=[],r)=>(e.push({id:a.content_block.id,name:a.content_block.name,args:{}}),e)}]}if(a.type==="content_block_delta"){if(a.delta?.type==="text_delta")return{identity:"content",value:a.delta.text};if(a.delta?.type==="thinking_delta")return{identity:"thinking",value:a.delta.thinking};if(a.delta?.type==="signature_delta")return{identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(t={},e)=>({...t,anthropic:{...t.anthropic??{},signature:a.delta.signature}})};if(a.delta?.type==="input_json_delta")return{identity:"tool_calls",value:a.delta.partial_json,buffer:!0,accumulate:(t=[],e)=>{let r=t[t.length-1];return r&&(r._rawArgs=(r._rawArgs??"")+e),t}}}return a.type==="content_block_stop"?{identity:"tool_calls",value:null,buffer:!0,accumulate:(t=[],e)=>{let r=t[t.length-1];if(r&&r._rawArgs!==void 0){try{r.args=JSON.parse(r._rawArgs||"{}")}catch{r.args={}}delete r._rawArgs}return t}}:null}},_e=()=>{let n=!1;return a=>{let t=a.choices?.[0]?.delta;if(!t)return null;let e=[];if(n||(n=!0,e.push({identity:"role",value:"assistant",silent:!0})),t.reasoning_content&&e.push({identity:"thinking",value:t.reasoning_content}),t.content&&e.push({identity:"content",value:t.content}),t.tool_calls){let r=t.tool_calls[0],o=r.index??0;e.push({identity:"tool_calls",value:r,buffer:!0,accumulate:(s=[],i)=>(s[o]||(s[o]={id:"",name:"",args:{}}),i.id&&(s[o].id=i.id),i.function?.name&&(s[o].name+=i.function.name),i.function?.arguments&&(s[o]._rawArgs=(s[o]._rawArgs??"")+i.function.arguments),s)})}return a.choices?.[0]?.finish_reason==="tool_calls"&&e.push({identity:"tool_calls",value:null,buffer:!0,accumulate:(r=[],o)=>r.map(s=>{if(s._rawArgs!==void 0){try{s.args=JSON.parse(s._rawArgs||"{}")}catch{s.args={}}delete s._rawArgs}return s})}),e.length===0?null:e.length===1?e[0]:e}},Me=()=>{let n=!1,a=[];return t=>{let e=t.candidates?.[0]?.content?.parts??[];if(!e.length)return null;let r=[];n||(n=!0,r.push({identity:"role",value:"assistant",silent:!0}));for(let o of e)if(o.thought===!0&&o.text){let s=a.find(i=>i.thought===!0);s?(s.text+=o.text,o.thoughtSignature&&(s.thoughtSignature=o.thoughtSignature)):a.push({...o}),r.push({identity:"thinking",value:o.text}),o.thoughtSignature&&r.push({identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(i={},c)=>({...i,gemini:{...i.gemini??{},thoughtSignature:o.thoughtSignature,parts:[...a]}})})}else if(o.text&&o.thought!==!0){let s=a.find(i=>i.text!==void 0&&!i.thought&&!i.functionCall);s?s.text+=o.text:a.push({text:o.text}),r.push({identity:"content",value:o.text}),r.push({identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(i={},c)=>({...i,gemini:{...i.gemini??{},parts:[...a]}})})}else o.functionCall&&(a.push({...o}),r.push({identity:"tool_calls",value:null,buffer:!0,accumulate:(s=[],i)=>a.filter(c=>c.functionCall).map(c=>({id:c.functionCall.id??c.functionCall.name,name:c.functionCall.name,args:c.functionCall.args??{}}))}),r.push({identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(s={},i)=>({...s,gemini:{...s.gemini??{},parts:[...a]}})}));return r.length===0?null:r.length===1?r[0]:r}},Te=()=>{let n=[];return a=>{if(a.type==="response.output_item.added"){let t=a.item;if(!t)return null;if(t.type==="reasoning")return n.push({id:t.id,type:"reasoning",summary:[{type:"summary_text",text:""}]}),$("openai_responses",n);if(t.type==="message")return n.push({id:t.id,type:"message",role:"assistant",content:[{type:"output_text",text:""}]}),[{identity:"role",value:"assistant",silent:!0},$("openai_responses",n)];if(t.type==="function_call")return n.push({id:t.id,type:"function_call",call_id:t.call_id,name:t.name,arguments:""}),$("openai_responses",n)}if(a.type==="response.reasoning_summary_text.delta"){let t=n.find(e=>e.id===a.item_id&&e.type==="reasoning");return t&&(t.summary[0].text+=a.delta),[$("openai_responses",n),{identity:"thinking",value:a.delta}]}if(a.type==="response.output_text.delta"){let t=n.find(e=>e.id===a.item_id&&e.type==="message");return t&&(t.content[0].text+=a.delta),[$("openai_responses",n),{identity:"content",value:a.delta}]}if(a.type==="response.function_call_arguments.delta"){let t=n.find(e=>e.id===a.item_id&&e.type==="function_call");return t&&(t.arguments+=a.delta),$("openai_responses",n)}if(a.type==="response.function_call_arguments.done"){let t=n.find(r=>r.id===a.item_id&&r.type==="function_call");t&&(t.arguments=a.arguments??"{}");let e=n.filter(r=>r.type==="function_call").map(r=>({id:r.call_id,name:r.name,args:(()=>{try{return JSON.parse(r.arguments||"{}")}catch{return{}}})()}));return[$("openai_responses",n),{identity:"tool_calls",value:e,buffer:!0,accumulate:(r,o)=>o}]}return null}};function $(n,a){return{identity:"extensions",value:null,buffer:!0,silent:!0,accumulate:(t={},e)=>({...t,[n]:{output:[...a]}})}}var q={anthropic:Ee,openai:_e,"gemini-genai":Me,"openai-responses":Te};import{v7 as Pe}from"uuid";import{createSelector as Z}from"reselect";var be=n=>n.workflow.activeNodes,le=n=>n.workflow.context,ue=(n,a)=>a,V=()=>Z([le,ue],(n,a)=>{let t=n[a];if(!t||t.length===0)return;let e=t[t.length-1].status,r={};return t.forEach(o=>{let{status:s,...i}=o;Object.entries(i).forEach(([c,d])=>{d!=null&&(r[c]||(r[c]=[]),Array.isArray(d)?r[c].push(...d):r[c].push(d))})}),{...r,status:e}}),J=()=>Z([be,ue],(n,a)=>Object.entries(n).filter(([t,e])=>e.initialContext?.cascadeId===a).map(([t,e])=>({nodeId:t,nodeName:e.nodeName,parentTriggerId:e.parentTriggerId,initialContext:e.initialContext,processed:e.processed}))),mt=Z([le],n=>Object.keys(n));import{v7 as Oe}from"uuid";function fe(n){return{updateContext:async a=>{await n.dispatch(S(a))},spawn:async a=>{let t=[];for(let[e,r]of Object.entries(a)){let o=`${e}_${Oe()}`;await n.dispatch(I({nodeId:o,nodeName:e,contextData:r},{cascadeId:r.cascadeId,userId:r.userId,functionId:0})),r.cascadeId&&t.push(r.cascadeId)}t.length!==0&&await n.condition((e,r)=>t.every(o=>{let s=J()(r,o),i=V()(r,o);return s.length===0&&i!==void 0}))},fork:async(a,t,e)=>{try{return await n.dispatch(j({sourceCascadeId:e,newCascadeId:a,upToFunctionId:t})),{status:"SUCCESS"}}catch{return{status:"FAILED"}}},waitUntil:async a=>{await n.condition((t,e)=>a(e))},getCascadeState:a=>V()(n.getState(),a),getCascadeNodes:a=>J()(n.getState(),a),isComplete:a=>{let t=n.getState();return J()(t,a).length===0&&V()(t,a)!==void 0},exists:a=>{let t=n.getState();return V()(t,a)!==void 0||J()(t,a).length>0},getState:()=>n.getState()}}var pe=process.env.NODE_ENV==="development",k=(...n)=>{pe&&console.log(...n)},Re=(...n)=>{pe&&console.error(...n)};function kt(n,a,t,e,r,o){let s=`
|
|
5
5
|
__END_STREAM_METADATA__
|
|
6
|
-
`,{
|
|
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};
|
|
6
|
+
`,{writeRaw:i,close:c,send:d}=t;n.startListening({actionCreator:I,effect:async(f,l)=>{let{nodeId:u,nodeName:m,contextData:p}=f.payload,{functionId:h=0}=f.meta??{},y=a.workflowGraph[m],O=p.userId,G=fe(l);k(`
|
|
7
|
+
[Node ] \u{1F680} Starting: ${m}`);let C=p.cascadeId?.startsWith("call");if(!y||y.isUINode){k("[Node ] \u{1F5A5}\uFE0F UI Node detected. Handing off to client listener."),await d({type:"ui_spawn",nodeName:m,contextData:p}),await l.dispatch(N({nodeId:u,hasSpawns:!1},{origin:"server"}));let E=l.getState().workflow?.activeNodes||{},g=Object.keys(E);k("[Server] Active node keys remaining:",g),g.length===0&&(k(`[Server] \u{1F3C1} State reached Zero. Closing stream. Triggered by completion of: ${m}`),await c());return}try{if(h==0){let{cascadeId:v,userId:L,history:U,sentFromClient:F,..._}=p;await l.dispatch(S({[p?.cascadeId]:{..._,history:[...p?.history],status:"completed"}},{origin:"server"})),p.sentFromClient||await d({type:"sync",cascadeId:p.cascadeId,history:[...p?.history],status:"completed"})}let x=structuredClone(p),E={};if(y.prep){let v=l.getState().workflow.context;E=await y.prep(v,x)}let g=E.cascadeId||p.cascadeId,M=f.meta?.functionId??0,w=null;if(y.isStreaming){k("[Node ] \u{1F30A} Executing Streaming Node...");let v=await y.exec(E,G),{canonical:L,uiMessage:U}=await Ae(v,g,d,o);w=await y.post({assistantMessage:L,uiAssistantMessage:U,cascadeId:g,history:structuredClone(E.history),userId:p.userId})}else{k("[Node ] \u26A1 Executing Standard Node...");let v=await y.exec(E,G);w=await y.post(v)}if(w){let v=Date.now()-r,L=a.maxExecutionTime-v,U=w.spawns?Object.keys(w.spawns):[];if(U.length)if(L>a.safeBuffer){k(`[Node ] \u2705 Internally Spawning: ${U.join(", ")} (${Math.round(L/1e3)}s remaining)`);let F=w.updates[g];if(w.updates){await l.dispatch(S(w.updates,{functionId:M,cascadeId:g,uiUpdates:w.uiUpdates}));let P=w.uiUpdates?.[g]??w.updates?.[g];P&&!y.isStreaming&&(k("[Node ] \u{1F504} Syncing context chunk to client UI."),await d({type:"sync",cascadeId:g,...P}))}let _=Object.entries(w.spawns);_.every(([P])=>!a.workflowGraph[P]||a.workflowGraph[P].isUINode)?await i(s+JSON.stringify(w)):_.forEach(async([P,H],Q)=>{await l.dispatch(I({nodeId:`${P}_${Pe()}_${Q}`,nodeName:P,parentTriggerId:u,contextData:H?.userId?H:{...H,userId:O}},{functionId:M+1+Q,cascadeId:H?.cascadeId,userId:H?.userId||O}))}),await l.dispatch(N({nodeId:u,hasSpawns:!0,fullOutput:F},{functionId:M,cascadeId:g}))}else{k("[Node ] \u23F3 Time Buffer Reached. Handing off to client to checkpoint.");let F=w.updates[g];if(w.updates){await l.dispatch(S(w.updates,{functionId:M,cascadeId:g,uiUpdates:w.uiUpdates}));let _=w.uiUpdates?.[g]??w.updates?.[g];_&&!y.isStreaming&&(k("[Node ] \u{1F504} Syncing context chunk to client UI."),await d({type:"sync",cascadeId:g,..._}))}await l.dispatch(N({nodeId:u,hasSpawns:!0,fullOutput:F},{functionId:M,cascadeId:g})),await i(s+JSON.stringify(w))}else{k("[Node ] \u{1F3C1} Chain Terminal. Dispatching completion.");let F=w.updates[g];if(w.updates){await l.dispatch(S(w.updates,{functionId:M,cascadeId:g,uiUpdates:w.uiUpdates}));let _=w.uiUpdates?.[g]??w.updates?.[g];_&&!y.isStreaming&&(k("[Node ] \u{1F504} Syncing context chunk to client UI."),await d({type:"sync",cascadeId:g,..._}))}await l.dispatch(N({nodeId:u,hasSpawns:!1,fullOutput:F},{functionId:M,cascadeId:g})),C||await i(s+JSON.stringify(w))}}}catch(x){Re("[Node ] \u274C Execution Error:",x.message),await l.dispatch(R({nodeId:u,error:x.message},{functionId:f.meta?.functionId,cascadeId:p?.cascadeId})),await l.dispatch(N({nodeId:u,hasSpawns:!1,fullOutput:void 0},{functionId:f.meta?.functionId,cascadeId:p?.cascadeId,origin:"server"})),await i(s+JSON.stringify({error:x.message}))}finally{let E=l.getState().workflow?.activeNodes||{},g=Object.keys(E);k("[Server] Active node keys remaining:",g),g.length===0&&(k(`[Server] \u{1F3C1} State reached Zero. Closing stream. Triggered by completion of: ${m}`),await c())}}})}async function Ae(n,a,t,e){let{stream:r,provider:o,mapper:s,filter:i}=n,c=s??q[o];if(!c)throw new Error(`[handleProviderStream] No mapper found for provider "${o}". Pass a custom mapper via StreamConfig.mapper, or use one of the built-in providers: ${Object.keys(q).join(", ")}.`);let d=typeof c=="function"&&c.length===0?c():c,f=a.startsWith("_");f||await t({type:"init",cascadeId:a});let l={},u={},m=!1,p=new Set;for await(let h of r){let y=d(h);if(!y)continue;let O=Array.isArray(y)?y:[y];for(let G of O){let{identity:C,value:x,accumulate:E,buffer:g,silent:M}=G;if(E?l[C]=E(l[C],x):typeof l[C]=="string"&&typeof x=="string"?l[C]+=x:l[C]=x,!(M&&(!e||C==="role"))){if(g){p.add(C);continue}if(!f){let w=typeof x=="string"?x:l[C];if(i&&!e){let v=i(C,w);m=!0,v!==!1&&(await t({cascadeId:a,identity:C,value:v}),typeof v=="string"?u[C]=(u[C]??"")+v:u[C]=v)}else await t({cascadeId:a,identity:C,value:w})}}}}if(!f)for(let h of p){if(l[h]===void 0)continue;let y=l[h];if(i&&!e){let O=i(h,y);m=!0,O!==!1&&(await t({cascadeId:a,identity:h,value:O}),u[h]=O)}else await t({cascadeId:a,identity:h,value:y})}return{canonical:l,...m?{uiMessage:u}:{}}}var A=process.env.NODE_ENV==="development";async function z(n,a=3,t=100){for(let e=1;e<=a;e++)try{return await n()}catch(r){if(e===a)return A&&console.error(`[CLIENT MW] \u274C All ${a} retry attempts failed:`,r),null;let o=t*Math.pow(2,e-1);A&&console.warn(`[CLIENT MW] \u26A0\uFE0F Attempt ${e} failed, retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o))}return null}var oe=n=>a=>t=>async e=>{if(I.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,{nodeId:i,nodeName:c,contextData:d}=e.payload;if(!s||r)return t(e);let f=o??0,l=await z(async()=>{let p=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"claim",nodeInstanceId:i,cascadeId:s,userId:d.userId,nodeName:c,functionId:f,inputContext:d,location:"client"})});if(!p.ok)throw new Error(`Persistence sync failed: ${p.status}`);return await p.json()});if(!l){A&&console.error(`[CLIENT MW] \u274C Failed to claim node ${i} after retries`);return}let u=l.functionId;A&&console.log(`[CLIENT MW] \u2705 Node ${i} bound to FnId: ${u}`);let m={...e,meta:{...e.meta,origin:"client",functionId:u,cascadeId:s}};return t(m)}if(N.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,i=typeof e.payload=="string"?e.payload:e.payload.nodeId,c=e.payload.hasSpawns,d=e.payload.fullOutput,f=a.getState(),l=f.workflow.activeNodes[i],u=s||l?.cascadeId,m=o??l?.functionId??0;if(!u||r)return t(e);let p=d||f.workflow.context[u];if(!await z(async()=>{let y=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"finalize",nodeInstanceId:i,cascadeId:u,fullOutput:p,hasSpawns:c})});if(!y.ok)throw new Error(`Persistence sync failed: ${y.status}`);return await y.json()})){A&&console.error(`[CLIENT MW] \u274C Failed to finalize node ${i} after retries`);return}return t({...e,meta:{...e.meta,origin:"client",functionId:m,cascadeId:u}})}if(R.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta,{nodeId:i,error:c}=e.payload,f=a.getState().workflow.activeNodes[i],l=s||f?.cascadeId;if(!l||r)return t(e);if(!await z(async()=>{let m=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"error",nodeInstanceId:i,cascadeId:l,error:c})});if(!m.ok)throw new Error(`Persistence sync failed: ${m.status}`);return await m.json()})){A&&console.error(`[CLIENT MW] \u274C Failed to mark node ${i} as failed after retries`);return}return t({...e,meta:{...e.meta,origin:"client",cascadeId:l}})}if(S.match(e)){let{origin:r,functionId:o,cascadeId:s,uiUpdates:i}=e.meta,c=e.payload,d=s,f=o??0;if(!d||r||(A&&console.log("[CLIENT MW] \u{1F504} Persisting context:",JSON.stringify(c,null,2)),c[d]?.status==="streaming"))return t(e);if(!await z(async()=>{let u=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"context",cascadeId:d,functionId:f,updates:c,uiUpdates:i})});if(!u.ok)throw new Error(`Persistence sync failed: ${u.status}`);return await u.json()})){A&&console.error(`[CLIENT MW] \u274C Failed to record context for cascade ${d} after retries`);return}return t({...e,meta:{...e.meta,origin:"client",functionId:f,cascadeId:d}})}return t(e)};var b=process.env.NODE_ENV==="development";async function me(n,a=3,t=100){for(let e=1;e<=a;e++)try{return await n()}catch(r){if(e===a)return b&&console.error(`[HYDRATION] \u274C All ${a} attempts failed:`,r),null;let o=t*Math.pow(2,e-1);b&&console.warn(`[HYDRATION] \u26A0\uFE0F Attempt ${e} failed, retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o))}return null}var se=n=>a=>t=>async e=>{if(I.match(e)){let{origin:r,functionId:o,cascadeId:s}=e.meta;if(s&&o>0&&r==="client"){let c=a.getState().workflow.context[s];if(!c||Object.keys(c).length===0){b&&console.log(`[HYDRATION] \u{1F9CA} Cold start for ${s}`);let d=await me(async()=>{let f=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"hydrate",cascadeId:s,functionId:o,ui:!0})});if(!f.ok)throw new Error(`Status ${f.status}`);return await f.json()});if(!d){let f=`[HYDRATION] Critical Failure: Could not hydrate cascade ${s}. Action terminated.`;throw b&&console.error(f),new Error("Hydration failed")}Object.keys(d).length>0&&(a.dispatch(W(d)),b&&console.log("[HYDRATION] \u2705 State restored successfully"))}}}if(j.match(e)){let{sourceCascadeId:r,newCascadeId:o,upToFunctionId:s}=e.payload;b&&console.log(`[FORK] \u{1F374} Forking ${r} \u2192 ${o} at fn ${s}`);let i=await me(async()=>{let c=await fetch(n.persistenceEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"forkAndHydrate",sourceCascadeId:r,newCascadeId:o,upToFunctionId:s})});if(!c.ok)throw new Error(`Fork failed with status ${c.status}`);return await c.json()});if(!i){let c=`[FORK] Critical Failure: Could not fork cascade ${r}. Action terminated.`;throw b&&console.error(c),new Error("Fork failed")}i.context&&Object.keys(i.context).length>0?(a.dispatch(W(i.context)),b&&console.log(`[FORK] \u2705 Fork complete, context hydrated for ${o}`)):b&&console.log(`[FORK] \u2705 Fork complete, no context to hydrate for ${o}`)}return t(e)};export{I as addActiveNode,se as createClientHydrationMiddleware,oe as createClientPersistenceMiddleware,Ze as createClientStore,de as createServerHydrationMiddleware,ie as createServerPersistenceMiddleware,ct as createServerStore,j as forkAndHydrate,lt as handlePersistenceAction,Ae as handleProviderStream,W as hydrateContext,J as makeSelectCascadeNodes,V as makeSelectCascadeState,We as markNodeProcessed,N as removeActiveNode,mt as selectAllCascadeIds,R as setError,kt as setupServerWorkflowListener,X as streamChunkReceived,S as updateContext,K as workflowSlice};
|
package/package.json
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cascaide-ts/core",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"license": "MIT",
|
|
4
5
|
"files": [
|
|
5
|
-
"dist"
|
|
6
|
+
"dist",
|
|
7
|
+
"LICENSE",
|
|
8
|
+
"README.md"
|
|
6
9
|
],
|
|
7
10
|
"type": "module",
|
|
8
11
|
"main": "./dist/index.cjs",
|
|
@@ -21,13 +24,20 @@
|
|
|
21
24
|
"sideEffects": false,
|
|
22
25
|
"peerDependencies": {
|
|
23
26
|
"@reduxjs/toolkit": "^2.0.0",
|
|
24
|
-
"reselect": "^5.0.0"
|
|
27
|
+
"reselect": "^5.0.0",
|
|
28
|
+
"uuid": "^13.0.0"
|
|
25
29
|
},
|
|
26
30
|
"devDependencies": {
|
|
27
31
|
"@reduxjs/toolkit": "^2.0.0",
|
|
32
|
+
"@types/uuid": "^10.0.0",
|
|
33
|
+
"@typescript-eslint/eslint-plugin": "^8.58.1",
|
|
34
|
+
"@typescript-eslint/parser": "^8.58.1",
|
|
35
|
+
"eslint": "^10.2.0",
|
|
28
36
|
"reselect": "^5.0.0",
|
|
37
|
+
"ts-prune": "^0.10.3",
|
|
29
38
|
"tsup": "^8.5.1",
|
|
30
|
-
"typescript": "^5.0.0"
|
|
39
|
+
"typescript": "^5.0.0",
|
|
40
|
+
"uuid": "^13.0.0"
|
|
31
41
|
},
|
|
32
42
|
"scripts": {
|
|
33
43
|
"build": "tsup",
|