yaml-flow 8.1.1 → 8.2.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/browser/asset-integrity.json +3 -3
- package/browser/board-livecards-client.js +1 -1
- package/browser/board-livecards-localstorage.js +4 -6
- package/cli/{board-live-cards-lib-tjYsPt5U.d.ts → board-live-cards-lib-Iq_XAC09.d.ts} +1 -1
- package/cli/browser-api/board-live-cards-browser-adapter.d.ts +4 -3
- package/cli/browser-api/board-live-cards-browser-adapter.js +2 -2
- package/cli/browser-api/card-store-browser-api.d.ts +1 -1
- package/cli/node/artifacts-store-cli.js +8 -8
- package/cli/node/board-live-cards-cli.js +8 -8
- package/cli/node/card-store-cli.js +4 -4
- package/cli/node/fs-board-adapter.d.ts +6 -33
- package/cli/node/fs-board-adapter.js +10 -8
- package/cli/node/step-machine-cli.js +3 -3
- package/cli/{types-D2XnLbBj.d.ts → types--rXGWbSR.d.ts} +77 -5
- package/examples/board/.board-ws/cards/store/_index.json +17 -0
- package/examples/board/.board-ws/cards/store/card-market-prices.json +80 -0
- package/examples/board/.board-ws/cards/store/card-portfolio-value.json +90 -0
- package/examples/board/.board-ws/cards/store/card-portfolio.json +78 -0
- package/examples/board/cards/cardT-market-prices.json +6 -4
- package/examples/board/cards/cardT-portfolio-value.json +10 -38
- package/examples/board/cards/cardT-portfolio.json +9 -4
- package/examples/board/demo-shell-with-server.html +3 -3
- package/examples/board/server/board-server.js +593 -0
- package/examples/board/server/board-worker/source-def-flows/mock-handler/mock-db.js +13 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/.retain/compliance.db +0 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/.retain/optimus.db +0 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/query.cjs +51 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/seed-cpm.cjs +197 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/seed-cpmV2.cjs +128 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/seed-optimus.cjs +352 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/sqlite-config.json +3 -0
- package/examples/board/server/board-worker/source-def-flows/sqlite-handler/sqlite-handler.js +84 -0
- package/examples/board/{source-def-flows/url.flow.json → server/board-worker/source-def-flows/sqlite.flow.json} +7 -7
- package/examples/board/{source-def-handlers → server/board-worker/source-def-flows/url-handler}/http-source-handler.js +29 -21
- package/examples/board/server/board-worker/source-def-flows/url.flow.json +73 -0
- package/examples/board/{source_def_flows.json → server/board-worker/source_def_flows.json} +61 -115
- package/examples/board/server/board-worker/task-executor.js +475 -0
- package/examples/board/server/chat-flow/chat-clear-processing.js +41 -0
- package/examples/board/server/chat-flow/chat-open-turn.js +144 -0
- package/examples/board/server/chat-flow/chat-write-assistant.js +44 -0
- package/examples/board/server/chat-flow/copilot-chat/assistant.js +253 -0
- package/examples/board/server/chat-flow/echo-probe/assistant.js +28 -0
- package/examples/board/server/chat-flow/flow-steps.json +167 -0
- package/examples/board/server-config.json +22 -0
- package/examples/board/test/server-http-test.js +707 -0
- package/examples/board/test/{portfolio-tracker-sse-worker.js → sse-worker.js} +9 -8
- package/examples/board-local/demo-shell-localstorage.html +3 -3
- package/lib/{artifacts-store-lib-public-DBICnGL6.d.cts → artifacts-store-lib-public-C5UL5tyG.d.cts} +3 -31
- package/lib/{artifacts-store-lib-public-BWC3YuLa.d.ts → artifacts-store-lib-public-GD4H-fFp.d.ts} +3 -31
- package/lib/artifacts-store-public.d.cts +3 -3
- package/lib/artifacts-store-public.d.ts +3 -3
- package/lib/board-live-cards-node.cjs +10 -8
- package/lib/board-live-cards-node.d.cts +9 -8
- package/lib/board-live-cards-node.d.ts +9 -8
- package/lib/board-live-cards-node.js +10 -8
- package/lib/{board-live-cards-public-BF9FP0mL.d.cts → board-live-cards-public-BLXbcBNk.d.cts} +2 -2
- package/lib/{board-live-cards-public-dJAl5IL-.d.ts → board-live-cards-public-BZaNb2mi.d.ts} +2 -2
- package/lib/board-live-cards-public.cjs +2 -2
- package/lib/board-live-cards-public.d.cts +2 -2
- package/lib/board-live-cards-public.d.ts +2 -2
- package/lib/board-live-cards-public.js +2 -2
- package/lib/board-live-cards-server-runtime.cjs +4 -6
- package/lib/board-live-cards-server-runtime.d.cts +3 -3
- package/lib/board-live-cards-server-runtime.d.ts +3 -3
- package/lib/board-live-cards-server-runtime.js +4 -6
- package/lib/board-livegraph-runtime/index.cjs +2 -2
- package/lib/board-livegraph-runtime/index.js +2 -2
- package/lib/card-store-public.d.cts +2 -2
- package/lib/card-store-public.d.ts +2 -2
- package/lib/execution-refs.cjs +1 -1
- package/lib/execution-refs.js +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.d.cts +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/server-runtime/index.cjs +4 -6
- package/lib/server-runtime/index.d.cts +4 -4
- package/lib/server-runtime/index.d.ts +4 -4
- package/lib/server-runtime/index.js +4 -6
- package/lib/step-machine-public/index.cjs +3 -3
- package/lib/step-machine-public/index.d.cts +27 -10
- package/lib/step-machine-public/index.d.ts +27 -10
- package/lib/step-machine-public/index.js +3 -3
- package/lib/{storage-interface-BhAON-gW.d.ts → storage-interface-B6ecOulj.d.cts} +25 -3
- package/lib/{storage-interface-BhAON-gW.d.cts → storage-interface-B6ecOulj.d.ts} +25 -3
- package/lib/stores/index.d.cts +1 -1
- package/lib/stores/index.d.ts +1 -1
- package/lib/stores/kv.d.cts +1 -1
- package/lib/stores/kv.d.ts +1 -1
- package/lib/{types-CXBzvC0s.d.cts → types-Bztd1KoK.d.cts} +75 -3
- package/lib/{types-D48hpnTR.d.ts → types-D-xVWPdY.d.ts} +75 -3
- package/package.json +1 -1
- package/examples/board/demo-chat-handler.js +0 -169
- package/examples/board/demo-server-config.json +0 -10
- package/examples/board/demo-server.js +0 -580
- package/examples/board/demo-task-executor.js +0 -721
- package/examples/board/gandalf-cards/card-source-kinds.json +0 -36
- package/examples/board/gandalf-cards/cards/_index.json +0 -7
- package/examples/board/gandalf-cards/cards/card-source-kinds.json +0 -64
- package/examples/board/scripts/copilot_wrapper.bat +0 -157
- package/examples/board/scripts/copilot_wrapper_helper.ps1 +0 -190
- package/examples/board/scripts/workiq_wrapper.mjs +0 -66
- package/examples/board/source-def-flows/copilot.flow.json +0 -33
- package/examples/board/source-def-flows/url-list.flow.json +0 -33
- package/examples/board/source-def-flows/workiq.flow.json +0 -34
- package/examples/board/source-def-handlers/copilot-source-handler.js +0 -141
- package/examples/board/test/demo-http-test.js +0 -317
- /package/examples/board/{source-def-flows → server/board-worker/source-def-flows}/mock.flow.json +0 -0
|
@@ -1,16 +1,9 @@
|
|
|
1
1
|
export { c as createStepMachine, l as loadStepFlow } from '../loader-Zborm2pq.js';
|
|
2
|
-
|
|
2
|
+
import { l as StepMachineStore } from '../types-DQ1bKuB1.js';
|
|
3
3
|
export { MemoryStore } from '../stores/memory.js';
|
|
4
4
|
export { KVStorageStore } from '../stores/kv.js';
|
|
5
5
|
import { ExecutionRef } from '../execution-refs.js';
|
|
6
|
-
import '../storage-interface-
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* step-machine-public — types
|
|
10
|
-
*
|
|
11
|
-
* Platform-free types for the declarative handler model.
|
|
12
|
-
* No Node imports. Safe for any runtime (Node, browser, Python via codegen, etc.).
|
|
13
|
-
*/
|
|
6
|
+
import '../storage-interface-B6ecOulj.js';
|
|
14
7
|
|
|
15
8
|
/**
|
|
16
9
|
* The single normalized shape the engine consumes.
|
|
@@ -74,6 +67,17 @@ type HandlerSpec = ComputeJsonataSpec | RefSpec;
|
|
|
74
67
|
* The framework awaits regardless.
|
|
75
68
|
*/
|
|
76
69
|
type InvokeRefFn = (ref: ExecutionRef, args: Record<string, unknown>) => NormalizedHandlerResult | Promise<NormalizedHandlerResult>;
|
|
70
|
+
interface CreateStepMachineChatFlowRunnerOptions$1 {
|
|
71
|
+
invokeRef: InvokeRefFn;
|
|
72
|
+
storeFactory?: () => StepMachineStore;
|
|
73
|
+
}
|
|
74
|
+
interface StepMachineChatFlowRunnerResult$1 {
|
|
75
|
+
dispatched: boolean;
|
|
76
|
+
error?: string;
|
|
77
|
+
}
|
|
78
|
+
interface StepMachineChatFlowRunner$1 {
|
|
79
|
+
run(flow: unknown, args: Record<string, unknown>): Promise<StepMachineChatFlowRunnerResult$1>;
|
|
80
|
+
}
|
|
77
81
|
/**
|
|
78
82
|
* Handler signature consumed by the existing pure step machine.
|
|
79
83
|
*
|
|
@@ -176,4 +180,17 @@ type JsonataExpression = {
|
|
|
176
180
|
};
|
|
177
181
|
declare const jsonata: (expr: string) => JsonataExpression;
|
|
178
182
|
|
|
179
|
-
|
|
183
|
+
interface CreateStepMachineChatFlowRunnerOptions {
|
|
184
|
+
invokeRef: InvokeRefFn;
|
|
185
|
+
storeFactory?: () => StepMachineStore;
|
|
186
|
+
}
|
|
187
|
+
interface StepMachineChatFlowRunnerResult {
|
|
188
|
+
dispatched: boolean;
|
|
189
|
+
error?: string;
|
|
190
|
+
}
|
|
191
|
+
interface StepMachineChatFlowRunner {
|
|
192
|
+
run(flow: unknown, args: Record<string, unknown>): Promise<StepMachineChatFlowRunnerResult>;
|
|
193
|
+
}
|
|
194
|
+
declare function createStepMachineChatFlowRunner(options: CreateStepMachineChatFlowRunnerOptions): StepMachineChatFlowRunner;
|
|
195
|
+
|
|
196
|
+
export { type BuildStepHandlersOptions, type ComputeJsonataSpec, type CreateStepMachineChatFlowRunnerOptions$1 as CreateStepMachineChatFlowRunnerOptions, type HandlerSpec, type InvokeRefFn, type JsonataExpression, type NormalizedHandlerResult, type RefSpec, type ResolveStepHandlerOptions, type StepConfigForFactory, type StepHandler, type StepMachineChatFlowRunner$1 as StepMachineChatFlowRunner, type StepMachineChatFlowRunnerResult$1 as StepMachineChatFlowRunnerResult, StepMachineStore, buildStepHandlersForFlow, createComputeJsonataHandler, createPassthroughHandler, createRefStepHandler, createStepMachineChatFlowRunner, filterProducedData, isComputeJsonataSpec, isRefSpec, jsonata, normalizeHandlerResult, resolveStepHandler, runInputValidations, wrapWithInputValidations, wrapWithOutputFiltering };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import'ajv-formats';import {createRequire}from'module';import {fileURLToPath}from'url';import {dirname,resolve}from'path';import {existsSync}from'fs';function R(r,t,e,n){let s=r.steps[e];if(!s)throw new Error(`Step "${e}" not found in flow configuration`);if(n.result==="failure"&&s.retry){let a=t.retryCounts[e]??0;if(a<s.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[e]:a+1},updatedAt:Date.now()},nextStep:e,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let o=s.failure_transitions?.[n.result]??s.transitions[n.result];if(!o)throw new Error(`No transition defined for result "${n.result}" in step "${e}"`);let i=!!r.terminal_states[o];return {newState:{...t,currentStep:o,stepHistory:[...t.stepHistory,e],retryCounts:{...t.retryCounts,[e]:0},updatedAt:Date.now()},nextStep:o,isTerminal:i,isCircuitBroken:false,shouldRetry:false}}function b(r,t,e){let n=r.steps[e];if(!n?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:(t.iterationCounts[e]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[e]??0;return s>=n.circuit_breaker.max_iterations?{broken:true,redirectStep:n.circuit_breaker.on_open,newState:{...t,currentStep:n.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:s+1},updatedAt:Date.now()}}}function j(r,t,e){let n=r.steps[t];if(!n)throw new Error(`Step "${t}" not found`);if(n.expects_data){let s={};for(let o of n.expects_data)s[o]=e[o];return s}return {...e}}function E(r,t){if(r===false||r===void 0)return {};if(typeof r=="string")return {[r]:t[r]};if(Array.isArray(r)){let e={};for(let n of r)e[n]=t[n];return e}return {}}function $(r,t){let e=Date.now();return {runId:t,flowId:r.id??"unnamed",currentStep:r.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:e,updatedAt:e}}var S=class{runs=new Map;data=new Map;async saveRunState(t,e){this.runs.set(t,{...e});}async loadRunState(t){let e=this.runs.get(t);return e?{...e}:null}async deleteRunState(t){this.runs.delete(t),this.data.delete(t);}async setData(t,e,n){this.data.has(t)||this.data.set(t,{});let s=this.data.get(t);s[e]=n;}async getData(t,e){return this.data.get(t)?.[e]}async getAllData(t){return {...this.data.get(t)??{}}}async clearData(t){this.data.delete(t);}async listRuns(){return Array.from(this.runs.keys())}clear(){this.runs.clear(),this.data.clear();}};function tt(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return (r==="x"?t:t&3|8).toString(16)})}var x=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,e,n={}){this.flow=t,this.handlers=new Map(Object.entries(e)),this.store=n.store??new S,this.components=n.components??{},this.options=n,n.signal&&n.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:e,terminal_states:n}=this.flow;if(!t?.start_step)throw new Error("Flow must have settings.start_step defined");if(!e||Object.keys(e).length===0)throw new Error("Flow must have at least one step defined");if(!n||Object.keys(n).length===0)throw new Error("Flow must have at least one terminal_state defined");if(!e[t.start_step]&&!n[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,o]of Object.entries(e)){for(let[i,a]of Object.entries(o.transitions))if(!e[a]&&!n[a])throw new Error(`Step "${s}" transition "${i}" points to unknown step "${a}"`);if(o.failure_transitions){for(let[i,a]of Object.entries(o.failure_transitions))if(!e[a]&&!n[a])throw new Error(`Step "${s}" failure_transition "${i}" points to unknown step "${a}"`)}}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e);}off(t,e){this.listeners.get(t)?.delete(e);}emit(t){let e=this.listeners.get(t.type);if(e)for(let n of e)try{n(t);}catch{}}sleep(t){return new Promise(e=>setTimeout(e,t))}async run(t){let e=tt(),n=$(this.flow,e);if(await this.store.saveRunState(e,n),t)for(let[s,o]of Object.entries(t))await this.store.setData(e,s,o);this.emit({type:"flow:start",runId:e,timestamp:n.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(e,n)}catch(s){let o=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:e,timestamp:Date.now(),data:{error:o.message}}),this.options.onError?.(o),n={...n,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(e,n),{runId:e,status:"failed",data:await this.store.getAllData(e),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt,error:o}}}async resume(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);if(e.status==="completed"||e.status==="failed")throw new Error(`Cannot resume a ${e.status} run`);let n={...e,status:"running",pausedAt:void 0,updatedAt:Date.now()};return await this.store.saveRunState(t,n),this.emit({type:"flow:resumed",runId:t,timestamp:Date.now(),data:{currentStep:n.currentStep}}),this.executeLoop(t,n)}async pause(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);let n={...e,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};await this.store.saveRunState(t,n),this.emit({type:"flow:paused",runId:t,timestamp:Date.now(),data:{currentStep:n.currentStep}});}async executeLoop(t,e){let n=this.flow.settings.max_total_steps??100,s=this.flow.settings.timeout_ms,o=e,i=0;for(;i<n;){if(this.aborted)return o={...o,status:"cancelled",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"cancelled",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};if(s&&Date.now()-o.startedAt>s)return o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"timeout",intent:"timeout",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};let a=o.currentStep,c=this.flow.terminal_states[a];if(c){o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o);let p=await this.store.getAllData(t),u={runId:t,status:"completed",intent:c.return_intent,data:E(c.return_artifacts,p),finalStep:a,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...u}}),this.options.onComplete?.(u),u}let d=b(this.flow,o,a);if(d.broken){o=d.newState,await this.store.saveRunState(t,o),i++;continue}o=d.newState;let f=await this.store.getAllData(t),l=j(this.flow,a,f),m={runId:t,stepName:a,components:this.components,store:this.store,signal:this.options.signal,emit:(p,u)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:p,payload:u}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:a,input:l}});let g;try{let p=this.handlers.get(a);if(!p)throw new Error(`No handler registered for step "${a}"`);g=await p(l,m);}catch(p){let u=p instanceof Error?p:new Error(String(p));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:a,error:u.message}}),g={result:"failure",data:{error:u.message}};}if(g.data)for(let[p,u]of Object.entries(g.data))await this.store.setData(t,p,u);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:a,result:g.result}}),this.options.onStep?.(a,g);let w=R(this.flow,o,a,g);if(o=w.newState,w.shouldRetry){await this.store.saveRunState(t,o);let p=this.flow.steps[a];if(p.retry?.delay_ms){let u=o.retryCounts[a]??0,h=p.retry.backoff_multiplier?p.retry.delay_ms*Math.pow(p.retry.backoff_multiplier,u-1):p.retry.delay_ms;await this.sleep(h);}i++;continue}await this.store.saveRunState(t,o),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:a,to:o.currentStep,result:g.result}}),this.options.onTransition?.(a,o.currentStep),i++;}return o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"max_iterations",intent:"max_iterations",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt}}};function H(r,t,e){return new x(r,t,e)}async function C(r){return (await import('yaml')).parse(r)}async function et(r){let t=await fetch(r);if(!t.ok)throw new Error(`Failed to load flow from ${r}: ${t.statusText}`);let e=t.headers.get("content-type")??"",n=await t.text();return e.includes("json")||r.endsWith(".json")?JSON.parse(n):C(n)}async function rt(r){let e=await(await import('fs/promises')).readFile(r,"utf-8");return r.endsWith(".json")?JSON.parse(e):C(e)}function M(r){let t=[];if(!r||typeof r!="object")return ["Flow must be an object"];let e=r;if(!e.settings||typeof e.settings!="object"?t.push('Flow must have a "settings" object'):typeof e.settings.start_step!="string"&&t.push("settings.start_step must be a string"),!e.steps||typeof e.steps!="object")t.push('Flow must have a "steps" object');else {let n=e.steps;for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object"){t.push(`Step "${s}" must be an object`);continue}let i=o;(!i.transitions||typeof i.transitions!="object")&&t.push(`Step "${s}" must have a "transitions" object`),i.failure_transitions!==void 0&&typeof i.failure_transitions!="object"&&t.push(`Step "${s}" failure_transitions must be an object when provided`);}}if(!e.terminal_states||typeof e.terminal_states!="object")t.push('Flow must have a "terminal_states" object');else {let n=e.terminal_states;for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object"){t.push(`Terminal state "${s}" must be an object`);continue}typeof o.return_intent!="string"&&t.push(`Terminal state "${s}" must have a "return_intent" string`);}}return t}async function D(r){let t;typeof r=="string"?r.startsWith("http://")||r.startsWith("https://")?t=await et(r):r.includes("{")?t=JSON.parse(r):t=await rt(r):t=r;let e=M(t);if(e.length>0)throw new Error(`Invalid step flow configuration:
|
|
1
|
+
import'ajv-formats';import {createRequire}from'module';import {fileURLToPath}from'url';import {dirname,resolve}from'path';import {existsSync}from'fs';function b(r,t,e,n){let s=r.steps[e];if(!s)throw new Error(`Step "${e}" not found in flow configuration`);if(n.result==="failure"&&s.retry){let a=t.retryCounts[e]??0;if(a<s.retry.max_attempts)return {newState:{...t,retryCounts:{...t.retryCounts,[e]:a+1},updatedAt:Date.now()},nextStep:e,isTerminal:false,isCircuitBroken:false,shouldRetry:true}}let o=s.failure_transitions?.[n.result]??s.transitions[n.result];if(!o)throw new Error(`No transition defined for result "${n.result}" in step "${e}"`);let i=!!r.terminal_states[o];return {newState:{...t,currentStep:o,stepHistory:[...t.stepHistory,e],retryCounts:{...t.retryCounts,[e]:0},updatedAt:Date.now()},nextStep:o,isTerminal:i,isCircuitBroken:false,shouldRetry:false}}function j(r,t,e){let n=r.steps[e];if(!n?.circuit_breaker)return {broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:(t.iterationCounts[e]??0)+1},updatedAt:Date.now()}};let s=t.iterationCounts[e]??0;return s>=n.circuit_breaker.max_iterations?{broken:true,redirectStep:n.circuit_breaker.on_open,newState:{...t,currentStep:n.circuit_breaker.on_open,updatedAt:Date.now()}}:{broken:false,newState:{...t,iterationCounts:{...t.iterationCounts,[e]:s+1},updatedAt:Date.now()}}}function F(r,t,e){let n=r.steps[t];if(!n)throw new Error(`Step "${t}" not found`);if(n.expects_data){let s={};for(let o of n.expects_data)s[o]=e[o];return s}return {...e}}function C(r,t){if(r===false||r===void 0)return {};if(typeof r=="string")return {[r]:t[r]};if(Array.isArray(r)){let e={};for(let n of r)e[n]=t[n];return e}return {}}function E(r,t){let e=Date.now();return {runId:t,flowId:r.id??"unnamed",currentStep:r.settings.start_step,status:"running",stepHistory:[],iterationCounts:{},retryCounts:{},startedAt:e,updatedAt:e}}var h=class{runs=new Map;data=new Map;async saveRunState(t,e){this.runs.set(t,{...e});}async loadRunState(t){let e=this.runs.get(t);return e?{...e}:null}async deleteRunState(t){this.runs.delete(t),this.data.delete(t);}async setData(t,e,n){this.data.has(t)||this.data.set(t,{});let s=this.data.get(t);s[e]=n;}async getData(t,e){return this.data.get(t)?.[e]}async getAllData(t){return {...this.data.get(t)??{}}}async clearData(t){this.data.delete(t);}async listRuns(){return Array.from(this.runs.keys())}clear(){this.runs.clear(),this.data.clear();}};function et(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return (r==="x"?t:t&3|8).toString(16)})}var k=class{flow;handlers;store;components;options;listeners=new Map;aborted=false;constructor(t,e,n={}){this.flow=t,this.handlers=new Map(Object.entries(e)),this.store=n.store??new h,this.components=n.components??{},this.options=n,n.signal&&n.signal.addEventListener("abort",()=>{this.aborted=true;}),this.validateFlow();}validateFlow(){let{settings:t,steps:e,terminal_states:n}=this.flow;if(!t?.start_step)throw new Error("Flow must have settings.start_step defined");if(!e||Object.keys(e).length===0)throw new Error("Flow must have at least one step defined");if(!n||Object.keys(n).length===0)throw new Error("Flow must have at least one terminal_state defined");if(!e[t.start_step]&&!n[t.start_step])throw new Error(`Start step "${t.start_step}" not found`);for(let[s,o]of Object.entries(e)){for(let[i,a]of Object.entries(o.transitions))if(!e[a]&&!n[a])throw new Error(`Step "${s}" transition "${i}" points to unknown step "${a}"`);if(o.failure_transitions){for(let[i,a]of Object.entries(o.failure_transitions))if(!e[a]&&!n[a])throw new Error(`Step "${s}" failure_transition "${i}" points to unknown step "${a}"`)}}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e);}off(t,e){this.listeners.get(t)?.delete(e);}emit(t){let e=this.listeners.get(t.type);if(e)for(let n of e)try{n(t);}catch{}}sleep(t){return new Promise(e=>setTimeout(e,t))}async run(t){let e=et(),n=E(this.flow,e);if(await this.store.saveRunState(e,n),t)for(let[s,o]of Object.entries(t))await this.store.setData(e,s,o);this.emit({type:"flow:start",runId:e,timestamp:n.startedAt,data:{initialData:t??{}}});try{return await this.executeLoop(e,n)}catch(s){let o=s instanceof Error?s:new Error(String(s));return this.emit({type:"flow:error",runId:e,timestamp:Date.now(),data:{error:o.message}}),this.options.onError?.(o),n={...n,status:"failed",updatedAt:Date.now()},await this.store.saveRunState(e,n),{runId:e,status:"failed",data:await this.store.getAllData(e),finalStep:n.currentStep,stepHistory:n.stepHistory,durationMs:Date.now()-n.startedAt,error:o}}}async resume(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);if(e.status==="completed"||e.status==="failed")throw new Error(`Cannot resume a ${e.status} run`);let n={...e,status:"running",pausedAt:void 0,updatedAt:Date.now()};return await this.store.saveRunState(t,n),this.emit({type:"flow:resumed",runId:t,timestamp:Date.now(),data:{currentStep:n.currentStep}}),this.executeLoop(t,n)}async pause(t){let e=await this.store.loadRunState(t);if(!e)throw new Error(`No run found with ID: ${t}`);let n={...e,status:"paused",pausedAt:Date.now(),updatedAt:Date.now()};await this.store.saveRunState(t,n),this.emit({type:"flow:paused",runId:t,timestamp:Date.now(),data:{currentStep:n.currentStep}});}async executeLoop(t,e){let n=this.flow.settings.max_total_steps??100,s=this.flow.settings.timeout_ms,o=e,i=0;for(;i<n;){if(this.aborted)return o={...o,status:"cancelled",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"cancelled",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};if(s&&Date.now()-o.startedAt>s)return o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"timeout",intent:"timeout",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};let a=o.currentStep,c=this.flow.terminal_states[a];if(c){o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o);let p=await this.store.getAllData(t),l={runId:t,status:"completed",intent:c.return_intent,data:C(c.return_artifacts,p),finalStep:a,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt};return this.emit({type:"flow:complete",runId:t,timestamp:Date.now(),data:{...l}}),this.options.onComplete?.(l),l}let d=j(this.flow,o,a);if(d.broken){o=d.newState,await this.store.saveRunState(t,o),i++;continue}o=d.newState;let f=await this.store.getAllData(t),u=F(this.flow,a,f),m={runId:t,stepName:a,components:this.components,store:this.store,signal:this.options.signal,emit:(p,l)=>{this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{event:p,payload:l}});}};this.emit({type:"step:start",runId:t,timestamp:Date.now(),data:{step:a,input:u}});let g;try{let p=this.handlers.get(a);if(!p)throw new Error(`No handler registered for step "${a}"`);g=await p(u,m);}catch(p){let l=p instanceof Error?p:new Error(String(p));this.emit({type:"step:error",runId:t,timestamp:Date.now(),data:{step:a,error:l.message}}),g={result:"failure",data:{error:l.message}};}if(g.data)for(let[p,l]of Object.entries(g.data))await this.store.setData(t,p,l);this.emit({type:"step:complete",runId:t,timestamp:Date.now(),data:{step:a,result:g.result}}),this.options.onStep?.(a,g);let w=b(this.flow,o,a,g);if(o=w.newState,w.shouldRetry){await this.store.saveRunState(t,o);let p=this.flow.steps[a];if(p.retry?.delay_ms){let l=o.retryCounts[a]??0,S=p.retry.backoff_multiplier?p.retry.delay_ms*Math.pow(p.retry.backoff_multiplier,l-1):p.retry.delay_ms;await this.sleep(S);}i++;continue}await this.store.saveRunState(t,o),this.emit({type:"transition",runId:t,timestamp:Date.now(),data:{from:a,to:o.currentStep,result:g.result}}),this.options.onTransition?.(a,o.currentStep),i++;}return o={...o,status:"completed",updatedAt:Date.now()},await this.store.saveRunState(t,o),{runId:t,status:"max_iterations",intent:"max_iterations",data:await this.store.getAllData(t),finalStep:o.currentStep,stepHistory:o.stepHistory,durationMs:Date.now()-o.startedAt}}};function v(r,t,e){return new k(r,t,e)}async function $(r){return (await import('yaml')).parse(r)}async function rt(r){let t=await fetch(r);if(!t.ok)throw new Error(`Failed to load flow from ${r}: ${t.statusText}`);let e=t.headers.get("content-type")??"",n=await t.text();return e.includes("json")||r.endsWith(".json")?JSON.parse(n):$(n)}async function nt(r){let e=await(await import('fs/promises')).readFile(r,"utf-8");return r.endsWith(".json")?JSON.parse(e):$(e)}function D(r){let t=[];if(!r||typeof r!="object")return ["Flow must be an object"];let e=r;if(!e.settings||typeof e.settings!="object"?t.push('Flow must have a "settings" object'):typeof e.settings.start_step!="string"&&t.push("settings.start_step must be a string"),!e.steps||typeof e.steps!="object")t.push('Flow must have a "steps" object');else {let n=e.steps;for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object"){t.push(`Step "${s}" must be an object`);continue}let i=o;(!i.transitions||typeof i.transitions!="object")&&t.push(`Step "${s}" must have a "transitions" object`),i.failure_transitions!==void 0&&typeof i.failure_transitions!="object"&&t.push(`Step "${s}" failure_transitions must be an object when provided`);}}if(!e.terminal_states||typeof e.terminal_states!="object")t.push('Flow must have a "terminal_states" object');else {let n=e.terminal_states;for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object"){t.push(`Terminal state "${s}" must be an object`);continue}typeof o.return_intent!="string"&&t.push(`Terminal state "${s}" must have a "return_intent" string`);}}return t}async function P(r){let t;typeof r=="string"?r.startsWith("http://")||r.startsWith("https://")?t=await rt(r):r.includes("{")?t=JSON.parse(r):t=await nt(r):t=r;let e=D(t);if(e.length>0)throw new Error(`Invalid step flow configuration:
|
|
2
2
|
- ${e.join(`
|
|
3
|
-
- `)}`);return t}function
|
|
4
|
-
export{
|
|
3
|
+
- `)}`);return t}function M(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function O(r){return atob(r.replace(/-/g,"+").replace(/_/g,"/"))}var A=class{constructor(t){this.kv=t;}kv;stateKey(t){return `state_${M(t)}`}dataPrefix(t){return `data_${M(t)}_`}dataKey(t,e){return `${this.dataPrefix(t)}${M(e)}`}async saveRunState(t,e){this.kv.write(this.stateKey(t),e);}async loadRunState(t){let e=this.kv.read(this.stateKey(t));return e!=null&&typeof e=="object"?e:null}async deleteRunState(t){this.kv.delete(this.stateKey(t));for(let e of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(e);}async setData(t,e,n){this.kv.write(this.dataKey(t,e),n);}async getData(t,e){return this.kv.read(this.dataKey(t,e))}async getAllData(t){let e=this.dataPrefix(t),n={};for(let s of this.kv.listKeys(e))n[O(s.slice(e.length))]=this.kv.read(s);return n}async clearData(t){for(let e of this.kv.listKeys(this.dataPrefix(t)))this.kv.delete(e);}async listRuns(){return this.kv.listKeys("state_").map(t=>O(t.slice(6)))}};var K=dirname(fileURLToPath(import.meta.url)),pt=createRequire(import.meta.url);function ut(){let r=resolve(K,"./jsonata-sync.cjs");return existsSync(r)?r:resolve(K,"../card-compute/jsonata-sync.cjs")}var R=pt(ut());function B(r,t){if(!r||typeof r!="object")throw new Error(`[step-machine-public] Step "${t}" returned a non-object result.`);let e=r,n=e.result??e.status;if(typeof n=="string"&&n.trim().length>0){let s=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?{...e.data}:{},o=typeof e.error=="string"?e.error:void 0;return o&&!("error"in s)&&(s.error=o),{result:n,data:s,...o?{error:o}:{}}}return {result:"success",data:{...e}}}function z(r,t){if(!t||t.length===0)return r;let e={};for(let n of t)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n]);return e}function _(r,t){return async(e,n)=>{let s=await r(e,n),o=B(s,n?.stepName??"unknown");return {result:o.result,data:z(o.data,t),...o.error?{error:o.error}:{}}}}function V(r,t,e){if(!t||t.length===0)return null;for(let n of t)try{if(!R(n).evaluate(r))return {result:"failure",data:{error:`[${e}] input validation failed: ${n}`}}}catch(s){let o=s instanceof Error?s.message:String(s);return {result:"failure",data:{error:`[${e}] input validation error on "${n}": ${o}`}}}return null}function T(r,t,e){return !t||t.length===0?r:async(n,s)=>{let o=V(n,t,e);return o||r(n,s)}}var N=dirname(fileURLToPath(import.meta.url)),gt=createRequire(import.meta.url);function mt(){let r=resolve(N,"./jsonata-sync.cjs");return existsSync(r)?r:resolve(N,"../../card-compute/jsonata-sync.cjs")}var x=gt(mt());function U(r,t,e){if(!r||typeof r!="object")return t;let n={output:t},s=t.result,o=t.data,i=t.error;if(typeof r.resultExpr=="string")try{let a=x(r.resultExpr).evaluate(n);if(typeof a!="string"||!a.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(a)})`);s=a;}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`[${e}] outputTransforms.resultExpr failed: ${c}`)}if(typeof r.dataTemplate=="string")try{let a=x(r.dataTemplate).evaluate(n);if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(a)})`);o=a;}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`[${e}] outputTransforms.dataTemplate failed: ${c}`)}if(typeof r.errorExpr=="string")try{let a=x(r.errorExpr).evaluate(n);i=a!=null?String(a):void 0;}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`[${e}] outputTransforms.errorExpr failed: ${c}`)}return i!==void 0?{result:s,data:o,error:i}:{result:s,data:o}}var ht="b64:";function wt(r){let t=new TextEncoder().encode(r),e=globalThis.Buffer,n;if(e)n=e.from(t).toString("base64");else if(typeof btoa=="function"){let s="";for(let o of t)s+=String.fromCharCode(o);n=btoa(s);}else throw new Error("No base64 encoder available in this runtime");return n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function W(r){return `${ht}${wt(JSON.stringify(r))}`}function q(r){return !!r&&typeof r=="object"&&r.type==="compute-jsonata"&&Array.isArray(r.expr)&&r.expr.length>0}function I(r){if(!r||typeof r!="object")return false;let t=r;if(t.type!=="ref"||typeof t.howToRun!="string")return false;if(typeof t.whatToRun=="string")return true;if(t.whatToRun&&typeof t.whatToRun=="object"){let e=t.whatToRun;return typeof e.kind=="string"&&typeof e.value=="string"}return false}function St(r){if(typeof r=="string"){let t=r.indexOf("=");if(t<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${r}"`);return {bindTo:r.slice(0,t).trim(),expr:r.slice(t+1).trim()}}if(r&&typeof r=="object"&&typeof r.bindTo=="string"&&typeof r.expr=="string")return r;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(r)}`)}function yt(r,t,e){let n=t.split("."),s=r;for(let o=0;o<n.length-1;o++){let i=n[o];(s[i]==null||typeof s[i]!="object")&&(s[i]={}),s=s[i];}s[n[n.length-1]]=e;}function Y(r,t,e){let n=r.expr.map(St);return async s=>{let o=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},i={},a={expects_data:o,data:i,...e?{config:e}:{}},c,d;for(let f of n)try{let u=R(f.expr).evaluate(a);if(f.bindTo==="result")c=u!=null?String(u):"success";else if(f.bindTo==="error")d=u!=null?String(u):void 0;else if(f.bindTo.startsWith("data."))yt(i,f.bindTo.slice(5),u);else return {result:"failure",data:{},error:`[${t}] invalid bindTo "${f.bindTo}": must be "result", "error", or start with "data."`}}catch(u){let m=u instanceof Error?u.message:String(u);return {result:"failure",data:{},error:`[${t}] compute "${f.bindTo}" failed: ${m}`}}return c===void 0?{result:"failure",data:{},error:`[${t}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:d?{result:c,data:i,error:d}:{result:c,data:i}}}function X(r,t,e,n){let{type:s,...o}=r,i={...o,whatToRun:typeof o.whatToRun=="object"?W(o.whatToRun):o.whatToRun};return async a=>{let c=a&&typeof a=="object"&&!Array.isArray(a)?{...a}:{};n&&(c.config=n);try{let d=await e(i,c);if(!r.outputTransforms)return d;try{return U(r.outputTransforms,d,t)}catch(f){let u=f instanceof Error?f.message:String(f);return {result:"failure",data:{},error:u}}}catch(d){let f=d instanceof Error?d.message:String(d);return {result:"failure",data:{error:`[step-machine-public] step "${t}" invoke threw: ${f}`}}}}}function G(){return async r=>({result:"success",data:r&&typeof r=="object"&&!Array.isArray(r)?r:{}})}function Rt(r,t,e){return async(n,s)=>{let o=n?.[t.items];if(!Array.isArray(o))return {result:"failure",data:{},error:`[${e}] forEach: "${t.items}" is not an array (got ${typeof o})`};let i=o,a=t.collectAs??`${t.items}_results`;if(i.length===0)return {result:"success",data:{[a]:[]}};let{[t.items]:c,...d}=n,f=Math.max(1,t.concurrency??1),u=new Array(i.length),m=0,g=0,w=0;return await new Promise(p=>{function l(){for(;m<f&&g<i.length;){let S=g++;m++;let Z={...d,[t.as]:i[S]};r(Z,s).then(y=>{u[S]=y;}).catch(y=>{let tt=y instanceof Error?y.message:String(y);u[S]={result:"failure",data:{},error:tt};}).finally(()=>{m--,u[S]?.result==="failure"&&w++,g>=i.length&&m===0?p():l();});}m===0&&g>=i.length&&p();}l();}),w>0?{result:"failure",data:{errors:u.filter(l=>l.result==="failure").map(l=>l.error)},error:`[${e}] forEach: ${w}/${i.length} items failed`}:{result:"success",data:{[a]:u.map(p=>p.data)}}}}function Q(r,t,e){let n=Array.isArray(t?.produces_data)?t?.produces_data:void 0,s=Array.isArray(t?.input_validations)?t?.input_validations:void 0,o=t?.config??void 0,i=t?.handler,a;return q(i)?a=Y(i,r,o):I(i)?a=X(i,r,e.invoke,o):a=G(),t?.forEach&&(a=Rt(a,t.forEach,r)),T(_(a,n),s,r)}function H(r,t){let e={};for(let[n,s]of Object.entries(r.steps??{}))e[n]=Q(n,s,t);return e}function kt(r){let t=r.storeFactory||(()=>new h);return {async run(e,n){try{let s=H(e,{invoke:r.invokeRef}),i=await v(e,s,{store:t()}).run(n);return i.status!=="completed"?{dispatched:!1,error:i.error?.message||i.status}:{dispatched:!0}}catch(s){return {dispatched:false,error:s instanceof Error?s.message:String(s)}}}}}
|
|
4
|
+
export{A as KVStorageStore,h as MemoryStore,H as buildStepHandlersForFlow,Y as createComputeJsonataHandler,G as createPassthroughHandler,X as createRefStepHandler,v as createStepMachine,kt as createStepMachineChatFlowRunner,z as filterProducedData,q as isComputeJsonataSpec,I as isRefSpec,R as jsonata,P as loadStepFlow,B as normalizeHandlerResult,Q as resolveStepHandler,V as runInputValidations,T as wrapWithInputValidations,_ as wrapWithOutputFiltering};//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
@@ -46,8 +46,8 @@ interface BlobStorage {
|
|
|
46
46
|
readBytes?(key: string): Uint8Array | null;
|
|
47
47
|
/** Optional binary write for file-like artifacts. */
|
|
48
48
|
writeBytes?(key: string, content: Uint8Array): void;
|
|
49
|
-
/**
|
|
50
|
-
listKeys
|
|
49
|
+
/** List all keys that start with the given prefix. */
|
|
50
|
+
listKeys(prefix?: string): string[];
|
|
51
51
|
/** Optional metadata lookup. */
|
|
52
52
|
stat?(key: string): BlobStat | null;
|
|
53
53
|
}
|
|
@@ -59,6 +59,28 @@ interface KindValueRef {
|
|
|
59
59
|
declare function serializeRef(ref: KindValueRef): string;
|
|
60
60
|
/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */
|
|
61
61
|
declare function parseRef(s: string): KindValueRef;
|
|
62
|
+
interface JournalEntry {
|
|
63
|
+
id: string;
|
|
64
|
+
payload: unknown;
|
|
65
|
+
}
|
|
66
|
+
interface JournalReadResult {
|
|
67
|
+
entries: JournalEntry[];
|
|
68
|
+
/** The id of the last entry returned, suitable for use as the next cursor. */
|
|
69
|
+
newCursor: string | null;
|
|
70
|
+
}
|
|
71
|
+
interface JournalStorage {
|
|
72
|
+
/** Append an entry. The storage layer assigns the id. */
|
|
73
|
+
append(payload: unknown): JournalEntry;
|
|
74
|
+
/** Read ALL entries (for index rebuilds, full replay). */
|
|
75
|
+
readAll(): JournalEntry[];
|
|
76
|
+
/**
|
|
77
|
+
* Read entries appended after the given cursor id.
|
|
78
|
+
* If cursor is null/empty, returns all entries from the beginning.
|
|
79
|
+
*/
|
|
80
|
+
readAfter(cursor: string | null): JournalReadResult;
|
|
81
|
+
/** Truncate all entries. Optional — not all backends support it. */
|
|
82
|
+
clear?(): void;
|
|
83
|
+
}
|
|
62
84
|
interface KVStorage {
|
|
63
85
|
/** Returns the stored value, or null if the key does not exist. */
|
|
64
86
|
read(key: string): unknown | null;
|
|
@@ -81,4 +103,4 @@ interface AtomicRelayLock {
|
|
|
81
103
|
tryAcquire(): (() => void) | null;
|
|
82
104
|
}
|
|
83
105
|
|
|
84
|
-
export { type AtomicRelayLock as A, type BlobStorage as B, type KVStorage as K, type KindValueRef as a, parseRef as p, serializeRef as s };
|
|
106
|
+
export { type AtomicRelayLock as A, type BlobStorage as B, type JournalStorage as J, type KVStorage as K, type KindValueRef as a, parseRef as p, serializeRef as s };
|
|
@@ -46,8 +46,8 @@ interface BlobStorage {
|
|
|
46
46
|
readBytes?(key: string): Uint8Array | null;
|
|
47
47
|
/** Optional binary write for file-like artifacts. */
|
|
48
48
|
writeBytes?(key: string, content: Uint8Array): void;
|
|
49
|
-
/**
|
|
50
|
-
listKeys
|
|
49
|
+
/** List all keys that start with the given prefix. */
|
|
50
|
+
listKeys(prefix?: string): string[];
|
|
51
51
|
/** Optional metadata lookup. */
|
|
52
52
|
stat?(key: string): BlobStat | null;
|
|
53
53
|
}
|
|
@@ -59,6 +59,28 @@ interface KindValueRef {
|
|
|
59
59
|
declare function serializeRef(ref: KindValueRef): string;
|
|
60
60
|
/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */
|
|
61
61
|
declare function parseRef(s: string): KindValueRef;
|
|
62
|
+
interface JournalEntry {
|
|
63
|
+
id: string;
|
|
64
|
+
payload: unknown;
|
|
65
|
+
}
|
|
66
|
+
interface JournalReadResult {
|
|
67
|
+
entries: JournalEntry[];
|
|
68
|
+
/** The id of the last entry returned, suitable for use as the next cursor. */
|
|
69
|
+
newCursor: string | null;
|
|
70
|
+
}
|
|
71
|
+
interface JournalStorage {
|
|
72
|
+
/** Append an entry. The storage layer assigns the id. */
|
|
73
|
+
append(payload: unknown): JournalEntry;
|
|
74
|
+
/** Read ALL entries (for index rebuilds, full replay). */
|
|
75
|
+
readAll(): JournalEntry[];
|
|
76
|
+
/**
|
|
77
|
+
* Read entries appended after the given cursor id.
|
|
78
|
+
* If cursor is null/empty, returns all entries from the beginning.
|
|
79
|
+
*/
|
|
80
|
+
readAfter(cursor: string | null): JournalReadResult;
|
|
81
|
+
/** Truncate all entries. Optional — not all backends support it. */
|
|
82
|
+
clear?(): void;
|
|
83
|
+
}
|
|
62
84
|
interface KVStorage {
|
|
63
85
|
/** Returns the stored value, or null if the key does not exist. */
|
|
64
86
|
read(key: string): unknown | null;
|
|
@@ -81,4 +103,4 @@ interface AtomicRelayLock {
|
|
|
81
103
|
tryAcquire(): (() => void) | null;
|
|
82
104
|
}
|
|
83
105
|
|
|
84
|
-
export { type AtomicRelayLock as A, type BlobStorage as B, type KVStorage as K, type KindValueRef as a, parseRef as p, serializeRef as s };
|
|
106
|
+
export { type AtomicRelayLock as A, type BlobStorage as B, type JournalStorage as J, type KVStorage as K, type KindValueRef as a, parseRef as p, serializeRef as s };
|
package/lib/stores/index.d.cts
CHANGED
package/lib/stores/index.d.ts
CHANGED
package/lib/stores/kv.d.cts
CHANGED
package/lib/stores/kv.d.ts
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
|
-
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-
|
|
1
|
+
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-BLXbcBNk.cjs';
|
|
2
2
|
import { ExecutionRef } from './execution-refs.cjs';
|
|
3
|
-
import { a as KindValueRef } from './storage-interface-
|
|
3
|
+
import { J as JournalStorage, K as KVStorage, a as KindValueRef } from './storage-interface-B6ecOulj.cjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* chat-storage-lib.ts
|
|
7
|
+
*
|
|
8
|
+
* ChatStorage interface + factories backed by JournalStorage (history) and
|
|
9
|
+
* KVStorage (processing state and config).
|
|
10
|
+
*
|
|
11
|
+
* Platform-free — no node:fs or node:crypto imports.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
interface ChatRecord {
|
|
15
|
+
/** Journal entry id — also used as SSE cursor. */
|
|
16
|
+
id: string;
|
|
17
|
+
role: string;
|
|
18
|
+
text: string;
|
|
19
|
+
files: unknown[];
|
|
20
|
+
updated_at: string;
|
|
21
|
+
}
|
|
22
|
+
interface ChatConfig {
|
|
23
|
+
systemPrompt?: string;
|
|
24
|
+
}
|
|
25
|
+
interface ChatReadAfterResult {
|
|
26
|
+
records: ChatRecord[];
|
|
27
|
+
/** Pass as cursor on the next call. Null when the journal is empty. */
|
|
28
|
+
cursor: string | null;
|
|
29
|
+
}
|
|
30
|
+
interface ChatStorage {
|
|
31
|
+
/** Append a message; returns the new entry id (usable as a cursor). */
|
|
32
|
+
append(cardId: string, role: string, text: string, files?: unknown[]): string;
|
|
33
|
+
/** Read all messages in insertion order. */
|
|
34
|
+
readAll(cardId: string): ChatRecord[];
|
|
35
|
+
/**
|
|
36
|
+
* Read messages appended after cursor.
|
|
37
|
+
* Pass null to read from the beginning.
|
|
38
|
+
*/
|
|
39
|
+
readAfter(cardId: string, cursor: string | null): ChatReadAfterResult;
|
|
40
|
+
/** Remove all messages for this card. */
|
|
41
|
+
clear(cardId: string): void;
|
|
42
|
+
setProcessing(cardId: string, active: boolean): void;
|
|
43
|
+
isProcessing(cardId: string): boolean;
|
|
44
|
+
getConfig(cardId: string): ChatConfig;
|
|
45
|
+
setConfig(cardId: string, patch: Partial<ChatConfig>): void;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Create a ChatStorage backed by:
|
|
49
|
+
* - journalFactory(cardId) → JournalStorage (one per-card journal for history)
|
|
50
|
+
* - kv → KVStorage (shared processing flags + config)
|
|
51
|
+
*/
|
|
52
|
+
declare function createChatStorage(journalFactory: (cardId: string) => JournalStorage, kv: KVStorage): ChatStorage;
|
|
53
|
+
declare function createInMemoryChatStorage(): ChatStorage;
|
|
4
54
|
|
|
5
55
|
/**
|
|
6
56
|
* server-runtime/types.ts
|
|
@@ -31,6 +81,23 @@ interface InvocationAdapter {
|
|
|
31
81
|
*/
|
|
32
82
|
describe?(ref: ExecutionRef): Promise<DescribeEnvelope | null>;
|
|
33
83
|
}
|
|
84
|
+
interface ChatHandlerFlowRunner {
|
|
85
|
+
/**
|
|
86
|
+
* Execute a stored chat-handler flow using host-defined step-machine bindings.
|
|
87
|
+
* The runtime stays platform-free and delegates actual execution to the host.
|
|
88
|
+
*/
|
|
89
|
+
run(flow: unknown, args: Record<string, unknown>, context: {
|
|
90
|
+
boardId: string;
|
|
91
|
+
cardId: string;
|
|
92
|
+
label: string;
|
|
93
|
+
logger: RuntimeLogger;
|
|
94
|
+
serverUrl?: string | null;
|
|
95
|
+
executionExtra?: Record<string, unknown>;
|
|
96
|
+
}): Promise<{
|
|
97
|
+
dispatched: boolean;
|
|
98
|
+
error?: string;
|
|
99
|
+
}>;
|
|
100
|
+
}
|
|
34
101
|
interface NotificationTransport {
|
|
35
102
|
/**
|
|
36
103
|
* Start listening for events on a notification endpoint identified by a kind-ref.
|
|
@@ -65,7 +132,9 @@ interface BoardContextConfig {
|
|
|
65
132
|
/** Notification endpoint ref — e.g. ::named-pipe::<path> or ::firestore-watch::<path> */
|
|
66
133
|
notifyRef?: KindValueRef;
|
|
67
134
|
taskExecutorRef?: ExecutionRef;
|
|
135
|
+
/** Internal fallback only; public board config now uses chatHandlerFlow. */
|
|
68
136
|
chatHandlerRef?: ExecutionRef;
|
|
137
|
+
chatHandlerFlow?: unknown;
|
|
69
138
|
inferenceAdapterRef?: ExecutionRef;
|
|
70
139
|
}
|
|
71
140
|
interface SingleBoardRuntimeOptions {
|
|
@@ -75,6 +144,9 @@ interface SingleBoardRuntimeOptions {
|
|
|
75
144
|
/** One or more board layers composing this board surface (e.g. base cards + admin cards). */
|
|
76
145
|
boards: BoardContextConfig[];
|
|
77
146
|
invocationAdapter: InvocationAdapter;
|
|
147
|
+
chatFlowRunner?: ChatHandlerFlowRunner;
|
|
148
|
+
/** Chat storage backend. Defaults to an in-memory store when omitted. */
|
|
149
|
+
chatStorage?: ChatStorage;
|
|
78
150
|
notificationTransport?: NotificationTransport;
|
|
79
151
|
logger?: RuntimeLogger;
|
|
80
152
|
serverUrl?: string;
|
|
@@ -145,4 +217,4 @@ interface RuntimeResponse {
|
|
|
145
217
|
end(data?: string | Buffer): void;
|
|
146
218
|
}
|
|
147
219
|
|
|
148
|
-
export type
|
|
220
|
+
export { type BoardContextConfig as B, type ChatHandlerFlowRunner as C, type DescribeEnvelope as D, type InvocationAdapter as I, type MultiBoardRuntimeOptions as M, type NotificationTransport as N, type RuntimeLogger as R, type SingleBoardRuntimeOptions as S, type MultiBoardRuntime as a, type SingleBoardRuntime as b, type ChatStorage as c, type RuntimeRequest as d, type RuntimeResponse as e, type ChatConfig as f, type ChatRecord as g, createChatStorage as h, createInMemoryChatStorage as i };
|
|
@@ -1,6 +1,56 @@
|
|
|
1
|
-
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-
|
|
1
|
+
import { d as BoardPlatformAdapter, a as CommandResult } from './board-live-cards-public-BZaNb2mi.js';
|
|
2
2
|
import { ExecutionRef } from './execution-refs.js';
|
|
3
|
-
import { a as KindValueRef } from './storage-interface-
|
|
3
|
+
import { J as JournalStorage, K as KVStorage, a as KindValueRef } from './storage-interface-B6ecOulj.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* chat-storage-lib.ts
|
|
7
|
+
*
|
|
8
|
+
* ChatStorage interface + factories backed by JournalStorage (history) and
|
|
9
|
+
* KVStorage (processing state and config).
|
|
10
|
+
*
|
|
11
|
+
* Platform-free — no node:fs or node:crypto imports.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
interface ChatRecord {
|
|
15
|
+
/** Journal entry id — also used as SSE cursor. */
|
|
16
|
+
id: string;
|
|
17
|
+
role: string;
|
|
18
|
+
text: string;
|
|
19
|
+
files: unknown[];
|
|
20
|
+
updated_at: string;
|
|
21
|
+
}
|
|
22
|
+
interface ChatConfig {
|
|
23
|
+
systemPrompt?: string;
|
|
24
|
+
}
|
|
25
|
+
interface ChatReadAfterResult {
|
|
26
|
+
records: ChatRecord[];
|
|
27
|
+
/** Pass as cursor on the next call. Null when the journal is empty. */
|
|
28
|
+
cursor: string | null;
|
|
29
|
+
}
|
|
30
|
+
interface ChatStorage {
|
|
31
|
+
/** Append a message; returns the new entry id (usable as a cursor). */
|
|
32
|
+
append(cardId: string, role: string, text: string, files?: unknown[]): string;
|
|
33
|
+
/** Read all messages in insertion order. */
|
|
34
|
+
readAll(cardId: string): ChatRecord[];
|
|
35
|
+
/**
|
|
36
|
+
* Read messages appended after cursor.
|
|
37
|
+
* Pass null to read from the beginning.
|
|
38
|
+
*/
|
|
39
|
+
readAfter(cardId: string, cursor: string | null): ChatReadAfterResult;
|
|
40
|
+
/** Remove all messages for this card. */
|
|
41
|
+
clear(cardId: string): void;
|
|
42
|
+
setProcessing(cardId: string, active: boolean): void;
|
|
43
|
+
isProcessing(cardId: string): boolean;
|
|
44
|
+
getConfig(cardId: string): ChatConfig;
|
|
45
|
+
setConfig(cardId: string, patch: Partial<ChatConfig>): void;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Create a ChatStorage backed by:
|
|
49
|
+
* - journalFactory(cardId) → JournalStorage (one per-card journal for history)
|
|
50
|
+
* - kv → KVStorage (shared processing flags + config)
|
|
51
|
+
*/
|
|
52
|
+
declare function createChatStorage(journalFactory: (cardId: string) => JournalStorage, kv: KVStorage): ChatStorage;
|
|
53
|
+
declare function createInMemoryChatStorage(): ChatStorage;
|
|
4
54
|
|
|
5
55
|
/**
|
|
6
56
|
* server-runtime/types.ts
|
|
@@ -31,6 +81,23 @@ interface InvocationAdapter {
|
|
|
31
81
|
*/
|
|
32
82
|
describe?(ref: ExecutionRef): Promise<DescribeEnvelope | null>;
|
|
33
83
|
}
|
|
84
|
+
interface ChatHandlerFlowRunner {
|
|
85
|
+
/**
|
|
86
|
+
* Execute a stored chat-handler flow using host-defined step-machine bindings.
|
|
87
|
+
* The runtime stays platform-free and delegates actual execution to the host.
|
|
88
|
+
*/
|
|
89
|
+
run(flow: unknown, args: Record<string, unknown>, context: {
|
|
90
|
+
boardId: string;
|
|
91
|
+
cardId: string;
|
|
92
|
+
label: string;
|
|
93
|
+
logger: RuntimeLogger;
|
|
94
|
+
serverUrl?: string | null;
|
|
95
|
+
executionExtra?: Record<string, unknown>;
|
|
96
|
+
}): Promise<{
|
|
97
|
+
dispatched: boolean;
|
|
98
|
+
error?: string;
|
|
99
|
+
}>;
|
|
100
|
+
}
|
|
34
101
|
interface NotificationTransport {
|
|
35
102
|
/**
|
|
36
103
|
* Start listening for events on a notification endpoint identified by a kind-ref.
|
|
@@ -65,7 +132,9 @@ interface BoardContextConfig {
|
|
|
65
132
|
/** Notification endpoint ref — e.g. ::named-pipe::<path> or ::firestore-watch::<path> */
|
|
66
133
|
notifyRef?: KindValueRef;
|
|
67
134
|
taskExecutorRef?: ExecutionRef;
|
|
135
|
+
/** Internal fallback only; public board config now uses chatHandlerFlow. */
|
|
68
136
|
chatHandlerRef?: ExecutionRef;
|
|
137
|
+
chatHandlerFlow?: unknown;
|
|
69
138
|
inferenceAdapterRef?: ExecutionRef;
|
|
70
139
|
}
|
|
71
140
|
interface SingleBoardRuntimeOptions {
|
|
@@ -75,6 +144,9 @@ interface SingleBoardRuntimeOptions {
|
|
|
75
144
|
/** One or more board layers composing this board surface (e.g. base cards + admin cards). */
|
|
76
145
|
boards: BoardContextConfig[];
|
|
77
146
|
invocationAdapter: InvocationAdapter;
|
|
147
|
+
chatFlowRunner?: ChatHandlerFlowRunner;
|
|
148
|
+
/** Chat storage backend. Defaults to an in-memory store when omitted. */
|
|
149
|
+
chatStorage?: ChatStorage;
|
|
78
150
|
notificationTransport?: NotificationTransport;
|
|
79
151
|
logger?: RuntimeLogger;
|
|
80
152
|
serverUrl?: string;
|
|
@@ -145,4 +217,4 @@ interface RuntimeResponse {
|
|
|
145
217
|
end(data?: string | Buffer): void;
|
|
146
218
|
}
|
|
147
219
|
|
|
148
|
-
export type
|
|
220
|
+
export { type BoardContextConfig as B, type ChatHandlerFlowRunner as C, type DescribeEnvelope as D, type InvocationAdapter as I, type MultiBoardRuntimeOptions as M, type NotificationTransport as N, type RuntimeLogger as R, type SingleBoardRuntimeOptions as S, type MultiBoardRuntime as a, type SingleBoardRuntime as b, type ChatStorage as c, type RuntimeRequest as d, type RuntimeResponse as e, type ChatConfig as f, type ChatRecord as g, createChatStorage as h, createInMemoryChatStorage as i };
|