@dudko.dev/agent 0.0.49 → 0.0.51
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/README.md +353 -26
- package/dist/cli.js +140 -129
- package/dist/index.cjs +115 -109
- package/dist/index.d.cts +354 -234
- package/dist/index.d.ts +354 -234
- package/dist/index.js +115 -109
- package/dist/pipeline-engine.cjs +17 -0
- package/dist/pipeline-engine.d.cts +226 -0
- package/dist/pipeline-engine.d.ts +226 -0
- package/dist/pipeline-engine.js +17 -0
- package/dist/subagent-worker.js +98 -92
- package/package.json +15 -5
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
'use strict';var be=Object.defineProperty;var o=(e,t)=>be(e,"name",{value:t,configurable:true});var C={maxNodeVisits:3,maxRuns:25,maxNodeVisitsCeiling:100,maxRunsCeiling:1e3,maxNodes:200,maxEdges:1e3,maxRoutes:20,maxPatternLength:500,maxPatternProgram:1e3,conditionInputChars:5e4},X=class extends Error{static{o(this,"PipelineValidationError");}errors;constructor(t){super(`Invalid pipeline: ${t.map(i=>i.message).join("; ")}`),this.name="PipelineValidationError",this.errors=t;}},Y=class extends Error{static{o(this,"PipelineNodeError");}nodeId;visit;constructor(t,i,n){let s=n instanceof Error?n.message:String(n);super(`Pipeline node "${t}" failed (visit ${i}): ${s}`,{cause:n}),this.name="PipelineNodeError",this.nodeId=t,this.visit=i;}},T=o(e=>e.codePointAt(0),"cp"),ae=[48,57],K=[48,57,65,90,95,95,97,122],ce=[9,13,32,32,160,160,5760,5760,8192,8202,8232,8233,8239,8239,8287,8287,12288,12288,65279,65279],Z=1114111,J=1e3,W=o((e,t)=>{for(let i=0;i<e.length;i+=2)if(t>=e[i]&&t<=e[i+1])return true;return false},"inRanges"),G=o(e=>{let t=[];for(let s=0;s<e.length;s+=2)t.push([e[s],e[s+1]]);t.sort((s,r)=>s[0]-r[0]);let i=[],n=0;for(let[s,r]of t)s>n&&i.push(n,s-1),n=Math.max(n,r+1);return n<=Z&&i.push(n,Z),i},"complement"),F=o(e=>e===10||e===13||e===8232||e===8233,"isLineEnd"),B=o(e=>e!==void 0&&W(K,e),"isWordChar"),ue=o(e=>e!==void 0&&/^[0-9a-fA-F]$/.test(String.fromCodePoint(e)),"isHex"),H=o(e=>e!==void 0&&e>=48&&e<=57,"isDigit"),xe=o(e=>{let t=Array.from(e,T),i=0,n=o((c=0)=>t[i+c],"peek"),s=o((c,l=0)=>t[i+l]===T(c),"is"),r=o(c=>{throw new Error(`${c} (at ${i})`)},"fail"),a=o(c=>{let l=0;for(let v=0;v<c;v++)ue(n())||r("a bad hexadecimal escape"),l=l*16+parseInt(String.fromCodePoint(t[i++]),16);return l},"hex"),u=o(c=>{let l=n();if(l===void 0)return r("a pattern cannot end with a backslash");i++;let v=String.fromCodePoint(l);switch(v){case "d":return {r:ae};case "D":return {r:G(ae)};case "w":return {r:K};case "W":return {r:G(K)};case "s":return {r:ce};case "S":return {r:G(ce)};case "b":return c?{c:8}:{k:"word"};case "B":return c?r("\\B is not allowed in a class"):{k:"not-word"};case "n":return {c:10};case "r":return {c:13};case "t":return {c:9};case "f":return {c:12};case "v":return {c:11};case "0":return H(n())?r("octal escapes are not supported"):{c:0};case "x":return {c:a(2)};case "u":{if(!s("{"))return {c:a(4)};i++;let x=0,k=0;for(;ue(n());)x=x*16+parseInt(String.fromCodePoint(t[i++]),16),k++,x>Z&&r("a code point out of range");return (!k||!s("}"))&&r("a bad \\u{...} escape"),i++,{c:x}}case "k":return r("backreferences are not supported");case "p":case "P":return r("\\p{...} is not supported");case "c":return r("\\c control escapes are not supported");default:return H(l)?r("backreferences are not supported"):/^[a-zA-Z]$/.test(v)?r(`unknown escape \\${v}`):{c:l}}},"escape"),h=o(()=>{let c=s("^");c&&i++;let l=[];for(;;){let v=n();if(v===void 0)return r("an unterminated class");if(s("]")){i++;break}i++;let x;if(v===T("\\")){let k=u(true);if("r"in k){l.push(...k.r);continue}x=k.c;}else x=v;if(s("-")&&n(1)!==void 0&&!s("]",1)){i++;let k=t[i++];if(k===T("\\")){let m=u(true);if(!("c"in m))return r("a bad range in a class");k=m.c;}k<x&&r("a range out of order in a class"),l.push(x,k);}else l.push(x,x);}return {t:"set",r:l,neg:c}},"klass"),f=o(()=>{let c=i+1,l=o(()=>{let k=c;for(;H(t[c]);)c++;return c>k?Number(String.fromCodePoint(...t.slice(k,c))):void 0},"number"),v=l();if(v===void 0)return;let x=v;if(t[c]===T(",")&&(c++,x=l()??1/0),t[c]===T("}"))return i=c+1,x<v&&r("a quantifier out of order"),(v>J||x!==1/0&&x>J)&&r(`a repeat count above ${J}`),{min:v,max:x}},"braces"),b=o(()=>{let c=t[i++];switch(String.fromCodePoint(c)){case "(":{if(s("?"))if(s(":",1))i+=2;else if(s("<",1)&&!s("=",2)&&!s("!",2)){for(;n()!==void 0&&!s(">");)i++;n()===void 0&&r("an unterminated group name"),i++;}else r("lookaround is not supported");let l=O();return s(")")||r("an unterminated group"),i++,l}case "[":return h();case ".":return {t:"any"};case "^":return {t:"assert",k:"start"};case "$":return {t:"assert",k:"end"};case "\\":{let l=u(false);return "k"in l?{t:"assert",k:l.k}:"r"in l?{t:"set",r:l.r,neg:false}:{t:"char",c:l.c}}case "*":case "+":case "?":return r("nothing to repeat");case "{":return i--,f()&&r("nothing to repeat"),i++,{t:"char",c};default:return {t:"char",c}}},"atom"),R=o(()=>{let c=b();for(;;){let l;if(s("*")?l={min:0,max:1/0}:s("+")?l={min:1,max:1/0}:s("?")&&(l={min:0,max:1}),l?i++:s("{")&&(l=f()),!l)return c;c.t==="assert"&&r("nothing to repeat"),s("?")&&i++,c={t:"rep",item:c,min:l.min,max:l.max};}},"repetition"),S=o(()=>{let c=[];for(;n()!==void 0&&!s("|")&&!s(")");)c.push(R());return c.length===1?c[0]:{t:"cat",items:c}},"sequence");function O(){let c=[S()];for(;s("|");)i++,c.push(S());return c.length===1?c[0]:{t:"alt",items:c}}o(O,"alternation");let j=O();return i<t.length&&r("an unmatched )"),j},"parsePattern"),we=o(e=>{let t=[],i=o(s=>{if(t.length>=C.maxPatternProgram)throw new Error(`the pattern is too complex (more than ${C.maxPatternProgram} steps once its repeats are unrolled)`);return t.push(s),t.length-1},"push"),n=o(s=>{switch(s.t){case "char":i({op:"char",c:s.c});return;case "any":i({op:"any"});return;case "set":i({op:"set",r:s.r,neg:s.neg});return;case "assert":i({op:"assert",k:s.k});return;case "cat":for(let r of s.items)n(r);return;case "alt":{let r=[];s.items.forEach((a,u)=>{if(u===s.items.length-1){n(a);return}let h={op:"split",x:0,y:0};h.x=i(h)+1,n(a);let f={op:"jmp",x:0};i(f),r.push(f),h.y=t.length;});for(let a of r)a.x=t.length;return}case "rep":{for(let a=0;a<s.min;a++)n(s.item);if(s.max===1/0){let a={op:"split",x:0,y:0},u=i(a);a.x=u+1,n(s.item),i({op:"jmp",x:u}),a.y=t.length;return}let r=[];for(let a=s.min;a<s.max;a++){let u={op:"split",x:0,y:0};u.x=i(u)+1,r.push(u),n(s.item);}for(let a of r)a.y=t.length;return}}},"emit");return n(e),i({op:"match"}),t},"compileAst"),de="imsu",Q=o((e,t="")=>{if(typeof e!="string"||e.length===0)throw new Error("the pattern is empty");if(e.length>C.maxPatternLength)throw new Error(`the pattern is longer than ${C.maxPatternLength} characters`);if(typeof t!="string")throw new Error("flags must be a string");for(let f of t)if(!de.includes(f))throw new Error(`flag "${f}" is not allowed (allowed: ${de})`);if(new Set(t).size!==t.length)throw new Error("a flag is repeated");try{new RegExp(e,t);}catch(f){throw new Error(f instanceof Error?f.message:String(f))}let i=we(xe(e)),n=t.includes("i"),s=t.includes("m"),r=t.includes("s"),a=o((f,b)=>b.length===String.fromCodePoint(T(b)).length?T(b):f,"single"),u=o(f=>a(f,String.fromCodePoint(f).toLowerCase()),"lower"),h=o(f=>a(f,String.fromCodePoint(f).toUpperCase()),"upper");return f=>{let b=Array.from(f.slice(0,C.conditionInputChars),T),R=b.length,S=new Int32Array(i.length),O=0,j=false,c=[],l=o((m,d)=>{switch(m){case "start":return d===0||s&&F(b[d-1]);case "end":return d===R||s&&F(b[d]);case "word":return B(b[d-1])!==B(b[d]);case "not-word":return B(b[d-1])===B(b[d])}},"holds"),v=o((m,d,g)=>{for(c.push(d);c.length;){let E=c.pop();if(S[E]===O)continue;S[E]=O;let y=i[E];switch(y.op){case "jmp":c.push(y.x);break;case "split":c.push(y.y,y.x);break;case "assert":l(y.k,g)&&c.push(E+1);break;case "match":j=true;break;default:m.push(E);}}},"add"),x=[],k=[];O++,v(x,0,0);for(let m=0;m<R&&!j;m++){let d=b[m],g=n?u(d):d,E=n?h(d):d;O++;for(let y of x){let N=i[y],p=false;N.op==="char"?p=N.c===d||n&&(N.c===g||N.c===E||u(N.c)===g):N.op==="any"?p=r||!F(d):N.op==="set"&&(p=(W(N.r,d)||n&&(W(N.r,g)||W(N.r,E)))!==N.neg),p&&v(k,y+1,m+1);}v(k,0,m+1),x=k,k=[];}return j}},"compileMatcher"),ye=["always","contains","matches","route","otherwise"],Pe=o((e,t,i)=>{if(!e||e.kind==="always")return true;switch(e.kind){case "contains":{let n=t.text.slice(0,C.conditionInputChars);return e.caseSensitive?n.includes(e.text):n.toLowerCase().includes(e.text.toLowerCase())}case "matches":return (i??Q(e.pattern,e.flags))(t.text);case "route":return t.route!==void 0&&t.route===e.label;default:return false}},"testPipelineCondition"),V=o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isRecord"),M=o(e=>typeof e=="string"&&e.trim().length>0,"isId"),ge=o((e,t)=>V(e)&&M(e.id)?e.id:`e${t}`,"edgeIdOf"),ve=o((e,t)=>({edgeId:ge(e,t),edgeIndex:t}),"edgeRef"),ke=o(e=>{let t=JSON.parse(JSON.stringify(e));return V(t)&&Array.isArray(t.edges)&&t.edges.forEach((i,n)=>{V(i)&&(i.id=ge(i,n));}),t},"normalizePipeline"),le=o((e,t)=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=t,"inRange"),Ee=o(e=>{let t=[],i=[],n=o((m,d,g={})=>{t.push({code:m,message:d,...g});},"error"),s=o(()=>({ok:t.length===0,errors:t,warnings:i}),"done"),r=e;if(!V(r))return n("definition","a pipeline definition must be an object"),s();r.version!==1&&n("version",`unsupported pipeline version ${JSON.stringify(r.version)} (expected 1)`);let a=Array.isArray(r.nodes)?r.nodes:void 0,u=Array.isArray(r.edges)?r.edges:void 0;(!a||a.length===0)&&n("nodes","a pipeline needs at least one node"),u||n("edges","`edges` must be an array"),a&&a.length>C.maxNodes&&n("nodes",`more than ${C.maxNodes} nodes`),u&&u.length>C.maxEdges&&n("edges",`more than ${C.maxEdges} edges`);let h=new Set,f=new Map;for(let[m,d]of (a??[]).entries()){if(!V(d)||!M(d.id)){n("node.id",`node #${m+1} has no id`);continue}let g=d.id;if(h.has(g)){n("node.duplicate",`duplicate node id "${g}"`,{nodeId:g});continue}h.add(g),d.join!==void 0&&d.join!=="all"&&d.join!=="any"&&n("node.join",`node "${g}": join must be "all" or "any"`,{nodeId:g});let E=[];if(d.routes!==void 0)if(!Array.isArray(d.routes)||d.routes.length>C.maxRoutes)n("node.routes",`node "${g}": routes must be a list of at most ${C.maxRoutes}`,{nodeId:g});else for(let y of d.routes)!V(y)||!M(y.label)?n("node.routes",`node "${g}": a route has no label`,{nodeId:g}):E.includes(y.label)?n("node.routes",`node "${g}": duplicate route "${y.label}"`,{nodeId:g}):E.push(y.label);f.set(g,E);}M(r.entry)?h.has(r.entry)||n("entry",`the entry node "${r.entry}" does not exist`):n("entry","the pipeline has no entry node");let b=new Map,R=new Set,S=new Set,O=new Set;for(let[m,d]of (u??[]).entries()){let g=ve(d,m),E=`edge "${g.edgeId}"`;if(!V(d)){n("edge",`${E} is not an object`,g);continue}d.id!==void 0&&!M(d.id)&&n("edge.id",`${E} has an empty id`,g),R.has(g.edgeId)&&n("edge.duplicate",`duplicate edge id "${g.edgeId}"`,g),R.add(g.edgeId);let y=d.from,N=d.to,p=M(y)&&h.has(y),I=M(N)&&h.has(N);p||n("edge.from",`${E} starts at an unknown node ${JSON.stringify(y)}`,g),I||n("edge.to",`${E} leads to an unknown node ${JSON.stringify(N)}`,g),p&&I&&b.set(y,[...b.get(y)??[],N]);let w=d.when;if(w!==void 0){if(!V(w)||!ye.includes(w.kind)){n("edge.when",`${E} has an unknown condition`,g);continue}switch(w.kind){case "contains":(typeof w.text!="string"||w.text.length===0)&&n("edge.when",`${E}: "contains" needs a text`,g);break;case "matches":try{Q(w.pattern,w.flags??"");}catch(P){n("edge.pattern",`${E}: ${P.message}`,g);}break;case "route":p&&O.add(y),M(w.label)?p&&!(f.get(y)??[]).includes(w.label)&&n("edge.route",`${E}: node "${y}" has no route "${w.label}"`,p?{...g,nodeId:y}:g):n("edge.route",`${E}: "route" needs a label`,g);break;case "otherwise":p&&(S.has(y)&&n("edge.otherwise",`node "${y}" has more than one "otherwise" edge`,{...g,nodeId:y}),S.add(y));break}}}if(r.limits!==void 0)if(!V(r.limits))n("limits","`limits` must be an object");else {let{maxNodeVisits:m,maxRuns:d}=r.limits;m!==void 0&&!le(m,C.maxNodeVisitsCeiling)&&n("limits",`limits.maxNodeVisits must be a whole number from 1 to ${C.maxNodeVisitsCeiling}`),d!==void 0&&!le(d,C.maxRunsCeiling)&&n("limits",`limits.maxRuns must be a whole number from 1 to ${C.maxRunsCeiling}`);}if(t.length>0||!M(r.entry))return s();let j=new Set([r.entry]),c=[r.entry];for(;c.length;)for(let m of b.get(c.pop())??[])j.has(m)||(j.add(m),c.push(m));for(let m of h)j.has(m)||i.push({code:"unreachable",message:`node "${m}" cannot be reached from the entry node`,nodeId:m}),(f.get(m)??[]).length>0&&!O.has(m)&&i.push({code:"routes.unused",message:`node "${m}" has routes but no edge with a "route" condition`,nodeId:m});let l=new Map,v=[],x=o(m=>{l.set(m,"open"),v.push(m);for(let d of b.get(m)??[]){if(l.get(d)==="open")return [...v.slice(v.indexOf(d)),d];if(!l.has(d)){let g=x(d);if(g)return g}}v.pop(),l.set(m,"closed");},"findCycle"),k=x(r.entry);return k&&i.push({code:"cycle",message:`the pipeline has a loop (${k.join(" \u2192 ")}); limits.maxNodeVisits and limits.maxRuns bound it`,nodeId:k[0]}),s()},"validatePipeline"),ee=o(e=>e.name||e.nodeId,"titleOf"),Re=o(e=>{if(e.from.length===0&&e.visit<=1)return e.request;let t=[`Request:
|
|
2
|
+
${e.request}`];for(let i of e.from)t.push(`Output of "${ee(i)}":
|
|
3
|
+
${i.text}`);return e.visit>1&&t.push(`(This is visit ${e.visit} of this step.)`),t.join(`
|
|
4
|
+
|
|
5
|
+
`)},"renderPipelineNodeInput"),Se="You are the Router of one step in a pipeline of agents. The step has answered. Pick the ONE route label that fits its answer, from the list you are given. Answer with a label exactly as it is written in the list, and nothing else.",pe=2e3,fe=6e3,Ce=o((e,t)=>{let i=(e.routes??[]).map(s=>`- ${s.label}${s.description?`: ${s.description}`:""}`).join(`
|
|
6
|
+
`),n=t.length>pe+fe?`${t.slice(0,pe)}
|
|
7
|
+
[...]
|
|
8
|
+
${t.slice(-fe)}`:t;return [`Step: ${ee({nodeId:e.id,name:e.name})}`,e.instructions?`Its role:
|
|
9
|
+
${e.instructions}`:"",`Routes:
|
|
10
|
+
${i}`,`The step's answer:
|
|
11
|
+
${n}`,"Which route? Answer with one label from the list."].filter(Boolean).join(`
|
|
12
|
+
|
|
13
|
+
`)},"renderPipelineRoutePrompt"),Oe=o((e,t)=>{let i=(e.routes??[]).map(r=>r.label),n=t;if(typeof n=="string"){let r=n.trim();if(r.startsWith("{"))try{n=JSON.parse(r);}catch{n=r;}else n=r;}if(V(n)&&(n=n.route),typeof n!="string")return;let s=n.trim().replace(/^["'`]+|["'`.]+$/g,"").toLowerCase();return i.find(r=>r.toLowerCase()===s)},"matchPipelineRoute"),je=o(e=>{let{errors:t}=Ee(e);if(t.length>0)throw new X(t);let i=ke(e),n=new Map(i.nodes.map(u=>[u.id,u])),s=new Map(i.nodes.map(u=>[u.id,[]]));for(let u of i.edges){let h={edge:u};u.when?.kind==="matches"&&(h.matcher=Q(u.when.pattern,u.when.flags)),s.get(u.from)?.push(h);}let r=new Map,a=o(u=>{let h=r.get(u);if(!h){h=new Set;let f=[u];for(;f.length;)for(let{edge:b}of s.get(f.pop())??[])h.has(b.to)||(h.add(b.to),f.push(b.to));r.set(u,h);}return h},"descendants");return {definition:i,nodes:n,outgoing:s,maxNodeVisits:i.limits?.maxNodeVisits??C.maxNodeVisits,maxRuns:i.limits?.maxRuns??C.maxRuns,reaches:o((u,h)=>a(u).has(h),"reaches")}},"preparePipeline"),Ae=o(e=>{let t=e.definition.entry,i=[t],n=new Map([[t,[]]]);for(let a=0;a<i.length;a++)for(let{edge:u}of e.outgoing.get(i[a])??[])n.has(u.to)||(n.set(u.to,[]),i.push(u.to)),n.get(u.to).push(i[a]);let s=new Map;for(let a of i)s.set(a,new Set(a===t?[t]:i));for(let a=true;a;){a=false;for(let u of i){if(u===t)continue;let[h,...f]=n.get(u).map(R=>s.get(R)),b=new Set([u]);for(let R of h)f.every(S=>S.has(R))&&b.add(R);b.size<s.get(u).size&&(s.set(u,b),a=true);}}let r=new Map;return (a,u)=>{let h=r.get(a);if(!h){let f=new Set,b=[a];for(;b.length;){let R=b.pop();for(let{edge:S}of e.outgoing.get(R)??[])s.get(R)?.has(S.to)||f.has(S.to)||(f.add(S.to),b.push(S.to));}r.set(a,h=f);}return h.has(u)}},"passReach"),me=o(()=>{if(typeof DOMException=="function")return new DOMException("Aborted","AbortError");let e=new Error("Aborted");return e.name="AbortError",e},"abortError"),Ie=o(()=>{if(typeof AbortController=="function"){let n=new AbortController;return {signal:n.signal,abort:o(()=>n.abort(),"abort")}}let e=[],t={aborted:false,reason:void 0,onabort:null,addEventListener(n,s){n==="abort"&&s&&!e.includes(s)&&e.push(s);},removeEventListener(n,s){let r=s?e.indexOf(s):-1;n==="abort"&&r>=0&&e.splice(r,1);},throwIfAborted(){if(t.aborted)throw t.reason}};return {signal:t,abort:o(()=>{if(t.aborted)return;t.aborted=true,t.reason=me();let n={type:"abort",target:t},s=o((r,a)=>{try{r.call(a,n);}catch{}},"call");for(let r of e.splice(0))typeof r=="function"?s(r,t):s(r.handleEvent,r);typeof t.onabort=="function"&&s(t.onabort,t);},"abort")}},"createStopper"),$e=o((e,t)=>{if(!t)return;let i=e;for(let[n,s]of Object.entries(t))typeof s=="number"&&Number.isFinite(s)&&(i[n]=(i[n]??0)+s);},"addUsage"),Ve=o(async(e,t,i)=>{let{definition:n}=e,s=i.onAbort??"reject",r=Ie(),a,u=o(()=>{},"halt"),h=new Promise((p,I)=>{u=I;});h.catch(()=>{});let f=o(p=>{try{i.onEvent?.(p);}catch{}},"emit"),b=new Map,R={inputTokens:0,outputTokens:0,totalTokens:0},S={},O=[],j=[],c=new Set,l=0,v=0,x=new Map([[n.entry,[]]]),k=o(p=>{let I=Math.max(-1,...j.map($=>$.wave)),w=j.filter($=>$.wave===I);return {text:w.length===1?w[0].text:w.map($=>`## ${ee($)}
|
|
14
|
+
|
|
15
|
+
${$.text}`).join(`
|
|
16
|
+
|
|
17
|
+
`),outputs:S,trace:O,usage:R,...p?{stoppedBy:p}:{},runs:l}},"result"),m=o(()=>{a||(a="aborted",r.abort(),u(me()));},"onOuterAbort"),d=o(async(p,I)=>{let w=e.nodes.get(p),P=(b.get(p)??0)+1;b.set(p,P),l++;let $=I.map(A=>A.source.nodeId);f({type:"pipeline.node.started",nodeId:p,visit:P,from:$});let L;try{L=await t(w,{request:i.input,from:I.map(A=>({...A.source})),visit:P},{signal:r.signal,pipeline:n,emit:o(A=>{a||f({...A,nodeId:p,visit:P});},"emit")});}catch(A){if(a)return;a="failed";let U=new Y(p,P,A);f({type:"pipeline.node.failed",nodeId:p,visit:P,error:A instanceof Error?A.message:String(A)}),r.abort(),u(U);return}if(a)return;let D=typeof L?.text=="string"?L.text:"",_=(w.routes??[]).some(A=>A.label===L?.route)?L.route:void 0;$e(R,L?.usage);let ne={..._!==void 0?{route:_}:{},...L?.usage?{usage:L.usage}:{}};(S[p]??=[]).push({visit:P,text:D,..._!==void 0?{route:_}:{}}),O.push({type:"node",nodeId:p,visit:P,wave:v,from:$,text:D,...ne}),f({type:"pipeline.node.finished",nodeId:p,visit:P,text:D,...ne});let te=e.outgoing.get(p)??[],ie=te.map(({edge:A,matcher:U})=>Pe(A.when,{text:D,route:_},U)),he=ie.some(Boolean),q={nodeId:p,name:w.name,text:D,wave:v,live:0},z=new Set;te.forEach(({edge:A},U)=>{let se=A.when?.kind==="otherwise"?!he:ie[U],re={from:p,to:A.to,edgeId:A.id,visit:P,fired:se};if(O.push({type:"edge",...re}),f({type:"pipeline.edge",...re}),!se||z.has(A.to))return;z.add(A.to);let oe=x.get(A.to)??[];oe.push({source:{nodeId:p,...w.name?{name:w.name}:{},text:D},record:q}),x.set(A.to,oe);}),q.live=z.size,q.live===0&&j.push(q);},"visit"),g=o((p,I,w)=>{c.add(w);let P=I.map($=>$.source.nodeId);O.push({type:"dropped",nodeId:p,from:P,reason:w}),f({type:"pipeline.node.skipped",nodeId:p,from:P,reason:w});for(let{record:$}of I)$.live--,$.live===0&&j.push($);},"drop"),E=o((p,I,w=e.reaches)=>(e.nodes.get(p)?.join??"all")==="all"&&I.some(P=>P!==p&&w(P,p)),"deferred"),y;f({type:"pipeline.started",...n.name?{pipeline:n.name}:{}}),i.signal?.addEventListener("abort",m,{once:true});try{for(i.signal?.aborted&&m();x.size>0&&!a;){let p=[...x.keys()],I=p.filter(P=>!E(P,p));if(I.length===0){let P=y??=Ae(e);I=p.filter($=>!E($,p,P));}I.length===0&&(I=p);let w=[];for(let P of I){let $=x.get(P);x.delete(P),(b.get(P)??0)>=e.maxNodeVisits?g(P,$,"maxNodeVisits"):l>=e.maxRuns?g(P,$,"maxRuns"):w.push(d(P,$));}w.length!==0&&(await Promise.race([Promise.all(w),h]),v++);}a&&await h;}catch(p){if(a!=="aborted"||(f({type:"pipeline.finished",stoppedBy:"aborted",runs:l}),s==="reject"))throw p;return k("aborted")}finally{i.signal?.removeEventListener("abort",m);}let N=c.has("maxRuns")?"maxRuns":c.has("maxNodeVisits")?"maxNodeVisits":void 0;return f({type:"pipeline.finished",...N?{stoppedBy:N}:{},runs:l}),k(N)},"runPipelineGraph");exports.PIPELINE_LIMITS=C;exports.PIPELINE_ROUTER_SYSTEM=Se;exports.PipelineNodeError=Y;exports.PipelineValidationError=X;exports.matchPipelineRoute=Oe;exports.normalizePipeline=ke;exports.preparePipeline=je;exports.renderPipelineNodeInput=Re;exports.renderPipelineRoutePrompt=Ce;exports.runPipelineGraph=Ve;exports.testPipelineCondition=Pe;exports.validatePipeline=Ee;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
interface PipelineDefinition {
|
|
2
|
+
version: 1;
|
|
3
|
+
name?: string;
|
|
4
|
+
entry: string;
|
|
5
|
+
nodes: PipelineNode[];
|
|
6
|
+
edges: PipelineEdge[];
|
|
7
|
+
limits?: {
|
|
8
|
+
maxNodeVisits?: number;
|
|
9
|
+
maxRuns?: number;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
interface PipelineNode {
|
|
13
|
+
id: string;
|
|
14
|
+
name?: string;
|
|
15
|
+
instructions?: string;
|
|
16
|
+
model?: string;
|
|
17
|
+
skills?: string[];
|
|
18
|
+
tools?: string[];
|
|
19
|
+
mcpServers?: string[];
|
|
20
|
+
routes?: PipelineRoute[];
|
|
21
|
+
join?: 'all' | 'any';
|
|
22
|
+
settings?: Record<string, unknown>;
|
|
23
|
+
position?: {
|
|
24
|
+
x: number;
|
|
25
|
+
y: number;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
interface PipelineRoute {
|
|
29
|
+
label: string;
|
|
30
|
+
description?: string;
|
|
31
|
+
}
|
|
32
|
+
type PipelineCondition = {
|
|
33
|
+
kind: 'always';
|
|
34
|
+
} | {
|
|
35
|
+
kind: 'contains';
|
|
36
|
+
text: string;
|
|
37
|
+
caseSensitive?: boolean;
|
|
38
|
+
} | {
|
|
39
|
+
kind: 'matches';
|
|
40
|
+
pattern: string;
|
|
41
|
+
flags?: string;
|
|
42
|
+
} | {
|
|
43
|
+
kind: 'route';
|
|
44
|
+
label: string;
|
|
45
|
+
} | {
|
|
46
|
+
kind: 'otherwise';
|
|
47
|
+
};
|
|
48
|
+
interface PipelineEdge {
|
|
49
|
+
id?: string;
|
|
50
|
+
from: string;
|
|
51
|
+
to: string;
|
|
52
|
+
when?: PipelineCondition;
|
|
53
|
+
}
|
|
54
|
+
declare const PIPELINE_LIMITS: {
|
|
55
|
+
readonly maxNodeVisits: 3;
|
|
56
|
+
readonly maxRuns: 25;
|
|
57
|
+
readonly maxNodeVisitsCeiling: 100;
|
|
58
|
+
readonly maxRunsCeiling: 1000;
|
|
59
|
+
readonly maxNodes: 200;
|
|
60
|
+
readonly maxEdges: 1000;
|
|
61
|
+
readonly maxRoutes: 20;
|
|
62
|
+
readonly maxPatternLength: 500;
|
|
63
|
+
readonly maxPatternProgram: 1000;
|
|
64
|
+
readonly conditionInputChars: 50000;
|
|
65
|
+
};
|
|
66
|
+
interface PipelineUsage {
|
|
67
|
+
inputTokens: number;
|
|
68
|
+
outputTokens: number;
|
|
69
|
+
totalTokens: number;
|
|
70
|
+
reasoningTokens?: number;
|
|
71
|
+
cachedInputTokens?: number;
|
|
72
|
+
cacheWriteTokens?: number;
|
|
73
|
+
}
|
|
74
|
+
interface PipelineNodeSource {
|
|
75
|
+
nodeId: string;
|
|
76
|
+
name?: string;
|
|
77
|
+
text: string;
|
|
78
|
+
}
|
|
79
|
+
interface PipelineNodeInput {
|
|
80
|
+
request: string;
|
|
81
|
+
from: PipelineNodeSource[];
|
|
82
|
+
visit: number;
|
|
83
|
+
}
|
|
84
|
+
interface PipelineNodeOutput {
|
|
85
|
+
text: string;
|
|
86
|
+
usage?: PipelineUsage;
|
|
87
|
+
route?: string;
|
|
88
|
+
}
|
|
89
|
+
interface PipelineNodeContext<E = never> {
|
|
90
|
+
signal: AbortSignal;
|
|
91
|
+
pipeline: PipelineDefinition;
|
|
92
|
+
emit: (event: E) => void;
|
|
93
|
+
}
|
|
94
|
+
type PipelineNodeRunner<E = never> = (node: PipelineNode, input: PipelineNodeInput, ctx: PipelineNodeContext<E>) => Promise<PipelineNodeOutput>;
|
|
95
|
+
type PipelineStop = 'maxRuns' | 'maxNodeVisits' | 'aborted';
|
|
96
|
+
type PipelineEvent = {
|
|
97
|
+
type: 'pipeline.started';
|
|
98
|
+
pipeline?: string;
|
|
99
|
+
} | {
|
|
100
|
+
type: 'pipeline.node.started';
|
|
101
|
+
nodeId: string;
|
|
102
|
+
visit: number;
|
|
103
|
+
from: string[];
|
|
104
|
+
} | {
|
|
105
|
+
type: 'pipeline.node.finished';
|
|
106
|
+
nodeId: string;
|
|
107
|
+
visit: number;
|
|
108
|
+
text: string;
|
|
109
|
+
route?: string;
|
|
110
|
+
usage?: PipelineUsage;
|
|
111
|
+
} | {
|
|
112
|
+
type: 'pipeline.node.failed';
|
|
113
|
+
nodeId: string;
|
|
114
|
+
visit: number;
|
|
115
|
+
error: string;
|
|
116
|
+
} | {
|
|
117
|
+
type: 'pipeline.node.skipped';
|
|
118
|
+
nodeId: string;
|
|
119
|
+
from: string[];
|
|
120
|
+
reason: 'maxRuns' | 'maxNodeVisits';
|
|
121
|
+
} | {
|
|
122
|
+
type: 'pipeline.edge';
|
|
123
|
+
from: string;
|
|
124
|
+
to: string;
|
|
125
|
+
edgeId: string;
|
|
126
|
+
visit: number;
|
|
127
|
+
fired: boolean;
|
|
128
|
+
} | {
|
|
129
|
+
type: 'pipeline.finished';
|
|
130
|
+
stoppedBy?: PipelineStop;
|
|
131
|
+
runs: number;
|
|
132
|
+
};
|
|
133
|
+
type PipelineNodeEvent<E> = E & {
|
|
134
|
+
nodeId: string;
|
|
135
|
+
visit: number;
|
|
136
|
+
};
|
|
137
|
+
type PipelineTraceEntry = {
|
|
138
|
+
type: 'node';
|
|
139
|
+
nodeId: string;
|
|
140
|
+
visit: number;
|
|
141
|
+
wave: number;
|
|
142
|
+
from: string[];
|
|
143
|
+
text: string;
|
|
144
|
+
route?: string;
|
|
145
|
+
usage?: PipelineUsage;
|
|
146
|
+
} | {
|
|
147
|
+
type: 'edge';
|
|
148
|
+
from: string;
|
|
149
|
+
to: string;
|
|
150
|
+
edgeId: string;
|
|
151
|
+
visit: number;
|
|
152
|
+
fired: boolean;
|
|
153
|
+
} | {
|
|
154
|
+
type: 'dropped';
|
|
155
|
+
nodeId: string;
|
|
156
|
+
from: string[];
|
|
157
|
+
reason: 'maxRuns' | 'maxNodeVisits';
|
|
158
|
+
};
|
|
159
|
+
interface PipelineResult {
|
|
160
|
+
text: string;
|
|
161
|
+
outputs: Record<string, {
|
|
162
|
+
visit: number;
|
|
163
|
+
text: string;
|
|
164
|
+
route?: string;
|
|
165
|
+
}[]>;
|
|
166
|
+
trace: PipelineTraceEntry[];
|
|
167
|
+
usage: PipelineUsage;
|
|
168
|
+
stoppedBy?: PipelineStop;
|
|
169
|
+
runs: number;
|
|
170
|
+
}
|
|
171
|
+
interface PipelineIssue {
|
|
172
|
+
code: string;
|
|
173
|
+
message: string;
|
|
174
|
+
nodeId?: string;
|
|
175
|
+
edgeId?: string;
|
|
176
|
+
edgeIndex?: number;
|
|
177
|
+
}
|
|
178
|
+
interface PipelineValidation {
|
|
179
|
+
ok: boolean;
|
|
180
|
+
errors: PipelineIssue[];
|
|
181
|
+
warnings: PipelineIssue[];
|
|
182
|
+
}
|
|
183
|
+
declare class PipelineValidationError extends Error {
|
|
184
|
+
errors: PipelineIssue[];
|
|
185
|
+
constructor(errors: PipelineIssue[]);
|
|
186
|
+
}
|
|
187
|
+
declare class PipelineNodeError extends Error {
|
|
188
|
+
nodeId: string;
|
|
189
|
+
visit: number;
|
|
190
|
+
constructor(nodeId: string, visit: number, cause: unknown);
|
|
191
|
+
}
|
|
192
|
+
type Matcher = (text: string) => boolean;
|
|
193
|
+
declare const testPipelineCondition: (when: PipelineCondition | undefined, output: {
|
|
194
|
+
text: string;
|
|
195
|
+
route?: string;
|
|
196
|
+
}, matcher?: (text: string) => boolean) => boolean;
|
|
197
|
+
declare const normalizePipeline: (definition: PipelineDefinition) => PipelineDefinition;
|
|
198
|
+
declare const validatePipeline: (definition: PipelineDefinition) => PipelineValidation;
|
|
199
|
+
declare const renderPipelineNodeInput: (input: PipelineNodeInput) => string;
|
|
200
|
+
declare const PIPELINE_ROUTER_SYSTEM: string;
|
|
201
|
+
declare const renderPipelineRoutePrompt: (node: PipelineNode, text: string) => string;
|
|
202
|
+
declare const matchPipelineRoute: (node: PipelineNode, answer: unknown) => string | undefined;
|
|
203
|
+
interface PlannedEdge {
|
|
204
|
+
edge: PipelineEdge;
|
|
205
|
+
matcher?: Matcher;
|
|
206
|
+
}
|
|
207
|
+
interface PipelinePlan {
|
|
208
|
+
definition: PipelineDefinition;
|
|
209
|
+
nodes: Map<string, PipelineNode>;
|
|
210
|
+
outgoing: Map<string, PlannedEdge[]>;
|
|
211
|
+
maxNodeVisits: number;
|
|
212
|
+
maxRuns: number;
|
|
213
|
+
reaches: (from: string, to: string) => boolean;
|
|
214
|
+
}
|
|
215
|
+
declare const preparePipeline: (definition: PipelineDefinition) => PipelinePlan;
|
|
216
|
+
type PipelineAbortBehaviour = 'reject' | 'resolve';
|
|
217
|
+
interface PipelineGraphRunOptions<E = never> {
|
|
218
|
+
input: string;
|
|
219
|
+
signal?: AbortSignal;
|
|
220
|
+
onEvent?: (event: PipelineEvent | PipelineNodeEvent<E>) => void;
|
|
221
|
+
onAbort?: PipelineAbortBehaviour;
|
|
222
|
+
}
|
|
223
|
+
declare const runPipelineGraph: <E = never>(plan: PipelinePlan, runNode: PipelineNodeRunner<E>, options: PipelineGraphRunOptions<E>) => Promise<PipelineResult>;
|
|
224
|
+
|
|
225
|
+
export { PIPELINE_LIMITS, PIPELINE_ROUTER_SYSTEM, PipelineNodeError, PipelineValidationError, matchPipelineRoute, normalizePipeline, preparePipeline, renderPipelineNodeInput, renderPipelineRoutePrompt, runPipelineGraph, testPipelineCondition, validatePipeline };
|
|
226
|
+
export type { PipelineAbortBehaviour, PipelineCondition, PipelineDefinition, PipelineEdge, PipelineEvent, PipelineGraphRunOptions, PipelineIssue, PipelineNode, PipelineNodeContext, PipelineNodeEvent, PipelineNodeInput, PipelineNodeOutput, PipelineNodeRunner, PipelineNodeSource, PipelinePlan, PipelineResult, PipelineRoute, PipelineStop, PipelineTraceEntry, PipelineUsage, PipelineValidation };
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
interface PipelineDefinition {
|
|
2
|
+
version: 1;
|
|
3
|
+
name?: string;
|
|
4
|
+
entry: string;
|
|
5
|
+
nodes: PipelineNode[];
|
|
6
|
+
edges: PipelineEdge[];
|
|
7
|
+
limits?: {
|
|
8
|
+
maxNodeVisits?: number;
|
|
9
|
+
maxRuns?: number;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
interface PipelineNode {
|
|
13
|
+
id: string;
|
|
14
|
+
name?: string;
|
|
15
|
+
instructions?: string;
|
|
16
|
+
model?: string;
|
|
17
|
+
skills?: string[];
|
|
18
|
+
tools?: string[];
|
|
19
|
+
mcpServers?: string[];
|
|
20
|
+
routes?: PipelineRoute[];
|
|
21
|
+
join?: 'all' | 'any';
|
|
22
|
+
settings?: Record<string, unknown>;
|
|
23
|
+
position?: {
|
|
24
|
+
x: number;
|
|
25
|
+
y: number;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
interface PipelineRoute {
|
|
29
|
+
label: string;
|
|
30
|
+
description?: string;
|
|
31
|
+
}
|
|
32
|
+
type PipelineCondition = {
|
|
33
|
+
kind: 'always';
|
|
34
|
+
} | {
|
|
35
|
+
kind: 'contains';
|
|
36
|
+
text: string;
|
|
37
|
+
caseSensitive?: boolean;
|
|
38
|
+
} | {
|
|
39
|
+
kind: 'matches';
|
|
40
|
+
pattern: string;
|
|
41
|
+
flags?: string;
|
|
42
|
+
} | {
|
|
43
|
+
kind: 'route';
|
|
44
|
+
label: string;
|
|
45
|
+
} | {
|
|
46
|
+
kind: 'otherwise';
|
|
47
|
+
};
|
|
48
|
+
interface PipelineEdge {
|
|
49
|
+
id?: string;
|
|
50
|
+
from: string;
|
|
51
|
+
to: string;
|
|
52
|
+
when?: PipelineCondition;
|
|
53
|
+
}
|
|
54
|
+
declare const PIPELINE_LIMITS: {
|
|
55
|
+
readonly maxNodeVisits: 3;
|
|
56
|
+
readonly maxRuns: 25;
|
|
57
|
+
readonly maxNodeVisitsCeiling: 100;
|
|
58
|
+
readonly maxRunsCeiling: 1000;
|
|
59
|
+
readonly maxNodes: 200;
|
|
60
|
+
readonly maxEdges: 1000;
|
|
61
|
+
readonly maxRoutes: 20;
|
|
62
|
+
readonly maxPatternLength: 500;
|
|
63
|
+
readonly maxPatternProgram: 1000;
|
|
64
|
+
readonly conditionInputChars: 50000;
|
|
65
|
+
};
|
|
66
|
+
interface PipelineUsage {
|
|
67
|
+
inputTokens: number;
|
|
68
|
+
outputTokens: number;
|
|
69
|
+
totalTokens: number;
|
|
70
|
+
reasoningTokens?: number;
|
|
71
|
+
cachedInputTokens?: number;
|
|
72
|
+
cacheWriteTokens?: number;
|
|
73
|
+
}
|
|
74
|
+
interface PipelineNodeSource {
|
|
75
|
+
nodeId: string;
|
|
76
|
+
name?: string;
|
|
77
|
+
text: string;
|
|
78
|
+
}
|
|
79
|
+
interface PipelineNodeInput {
|
|
80
|
+
request: string;
|
|
81
|
+
from: PipelineNodeSource[];
|
|
82
|
+
visit: number;
|
|
83
|
+
}
|
|
84
|
+
interface PipelineNodeOutput {
|
|
85
|
+
text: string;
|
|
86
|
+
usage?: PipelineUsage;
|
|
87
|
+
route?: string;
|
|
88
|
+
}
|
|
89
|
+
interface PipelineNodeContext<E = never> {
|
|
90
|
+
signal: AbortSignal;
|
|
91
|
+
pipeline: PipelineDefinition;
|
|
92
|
+
emit: (event: E) => void;
|
|
93
|
+
}
|
|
94
|
+
type PipelineNodeRunner<E = never> = (node: PipelineNode, input: PipelineNodeInput, ctx: PipelineNodeContext<E>) => Promise<PipelineNodeOutput>;
|
|
95
|
+
type PipelineStop = 'maxRuns' | 'maxNodeVisits' | 'aborted';
|
|
96
|
+
type PipelineEvent = {
|
|
97
|
+
type: 'pipeline.started';
|
|
98
|
+
pipeline?: string;
|
|
99
|
+
} | {
|
|
100
|
+
type: 'pipeline.node.started';
|
|
101
|
+
nodeId: string;
|
|
102
|
+
visit: number;
|
|
103
|
+
from: string[];
|
|
104
|
+
} | {
|
|
105
|
+
type: 'pipeline.node.finished';
|
|
106
|
+
nodeId: string;
|
|
107
|
+
visit: number;
|
|
108
|
+
text: string;
|
|
109
|
+
route?: string;
|
|
110
|
+
usage?: PipelineUsage;
|
|
111
|
+
} | {
|
|
112
|
+
type: 'pipeline.node.failed';
|
|
113
|
+
nodeId: string;
|
|
114
|
+
visit: number;
|
|
115
|
+
error: string;
|
|
116
|
+
} | {
|
|
117
|
+
type: 'pipeline.node.skipped';
|
|
118
|
+
nodeId: string;
|
|
119
|
+
from: string[];
|
|
120
|
+
reason: 'maxRuns' | 'maxNodeVisits';
|
|
121
|
+
} | {
|
|
122
|
+
type: 'pipeline.edge';
|
|
123
|
+
from: string;
|
|
124
|
+
to: string;
|
|
125
|
+
edgeId: string;
|
|
126
|
+
visit: number;
|
|
127
|
+
fired: boolean;
|
|
128
|
+
} | {
|
|
129
|
+
type: 'pipeline.finished';
|
|
130
|
+
stoppedBy?: PipelineStop;
|
|
131
|
+
runs: number;
|
|
132
|
+
};
|
|
133
|
+
type PipelineNodeEvent<E> = E & {
|
|
134
|
+
nodeId: string;
|
|
135
|
+
visit: number;
|
|
136
|
+
};
|
|
137
|
+
type PipelineTraceEntry = {
|
|
138
|
+
type: 'node';
|
|
139
|
+
nodeId: string;
|
|
140
|
+
visit: number;
|
|
141
|
+
wave: number;
|
|
142
|
+
from: string[];
|
|
143
|
+
text: string;
|
|
144
|
+
route?: string;
|
|
145
|
+
usage?: PipelineUsage;
|
|
146
|
+
} | {
|
|
147
|
+
type: 'edge';
|
|
148
|
+
from: string;
|
|
149
|
+
to: string;
|
|
150
|
+
edgeId: string;
|
|
151
|
+
visit: number;
|
|
152
|
+
fired: boolean;
|
|
153
|
+
} | {
|
|
154
|
+
type: 'dropped';
|
|
155
|
+
nodeId: string;
|
|
156
|
+
from: string[];
|
|
157
|
+
reason: 'maxRuns' | 'maxNodeVisits';
|
|
158
|
+
};
|
|
159
|
+
interface PipelineResult {
|
|
160
|
+
text: string;
|
|
161
|
+
outputs: Record<string, {
|
|
162
|
+
visit: number;
|
|
163
|
+
text: string;
|
|
164
|
+
route?: string;
|
|
165
|
+
}[]>;
|
|
166
|
+
trace: PipelineTraceEntry[];
|
|
167
|
+
usage: PipelineUsage;
|
|
168
|
+
stoppedBy?: PipelineStop;
|
|
169
|
+
runs: number;
|
|
170
|
+
}
|
|
171
|
+
interface PipelineIssue {
|
|
172
|
+
code: string;
|
|
173
|
+
message: string;
|
|
174
|
+
nodeId?: string;
|
|
175
|
+
edgeId?: string;
|
|
176
|
+
edgeIndex?: number;
|
|
177
|
+
}
|
|
178
|
+
interface PipelineValidation {
|
|
179
|
+
ok: boolean;
|
|
180
|
+
errors: PipelineIssue[];
|
|
181
|
+
warnings: PipelineIssue[];
|
|
182
|
+
}
|
|
183
|
+
declare class PipelineValidationError extends Error {
|
|
184
|
+
errors: PipelineIssue[];
|
|
185
|
+
constructor(errors: PipelineIssue[]);
|
|
186
|
+
}
|
|
187
|
+
declare class PipelineNodeError extends Error {
|
|
188
|
+
nodeId: string;
|
|
189
|
+
visit: number;
|
|
190
|
+
constructor(nodeId: string, visit: number, cause: unknown);
|
|
191
|
+
}
|
|
192
|
+
type Matcher = (text: string) => boolean;
|
|
193
|
+
declare const testPipelineCondition: (when: PipelineCondition | undefined, output: {
|
|
194
|
+
text: string;
|
|
195
|
+
route?: string;
|
|
196
|
+
}, matcher?: (text: string) => boolean) => boolean;
|
|
197
|
+
declare const normalizePipeline: (definition: PipelineDefinition) => PipelineDefinition;
|
|
198
|
+
declare const validatePipeline: (definition: PipelineDefinition) => PipelineValidation;
|
|
199
|
+
declare const renderPipelineNodeInput: (input: PipelineNodeInput) => string;
|
|
200
|
+
declare const PIPELINE_ROUTER_SYSTEM: string;
|
|
201
|
+
declare const renderPipelineRoutePrompt: (node: PipelineNode, text: string) => string;
|
|
202
|
+
declare const matchPipelineRoute: (node: PipelineNode, answer: unknown) => string | undefined;
|
|
203
|
+
interface PlannedEdge {
|
|
204
|
+
edge: PipelineEdge;
|
|
205
|
+
matcher?: Matcher;
|
|
206
|
+
}
|
|
207
|
+
interface PipelinePlan {
|
|
208
|
+
definition: PipelineDefinition;
|
|
209
|
+
nodes: Map<string, PipelineNode>;
|
|
210
|
+
outgoing: Map<string, PlannedEdge[]>;
|
|
211
|
+
maxNodeVisits: number;
|
|
212
|
+
maxRuns: number;
|
|
213
|
+
reaches: (from: string, to: string) => boolean;
|
|
214
|
+
}
|
|
215
|
+
declare const preparePipeline: (definition: PipelineDefinition) => PipelinePlan;
|
|
216
|
+
type PipelineAbortBehaviour = 'reject' | 'resolve';
|
|
217
|
+
interface PipelineGraphRunOptions<E = never> {
|
|
218
|
+
input: string;
|
|
219
|
+
signal?: AbortSignal;
|
|
220
|
+
onEvent?: (event: PipelineEvent | PipelineNodeEvent<E>) => void;
|
|
221
|
+
onAbort?: PipelineAbortBehaviour;
|
|
222
|
+
}
|
|
223
|
+
declare const runPipelineGraph: <E = never>(plan: PipelinePlan, runNode: PipelineNodeRunner<E>, options: PipelineGraphRunOptions<E>) => Promise<PipelineResult>;
|
|
224
|
+
|
|
225
|
+
export { PIPELINE_LIMITS, PIPELINE_ROUTER_SYSTEM, PipelineNodeError, PipelineValidationError, matchPipelineRoute, normalizePipeline, preparePipeline, renderPipelineNodeInput, renderPipelineRoutePrompt, runPipelineGraph, testPipelineCondition, validatePipeline };
|
|
226
|
+
export type { PipelineAbortBehaviour, PipelineCondition, PipelineDefinition, PipelineEdge, PipelineEvent, PipelineGraphRunOptions, PipelineIssue, PipelineNode, PipelineNodeContext, PipelineNodeEvent, PipelineNodeInput, PipelineNodeOutput, PipelineNodeRunner, PipelineNodeSource, PipelinePlan, PipelineResult, PipelineRoute, PipelineStop, PipelineTraceEntry, PipelineUsage, PipelineValidation };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
var be=Object.defineProperty;var o=(e,t)=>be(e,"name",{value:t,configurable:true});var C={maxNodeVisits:3,maxRuns:25,maxNodeVisitsCeiling:100,maxRunsCeiling:1e3,maxNodes:200,maxEdges:1e3,maxRoutes:20,maxPatternLength:500,maxPatternProgram:1e3,conditionInputChars:5e4},X=class extends Error{static{o(this,"PipelineValidationError");}errors;constructor(t){super(`Invalid pipeline: ${t.map(i=>i.message).join("; ")}`),this.name="PipelineValidationError",this.errors=t;}},Y=class extends Error{static{o(this,"PipelineNodeError");}nodeId;visit;constructor(t,i,n){let s=n instanceof Error?n.message:String(n);super(`Pipeline node "${t}" failed (visit ${i}): ${s}`,{cause:n}),this.name="PipelineNodeError",this.nodeId=t,this.visit=i;}},T=o(e=>e.codePointAt(0),"cp"),ae=[48,57],K=[48,57,65,90,95,95,97,122],ce=[9,13,32,32,160,160,5760,5760,8192,8202,8232,8233,8239,8239,8287,8287,12288,12288,65279,65279],Z=1114111,J=1e3,W=o((e,t)=>{for(let i=0;i<e.length;i+=2)if(t>=e[i]&&t<=e[i+1])return true;return false},"inRanges"),G=o(e=>{let t=[];for(let s=0;s<e.length;s+=2)t.push([e[s],e[s+1]]);t.sort((s,r)=>s[0]-r[0]);let i=[],n=0;for(let[s,r]of t)s>n&&i.push(n,s-1),n=Math.max(n,r+1);return n<=Z&&i.push(n,Z),i},"complement"),F=o(e=>e===10||e===13||e===8232||e===8233,"isLineEnd"),B=o(e=>e!==void 0&&W(K,e),"isWordChar"),ue=o(e=>e!==void 0&&/^[0-9a-fA-F]$/.test(String.fromCodePoint(e)),"isHex"),H=o(e=>e!==void 0&&e>=48&&e<=57,"isDigit"),xe=o(e=>{let t=Array.from(e,T),i=0,n=o((c=0)=>t[i+c],"peek"),s=o((c,l=0)=>t[i+l]===T(c),"is"),r=o(c=>{throw new Error(`${c} (at ${i})`)},"fail"),a=o(c=>{let l=0;for(let v=0;v<c;v++)ue(n())||r("a bad hexadecimal escape"),l=l*16+parseInt(String.fromCodePoint(t[i++]),16);return l},"hex"),u=o(c=>{let l=n();if(l===void 0)return r("a pattern cannot end with a backslash");i++;let v=String.fromCodePoint(l);switch(v){case "d":return {r:ae};case "D":return {r:G(ae)};case "w":return {r:K};case "W":return {r:G(K)};case "s":return {r:ce};case "S":return {r:G(ce)};case "b":return c?{c:8}:{k:"word"};case "B":return c?r("\\B is not allowed in a class"):{k:"not-word"};case "n":return {c:10};case "r":return {c:13};case "t":return {c:9};case "f":return {c:12};case "v":return {c:11};case "0":return H(n())?r("octal escapes are not supported"):{c:0};case "x":return {c:a(2)};case "u":{if(!s("{"))return {c:a(4)};i++;let x=0,k=0;for(;ue(n());)x=x*16+parseInt(String.fromCodePoint(t[i++]),16),k++,x>Z&&r("a code point out of range");return (!k||!s("}"))&&r("a bad \\u{...} escape"),i++,{c:x}}case "k":return r("backreferences are not supported");case "p":case "P":return r("\\p{...} is not supported");case "c":return r("\\c control escapes are not supported");default:return H(l)?r("backreferences are not supported"):/^[a-zA-Z]$/.test(v)?r(`unknown escape \\${v}`):{c:l}}},"escape"),h=o(()=>{let c=s("^");c&&i++;let l=[];for(;;){let v=n();if(v===void 0)return r("an unterminated class");if(s("]")){i++;break}i++;let x;if(v===T("\\")){let k=u(true);if("r"in k){l.push(...k.r);continue}x=k.c;}else x=v;if(s("-")&&n(1)!==void 0&&!s("]",1)){i++;let k=t[i++];if(k===T("\\")){let m=u(true);if(!("c"in m))return r("a bad range in a class");k=m.c;}k<x&&r("a range out of order in a class"),l.push(x,k);}else l.push(x,x);}return {t:"set",r:l,neg:c}},"klass"),f=o(()=>{let c=i+1,l=o(()=>{let k=c;for(;H(t[c]);)c++;return c>k?Number(String.fromCodePoint(...t.slice(k,c))):void 0},"number"),v=l();if(v===void 0)return;let x=v;if(t[c]===T(",")&&(c++,x=l()??1/0),t[c]===T("}"))return i=c+1,x<v&&r("a quantifier out of order"),(v>J||x!==1/0&&x>J)&&r(`a repeat count above ${J}`),{min:v,max:x}},"braces"),b=o(()=>{let c=t[i++];switch(String.fromCodePoint(c)){case "(":{if(s("?"))if(s(":",1))i+=2;else if(s("<",1)&&!s("=",2)&&!s("!",2)){for(;n()!==void 0&&!s(">");)i++;n()===void 0&&r("an unterminated group name"),i++;}else r("lookaround is not supported");let l=O();return s(")")||r("an unterminated group"),i++,l}case "[":return h();case ".":return {t:"any"};case "^":return {t:"assert",k:"start"};case "$":return {t:"assert",k:"end"};case "\\":{let l=u(false);return "k"in l?{t:"assert",k:l.k}:"r"in l?{t:"set",r:l.r,neg:false}:{t:"char",c:l.c}}case "*":case "+":case "?":return r("nothing to repeat");case "{":return i--,f()&&r("nothing to repeat"),i++,{t:"char",c};default:return {t:"char",c}}},"atom"),R=o(()=>{let c=b();for(;;){let l;if(s("*")?l={min:0,max:1/0}:s("+")?l={min:1,max:1/0}:s("?")&&(l={min:0,max:1}),l?i++:s("{")&&(l=f()),!l)return c;c.t==="assert"&&r("nothing to repeat"),s("?")&&i++,c={t:"rep",item:c,min:l.min,max:l.max};}},"repetition"),S=o(()=>{let c=[];for(;n()!==void 0&&!s("|")&&!s(")");)c.push(R());return c.length===1?c[0]:{t:"cat",items:c}},"sequence");function O(){let c=[S()];for(;s("|");)i++,c.push(S());return c.length===1?c[0]:{t:"alt",items:c}}o(O,"alternation");let j=O();return i<t.length&&r("an unmatched )"),j},"parsePattern"),we=o(e=>{let t=[],i=o(s=>{if(t.length>=C.maxPatternProgram)throw new Error(`the pattern is too complex (more than ${C.maxPatternProgram} steps once its repeats are unrolled)`);return t.push(s),t.length-1},"push"),n=o(s=>{switch(s.t){case "char":i({op:"char",c:s.c});return;case "any":i({op:"any"});return;case "set":i({op:"set",r:s.r,neg:s.neg});return;case "assert":i({op:"assert",k:s.k});return;case "cat":for(let r of s.items)n(r);return;case "alt":{let r=[];s.items.forEach((a,u)=>{if(u===s.items.length-1){n(a);return}let h={op:"split",x:0,y:0};h.x=i(h)+1,n(a);let f={op:"jmp",x:0};i(f),r.push(f),h.y=t.length;});for(let a of r)a.x=t.length;return}case "rep":{for(let a=0;a<s.min;a++)n(s.item);if(s.max===1/0){let a={op:"split",x:0,y:0},u=i(a);a.x=u+1,n(s.item),i({op:"jmp",x:u}),a.y=t.length;return}let r=[];for(let a=s.min;a<s.max;a++){let u={op:"split",x:0,y:0};u.x=i(u)+1,r.push(u),n(s.item);}for(let a of r)a.y=t.length;return}}},"emit");return n(e),i({op:"match"}),t},"compileAst"),de="imsu",Q=o((e,t="")=>{if(typeof e!="string"||e.length===0)throw new Error("the pattern is empty");if(e.length>C.maxPatternLength)throw new Error(`the pattern is longer than ${C.maxPatternLength} characters`);if(typeof t!="string")throw new Error("flags must be a string");for(let f of t)if(!de.includes(f))throw new Error(`flag "${f}" is not allowed (allowed: ${de})`);if(new Set(t).size!==t.length)throw new Error("a flag is repeated");try{new RegExp(e,t);}catch(f){throw new Error(f instanceof Error?f.message:String(f))}let i=we(xe(e)),n=t.includes("i"),s=t.includes("m"),r=t.includes("s"),a=o((f,b)=>b.length===String.fromCodePoint(T(b)).length?T(b):f,"single"),u=o(f=>a(f,String.fromCodePoint(f).toLowerCase()),"lower"),h=o(f=>a(f,String.fromCodePoint(f).toUpperCase()),"upper");return f=>{let b=Array.from(f.slice(0,C.conditionInputChars),T),R=b.length,S=new Int32Array(i.length),O=0,j=false,c=[],l=o((m,d)=>{switch(m){case "start":return d===0||s&&F(b[d-1]);case "end":return d===R||s&&F(b[d]);case "word":return B(b[d-1])!==B(b[d]);case "not-word":return B(b[d-1])===B(b[d])}},"holds"),v=o((m,d,g)=>{for(c.push(d);c.length;){let E=c.pop();if(S[E]===O)continue;S[E]=O;let y=i[E];switch(y.op){case "jmp":c.push(y.x);break;case "split":c.push(y.y,y.x);break;case "assert":l(y.k,g)&&c.push(E+1);break;case "match":j=true;break;default:m.push(E);}}},"add"),x=[],k=[];O++,v(x,0,0);for(let m=0;m<R&&!j;m++){let d=b[m],g=n?u(d):d,E=n?h(d):d;O++;for(let y of x){let N=i[y],p=false;N.op==="char"?p=N.c===d||n&&(N.c===g||N.c===E||u(N.c)===g):N.op==="any"?p=r||!F(d):N.op==="set"&&(p=(W(N.r,d)||n&&(W(N.r,g)||W(N.r,E)))!==N.neg),p&&v(k,y+1,m+1);}v(k,0,m+1),x=k,k=[];}return j}},"compileMatcher"),ye=["always","contains","matches","route","otherwise"],Pe=o((e,t,i)=>{if(!e||e.kind==="always")return true;switch(e.kind){case "contains":{let n=t.text.slice(0,C.conditionInputChars);return e.caseSensitive?n.includes(e.text):n.toLowerCase().includes(e.text.toLowerCase())}case "matches":return (i??Q(e.pattern,e.flags))(t.text);case "route":return t.route!==void 0&&t.route===e.label;default:return false}},"testPipelineCondition"),V=o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isRecord"),M=o(e=>typeof e=="string"&&e.trim().length>0,"isId"),ge=o((e,t)=>V(e)&&M(e.id)?e.id:`e${t}`,"edgeIdOf"),ve=o((e,t)=>({edgeId:ge(e,t),edgeIndex:t}),"edgeRef"),ke=o(e=>{let t=JSON.parse(JSON.stringify(e));return V(t)&&Array.isArray(t.edges)&&t.edges.forEach((i,n)=>{V(i)&&(i.id=ge(i,n));}),t},"normalizePipeline"),le=o((e,t)=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=t,"inRange"),Ee=o(e=>{let t=[],i=[],n=o((m,d,g={})=>{t.push({code:m,message:d,...g});},"error"),s=o(()=>({ok:t.length===0,errors:t,warnings:i}),"done"),r=e;if(!V(r))return n("definition","a pipeline definition must be an object"),s();r.version!==1&&n("version",`unsupported pipeline version ${JSON.stringify(r.version)} (expected 1)`);let a=Array.isArray(r.nodes)?r.nodes:void 0,u=Array.isArray(r.edges)?r.edges:void 0;(!a||a.length===0)&&n("nodes","a pipeline needs at least one node"),u||n("edges","`edges` must be an array"),a&&a.length>C.maxNodes&&n("nodes",`more than ${C.maxNodes} nodes`),u&&u.length>C.maxEdges&&n("edges",`more than ${C.maxEdges} edges`);let h=new Set,f=new Map;for(let[m,d]of (a??[]).entries()){if(!V(d)||!M(d.id)){n("node.id",`node #${m+1} has no id`);continue}let g=d.id;if(h.has(g)){n("node.duplicate",`duplicate node id "${g}"`,{nodeId:g});continue}h.add(g),d.join!==void 0&&d.join!=="all"&&d.join!=="any"&&n("node.join",`node "${g}": join must be "all" or "any"`,{nodeId:g});let E=[];if(d.routes!==void 0)if(!Array.isArray(d.routes)||d.routes.length>C.maxRoutes)n("node.routes",`node "${g}": routes must be a list of at most ${C.maxRoutes}`,{nodeId:g});else for(let y of d.routes)!V(y)||!M(y.label)?n("node.routes",`node "${g}": a route has no label`,{nodeId:g}):E.includes(y.label)?n("node.routes",`node "${g}": duplicate route "${y.label}"`,{nodeId:g}):E.push(y.label);f.set(g,E);}M(r.entry)?h.has(r.entry)||n("entry",`the entry node "${r.entry}" does not exist`):n("entry","the pipeline has no entry node");let b=new Map,R=new Set,S=new Set,O=new Set;for(let[m,d]of (u??[]).entries()){let g=ve(d,m),E=`edge "${g.edgeId}"`;if(!V(d)){n("edge",`${E} is not an object`,g);continue}d.id!==void 0&&!M(d.id)&&n("edge.id",`${E} has an empty id`,g),R.has(g.edgeId)&&n("edge.duplicate",`duplicate edge id "${g.edgeId}"`,g),R.add(g.edgeId);let y=d.from,N=d.to,p=M(y)&&h.has(y),I=M(N)&&h.has(N);p||n("edge.from",`${E} starts at an unknown node ${JSON.stringify(y)}`,g),I||n("edge.to",`${E} leads to an unknown node ${JSON.stringify(N)}`,g),p&&I&&b.set(y,[...b.get(y)??[],N]);let w=d.when;if(w!==void 0){if(!V(w)||!ye.includes(w.kind)){n("edge.when",`${E} has an unknown condition`,g);continue}switch(w.kind){case "contains":(typeof w.text!="string"||w.text.length===0)&&n("edge.when",`${E}: "contains" needs a text`,g);break;case "matches":try{Q(w.pattern,w.flags??"");}catch(P){n("edge.pattern",`${E}: ${P.message}`,g);}break;case "route":p&&O.add(y),M(w.label)?p&&!(f.get(y)??[]).includes(w.label)&&n("edge.route",`${E}: node "${y}" has no route "${w.label}"`,p?{...g,nodeId:y}:g):n("edge.route",`${E}: "route" needs a label`,g);break;case "otherwise":p&&(S.has(y)&&n("edge.otherwise",`node "${y}" has more than one "otherwise" edge`,{...g,nodeId:y}),S.add(y));break}}}if(r.limits!==void 0)if(!V(r.limits))n("limits","`limits` must be an object");else {let{maxNodeVisits:m,maxRuns:d}=r.limits;m!==void 0&&!le(m,C.maxNodeVisitsCeiling)&&n("limits",`limits.maxNodeVisits must be a whole number from 1 to ${C.maxNodeVisitsCeiling}`),d!==void 0&&!le(d,C.maxRunsCeiling)&&n("limits",`limits.maxRuns must be a whole number from 1 to ${C.maxRunsCeiling}`);}if(t.length>0||!M(r.entry))return s();let j=new Set([r.entry]),c=[r.entry];for(;c.length;)for(let m of b.get(c.pop())??[])j.has(m)||(j.add(m),c.push(m));for(let m of h)j.has(m)||i.push({code:"unreachable",message:`node "${m}" cannot be reached from the entry node`,nodeId:m}),(f.get(m)??[]).length>0&&!O.has(m)&&i.push({code:"routes.unused",message:`node "${m}" has routes but no edge with a "route" condition`,nodeId:m});let l=new Map,v=[],x=o(m=>{l.set(m,"open"),v.push(m);for(let d of b.get(m)??[]){if(l.get(d)==="open")return [...v.slice(v.indexOf(d)),d];if(!l.has(d)){let g=x(d);if(g)return g}}v.pop(),l.set(m,"closed");},"findCycle"),k=x(r.entry);return k&&i.push({code:"cycle",message:`the pipeline has a loop (${k.join(" \u2192 ")}); limits.maxNodeVisits and limits.maxRuns bound it`,nodeId:k[0]}),s()},"validatePipeline"),ee=o(e=>e.name||e.nodeId,"titleOf"),Re=o(e=>{if(e.from.length===0&&e.visit<=1)return e.request;let t=[`Request:
|
|
2
|
+
${e.request}`];for(let i of e.from)t.push(`Output of "${ee(i)}":
|
|
3
|
+
${i.text}`);return e.visit>1&&t.push(`(This is visit ${e.visit} of this step.)`),t.join(`
|
|
4
|
+
|
|
5
|
+
`)},"renderPipelineNodeInput"),Se="You are the Router of one step in a pipeline of agents. The step has answered. Pick the ONE route label that fits its answer, from the list you are given. Answer with a label exactly as it is written in the list, and nothing else.",pe=2e3,fe=6e3,Ce=o((e,t)=>{let i=(e.routes??[]).map(s=>`- ${s.label}${s.description?`: ${s.description}`:""}`).join(`
|
|
6
|
+
`),n=t.length>pe+fe?`${t.slice(0,pe)}
|
|
7
|
+
[...]
|
|
8
|
+
${t.slice(-fe)}`:t;return [`Step: ${ee({nodeId:e.id,name:e.name})}`,e.instructions?`Its role:
|
|
9
|
+
${e.instructions}`:"",`Routes:
|
|
10
|
+
${i}`,`The step's answer:
|
|
11
|
+
${n}`,"Which route? Answer with one label from the list."].filter(Boolean).join(`
|
|
12
|
+
|
|
13
|
+
`)},"renderPipelineRoutePrompt"),Oe=o((e,t)=>{let i=(e.routes??[]).map(r=>r.label),n=t;if(typeof n=="string"){let r=n.trim();if(r.startsWith("{"))try{n=JSON.parse(r);}catch{n=r;}else n=r;}if(V(n)&&(n=n.route),typeof n!="string")return;let s=n.trim().replace(/^["'`]+|["'`.]+$/g,"").toLowerCase();return i.find(r=>r.toLowerCase()===s)},"matchPipelineRoute"),je=o(e=>{let{errors:t}=Ee(e);if(t.length>0)throw new X(t);let i=ke(e),n=new Map(i.nodes.map(u=>[u.id,u])),s=new Map(i.nodes.map(u=>[u.id,[]]));for(let u of i.edges){let h={edge:u};u.when?.kind==="matches"&&(h.matcher=Q(u.when.pattern,u.when.flags)),s.get(u.from)?.push(h);}let r=new Map,a=o(u=>{let h=r.get(u);if(!h){h=new Set;let f=[u];for(;f.length;)for(let{edge:b}of s.get(f.pop())??[])h.has(b.to)||(h.add(b.to),f.push(b.to));r.set(u,h);}return h},"descendants");return {definition:i,nodes:n,outgoing:s,maxNodeVisits:i.limits?.maxNodeVisits??C.maxNodeVisits,maxRuns:i.limits?.maxRuns??C.maxRuns,reaches:o((u,h)=>a(u).has(h),"reaches")}},"preparePipeline"),Ae=o(e=>{let t=e.definition.entry,i=[t],n=new Map([[t,[]]]);for(let a=0;a<i.length;a++)for(let{edge:u}of e.outgoing.get(i[a])??[])n.has(u.to)||(n.set(u.to,[]),i.push(u.to)),n.get(u.to).push(i[a]);let s=new Map;for(let a of i)s.set(a,new Set(a===t?[t]:i));for(let a=true;a;){a=false;for(let u of i){if(u===t)continue;let[h,...f]=n.get(u).map(R=>s.get(R)),b=new Set([u]);for(let R of h)f.every(S=>S.has(R))&&b.add(R);b.size<s.get(u).size&&(s.set(u,b),a=true);}}let r=new Map;return (a,u)=>{let h=r.get(a);if(!h){let f=new Set,b=[a];for(;b.length;){let R=b.pop();for(let{edge:S}of e.outgoing.get(R)??[])s.get(R)?.has(S.to)||f.has(S.to)||(f.add(S.to),b.push(S.to));}r.set(a,h=f);}return h.has(u)}},"passReach"),me=o(()=>{if(typeof DOMException=="function")return new DOMException("Aborted","AbortError");let e=new Error("Aborted");return e.name="AbortError",e},"abortError"),Ie=o(()=>{if(typeof AbortController=="function"){let n=new AbortController;return {signal:n.signal,abort:o(()=>n.abort(),"abort")}}let e=[],t={aborted:false,reason:void 0,onabort:null,addEventListener(n,s){n==="abort"&&s&&!e.includes(s)&&e.push(s);},removeEventListener(n,s){let r=s?e.indexOf(s):-1;n==="abort"&&r>=0&&e.splice(r,1);},throwIfAborted(){if(t.aborted)throw t.reason}};return {signal:t,abort:o(()=>{if(t.aborted)return;t.aborted=true,t.reason=me();let n={type:"abort",target:t},s=o((r,a)=>{try{r.call(a,n);}catch{}},"call");for(let r of e.splice(0))typeof r=="function"?s(r,t):s(r.handleEvent,r);typeof t.onabort=="function"&&s(t.onabort,t);},"abort")}},"createStopper"),$e=o((e,t)=>{if(!t)return;let i=e;for(let[n,s]of Object.entries(t))typeof s=="number"&&Number.isFinite(s)&&(i[n]=(i[n]??0)+s);},"addUsage"),Ve=o(async(e,t,i)=>{let{definition:n}=e,s=i.onAbort??"reject",r=Ie(),a,u=o(()=>{},"halt"),h=new Promise((p,I)=>{u=I;});h.catch(()=>{});let f=o(p=>{try{i.onEvent?.(p);}catch{}},"emit"),b=new Map,R={inputTokens:0,outputTokens:0,totalTokens:0},S={},O=[],j=[],c=new Set,l=0,v=0,x=new Map([[n.entry,[]]]),k=o(p=>{let I=Math.max(-1,...j.map($=>$.wave)),w=j.filter($=>$.wave===I);return {text:w.length===1?w[0].text:w.map($=>`## ${ee($)}
|
|
14
|
+
|
|
15
|
+
${$.text}`).join(`
|
|
16
|
+
|
|
17
|
+
`),outputs:S,trace:O,usage:R,...p?{stoppedBy:p}:{},runs:l}},"result"),m=o(()=>{a||(a="aborted",r.abort(),u(me()));},"onOuterAbort"),d=o(async(p,I)=>{let w=e.nodes.get(p),P=(b.get(p)??0)+1;b.set(p,P),l++;let $=I.map(A=>A.source.nodeId);f({type:"pipeline.node.started",nodeId:p,visit:P,from:$});let L;try{L=await t(w,{request:i.input,from:I.map(A=>({...A.source})),visit:P},{signal:r.signal,pipeline:n,emit:o(A=>{a||f({...A,nodeId:p,visit:P});},"emit")});}catch(A){if(a)return;a="failed";let U=new Y(p,P,A);f({type:"pipeline.node.failed",nodeId:p,visit:P,error:A instanceof Error?A.message:String(A)}),r.abort(),u(U);return}if(a)return;let D=typeof L?.text=="string"?L.text:"",_=(w.routes??[]).some(A=>A.label===L?.route)?L.route:void 0;$e(R,L?.usage);let ne={..._!==void 0?{route:_}:{},...L?.usage?{usage:L.usage}:{}};(S[p]??=[]).push({visit:P,text:D,..._!==void 0?{route:_}:{}}),O.push({type:"node",nodeId:p,visit:P,wave:v,from:$,text:D,...ne}),f({type:"pipeline.node.finished",nodeId:p,visit:P,text:D,...ne});let te=e.outgoing.get(p)??[],ie=te.map(({edge:A,matcher:U})=>Pe(A.when,{text:D,route:_},U)),he=ie.some(Boolean),q={nodeId:p,name:w.name,text:D,wave:v,live:0},z=new Set;te.forEach(({edge:A},U)=>{let se=A.when?.kind==="otherwise"?!he:ie[U],re={from:p,to:A.to,edgeId:A.id,visit:P,fired:se};if(O.push({type:"edge",...re}),f({type:"pipeline.edge",...re}),!se||z.has(A.to))return;z.add(A.to);let oe=x.get(A.to)??[];oe.push({source:{nodeId:p,...w.name?{name:w.name}:{},text:D},record:q}),x.set(A.to,oe);}),q.live=z.size,q.live===0&&j.push(q);},"visit"),g=o((p,I,w)=>{c.add(w);let P=I.map($=>$.source.nodeId);O.push({type:"dropped",nodeId:p,from:P,reason:w}),f({type:"pipeline.node.skipped",nodeId:p,from:P,reason:w});for(let{record:$}of I)$.live--,$.live===0&&j.push($);},"drop"),E=o((p,I,w=e.reaches)=>(e.nodes.get(p)?.join??"all")==="all"&&I.some(P=>P!==p&&w(P,p)),"deferred"),y;f({type:"pipeline.started",...n.name?{pipeline:n.name}:{}}),i.signal?.addEventListener("abort",m,{once:true});try{for(i.signal?.aborted&&m();x.size>0&&!a;){let p=[...x.keys()],I=p.filter(P=>!E(P,p));if(I.length===0){let P=y??=Ae(e);I=p.filter($=>!E($,p,P));}I.length===0&&(I=p);let w=[];for(let P of I){let $=x.get(P);x.delete(P),(b.get(P)??0)>=e.maxNodeVisits?g(P,$,"maxNodeVisits"):l>=e.maxRuns?g(P,$,"maxRuns"):w.push(d(P,$));}w.length!==0&&(await Promise.race([Promise.all(w),h]),v++);}a&&await h;}catch(p){if(a!=="aborted"||(f({type:"pipeline.finished",stoppedBy:"aborted",runs:l}),s==="reject"))throw p;return k("aborted")}finally{i.signal?.removeEventListener("abort",m);}let N=c.has("maxRuns")?"maxRuns":c.has("maxNodeVisits")?"maxNodeVisits":void 0;return f({type:"pipeline.finished",...N?{stoppedBy:N}:{},runs:l}),k(N)},"runPipelineGraph");export{C as PIPELINE_LIMITS,Se as PIPELINE_ROUTER_SYSTEM,Y as PipelineNodeError,X as PipelineValidationError,Oe as matchPipelineRoute,ke as normalizePipeline,je as preparePipeline,Re as renderPipelineNodeInput,Ce as renderPipelineRoutePrompt,Ve as runPipelineGraph,Pe as testPipelineCondition,Ee as validatePipeline};
|