@graphrefly/graphrefly 0.39.0 → 0.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{cascading-g2_rhhaM.d.ts → cascading-BNfxffgc.d.ts} +1 -1
- package/dist/{cascading-BzuxW0_w.d.cts → cascading-Cxs1eztH.d.cts} +1 -1
- package/dist/chunk-2W553JJC.js +1 -0
- package/dist/{chunk-5LK7XMEV.js → chunk-33N4TU3X.js} +1 -1
- package/dist/chunk-4MKL6Q3K.js +1 -0
- package/dist/chunk-5B3JDG5F.js +1 -0
- package/dist/chunk-5QSXEMXG.js +1 -0
- package/dist/{chunk-R75BMDLA.js → chunk-5TEFC2ZX.js} +1 -1
- package/dist/chunk-5TOPVRN6.js +1 -0
- package/dist/{chunk-INHC33EH.js → chunk-5VEZLQFN.js} +1 -1
- package/dist/{chunk-NQI2C36M.js → chunk-7PQLZMOG.js} +1 -1
- package/dist/{chunk-7NZMZJMW.js → chunk-AI7QC7J6.js} +1 -1
- package/dist/{chunk-L7WY6TZS.js → chunk-AK5RHMC5.js} +1 -1
- package/dist/{chunk-ZOX3LBRV.js → chunk-CGNOWGV6.js} +1 -1
- package/dist/{chunk-INH6FS2G.js → chunk-CYOSWFT2.js} +1 -1
- package/dist/{chunk-GX5LSSRE.js → chunk-EC2WNSZ7.js} +1 -1
- package/dist/{chunk-HAWKGIXM.js → chunk-ELAASRBT.js} +1 -1
- package/dist/{chunk-7QFRK3N3.js → chunk-F7VUYPP6.js} +1 -1
- package/dist/{chunk-LQNOXGET.js → chunk-G3M3IMEV.js} +1 -1
- package/dist/{chunk-HX3EGQ5Z.js → chunk-GI4Q7PNY.js} +1 -1
- package/dist/{chunk-XQ55HO5N.js → chunk-H5SCWHWP.js} +1 -1
- package/dist/{chunk-CGDMTXSY.js → chunk-KNVCCBIU.js} +1 -1
- package/dist/{chunk-IA7DUNGB.js → chunk-L77I47VU.js} +1 -1
- package/dist/{chunk-JNMC2WJ6.js → chunk-M3FQSXEW.js} +1 -1
- package/dist/{chunk-D47YVDR5.js → chunk-OLIKJUKI.js} +1 -1
- package/dist/{chunk-SC7BQDNP.js → chunk-OV5AA6HJ.js} +1 -1
- package/dist/{chunk-7JRF5YEK.js → chunk-POXANAJ6.js} +1 -1
- package/dist/chunk-RSMEXK53.js +43 -0
- package/dist/{chunk-KD4NHLMU.js → chunk-SC27WTSG.js} +1 -1
- package/dist/chunk-TSOYJ743.js +1 -0
- package/dist/{chunk-AU7YTQX7.js → chunk-TT4C7DXW.js} +1 -1
- package/dist/{chunk-TFPZLQ5H.js → chunk-UISPDFJ3.js} +1 -1
- package/dist/{chunk-N7UIBZCW.js → chunk-URJ2VFNC.js} +1 -1
- package/dist/{chunk-GEAO3TL3.js → chunk-VV62MIG4.js} +1 -1
- package/dist/{chunk-VJJLIEAL.js → chunk-VXPLLA4P.js} +1 -1
- package/dist/{chunk-WHIZM6JV.js → chunk-WZYB3JQS.js} +1 -1
- package/dist/{chunk-S2U57TFC.js → chunk-X7QKTXXC.js} +1 -1
- package/dist/{chunk-7SD73DS6.js → chunk-YQRN4CIV.js} +1 -1
- package/dist/chunk-Z6X7B6A4.js +61 -0
- package/dist/{chunk-RF3QZP6D.js → chunk-ZAJ7J7TO.js} +1 -1
- package/dist/compat/index.d.cts +6 -6
- package/dist/compat/index.d.ts +6 -6
- package/dist/compat/index.js +1 -1
- package/dist/compat/nestjs/index.d.cts +4 -4
- package/dist/compat/nestjs/index.d.ts +4 -4
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/zustand/index.d.cts +2 -2
- package/dist/compat/zustand/index.d.ts +2 -2
- package/dist/compat/zustand/index.js +1 -1
- package/dist/{composite-DGatA-JK.d.ts → decay-BnrlbxSv.d.ts} +38 -2
- package/dist/{composite-CKd0e2vz.d.cts → decay-C25AyNAj.d.cts} +38 -2
- package/dist/extra/index.cjs +15 -15
- package/dist/extra/index.d.cts +6 -6
- package/dist/extra/index.d.ts +6 -6
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.js +1 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.d.cts +1 -1
- package/dist/extra/reactive.d.ts +1 -1
- package/dist/extra/reactive.js +1 -1
- package/dist/extra/render/index.d.cts +1 -1
- package/dist/extra/render/index.d.ts +1 -1
- package/dist/extra/sources.cjs +1 -1
- package/dist/extra/sources.js +1 -1
- package/dist/graph/index.d.cts +3 -3
- package/dist/graph/index.d.ts +3 -3
- package/dist/graph/index.js +1 -1
- package/dist/{graph-30XSgtVX.d.ts → graph-BkIkog4h.d.ts} +1 -1
- package/dist/{graph-BUwMAxJI.d.cts → graph-E6likq7w.d.cts} +1 -1
- package/dist/{index-BXd6OMEy.d.ts → index-3k4Gg6-n.d.ts} +2 -2
- package/dist/{index-DszPlZzK.d.ts → index-40ZT4MHj.d.ts} +1 -1
- package/dist/index-8s-Qm-gz.d.ts +218 -0
- package/dist/{index-K-vl_c6A.d.cts → index-A3U3CSve.d.cts} +1 -1
- package/dist/{index-jKLph6cu.d.ts → index-B6iTqKtJ.d.ts} +1 -1
- package/dist/{index-WyFKER-c.d.ts → index-B72TQQHd.d.cts} +3 -3
- package/dist/{index-CmqiJZKM.d.ts → index-BAQrjuZF.d.ts} +64 -6
- package/dist/{index-CusEP3Sv.d.ts → index-BQ1fR4li.d.ts} +1 -1
- package/dist/{index-jr6PuSBt.d.ts → index-BaA-xpSw.d.ts} +2 -2
- package/dist/{index-FVoPvhAu.d.cts → index-Bd91Nmf4.d.cts} +2 -2
- package/dist/{index-PqbnoScQ.d.ts → index-BgjS2b8N.d.ts} +2 -2
- package/dist/{index-DCbE8fFM.d.cts → index-BiHUBEKq.d.cts} +2 -2
- package/dist/{index-DlgHqQxW.d.cts → index-BilOa6AE.d.cts} +6 -32
- package/dist/{index-DoYc8BWK.d.cts → index-BmSQLAZo.d.cts} +2 -2
- package/dist/{index-DlrWu9Hs.d.cts → index-C-dkXOpB.d.cts} +1 -1
- package/dist/{index-C7VV_qOs.d.ts → index-C5cQ7Gfx.d.ts} +2 -2
- package/dist/{index-CPhBvRJU.d.ts → index-C6ZUaos7.d.ts} +1 -1
- package/dist/{index-PlJ3MraE.d.ts → index-CAP3UGsq.d.ts} +1 -1
- package/dist/{index-B41Asm7D.d.ts → index-CD2dBMet.d.ts} +2 -2
- package/dist/{index-C19qqa38.d.ts → index-CG33HeBW.d.ts} +19 -4
- package/dist/index-CGhMJNHb.d.cts +128 -0
- package/dist/{index-BAlaVimV.d.ts → index-CQtWm7jS.d.ts} +2 -2
- package/dist/{index-8R1vzNOx.d.cts → index-CRm0YIzC.d.cts} +2 -2
- package/dist/index-CUIkE1l9.d.cts +230 -0
- package/dist/{index-KlZ_ZUip.d.cts → index-Cczxgd2D.d.ts} +3 -3
- package/dist/{index-DIHcMLr6.d.cts → index-CgnCFhr2.d.cts} +1 -1
- package/dist/{index-BC9VybQs.d.ts → index-Ck35nA-T.d.ts} +2 -2
- package/dist/{index-BndG0cpK.d.cts → index-Cnr1WrlX.d.cts} +1 -1
- package/dist/{index-H_I66pav.d.cts → index-CtFNGe-m.d.cts} +2 -2
- package/dist/index-CuPUehFa.d.cts +218 -0
- package/dist/index-D1Gc7wV5.d.ts +230 -0
- package/dist/{index-CWHtYmSh.d.cts → index-D4uimgee.d.cts} +1 -1
- package/dist/{index-xZYcDqFH.d.cts → index-DGD4_fj6.d.cts} +19 -4
- package/dist/{index-CwP_KAMS.d.cts → index-DGTo1yka.d.cts} +64 -6
- package/dist/{index-BUPVld1w.d.ts → index-DH4fm2Ck.d.ts} +2 -2
- package/dist/{index-DyM4tFAe.d.cts → index-DQQCOIt8.d.cts} +2 -2
- package/dist/{index-BJ26eEjs.d.cts → index-DVAlsmEU.d.cts} +2 -2
- package/dist/{index-DINuaZlJ.d.cts → index-DVDapw2k.d.cts} +1 -1
- package/dist/{index-iTX5IqSP.d.ts → index-DfOK_oL5.d.ts} +208 -203
- package/dist/{index-DTtBpuQy.d.cts → index-DgJc8Zgc.d.cts} +5 -3
- package/dist/{index-BKMdnYnk.d.ts → index-DhLyOHYZ.d.ts} +1 -1
- package/dist/{index-89FczVZ_.d.ts → index-DhnsQfa3.d.ts} +77 -51
- package/dist/{index-L8XI8Zql.d.cts → index-DktLSZOc.d.cts} +2 -2
- package/dist/{index-pVDQcbar.d.cts → index-DpiGqtrs.d.cts} +77 -51
- package/dist/{index-mNwgxC21.d.cts → index-DuRsN9ae.d.cts} +208 -203
- package/dist/{index-B9fmw5n2.d.ts → index-I1cCY3ZI.d.ts} +5 -3
- package/dist/index-N2MAxt7_.d.ts +128 -0
- package/dist/{index-Br3WnqEn.d.ts → index-WSlcjhQF.d.ts} +6 -32
- package/dist/{index-DQUVq1_d.d.ts → index-bXXLSvor.d.ts} +2 -2
- package/dist/{index-BhUaMYm_.d.ts → index-da2V5vPy.d.ts} +1 -1
- package/dist/{index-PsVHpPwP.d.cts → index-t6L2qpHh.d.cts} +2 -2
- package/dist/{index-IwFqHxCs.d.cts → index-tV3AA9hI.d.cts} +1 -1
- package/dist/index.cjs +48 -48
- package/dist/index.d.cts +33 -33
- package/dist/index.d.ts +33 -33
- package/dist/index.js +1 -1
- package/dist/patterns/ai/browser.cjs +5 -5
- package/dist/patterns/ai/browser.d.cts +2 -2
- package/dist/patterns/ai/browser.d.ts +2 -2
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +14 -14
- package/dist/patterns/ai/index.d.cts +11 -11
- package/dist/patterns/ai/index.d.ts +11 -11
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/audit/index.d.cts +3 -3
- package/dist/patterns/audit/index.d.ts +3 -3
- package/dist/patterns/audit/index.js +1 -1
- package/dist/patterns/cqrs/index.d.cts +3 -3
- package/dist/patterns/cqrs/index.d.ts +3 -3
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.d.cts +3 -3
- package/dist/patterns/demo-shell/index.d.ts +3 -3
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.d.cts +2 -2
- package/dist/patterns/domain-templates/index.d.ts +2 -2
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.d.cts +2 -2
- package/dist/patterns/graphspec/index.d.ts +2 -2
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +3 -3
- package/dist/patterns/guarded-execution/index.d.cts +4 -4
- package/dist/patterns/guarded-execution/index.d.ts +4 -4
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +8 -8
- package/dist/patterns/harness/index.d.cts +7 -7
- package/dist/patterns/harness/index.d.ts +7 -7
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +3 -3
- package/dist/patterns/job-queue/index.d.cts +3 -3
- package/dist/patterns/job-queue/index.d.ts +3 -3
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +3 -3
- package/dist/patterns/lens/index.d.cts +3 -4
- package/dist/patterns/lens/index.d.ts +3 -4
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +1 -1
- package/dist/patterns/memory/index.d.cts +3 -3
- package/dist/patterns/memory/index.d.ts +3 -3
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.d.cts +2 -2
- package/dist/patterns/messaging/index.d.ts +2 -2
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.d.cts +3 -3
- package/dist/patterns/orchestration/index.d.ts +3 -3
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/process/index.d.cts +4 -4
- package/dist/patterns/process/index.d.ts +4 -4
- package/dist/patterns/process/index.js +1 -1
- package/dist/patterns/reactive-layout/index.d.cts +3 -3
- package/dist/patterns/reactive-layout/index.d.ts +3 -3
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.d.cts +2 -2
- package/dist/patterns/reduction/index.d.ts +2 -2
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.d.cts +3 -3
- package/dist/patterns/refine-loop/index.d.ts +3 -3
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +3 -1
- package/dist/patterns/resilient-pipeline/index.d.cts +7 -3
- package/dist/patterns/resilient-pipeline/index.d.ts +7 -3
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.d.cts +3 -3
- package/dist/patterns/surface/index.d.ts +3 -3
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{pipeline-graph-D8vKcO_p.d.ts → pipeline-graph-CB4La-UW.d.ts} +2 -2
- package/dist/{pipeline-graph-BQPr2Lqs.d.cts → pipeline-graph-MWrQZXCq.d.cts} +2 -2
- package/dist/{reactive-layout-8CSc0tiA.d.cts → reactive-layout-BtZfUKuL.d.cts} +1 -1
- package/dist/{reactive-layout-DkTXxtSy.d.ts → reactive-layout-KJj4E2dT.d.ts} +1 -1
- package/dist/{reactive-map-B2qfD3hb.d.cts → reactive-map-6P_k3AQM.d.cts} +1 -1
- package/dist/{reactive-map-jFIsE6Kt.d.ts → reactive-map-CjXByDV-.d.ts} +1 -1
- package/dist/{resilience-HTF2LBRS.js → resilience-JISHQD2F.js} +1 -1
- package/dist/{topology-tree-B5Ngw3j0.d.cts → topology-tree-3LBKFsUo.d.cts} +1 -1
- package/dist/{topology-tree-BtvbgMXJ.d.ts → topology-tree-mF7Emqzm.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-5XRI6RM3.js +0 -1
- package/dist/chunk-73PBQNST.js +0 -1
- package/dist/chunk-A6ZSKGUG.js +0 -1
- package/dist/chunk-EWF7KCDJ.js +0 -61
- package/dist/chunk-IUB4NYI2.js +0 -1
- package/dist/chunk-MC4UYY2X.js +0 -1
- package/dist/chunk-XEUANKBO.js +0 -43
- package/dist/chunk-ZJ7SM3G2.js +0 -1
- package/dist/index-BEHmxORq.d.ts +0 -135
- package/dist/index-BM9szD8n.d.cts +0 -113
- package/dist/index-BskfDoZ_.d.ts +0 -113
- package/dist/index-CIRG8Hxp.d.cts +0 -135
- package/dist/index-Cey6VTnX.d.ts +0 -166
- package/dist/index-CpLpJb6A.d.cts +0 -166
package/dist/chunk-5XRI6RM3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as Q,h as I}from"./chunk-VJJLIEAL.js";import{a as C}from"./chunk-L6NSJVJZ.js";import{i as P}from"./chunk-7JRF5YEK.js";import{b as M}from"./chunk-35JTVPOX.js";import{b as W}from"./chunk-KGKJCHEK.js";import{b as G}from"./chunk-TZQPPQEQ.js";import{b as D}from"./chunk-AU7YTQX7.js";import{C as v,m as L}from"./chunk-IA7DUNGB.js";import{D as x,G as F,m as _,p as m}from"./chunk-LYCLF26R.js";import{b as N,j as $}from"./chunk-CK2E7BTU.js";import{b as X}from"./chunk-QYADASLV.js";var te={};X(te,{JobFlowGraph:()=>w,JobQueueGraph:()=>y,jobEventKeyOf:()=>Z,jobFlow:()=>ee,jobQueue:()=>B});var H=256,Y=1024;function z(i,e){if(!Number.isFinite(i)||!Number.isInteger(i)||i<0)throw new Error(`${e} must be a non-negative integer`);return i}function T(i,e){return C("job_queue",i,e)}var Z=i=>i.action,y=class extends P{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,t={}){super(e,t.graph),this._pending=W([],{name:"pending"}),this._jobs=G({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=F([this.pending],([o])=>o.length,{name:"depth",describeKind:"derived",meta:T("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(v(this.depth)),this.events=Q({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=I(this,"seq",0)}_bumpSeq(){let t=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(t),t}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,t={}){let o=this._bumpSeq(),n=t.id??`${this.name}-${o}`;if(this._jobs.get(n)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${n}"`);let d={id:n,payload:e,attempts:0,metadata:Object.freeze({...t.metadata??{}}),state:"queued"};return this._jobs.set(n,d),this._pending.append(n),this.events.append({action:"enqueue",id:n,payload:e,t_ns:m(),seq:o}),n}claim(e=1){let t=z(e,"job queue claim limit");if(t===0)return[];let o=[];for(;o.length<t&&this.pending.cache.length!==0;){let d=this._pending.pop(0),h=this._jobs.get(d);if(!h||h.state!=="queued")continue;let c={...h,state:"inflight",attempts:h.attempts+1};this._jobs.set(d,c),o.push(c),this.events.append({action:"claim",id:d,attempts:c.attempts,t_ns:m(),seq:this._bumpSeq()})}return o}ack(e){let t=this._jobs.get(e);return!t||t.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:t.attempts,t_ns:m(),seq:this._bumpSeq()}),!0)}nack(e,t={}){let o=this._jobs.get(e);return!o||o.state!=="inflight"?!1:t.requeue??!0?(this._jobs.set(e,{...o,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:o.attempts,t_ns:m(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:o.attempts,t_ns:m(),seq:this._bumpSeq()}),!0)}removeById(e){let t=this._jobs.get(e);if(!t)return!1;if(t.state==="queued"){let n=this.pending.cache.indexOf(e);n>=0&&this._pending.pop(n)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:t.attempts,t_ns:m(),seq:this._bumpSeq()}),!0}consumeFrom(e,t){return e.subscribe(o=>{for(let n of o){if(n[0]!==N)continue;let d=n[1];this.enqueue(d,t?{metadata:t.metadata}:void 0)}})}},w=class extends P{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,t={}){super(e,t.graph);let o=t.stages??["incoming","processing","done"],n=[],d=new Map;for(let s of o){let r=typeof s=="string"?s.trim():s.name.trim();typeof s!="string"&&s.work&&d.set(r,s.work),n.push(r)}if(n.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(n).size!==n.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...n]),this._stageWorkFns=d;for(let s of this._stageNames){let r=B(`${e}-${s}`);this._queues.set(s,r),this.mount(s,r)}this._completed=D([],{name:"completed",maxSize:Y}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=F([this.completed],([s])=>s.length,{name:"completedCount",describeKind:"derived",meta:T("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(v(this.completedCount));let c=Math.max(1,z(t.maxPerPump??H,"job flow maxPerPump"));for(let s=0;s<this._stageNames.length;s+=1){let r=this._stageNames[s],p=this.queue(r),j=s+1<this._stageNames.length?this.queue(this._stageNames[s+1]):null,R=this._stageWorkFns.get(r),S=j===null;if(R){let g=x([p.pending],()=>{let l=0;for(;l<c;){let b=p.claim(1);if(b.length===0)break;let a=b[0];if(!a)break;let q=[...a.metadata.job_flow_path??[],r],f;try{f=R(a)}catch{p.nack(a.id,{requeue:!1}),l+=1;continue}let k=L(f),E=!1,u;u=k.subscribe(U=>{if(!E){for(let J of U)if(J[0]===N){E=!0,u?u():Promise.resolve().then(()=>u?.());let A=J[1],O={...a.metadata,job_flow_path:q};if(S){let V={...a,payload:A,metadata:Object.freeze(O)};_(()=>{p.ack(a.id),this._completed.append(V)})}else _(()=>{p.ack(a.id),j.enqueue(A,{metadata:O})});return}else if(J[0]===$){E=!0,u?u():Promise.resolve().then(()=>u?.()),p.nack(a.id,{requeue:!1});return}}}),l+=1}},{name:`pump_${r}`,describeKind:"effect",meta:T("job_flow_pump",{stage:r,has_work:!0})});this.add(g,{name:`pump_${r}`}),this.addDisposer(v(g))}else{let g=x([p.pending],()=>{let l=0;for(;l<c;){let b=p.claim(1);if(b.length===0)break;let a=b[0];if(!a)break;let q=[...a.metadata.job_flow_path??[],r],f={...a.metadata,job_flow_path:q};if(S){let k={...a,metadata:Object.freeze(f)};_(()=>{p.ack(a.id),this._completed.append(k)})}else _(()=>{p.ack(a.id),j.enqueue(a.payload,{metadata:f})});l+=1}},{name:`pump_${r}`,describeKind:"effect",meta:T("job_flow_pump",{stage:r,has_work:!1})});this.add(g,{name:`pump_${r}`}),this.addDisposer(v(g))}}}stages(){return this._stageNames}queue(e){let t=this._queues.get(e);if(!t)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return t}enqueue(e,t={}){return this.queue(this._stageNames[0]).enqueue(e,t)}retainedCompleted(){return this.completed.cache}};function B(i,e){return new y(i,e)}function ee(i,e){let t=new w(i,e),{factory:o,factoryArgs:n,...d}=e??{};return t.tagFactory("jobFlow",M(d)),t}export{Z as a,y as b,w as c,B as d,ee as e,te as f};
|
package/dist/chunk-73PBQNST.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as w}from"./chunk-R75BMDLA.js";import{a as O}from"./chunk-L6NSJVJZ.js";import{i as R,k as S}from"./chunk-7JRF5YEK.js";import{b as _}from"./chunk-TZQPPQEQ.js";import{C as T}from"./chunk-IA7DUNGB.js";import{E as k,G as x,o as H}from"./chunk-LYCLF26R.js";import{b as M}from"./chunk-QYADASLV.js";var N={};M(N,{LensGraph:()=>C,graphLens:()=>L,watchTopologyTree:()=>w});function v(e){return O("lens",e)}function P(e){let t=Object.keys(e.nodes),o=new Map,n=new Map;for(let s of t){let a=e.nodes[s]?.deps??[];o.set(s,a);for(let h of a)n.has(h)||n.set(h,new Set),n.get(h).add(s)}let r=[],c=[];for(let s of t)(o.get(s)??[]).length===0&&r.push(s),n.has(s)||c.push(s);r.sort(),c.sort();let p=e.edges.length,f=0,m=1,g=2,d=new Map;for(let s of t)d.set(s,f);let y=!1,l=new Map,u=s=>{let a=d.get(s)??f;if(a===m)return y=!0,0;if(a===g)return l.get(s)??0;d.set(s,m);let h=0,b=n.get(s);if(b!=null)for(let F of b){let G=u(F);G+1>h&&(h=G+1)}return d.set(s,g),l.set(s,h),h},i=0;for(let s of r){let a=u(s);a>i&&(i=a)}for(let s of t)d.get(s)===f&&u(s);return{nodeCount:t.length,edgeCount:p,subgraphCount:e.subgraphs.length,sources:r,sinks:c,depth:i,hasCycles:y}}function $(e){let t=[];for(let[o,n]of Object.entries(e.nodes)){if(n.status!=="errored")continue;let r={path:o,status:"errored"},c=S(e,o,"upstream",{});for(let p of c)if(p!==o&&e.nodes[p]?.status==="errored"){r.upstreamCause=p;break}t.push(r)}return t.sort((o,n)=>o.path<n.path?-1:o.path>n.path?1:0),{ok:t.length===0,problems:t}}function E(e,t){return e.nodeCount===t.nodeCount&&e.edgeCount===t.edgeCount&&e.subgraphCount===t.subgraphCount&&e.depth===t.depth&&e.hasCycles===t.hasCycles&&D(e.sources,t.sources)&&D(e.sinks,t.sinks)}function q(e,t){if(e.ok!==t.ok||e.problems.length!==t.problems.length)return!1;for(let o=0;o<e.problems.length;o++){let n=e.problems[o],r=t.problems[o];if(n.path!==r.path||n.status!==r.status||n.upstreamCause!==r.upstreamCause)return!1}return!0}function D(e,t){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(e[o]!==t[o])return!1;return!0}var C=class extends R{stats;health;flow;_target;constructor(t,o={}){super(o.name??`${t.name}_lens`,o.graph),this._target=t;let n=0,r=0,c=k(0,{name:"stats_tick"}),p=k(0,{name:"health_tick"});this.add(c,{name:"stats_tick"}),this.add(p,{name:"health_tick"});let f={name:"flow"};o.maxFlowPaths!=null&&(f.maxSize=o.maxFlowPaths),this.flow=_(f),this.add(this.flow.entries,{name:"flow"});let m=o.pathFilter,g=w(t,(l,u,i)=>{if(n+=1,c.emit(n),r+=1,p.emit(r),l.kind==="removed")if(l.nodeKind==="node"){let s=`${i}${l.name}`;this.flow.delete(s)}else{let s=`${i}${l.name}::`,a=[];for(let h of l.audit.nodes){let b=h===""?`${i}${l.name}`:`${s}${h}`;a.push(b)}a.length>0&&this.flow.deleteMany(a)}});this.addDisposer(g);let d=t.observe({timeline:!0,structured:!0}),y=d.onEvent(l=>{let u=l.type;if((u==="error"||u==="complete"||u==="data"||u==="teardown")&&(r+=1,p.emit(r)),u==="data"){let i=l.path??"";if(!i||m!=null&&!m(i))return;let s=this.flow.get(i),a=s!=null?s.count+1:1;this.flow.set(i,{path:i,count:a,lastUpdate_ns:H()})}});this.addDisposer(()=>{y(),d.dispose()}),this.stats=x([c],()=>P(t.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:E,meta:v("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(T(this.stats)),this.health=x([p],()=>$(t.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:q,meta:v("health")}),this.add(this.health,{name:"health"}),this.addDisposer(T(this.health))}why(t,o,n){let r=this._target.explain(t,o,{reactive:!0,...n});return this.addDisposer(r.dispose),r}get target(){return this._target}};function L(e,t){return new C(e,t)}export{C as a,L as b,N as c};
|
package/dist/chunk-A6ZSKGUG.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as n}from"./chunk-GX5LSSRE.js";import{i as a}from"./chunk-7JRF5YEK.js";import{b as c}from"./chunk-QYADASLV.js";var s={};c(s,{GuardedExecutionGraph:()=>o,guardedExecution:()=>p});var o=class extends a{enforcer;violations;_target;_defaultActor;constructor(r,e){super(e.name??`${r.name}_guarded`,e.graph),this._target=r,this._defaultActor=e.actor;let t={mode:e.mode??"enforce",name:"enforcer"};e.violationsLimit!=null&&(t.violationsLimit=e.violationsLimit),this.enforcer=n(r,e.policies,t),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(r){let e=r?.actor??this._defaultActor,t={...r,...e!=null?{actor:e}:{}};return this._target.describe(t)}get target(){return this._target}};function p(i,r){return new o(i,r)}export{o as a,p as b,s as c};
|
package/dist/chunk-EWF7KCDJ.js
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import{h as Lt}from"./chunk-7QFRK3N3.js";import{a as kt,b as xt,c as Rt,d as wt}from"./chunk-HX3EGQ5Z.js";import{c as vt}from"./chunk-NQI2C36M.js";import{a as zt,b as Zt,c as er,d as tr,e as rr,f as Be,g as nr}from"./chunk-GEAO3TL3.js";import{a as Ge,b as V,c as Le,d as de,e as X,f as U,g as Yt,h as Fe,i as Jt,j as Qt,k as Xt}from"./chunk-TFPZLQ5H.js";import{f as $e}from"./chunk-N7UIBZCW.js";import{b as Tt}from"./chunk-WHIZM6JV.js";import{a as Mt}from"./chunk-ZJ7SM3G2.js";import{b as ut,c as Re,d as mt,f as _e}from"./chunk-IUB4NYI2.js";import{a as dt}from"./chunk-L6NSJVJZ.js";import{i as se}from"./chunk-7JRF5YEK.js";import{a as Q}from"./chunk-ESMPEKEV.js";import{R as bt,b as yt,s as ht,x as $}from"./chunk-L7WY6TZS.js";import{b as xe,c as J}from"./chunk-35JTVPOX.js";import{b as we}from"./chunk-TZQPPQEQ.js";import{b as pe}from"./chunk-AU7YTQX7.js";import{A as gt,C as _,f as ct,k as je,l as pt,m as L,x as ae,z as ft}from"./chunk-IA7DUNGB.js";import{D as le,E as w,F as oe,G as v,H as te,m as Y,o as q,p as Te}from"./chunk-LYCLF26R.js";import{b as B,d as ce,i as ee,j as W}from"./chunk-CK2E7BTU.js";import{b as Ht}from"./chunk-QYADASLV.js";var en={};Ht(en,{AgentLoopGraph:()=>Pe,AllTiersExhaustedError:()=>rr,BudgetExhaustedError:()=>Ce,ChatStreamGraph:()=>Oe,CircuitOpenError:()=>Re,DEFAULT_DECAY_RATE:()=>ot,FallbackMissError:()=>Qt,LLMTimeoutError:()=>ge,ReplayCacheMissError:()=>Yt,ToolRegistryGraph:()=>De,admissionFilter3D:()=>Vr,admissionScored:()=>Ft,agentLoop:()=>$r,agentMemory:()=>qr,anthropicAdapter:()=>zt,canonicalJson:()=>Jt,cascadingLlmAdapter:()=>Be,chatStream:()=>Ze,composePricing:()=>dr,computePrice:()=>We,contentGate:()=>jr,costMeterExtractor:()=>Er,createAdapter:()=>tr,createCapabilitiesRegistry:()=>or,createPricingRegistry:()=>ir,dryRunAdapter:()=>Ge,fallbackAdapter:()=>Xt,frozenContext:()=>wr,gatedStream:()=>Ar,gaugesAsContext:()=>Hr,googleAdapter:()=>Zt,graphFromSpec:()=>Wt,graphFromSpecReactive:()=>zr,handoff:()=>Wr,keywordFlagExtractor:()=>Or,knobsAsTools:()=>Jr,llmConsolidator:()=>nt,llmExtractor:()=>rt,memoryRetrieval:()=>lt,memoryWithKG:()=>st,memoryWithTiers:()=>it,memoryWithVectors:()=>at,observableAdapter:()=>ar,openAICompatAdapter:()=>er,parseRateLimitFromError:()=>qe,pricingFor:()=>ur,promptNode:()=>Xe,redactor:()=>Gr,registryPricing:()=>lr,resilientAdapter:()=>vr,streamExtractor:()=>Dr,streamingPromptNode:()=>Nr,suggestStrategy:()=>Kt,suggestStrategyReactive:()=>Xr,systemPromptBuilder:()=>Cr,tier:()=>nr,toolCallExtractor:()=>_r,toolExecution:()=>et,toolRegistry:()=>tt,toolSelector:()=>Kr,validateGraphDef:()=>Zr,withBreaker:()=>Ke,withBudgetGate:()=>Ue,withDryRun:()=>cr,withRateLimiter:()=>ze,withReplayCache:()=>Fe,withRetry:()=>Ye,withTimeout:()=>Je,zeroPrice:()=>Ae});function Me(t,e){return`${t}::${e}`}function or(t){let e=we({name:"capabilitiesRegistry"}),r=i=>{e.set(Me(i.provider,i.id),i)};if(t)for(let i of t)r(i);let n=(i,d)=>{let m=e.get(Me(i,d));if(m)return m;let c=e.entries.cache;if(!c)return;let p;for(let[,g]of c){if(g.provider!==i)continue;let y=g.id;d.startsWith(y)&&(!p||y.length>p.id.length)&&(p=g)}return p},o=128,a=new Map,s=new Map,l=(i,d,m,c)=>{for(i.has(d)&&i.delete(d),i.set(d,m);i.size>c;){let p=i.keys().next().value;if(p===void 0)break;i.delete(p)}},u=v([e.entries],([i])=>Array.from(i.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:r,lookup:n,remove(i,d){let m=e.has(Me(i,d));return m&&e.delete(Me(i,d)),m},entries(){let i=e.entries.cache;return(function*(){if(i)for(let d of i.values())yield d})()},lookupNode(i,d){let m=Me(i,d),c=a.get(m);if(c)return a.delete(m),a.set(m,c),c;let p=v([e.entries],()=>n(i,d),{name:`capabilitiesRegistry/lookup/${i}::${d}`,initial:void 0});return l(a,m,p,o),p},entriesNode:u,byProvider(i){let d=s.get(i);if(d)return s.delete(i),s.set(i,d),d;let m=v([u],([c])=>c.filter(p=>p.provider===i),{name:`capabilitiesRegistry/byProvider/${i}`,initial:[]});return l(s,i,m,o),m}}}function H(t){let e=t.input,r=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return r;let n=0;for(let o of Object.values(e.extensions))n+=o;return r+n}function re(t){let e=t.output,r=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return r;let n=0;for(let o of Object.values(e.extensions))n+=o;return r+n}function Nt(){return{input:{regular:0},output:{regular:0}}}function ar(t,e){let r=e?.logMax??1e3,n=pe(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:r}),o=w(null,{name:"adapterStats/lastCall"}),a=v([n.entries],([y])=>y.length,{name:"adapterStats/totalCalls",initial:0}),s=v([n.entries],([y])=>y.reduce((f,h)=>f+H(h.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),l=v([n.entries],([y])=>y.reduce((f,h)=>f+re(h.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[_(a),_(s),_(l)],i=y=>{n.append(y),o.emit(y)},d=()=>{n.clear(),o.emit(null)},m=V(t,{invoke(y,f){let h=q(),b=Te(),k=t.model??f?.model??"",x=A=>(i(de({provider:t.provider,model:t.model??f?.model??A.model??"",tier:f?.tier??A.tier,usage:A.usage??X(),startNs:h,startWallClockNs:b,method:"invoke"})),A),C=A=>{let D=A;i(de({provider:t.provider,model:k,tier:f?.tier,usage:X(),startNs:h,startWallClockNs:b,method:"invoke",error:{type:D?.name??"Error",message:D?.message??String(A)}}))};return Le(t.invoke(y,f),{onResp:x,onError:C,name:"adapterStats/invokeTap"})},async*stream(y,f){let h=q(),b=Te(),k=t.model??f?.model??"",x;try{for await(let C of t.stream(y,f))C.type==="usage"&&(x=C.usage),yield C;i(de({provider:t.provider,model:k,tier:f?.tier,usage:x??X(),startNs:h,startWallClockNs:b,method:"stream"}))}catch(C){let A=C;throw i(de({provider:t.provider,model:k,tier:f?.tier,usage:x??X(),startNs:h,startWallClockNs:b,method:"stream",error:{type:A?.name??"Error",message:A?.message??String(C)}})),C}}});U(m,"observableAdapter",t);let c=!1;return{adapter:m,stats:{lastCall:o,allCalls:n,totalCalls:a,totalInputTokens:s,totalOutputTokens:l,reset:d,dispose:()=>{if(!c){c=!0;for(let y of u)y();u.length=0}}}}}function sr(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Ae(t="USD"){return{total:0,currency:t}}function We(t,e,r){let n=H(t),o=e.currency??"USD",a=r?.withBreakdown===!0,s=a?{}:null,l=0,u=(f,h,b)=>{if(!h||b==null)return;let k=sr(b,n),x=h*k/1e6;l+=x,a&&(s[f]=(s[f]??0)+x)},i=t.input,d=e.input;if(d&&(u("input.regular",i.regular,d.regular),u("input.cacheRead",i.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",i.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",i.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",i.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",i.audio??0,d.audio),u("input.image",i.image??0,d.image),u("input.video",i.video??0,d.video),u("input.toolUse",i.toolUse??0,d.toolUse),i.extensions&&d.extensions))for(let[f,h]of Object.entries(i.extensions))u(`input.ext.${f}`,h,d.extensions[f]);let m=t.output,c=e.output;if(c&&(u("output.regular",m.regular,c.regular),u("output.reasoning",m.reasoning??0,c.reasoning),u("output.audio",m.audio??0,c.audio),u("output.predictionAccepted",m.predictionAccepted??0,c.predictionAccepted),u("output.predictionRejected",m.predictionRejected??0,c.predictionRejected),m.extensions&&c.extensions))for(let[f,h]of Object.entries(m.extensions))u(`output.ext.${f}`,h,c.extensions[f]);let p=r?.tier;if(p&&e.tierMultipliers){let f=e.tierMultipliers[p];if(f!=null&&(l*=f,a))for(let h of Object.keys(s))s[h]*=f}let g=t.auxiliary,y=e.auxiliary;if(g&&y)for(let[f,h]of Object.entries(g)){let b=y[f];if(b==null||!h)continue;let k=h*b;l+=k,a&&(s[`auxiliary.${f}`]=k)}return a?{total:l,currency:o,breakdown:s}:{total:l,currency:o}}function Ne(t,e){return`${t}::${e}`}function ir(t){let e=new Map,r=new Map,n=(o,a,s)=>{e.set(Ne(o,a),{provider:o,model:a,pricing:s});let l=r.get(o);l||(l=new Set,r.set(o,l)),l.add(a)};if(t)for(let[o,a,s]of t)n(o,a,s);return{register:n,lookup(o,a){let s=e.get(Ne(o,a));if(s)return s.pricing;let l=r.get(o);if(!l)return;let u;for(let i of l)if(a.startsWith(i)&&(!u||i.length>u.key.length)){let d=e.get(Ne(o,i));d&&(u={key:i,pricing:d.pricing})}return u?.pricing},remove(o,a){let s=e.delete(Ne(o,a));if(s){let l=r.get(o);l?.delete(a),l&&l.size===0&&r.delete(o)}return s},entries(){let o=e.values();return(function*(){for(let{provider:a,model:s,pricing:l}of o)yield[a,s,l]})()}}}function lr(t,e="USD"){return(r,n)=>{let o=t.lookup(n.provider,n.model);return o?We(r,o,{tier:n.tier,withBreakdown:n.withBreakdown}):Ae(e)}}function dr(...t){return(e,r)=>{for(let n of t){let o=n(e,r);if(o.total!==0)return o}return t.length>0?t[0](e,r):Ae()}}function ur(t,e,r){return t?.pricing?We(e,t.pricing,r):Ae()}function Ke(t,e={}){let r=e.breaker??mt(e),n=V(t,{async invoke(o,a){if(!r.canExecute())throw new Re;try{let s=await ae(L(t.invoke(o,a)));return r.recordSuccess(),s}catch(s){throw r.recordFailure(s),s}},async*stream(o,a){if(!r.canExecute())throw new Re;try{for await(let s of t.stream(o,a))yield s;r.recordSuccess()}catch(s){throw r.recordFailure(s),s}}});return U(n,"withBreaker",t),{adapter:n,breaker:r}}var Ce=class extends Error{constructor(r,n,o){super(`Budget exhausted: ${r} (limit=${n}, observed=${o})`);this.which=r;this.limit=n;this.observed=o}name="BudgetExhaustedError"},Ve=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),At=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Ue(t,e){let r=pe(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),n=w(At(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=v([n],([i])=>{let d=i;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(_(o),e.onExhausted!=null){let i=e.onExhausted,d=!1,m=!0;o.subscribe(c=>{for(let p of c)if(p[0]===B){let g=p[1];if(d&&m&&g===!1){let y=Ct(n.cache??Ve,e.caps);y&&i(y)}m=g,d=!0}})}let a=()=>{if(o.cache===!1){let i=n.cache??Ve,d=Ct(i,e.caps);return new Ce(d??"budget",e.caps[d??"calls"]??0,mr(i,d??"calls"))}},s=(i,d)=>{let m=t.provider,c=de({provider:m,model:d.model,tier:d.tier,usage:i,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});r.append(c);let p=n.cache??Ve,g=e.pricingFn?p.usd+e.pricingFn(i,{model:d.model,provider:m,tier:d.tier}).total:p.usd;n.emit({calls:p.calls+1,inputTokens:p.inputTokens+H(i),outputTokens:p.outputTokens+re(i),usd:g})},l=()=>{r.clear(),n.emit(At())},u=V(t,{invoke(i,d){let m=a();if(m)return Promise.reject(m);let c=q(),p=t.model??d?.model??"",g=f=>(s(f.usage??X(),{model:t.model??d?.model??f.model??"",tier:d?.tier??f.tier,startNs:c,method:"invoke"}),f),y=f=>{let h=f;s(X(),{model:p,tier:d?.tier,startNs:c,method:"invoke",error:{type:h?.name??"Error",message:h?.message??String(f)}})};return Le(t.invoke(i,d),{onResp:g,onError:y,name:"budgetGate/invokeTap"})},async*stream(i,d){let m=a();if(m)throw m;let c=q(),p;try{for await(let g of t.stream(i,d))g.type==="usage"&&(p=g.usage),yield g;s(p??X(),{model:t.model??d?.model??"",tier:d?.tier,startNs:c,method:"stream"})}catch(g){let y=g;throw s(p??X(),{model:t.model??d?.model??"",tier:d?.tier,startNs:c,method:"stream",error:{type:y?.name??"Error",message:y?.message??String(g)}}),g}}});return U(u,"withBudgetGate",t),{adapter:u,budget:{totals:n,isOpen:o,log:r,reset:l}}}function Ct(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function mr(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}function cr(t,e){let r=e.mock??Ge({provider:t.provider,model:t.model}),n=typeof e.enabled=="boolean"?e.enabled:void 0,o=n===void 0?L(e.enabled):void 0,a;o&&(a=_(o));let s=()=>n!==void 0?n:!!o?.cache,l=V(t,{invoke(i,d){return s()?r.invoke(i,d):t.invoke(i,d)},stream(i,d){return s()?r.stream(i,d):t.stream(i,d)}});return U(l,"withDryRun",t),{adapter:l,dispose:()=>{a&&(a(),a=void 0)}}}function qe(t){if(t==null||typeof t!="object")return;let e=t,r=e.status,n=pr(e.headers);if(r!==429&&r!==503&&!Tr(e.message))return;let o={},a=n("retry-after"),s=gr(a);s!=null&&(o.retryAfterMs=s);let l=n("anthropic-ratelimit-requests-reset");if(l){let p=St(l);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=n("anthropic-ratelimit-tokens-reset");if(u){let p=St(u);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let i=Se(n,"x-ratelimit-limit-requests");i!=null&&(o.rpmCap=i);let d=Se(n,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let m=Se(n,"x-ratelimit-remaining-requests"),c=Se(n,"x-ratelimit-remaining-tokens");if(m!=null&&i!=null&&i>0&&(o.usageHint??={},o.usageHint.rpm=1-m/i),c!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-c/d),o.retryAfterMs==null&&e.message){let p=hr(e.message);p!=null&&(o.retryAfterMs=p)}return e.headers&&(o.metadata={headers:fr(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function pr(t){if(!t)return()=>{};if(typeof t.get=="function"){let n=t;return o=>n.get(o)??n.get(o.toLowerCase())??void 0}let e=t,r={};for(let[n,o]of Object.entries(e)){let a=Array.isArray(o)?o.join(", "):o;a!=null&&(r[n.toLowerCase()]=a)}return n=>r[n.toLowerCase()]}function fr(t){let e={};if(typeof t.forEach=="function")return t.forEach((r,n)=>{e[n]=r}),e;for(let[r,n]of Object.entries(t))n!=null&&(e[r]=Array.isArray(n)?n.join(", "):n);return e}function Se(t,e){let r=t(e);if(r==null)return;let n=Number(r);return Number.isFinite(n)?n:void 0}function gr(t){if(!t)return;let e=t.trim(),r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;let n=Date.parse(e);if(Number.isFinite(n)){let o=n-Date.now();if(o>0)return o}}function St(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var yr=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function hr(t){let e=yr.exec(t);if(!e)return;let r=Number(e[1]);if(!Number.isFinite(r))return;let n=(e[2]??"s").toLowerCase();if(n==="ms")return r;if(n.startsWith("s"))return r*1e3;if(n.startsWith("m"))return r*6e4}var br=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Tr(t){return!!t&&br.test(t)}function He(t){let e=new Error(t);return e.name="AbortError",e}function It(t={}){let e=Math.max(1,t.burstMultiplier??1),r=t.clampCooldownMs??6e4,n=t.rpm!=null?L(t.rpm):w(Number.POSITIVE_INFINITY),o=t.tpm!=null?L(t.tpm):w(Number.POSITIVE_INFINITY),a=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),l=w({},{name:"adaptiveRateLimiter/lastSignal"}),u=v([n,a],([T,O])=>Math.min(Number(T??1/0),Number(O??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),i=v([o,s],([T,O])=>Math.min(Number(T??1/0),Number(O??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=fe(Number(n.cache??Number.POSITIVE_INFINITY),e),m=fe(Number(o.cache??Number.POSITIVE_INFINITY),e),c=!1,p=!1,g=u.subscribe(T=>{for(let O of T)if(O[0]===B){let P=Number(O[1]);Number.isFinite(P)&&P>0?(d=fe(P,e),c=!1):P===1/0?(d=fe(1/0,e),c=!1):P<=0&&(c=!0)}}),y=i.subscribe(T=>{for(let O of T)if(O[0]===B){let P=Number(O[1]);Number.isFinite(P)&&P>0?(m=fe(P,e),p=!1):P===1/0?(m=fe(1/0,e),p=!1):P<=0&&(p=!0)}}),f=0,h=new Q,b=new Q,k;t.adaptation!=null&&(k=L(t.adaptation).subscribe(O=>{for(let P of O)P[0]===B&&x(P[1])}));function x(T){if(l.emit(T),T.rpmCap!=null&&Number.isFinite(T.rpmCap)&&T.rpmCap>=0&&(a.emit(T.rpmCap),Number.isFinite(r)&&r>0&&h.start(r,()=>a.emit(Number.POSITIVE_INFINITY))),T.tpmCap!=null&&Number.isFinite(T.tpmCap)&&T.tpmCap>=0&&(s.emit(T.tpmCap),Number.isFinite(r)&&r>0&&b.start(r,()=>s.emit(Number.POSITIVE_INFINITY))),T.retryAfterMs!=null&&T.retryAfterMs>0){let O=q()+T.retryAfterMs*1e6;O>f&&(f=O)}}let C=w(0,{name:"adaptiveRateLimiter/pending"}),A=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),D=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),j=T=>{C.emit((C.cache??0)+T)},E=()=>{A.emit(d.available()),D.emit(m.available())};async function I(T={}){let O=T.requestCost??1,P=T.tokenCost??0,K=T.signal;j(1);try{for(;;){if(K?.aborted)throw He("AdaptiveRateLimiter.acquire aborted");let Z=q();if(f>Z){let M=Math.ceil((f-Z)/1e6);await Ee(M,K);continue}if(O>0&&c||P>0&&p){await Ee(250,K);continue}let ie=d,ue=m;if(!ie.tryConsume(O)){await Ee(Et(ie,O),K);continue}if(!(P>0?ue.tryConsume(P):!0)){ie.putBack(O),await Ee(Et(ue,P),K);continue}E();return}}finally{j(-1)}}function S(T){T>0?m.tryConsume(T):T<0&&m.putBack(-T),E()}function G(){g(),y(),k?.(),h.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:i,lastSignal:l,pending:C,rpmAvailable:A,tpmAvailable:D,acquire:I,recordUsage:S,recordSignal:x,dispose:G}}function fe(t,e){if(!Number.isFinite(t)||t===1/0)return _e(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),n=t/60;return _e(r,n)}function Et(t,e){let r=t.available(),n=Math.max(0,e-r);return n<=0?25:Math.min(5e3,Math.max(50,n*100))}function Ee(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(He("AdaptiveRateLimiter.acquire aborted")):new Promise((r,n)=>{let o=new Q,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(t,()=>{s(),r()}),e&&(a=()=>{s(),n(He("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function ze(t,e={}){let r=e.limiter??It({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),n=(s,l)=>e.costFn?e.costFn(s,l):0,o=s=>{let l=qe(s);l&&r.recordSignal(l)},a=V(t,{async invoke(s,l){let u=n(s,l);await r.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=await ae(L(t.invoke(s,l))),d=i.usage??Nt(),c=H(d)+re(d)-u;return c>0&&r.recordUsage(c),i}catch(i){throw o(i),i}},async*stream(s,l){let u=n(s,l);await r.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=0;for await(let m of t.stream(s,l))m.type==="usage"&&(i=H(m.usage)+re(m.usage)),yield m;let d=i-u;d>0&&r.recordUsage(d)}catch(i){throw o(i),i}}});return U(a,"withRateLimiter",t),{adapter:a,limiter:r}}function Ie(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Ot(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ie()):new Promise((r,n)=>{let o=new Q,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(t,()=>{s(),r()}),e&&(a=()=>{s(),n(Ie())},e.addEventListener("abort",a,{once:!0}))})}function Ye(t,e={}){let r=e.attempts??3,n=e.baseDelayMs??500,o=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,l=e.shouldRetry??Mr,u=e.retryStreaming??!0,i=(m,c)=>{if(a==="decorrelated"){let f=Math.min(o,Math.max(n,c*3));return n+Math.random()*(f-n)}let p=a==="exp"?n*2**(m-1):n*m,g=Math.min(o,p);if(!s)return g;let y=g*(.5+Math.random());return Math.min(o,y)},d=V(t,{async invoke(m,c){if(c?.signal?.aborted)throw Ie();let p,g=n;for(let y=1;y<=r;y++)try{return await ae(L(t.invoke(m,c)))}catch(f){if(p=f,y>=r||!l(f,y))throw f;let h=i(y,g);g=h,await Ot(h,c?.signal)}throw p},async*stream(m,c){if(c?.signal?.aborted)throw Ie();if(!u){for await(let y of t.stream(m,c))yield y;return}let p,g=n;for(let y=1;y<=r;y++){let f=!1;try{for await(let h of t.stream(m,c))f=!0,yield h;return}catch(h){if(p=h,f||y>=r||!l(h,y))throw h;let b=i(y,g);g=b,await Ot(b,c?.signal)}}throw p}});return U(d,"withRetry",t),d}function Mr(t,e){if(t==null)return!1;let r=t;return r.name==="LLMTimeoutError"?!0:r.name==="AbortError"||r.message==="aborted"||r.name==="DOMException"&&r.code!=null&&Number(r.code)===20||r.name==="BudgetExhaustedError"||r.name==="CircuitOpenError"?!1:r.status!=null?r.status===429||r.status>=500&&r.status<600:r.code&&typeof r.code=="string"&&/^E[A-Z]+$/.test(r.code)?!0:r.message?/network|timeout|socket|fetch|econn|eai_/i.test(r.message):!1}var ge=class extends Error{constructor(r){super(`LLM call timed out after ${r}ms`);this.ms=r}name="LLMTimeoutError"};function Je(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let r=a=>{let s=new AbortController,l=!1,u,i=new Q;return a&&(a.aborted?s.abort(a.reason):(u=()=>{i.cancel(),s.abort(a.reason)},a.addEventListener("abort",u,{once:!0}))),i.start(e,()=>{l=!0,s.abort(new ge(e))}),{signal:s.signal,cancel:()=>{i.cancel(),a&&u&&a.removeEventListener("abort",u)},timedOut:()=>l}},n=(a,s)=>{if(!s||a instanceof ge)throw a;let l=a;if(l?.name==="AbortError"||l?.name==="DOMException"&&Number(l.code)===20||a?.message==="aborted"){let i=new ge(e);throw i.cause=a,i}throw a},o=V(t,{async invoke(a,s){let{signal:l,cancel:u,timedOut:i}=r(s?.signal);try{return await ae(L(t.invoke(a,{...s,signal:l})))}catch(d){return n(d,i())}finally{u()}},async*stream(a,s){let{signal:l,cancel:u,timedOut:i}=r(s?.signal);try{for await(let d of t.stream(a,{...s,signal:l}))yield d}catch(d){n(d,i())}finally{u()}}});return U(o,"withTimeout",t),o}function vr(t,e={}){let r={adapter:t},n=t;if(e.rateLimit){let o=ze(n,e.rateLimit);n=o.adapter,r.rateLimiter=o.limiter}if(e.budget){let o=Ue(n,e.budget);n=o.adapter,r.budget=o.budget}if(e.breaker){let o=Ke(n,e.breaker);n=o.adapter,r.breaker=o.breaker}if(e.timeoutMs!=null&&(n=Je(n,e.timeoutMs)),e.retry&&(n=Ye(n,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),n=Be([{name:e.name??"primary",adapter:n},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(n=Fe(n,e.cache)),r.adapter=n,r}function N(t,e){return dt("ai",t,e)}function kr(t){return t!=null&&typeof t.then=="function"}function Qe(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function xr(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Rr=3e4;function Dt(t,e){if(t.status==="settled"){let n=t.cache;if(n!==void 0)return Promise.resolve(n)}let r=e?.timeoutMs??Rr;return new Promise((n,o)=>{let a=new Q,s=t.subscribe(l=>{for(let u of l){if(u[0]===B){a.cancel(),s(),n(u[1]);return}if(u[0]===W){a.cancel(),s(),o(u[1]);return}if(u[0]===ee){a.cancel(),s(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(r,()=>{s(),o(new Error(`firstDataFromNode: timed out after ${r}ms`))})})}async function ve(t){return kr(t)?ve(await t):Qe(t)?Dt(t):xr(t)?Dt(L(t)):t}function ye(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function wr(t,e){let r=L(t),n=e?.refreshTrigger!=null?L(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,a=J("frozenContext",o);return n==null?le([r],(s,l,u)=>{if(u.store.emitted===!0)return;let d=s[0],m=d!=null&&d.length>0?d.at(-1):u.prevData[0];if(m!==void 0)return u.store.emitted=!0,l.emit(m),{invalidate:()=>{u.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context",{...a})}):le([r,n],(s,l,u)=>{let i=s[1];if(!(i!=null&&i.length>0))return;let m=s[0],c=m!=null&&m.length>0?m.at(-1):u.prevData[0];l.emit(c)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context",{...a})})}function Pt(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Lr(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Xe(t,e,r,n){let o=n?.format??"text",a=n?.name??"prompt_node";n?.tools!==void 0&&o!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let s=v(e,u=>{if(u.some(d=>d==null))return[];let i=typeof r=="string"?r:r(...u);return i?[{role:"user",content:i}]:[]},{name:`${a}::messages`,meta:N("prompt_node")});return $(s,u=>!u||u.length===0?w(null):oe(i=>{let d=!1,m=!1,c,p={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,...n?.tools!==void 0?{tools:n.tools}:{}};if(n?.abort){let h=gt(n.abort);p.signal=h.signal,c=h.dispose}let g;try{g=t.invoke(u,p)}catch(h){return d=!0,i.down([[W,h]]),()=>{c?.()}}let f=L(g).subscribe(h=>{if(!(m||d))for(let b of h){if(d)return;if(b[0]===B){let k=b[1];if(o==="raw")i.emit(k);else try{let x=Pt(k),C=o==="json"?JSON.parse(ye(x)):x;i.emit(C)}catch(x){let C=Pt(k),A=new Error(`promptNode: failed to parse LLM response as JSON: ${x.message}
|
|
2
|
-
Raw content (first 200 chars): ${Lr(C)}`);d=!0,i.down([[W,A]]);return}}else if(b[0]===W){d=!0,i.down([[W,b[1]]]);return}else if(b[0]===ee){d=!0,i.down([[ee]]);return}else i.down([b])}});return()=>{m=!0,f(),c?.()}},{name:`${a}::call`,meta:N("prompt_node::call")}),{name:`${a}::output`,meta:n?.meta?{...N("prompt_node::output"),...n.meta}:N("prompt_node::output")})}async function _t(t,e,r,n){let o="",a=0;for await(let s of t.stream(e,r))n.publish({...s,seq:a++,ts:Te()}),s.type==="token"&&(o+=s.delta);return o}function jt(t,e){if(e==="json")try{return JSON.parse(ye(t))}catch(r){let n=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${r.message}; content preview: ${n}`)}return t}function Gt(t,e){return v([t.latest],([r],n)=>{let o=n.store;if(r==null)return o.acc??"";let a=r;return a.seq===0&&(o.acc=""),a.type==="token"&&(o.acc=(o.acc??"")+a.delta),o.acc??""},{name:e,meta:N("accumulated_text"),initial:""})}function Nr(t,e,r,n){let o=n?.name??"llm",a=n?.format??"text",s=$e(`${o}/stream`,{...n?.retainedLimit!=null?{retainedLimit:n.retainedLimit}:{}}),l=v(e,m=>{if(m.some(p=>p==null))return[];let c=typeof r=="string"?r:r(...m);return c?[{role:"user",content:c}]:[]},{name:`${o}::messages`,meta:N("prompt_node::messages"),initial:[]}),u=$(l,m=>{let c=m;if(!c||c.length===0)return w(null);let p=new AbortController;async function*g(){try{let y=await _t(t,c,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,signal:p.signal},s);yield jt(y,a)}finally{p.abort()}}return L(g())},{meta:J("streamingPromptNode")}),i=Gt(s,`${o}::accumulatedText`),d=_(u);return{output:u,deltaTopic:s,accumulatedText:i,dispose:()=>{d(),s.destroy()}}}function Ar(t,e,r,n,o,a){let s=w(0,{name:`${e}/cancel`}),l=0,u=[...n,s],i=a?.name??e,d=a?.format??"text",m=$e(`${i}/stream`,{...a?.retainedLimit!=null?{retainedLimit:a.retainedLimit}:{}}),c=v(u,D=>{let j=D.slice(0,-1);if(j.some(I=>I==null))return[];let E=typeof o=="string"?o:o(...j);return E?[{role:"user",content:E}]:[]},{name:`${i}::messages`,meta:N("prompt_node::messages"),initial:[]}),p=$(c,D=>{let j=D;if(!j||j.length===0)return w(null);let E=new AbortController;async function*I(){try{let S=await _t(r,j,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:E.signal},m);yield jt(S,d)}finally{E.abort()}}return L(I())},{meta:J("gatedStream")}),g=Gt(m,`${i}::accumulatedText`),y=yt(p,D=>D!=null);t.add(y,{name:`${e}/raw`});let f=vt(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,f),f.add(y,{name:`${e}/raw`});let h=f.approvalGate(`${e}/gate`,`${e}/raw`,a?.gate),b=_(p),k=_(h.node),x=_(g);t.addDisposer(b),t.addDisposer(k),t.addDisposer(x);let C=h.reject.bind(h),A={...h,reject(D=1){Y(()=>{C(D),s.emit(++l)})}};return{output:h.node,deltaTopic:m,accumulatedText:g,gate:A,dispose:()=>{b(),k(),x(),m.destroy()}}}function Cr(t,e){let r=e?.separator??`
|
|
3
|
-
|
|
4
|
-
`,n=t.map(s=>typeof s=="string"?w(s):L(s)),o=v(n,s=>s.filter(l=>l!=null&&l!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:N("system_prompt"),initial:""}),a=_(o);return Object.assign(o,{dispose:a})}var Sr=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function Er(t,e){let r=e?.charsPerToken??4,n={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return v([t.latest],([o],a)=>{if(o==null)return n;let s=o;"chunkCount"in a.store||(a.store.chunkCount=0,a.store.charCount=0,a.store.usageTokens=0,a.store.sawUsage=!1);let l=a.store;s.type==="token"?(l.chunkCount+=1,l.charCount+=s.delta.length):s.type==="usage"&&(l.sawUsage=!0,l.usageTokens=H(s.usage)+re(s.usage));let u=l.sawUsage?l.usageTokens:Math.ceil(l.charCount/r);return{chunkCount:l.chunkCount,charCount:l.charCount,estimatedTokens:u,estimated:!l.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:n,meta:N("cost_meter_extractor"),equals:Sr})}var Ir=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],o=e[r];if(n.label!==o.label||n.pattern!==o.pattern||n.match!==o.match||n.position!==o.position)return!1}return!0};function Or(t,e){let r=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>r)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${r}); raise the option or shorten the pattern.`);let n=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return v([t],([o],a)=>{if(o==null)return[];let s=o;"flags"in a.store||(a.store.flags=[],a.store.scannedTo=0);let l=a.store.flags,u=a.store.scannedTo,i=Math.max(0,u-r),d=s.slice(i),m=!1;for(let{pattern:c,label:p,compiled:g}of n){g.lastIndex=0;for(let y of d.matchAll(g)){let f=i+(y.index??0);f+y[0].length<=u||(l.push({label:p,pattern:c,match:y[0],position:f}),m=!0)}}return a.store.scannedTo=s.length,m?[...l]:l.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:N("keyword_flag_extractor"),equals:Ir})}function Dr(t,e,r){return v([t],([n])=>n==null?null:e(n),{name:r?.name??"extractor",describeKind:"derived",initial:null,meta:N("stream_extractor"),...r?.equals?{equals:r.equals}:{}})}var Pr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],o=e[r];if(n.startIndex!==o.startIndex||n.name!==o.name||n.raw!==o.raw)return!1}return!0};function _r(t,e){return v([t],([r],n)=>{if(r==null)return[];let o=r;"calls"in n.store||(n.store.calls=[],n.store.scanFrom=0);let a=n.store.calls,s=n.store.scanFrom,l=!1;for(;s<o.length;){let u=o.indexOf("{",s);if(u===-1){n.store.scanFrom=o.length;break}let i=0,d=-1,m=!1;for(let p=u;p<o.length;p++){let g=o[p];if(m)g==="\\"&&p+1<o.length?p++:g==='"'&&(m=!1);else if(g==='"')m=!0;else if(g==="{")i++;else if(g==="}"&&(i--,i===0)){d=p;break}}if(d===-1){n.store.scanFrom=u;break}let c=o.slice(u,d+1);try{let p=JSON.parse(c);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(a.push({name:p.name,arguments:p.arguments,raw:c,startIndex:u}),l=!0)}catch{}s=d+1,n.store.scanFrom=s}return l?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:N("tool_call_extractor"),equals:Pr})}function jr(t,e,r,n){let o=r*(n?.hardMultiplier??1.5),a=typeof e!="function",s=[t];return a&&s.push(e),v(s,l=>{let u=l[0]??"";if(u.length===0)return"allow";let i=a?l[1]??0:e(u);return i>=o?"block":i>=r?"review":"allow"},{name:n?.name??"content-gate",initial:"allow"})}function Gr(t,e,r,n){let o=r??(()=>"[REDACTED]");function a(s){let l=s;for(let u of e){let i=u.global?u:new RegExp(u.source,`${u.flags}g`);l=l.replace(i,d=>o(d,u))}return l}return v([t],([s])=>a(s??""),{name:n?.name??"redactor",initial:""})}var Oe=class extends se{_log;messages;latest;messageCount;constructor(e,r={}){super(e,r.graph),this._log=pe([],{name:"messages",maxSize:r.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=v([this.messages],([n])=>{let o=n;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:N("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(_(this.latest)),this.messageCount=v([this.messages],([n])=>n.length,{name:"messageCount",describeKind:"derived",meta:N("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(_(this.messageCount))}append(e,r,n){this._log.append({role:e,content:r,...n})}appendToolResult(e,r){this._log.append({role:"tool",content:r,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function Ze(t,e){return new Oe(t,e)}function et(t){let{toolCalls:e,tools:r}=t,n=t.retryCount??1,o=t.onError??"rescue",a=(s,l)=>{if(s===l)return!0;if(s.length!==l.length)return!1;for(let u=0;u<s.length;u++){let i=s[u],d=l[u];if(i?.id!==d?.id||i?.content!==d?.content)return!1}return!0};return $(e,s=>{if(s==null||s.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let l=s.map(u=>Fr(u,r,n,o));return v(l,u=>u,{name:"toolExecution::batch",equals:a})})}function Fr(t,e,r,n){let o=ut(()=>e.executeReactive(t.name,t.arguments),{count:r}),a=v([o],([s])=>({id:t.id,content:typeof s=="string"?s:JSON.stringify(s)}));return n==="propagate"?a:bt(a,s=>({id:t.id,content:JSON.stringify({error:String(s)})}))}var De=class extends se{definitions;schemas;_bundle;constructor(e,r={}){super(e,r.graph),this._bundle=we({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=v([this.definitions],([n])=>[...(n??new Map).values()],{name:"schemas",describeKind:"derived",meta:N("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(_(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,r){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);return oe(o=>{let a=new AbortController,s;try{let u=n.handler(r,{signal:a.signal});s=Br(u,a.signal)}catch(u){return o.down([[W,u]]),()=>{a.abort()}}let l=s.subscribe(u=>{o.down(u)});return()=>{a.abort(),l()}},{name:`executeReactive::${e}`,meta:N("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function tt(t,e){return new De(t,e)}function Br(t,e){return Qe(t)?t:t!=null&&typeof t.then=="function"?je(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?pt(t,{signal:e}):je(Promise.resolve(t),{signal:e})}var Pe=class extends se{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,r){if(super(e,r.graph),this.chat=Ze(`${e}-chat`,{maxMessages:r.maxMessages}),this.mount("chat",this.chat),this.tools=tt(`${e}-tools`),this.mount("tools",this.tools),r.tools)for(let R of r.tools)this.tools.register(R);this.status=w("idle",{name:"status",describeKind:"state",meta:N("agent_status")}),this.add(this.status,{name:"status"}),this.turn=w(0,{name:"turn",describeKind:"state",meta:N("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=w(!1,{name:"aborted",describeKind:"state",meta:N("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let n=0,o=this.turn.subscribe(R=>{for(let M of R)M[0]===B&&(n=M[1])}),a=!1,s=this.aborted.subscribe(R=>{for(let M of R)M[0]===B&&(a=M[1])}),l=this.chat.messages.cache??[],u=this.chat.messages.subscribe(R=>{for(let M of R)M[0]===B&&(l=M[1])}),i=this.tools.schemas.cache??[],d=this.tools.schemas.subscribe(R=>{for(let M of R)M[0]===B&&(i=M[1])}),m=r.adapter,c=r.systemPrompt,p=r.model,g=r.temperature,y=r.maxTokens,f=r.maxTurns??10,h=r.stopWhen,b=this.chat,k=this.tools,x=this.status,C=this.turn,A=this.aborted,D=le([x],(R,M,F)=>{if(ke(R,F.prevData,0,"idle")!=="thinking"||a||n>=f){M.down([[ce]]);return}if(l.length===0){M.down([[ce]]);return}M.emit({messages:l,tools:i})},{name:"promptInput",describeKind:"derived",meta:N("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),j=$(D,R=>{let M=new AbortController;return this._currentAbortController=M,a&&M.abort(new Error("agentLoop: aborted")),L(m.invoke(R.messages,{tools:R.tools.length>0?R.tools:void 0,systemPrompt:c,model:p,temperature:g,maxTokens:y,signal:M.signal}),{signal:M.signal})},{equals:()=>!1}),E=w(null,{name:"lastResponse",describeKind:"state",meta:N("agent_last_response")});this.lastResponse=E;let I=le([E,x],(R,M,F)=>{let z=ke(R,F.prevData,0,null);if(ke(R,F.prevData,1,"idle")!=="acting"){M.down([[ce]]);return}let ne=z?.toolCalls;if(ne==null||ne.length===0){M.down([[ce]]);return}M.emit(ne)},{name:"toolCallsRaw",describeKind:"derived",meta:N("agent_tool_calls_raw")}),S=r.interceptToolCalls?r.interceptToolCalls(I):I;this.toolCalls=S;let G=et({toolCalls:S,tools:k,retryCount:1});this.toolResults=G;let T=te([j],([R])=>{if(a)return;let M=R,F=n+1,z=M.toolCalls!=null&&M.toolCalls.length>0,be=M.finishReason==="end_turn"&&(!M.toolCalls||M.toolCalls.length===0),ne=h?.(M)===!0,Ut=F>=f,qt=ne||be||!z||Ut?"done":"acting";Y(()=>{E.emit(M),x.emit(qt),C.emit(F),b.append("assistant",M.content,{toolCalls:M.toolCalls})})}),O=te([G],([R])=>{if(a)return;let M=R;if(M.length===0)return;let F=n>=f?"done":"thinking";Y(()=>{x.emit(F);for(let z of M)b.appendToolResult(z.id,z.content)})}),P=x.cache??"idle",K=x.subscribe(R=>{for(let M of R)M[0]===B&&(P=M[1])}),Z=te([A],([R])=>{R===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),P!=="done"&&x.emit("done"))}),ie=_(T),ue=_(O),me=_(Z);this._terminalResult=le([x,E],(R,M,F)=>{let z=ke(R,F.prevData,0,"idle"),be=ke(R,F.prevData,1,null);if(z==="done"){if(be!=null){M.emit(be);return}let ne=new Error("agentLoop: aborted");ne.name="AbortError",M.down([[W,ne]]);return}if(z==="error"){M.down([[W,new Error("agentLoop: errored")]]);return}M.down([[ce]])},{name:"terminalResult",describeKind:"derived",meta:N("agent_terminal_result")}),this.add(D,{name:"promptInput"}),this.add(j,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===I?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(I,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(G,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(s),this.addDisposer(K),this.addDisposer(u),this.addDisposer(d),this.addDisposer(ie),this.addDisposer(ue),this.addDisposer(me),this._disposeRunWiring=()=>{}}async run(e,r){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let n;try{Y(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=ft(this._terminalResult,{skipCurrent:!0});if(r!=null)if(r.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);r.addEventListener("abort",a,{once:!0}),n=()=>r.removeEventListener("abort",a)}return r?.aborted!==!0&&this.status.emit("thinking"),await o}finally{n?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function ke(t,e,r,n){let o=t[r];if(o!=null&&o.length>0)return o[o.length-1];let a=e[r];return a!==void 0?a:n}function $r(t,e){let r=new Pe(t,e);return r.tagFactory("agentLoop",xe(e)),r}function Wr(t,e,r){let n=L(t),o=r?.condition!=null?L(r.condition):null,a=w(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(o==null)return $(n,l=>{if(l==null)return a;let u=w(l);return e(u)},{meta:J("handoff")});let s=v([n,o],([l,u])=>({v:l,open:u===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return $(s,({v:l,open:u})=>{if(l==null)return a;if(!u)return w(l);let i=w(l);return e(i)},{meta:J("handoff")})}function Kr(t,e,r){let n=L(t),o=e.map(s=>L(s)),a=[n,...o];return v(a,s=>{let l=s[0]??[],u=s.slice(1);return l.filter(i=>{for(let d of u)if(d!=null&&!d(i))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:{...N("tool_selector"),...J("toolSelector")},equals:(s,l)=>{let u=s,i=l;if(u.length!==i.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==i[d])return!1;return!0}})}function Ft(t){let e=t.thresholds??{};return r=>{let n=t.scoreFn(r);for(let o of Object.keys(e)){let a=e[o];if(a===void 0)continue;let s=n[o];if((Number.isFinite(s)?s:Number.NEGATIVE_INFINITY)<a)return!1}return!0}}function Vr(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},r=Ft({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?n=>{if(!r(n))return!1;let o=t.scoreFn(n).structure;return Number.isFinite(o)&&o>0}:r}function Bt(t,e,r,n){let o=r.name??n;return a=>{let s=w(a);return Xe(r.adapter,[s],l=>e(l),{name:o,format:"json",systemPrompt:t,model:r.model,temperature:r.temperature??0,maxTokens:r.maxTokens})}}function rt(t,e){let r=e.maxExistingKeys??100,n=Bt(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,a)=>{let s=r===Number.POSITIVE_INFINITY?[...a.keys()]:[...a.keys()].slice(0,r);return n({raw:o,existingKeys:s})}}function nt(t,e){let r=Bt(t,n=>JSON.stringify({memories:n}),e,"llmConsolidator");return n=>{let o=[...n.entries()].map(([a,s])=>({key:a,value:s}));return r(o)}}var ot=Math.LN2/604800;function he(t){return t instanceof Map?t:new Map}function at(t,e,r){let n=Rt({dimension:r.dimension});t.add(n.entries,{name:"vectorIndex"});let a=te([e.store.entries],([s])=>{let l=he(s);for(let[u,i]of l){let d=r.embedFn(i);d&&n.upsert(u,d,i)}}).subscribe(()=>{});return t.addDisposer(a),{vectors:n,dispose:()=>a()}}function st(t,e,r,n){let o=n.mountPath??r,a=wt(`${r}-kg`);if(t.mount(o,a),!n.entityFn)return{kg:a,dispose:()=>{}};let s=n.entityFn,u=te([e.store.entries],([i])=>{let d=he(i);for(let[m,c]of d){let p=s(m,c);if(p){for(let g of p.entities??[])a.upsertEntity(g.id,g.value);for(let g of p.relations??[])a.link(g.from,g.to,g.relation,g.weight)}}}).subscribe(()=>{});return t.addDisposer(u),{kg:a,dispose:()=>u()}}function it(t,e,r){let n=r.decayRate??ot,o=r.maxActive??1e3,a=r.archiveThreshold??.1,s=r.permanentFilter??(()=>!1),l=xt("permanent",{ranked:!1});t.mount("permanent",l);let u=new Set,i=b=>u.has(b)?"permanent":he(e.store.entries.cache).has(b)?"active":"archived",d=(b,k)=>{u.add(b),l.upsert(b,k)},m=new Map,c=e.store.entries,p=r.context?L(r.context):w(null),y=te([c,p],([b,k])=>{let x=he(b),C=q(),A=[],D=[];for(let[E,I]of x){if(m.has(E)||m.set(E,C),s(E,I)){D.push({key:E,value:I});continue}let S=r.score(I,k),G=m.get(E)??C,T=Number(C-G)/1e9;Mt(S,T,n)<a&&A.push(E)}for(let E of m.keys())x.has(E)||m.delete(E);for(let{key:E,value:I}of D)u.has(E)||d(E,I);let j=x.size-u.size;if(j>o){let E=[...x.entries()].filter(([S])=>!u.has(S)).map(([S,G])=>({key:S,score:r.score(G,k)})).sort((S,G)=>S.score-G.score),I=j-o;for(let S=0;S<I&&S<E.length;S++){let G=E[S].key;A.includes(G)||A.push(G)}}A.length>0&&Y(()=>{for(let E of A)e.store.delete(E)})}).subscribe(()=>{}),f=null;r.archiveTier&&(f=t.attachSnapshotStorage([r.archiveTier],r.archiveStorageOptions??{}));let h=()=>{y(),f?.dispose()};return t.addDisposer(h),{tiers:{permanent:l,activeEntries:c,archiveHandle:f,tierOf:i,markPermanent:d},dispose:h}}function Ur(t,e){if(!t||!e)return 0;let r=Math.min(t.length,e.length),n=0;for(;n<r&&t[n]===e[n];)n++;return n}function lt(t,e,r,n,o){let a=o.topK??20,s=o.graphDepth??1,l=o.budget??2e3,u=o.contextWeight??0,i=o.context?L(o.context):w(null),d=(f,h,b)=>{let k=new Map,x=[];if(r&&b.vector){let I=b.vector,S=r.entries.cache;if(S&&S.size>0&&a>0){x=[...S.values()].map(T=>({id:T.id,score:kt(I,T.vector),...T.meta!==void 0?{meta:T.meta}:{}})).sort((T,O)=>O.score-T.score).slice(0,a);for(let T of x){let O=f.get(T.id);O&&k.set(T.id,{value:O,sources:new Set(["vector"])})}}}let C=[];if(n){let I=n.adjacencyOut.cache,S=n.adjacencyIn.cache,G=[...b.entityIds??[],...k.keys()],T=new Set,O=G;for(let P=0;P<s;P++){let K=[];for(let Z of O){if(T.has(Z))continue;T.add(Z);let ie=I?.get(Z)??[],ue=S?.get(Z)??[];for(let me of ie){let R=me.to;if(!T.has(R)){K.push(R);let M=f.get(R);if(M){let F=k.get(R);F?F.sources.add("graph"):k.set(R,{value:M,sources:new Set(["graph"])}),C.push(R)}}}for(let me of ue){let R=me.from;if(!T.has(R)){K.push(R);let M=f.get(R);if(M){let F=k.get(R);F?F.sources.add("graph"):k.set(R,{value:M,sources:new Set(["graph"])}),C.push(R)}}}}O=K}}for(let[I,S]of f)k.has(I)||k.set(I,{value:S,sources:new Set(["store"])});let A=b.context?.length??0,D=[];for(let[I,{value:S,sources:G}]of k){let T=o.contextOf?o.contextOf(S):void 0,O=o.score(S,h);if(u>0&&A>0){let K=Ur(b.context,T);K>0&&(O=O*(1+u*K/A))}let P=T?{key:I,value:S,score:O,sources:[...G],context:T}:{key:I,value:S,score:O,sources:[...G]};D.push(P)}D.sort((I,S)=>S.score-I.score);let j=[],E=0;for(let I of D){let S=o.cost(I.value);if(E+S>l&&j.length>0)break;j.push(I),E+=S}return{packed:j,trace:{vectorCandidates:x,graphExpanded:C,ranked:D,packed:j}}},m=(f,h)=>{if(f===h)return!0;if(f.length!==h.length)return!1;for(let b=0;b<f.length;b++)if(f[b]!==h[b])return!1;return!0},c=w([],{name:"retrieval",describeKind:"state",meta:N("retrieval_pipeline"),equals:m});t.add(c,{name:"retrieval"});let p=w(null,{name:"retrievalTrace",describeKind:"state",meta:N("retrieval_trace")});return t.add(p,{name:"retrievalTrace"}),{retrieval:c,retrievalTrace:p,retrieve:f=>{let h=he(e.store.entries.cache),{packed:b,trace:k}=d(h,i.cache,f);return Y(()=>{c.emit(b),p.emit(k)}),b},retrieveReactive:f=>{let h=L(f),b=v([e.store.entries,i,h],([C,A,D])=>{if(D==null)return{packed:[],trace:null};let j=he(C),{packed:E,trace:I}=d(j,A,D);return{packed:E,trace:I}},{name:"retrievalReactive::result",describeKind:"derived",meta:N("retrieval_reactive_result"),initial:{packed:[],trace:null}}),x=te([b],([C])=>{let A=C;Y(()=>{c.emit(A.packed),A.trace&&p.emit(A.trace)})}).subscribe(()=>{});return t.addDisposer(x),v([b],([C])=>C.packed,{name:"retrievalReactive",describeKind:"derived",meta:N("retrieval_reactive"),initial:[],equals:m})}}}function qr(t,e,r){let n=new se(t,r.graph);n.tagFactory("agentMemory",xe(r));let o;if(r.extractFn)o=r.extractFn;else if(r.adapter&&r.extractPrompt)o=rt(r.extractPrompt,{adapter:r.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let a=(b,k)=>{let x=k.cache??new Map,C=k.subscribe(A=>{for(let D of A)D[0]===B&&(x=D[1])});return n.addDisposer(C),$(b,A=>A==null?{upsert:[]}:o(A,x))},s=e;if(r.admissionFilter){let b=L(e),k=r.admissionFilter;s=v([b],([x])=>{if(k(x))return x},{name:"admissionFilter",describeKind:"derived"})}let l;r.consolidateFn?l=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(l=nt(r.consolidatePrompt,{adapter:r.adapter}));let u=r.consolidateTrigger;if(!u&&l&&r.reflection?.enabled!==!1){let b=r.reflection?.interval??3e5;u=ct(b,{period:b})}let i={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:l,consolidateTrigger:u},d=Tt(s,a,i);n.add(d.store.entries,{name:"store"}),n.add(d.compact,{name:"compact"}),n.add(d.size,{name:"size"});let m=null;r.vectorDimensions&&r.vectorDimensions>0&&r.embedFn&&(m=at(n,d,{dimension:r.vectorDimensions,embedFn:r.embedFn}).vectors);let c=null;r.enableKnowledgeGraph&&(c=st(n,d,t,{mountPath:"kg",entityFn:r.entityFn}).kg);let p=null;r.tiers&&(p=it(n,d,{...r.tiers,score:r.score,context:r.context}).tiers);let g=null,y=null,f=null,h=null;if(m||c){let b=lt(n,d,m,c,{score:r.score,cost:r.cost,budget:r.budget,topK:r.retrieval?.topK,graphDepth:r.retrieval?.graphDepth,contextOf:r.contextOf,contextWeight:r.contextWeight,context:r.context});g=b.retrieval,y=b.retrievalTrace,f=b.retrieve,h=b.retrieveReactive}return Object.assign(n,{distillBundle:d,compact:d.compact,size:d.size,vectors:m,kg:c,memoryTiers:p,retrieval:g,retrievalTrace:y,retrieve:f,retrieveReactive:h})}function Hr(t,e,r){let n=t.describe({actor:e,detail:"full"}),o=r?.groupByTags??!0,a=r?.separator??`
|
|
5
|
-
`,s=[],l=r?.sinceVersion;for(let[u,i]of Object.entries(n.nodes)){let d=i.meta??{},m=d.description,c=d.format;if(!m&&!c)continue;if(l!=null&&i.v!=null){let h=l.get(u);if(h!=null&&h.id===i.v.id&&i.v.version<=h.version)continue}let p=m??u,g=i.value,y=d.unit,f;c==="currency"&&typeof g=="number"?f=`$${g.toFixed(2)}`:c==="percentage"&&typeof g=="number"?f=`${(g*100).toFixed(1)}%`:g==null?f="(no value)":f=String(g),y&&c!=="currency"&&c!=="percentage"&&(f=`${f} ${y}`),s.push({path:u,description:p,formatted:f})}if(s.length===0)return"";if(o){let u=new Map,i=[];for(let m of s){let p=n.nodes[m.path].meta?.tags;if(p&&p.length>0){let g=p[0],y=u.get(g);y||(y=[],u.set(g,y)),y.push(m)}else i.push(m)}if(u.size===0)return s.map(m=>`- ${m.description}: ${m.formatted}`).join(a);let d=[];for(let[m,c]of[...u.entries()].sort((p,g)=>p[0].localeCompare(g[0])))d.push(`[${m}]${a}${c.map(p=>`- ${p.description}: ${p.formatted}`).join(a)}`);return i.length>0&&d.push(i.map(m=>`- ${m.description}: ${m.formatted}`).join(a)),d.join(a+a)}return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a)}var $t=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
6
|
-
|
|
7
|
-
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
8
|
-
|
|
9
|
-
{
|
|
10
|
-
"name": "<graph_name>",
|
|
11
|
-
"nodes": {
|
|
12
|
-
"<node_name>": {
|
|
13
|
-
"type": "state" | "derived" | "producer" | "effect" | "operator",
|
|
14
|
-
"initial": <initial_value_for_state_nodes>,
|
|
15
|
-
"deps": ["<dep_node_name>", ...],
|
|
16
|
-
"meta": {
|
|
17
|
-
"description": "<human-readable purpose>",
|
|
18
|
-
"type": "string" | "number" | "boolean" | "integer" | "enum",
|
|
19
|
-
"range": [min, max],
|
|
20
|
-
"values": ["a", "b"],
|
|
21
|
-
"format": "currency" | "percentage" | "status",
|
|
22
|
-
"access": "human" | "llm" | "both" | "system",
|
|
23
|
-
"unit": "<unit>",
|
|
24
|
-
"tags": ["<tag>"]
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
Rules:
|
|
31
|
-
- "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
|
|
32
|
-
- "derived" nodes have deps and compute from them (pure, no side effects).
|
|
33
|
-
- "effect" nodes have deps but produce side effects (no return value).
|
|
34
|
-
- "producer" nodes have no deps but generate values asynchronously.
|
|
35
|
-
- "operator" nodes are parameterized transformations with deps.
|
|
36
|
-
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
37
|
-
- meta.description is required for every node.
|
|
38
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Wt(t,e,r){let o=[{role:"system",content:r?.systemPromptExtra?`${$t}
|
|
39
|
-
|
|
40
|
-
${r.systemPromptExtra}`:$t},{role:"user",content:t}],a=e.invoke(o,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),l=(await ve(a)).content.trim();l.startsWith("```")&&(l=ye(l));let u;try{u=JSON.parse(l)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${l.slice(0,200)}`)}return Lt(u,{catalog:r?.catalog})}function zr(t,e,r){let n=L(t);return $(n,o=>!o||typeof o!="string"||o.trim().length===0?w(null):oe(a=>{let s=new AbortController,l=!1;return Wt(o,e,{...r,signal:s.signal}).then(u=>{if(l){u.destroy();return}a.emit(u),a.down([[ee]])}).catch(u=>{l||a.down([[W,u]])}),()=>{l=!0,s.abort()}},{name:"graphFromSpec::call"}))}function Yr(t){let e={},r=t.type;return r==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):r==="integer"?e.type="integer":r==="number"?e.type="number":r==="boolean"?e.type="boolean":r==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function Jr(t,e){let r=t.describe({actor:e,detail:"full"}),n=[],o=[],a=[];for(let[s,l]of Object.entries(r.nodes)){if(l.type!=="state"||s.includes("::__meta__::")||l.status==="completed"||l.status==="errored")continue;let u=l.meta??{},i=u.access;if(i==="human"||i==="system")continue;let d=u.description??`Set the value of ${s}`,m=Yr(u),c={type:"object",required:["value"],properties:{value:m},additionalProperties:!1},p=s.replace(/::/g,"__");n.push({type:"function",function:{name:p,description:d,parameters:c}}),o.push({name:s,description:d,inputSchema:c});let g=t,y=e,f=l.v;a.push({name:s,description:d,parameters:c,handler(h){return g.set(s,h.value,y?{actor:y}:void 0),h.value},...f!=null?{version:{id:f.id,version:f.version}}:{}})}return{openai:n,mcp:o,definitions:a}}var Qr=`You are a reactive graph optimizer for GraphReFly.
|
|
41
|
-
|
|
42
|
-
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
43
|
-
|
|
44
|
-
Return ONLY valid JSON with this structure:
|
|
45
|
-
{
|
|
46
|
-
"summary": "<one-line summary of the strategy>",
|
|
47
|
-
"reasoning": "<explanation of why these changes help>",
|
|
48
|
-
"operations": [
|
|
49
|
-
{ "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
|
|
50
|
-
{ "type": "remove_node", "name": "<name>" },
|
|
51
|
-
{ "type": "connect", "from": "<source>", "to": "<target>" },
|
|
52
|
-
{ "type": "disconnect", "from": "<source>", "to": "<target>" },
|
|
53
|
-
{ "type": "set_value", "name": "<name>", "value": <new_value> },
|
|
54
|
-
{ "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
|
|
55
|
-
]
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
Rules:
|
|
59
|
-
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
60
|
-
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
61
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Kt(t,e,r,n){let{expand:o,...a}=t.describe({actor:n?.actor,detail:"standard"}),s=[{role:"system",content:Qr},{role:"user",content:JSON.stringify({graph:a,problem:e})}],l=r.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),i=(await ve(l)).content.trim();i.startsWith("```")&&(i=i.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(i)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${i.slice(0,200)}`)}let m=d;if(typeof m.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof m.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(m.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:m.summary,reasoning:m.reasoning,operations:m.operations}}function Xr(t,e,r,n){let o=L(e),a=ht(o,t);return $(a,s=>{if(s==null)return w(null);let[l,u]=s;return!u||!l||typeof l!="string"||l.trim().length===0?w(null):u.destroyed?w(null):oe(i=>{let d=new AbortController,m=!1;return Kt(u,l,r,{...n,signal:d.signal}).then(c=>{m||(i.emit(c),i.down([[ee]]))}).catch(c=>{m||i.down([[W,c]])}),()=>{m=!0,d.abort()}},{name:"suggestStrategy::call"})})}var Vt=new Set(["state","derived","producer","operator","effect"]);function Zr(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let n=new Set(Object.keys(r.nodes));for(let[o,a]of Object.entries(r.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${o}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Vt.has(s.type))&&e.push(`Node "${o}": invalid type "${String(s.type)}" (expected: ${[...Vt].join(", ")})`),Array.isArray(s.deps))for(let l of s.deps)typeof l=="string"&&!n.has(l)&&e.push(`Node "${o}": dep "${l}" does not reference an existing node`)}if(!Array.isArray(r.edges))r.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let a=0;a<r.edges.length;a++){let s=r.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let l=s;(typeof l.from!="string"||!n.has(l.from))&&e.push(`Edge [${a}]: 'from' "${String(l.from)}" does not reference an existing node`),(typeof l.to!="string"||!n.has(l.to))&&e.push(`Edge [${a}]: 'to' "${String(l.to)}" does not reference an existing node`);let u=`${l.from}->${l.to}`;o.has(u)&&e.push(`Edge [${a}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}export{or as a,ar as b,Ae as c,We as d,ir as e,lr as f,dr as g,ur as h,Ke as i,Ce as j,Ue as k,cr as l,qe as m,ze as n,Ye as o,ge as p,Je as q,vr as r,wr as s,Xe as t,Nr as u,Ar as v,Cr as w,Er as x,Or as y,Dr as z,_r as A,jr as B,Gr as C,Oe as D,Ze as E,et as F,De as G,tt as H,Pe as I,$r as J,Wr as K,Kr as L,Ft as M,Vr as N,rt as O,nt as P,ot as Q,at as R,st as S,it as T,lt as U,qr as V,Hr as W,Wt as X,zr as Y,Jr as Z,Kt as _,Xr as $,Zr as aa,en as ba};
|
package/dist/chunk-IUB4NYI2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as K}from"./chunk-L6NSJVJZ.js";import{a as Y}from"./chunk-SGS4OJGS.js";import{a as _}from"./chunk-ESMPEKEV.js";import{a as A,b as M,i as q}from"./chunk-4VVTGLXJ.js";import{c as N}from"./chunk-35JTVPOX.js";import{m as $}from"./chunk-IA7DUNGB.js";import{D as E,F as B,m as D,o as I}from"./chunk-LYCLF26R.js";import{b as w,c as y,d as h,f as F,g as P,h as C,i as T,j as k}from"./chunk-CK2E7BTU.js";var V=class{buf=[];head=0;get size(){return this.buf.length-this.head}push(t){this.buf.push(t)}shift(){if(this.head>=this.buf.length)return;let t=this.buf[this.head];return this.buf[this.head]=void 0,this.head++,this.head>32&&this.head*2>this.buf.length&&(this.buf=this.buf.slice(this.head),this.head=0),t}clear(){this.buf=[],this.head=0}};function ee(e,t,n){if(t.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=t.map(c=>c.node),s=[e,...r],d=new V,o=!1,i=!1,u=Symbol("budget-gate"),f=new Array(t.length);function p(){return t.every((c,m)=>c.check(f[m]))}function a(c){for(;d.size>0&&p();){let m=d.shift();c.emit(m)}d.size===0&&i&&(i=!1,c.down([[h]]))}return E([],(c,m)=>{for(let l=0;l<t.length;l++)f[l]=t[l].node.cache;let b=[];for(let l=0;l<s.length;l++){let v=s[l];b.push(v.subscribe(z=>{for(let S of z)g(S,l,m)}))}return()=>{for(let l of b)l()}},{...n,describeKind:"derived",meta:K("resilience","budget_gate",n?.meta)});function g(c,m,b){let l=c[0];if(m===0){if(l===w)return p()&&d.size===0?b.emit(c[1]):(d.push(c[1]),o||(o=!0,b.up([[F,u]]))),!0;if(l===y)return b.down([[y]]),!0;if(l===h)return d.size===0?b.down([[h]]):i=!0,!0;if(l===T||l===k){for(;d.size>0;)b.emit(d.shift());return i=!1,o&&(o=!1,b.up([[P,u]])),b.down([c]),!0}return!1}if(l===w&&(f[m-1]=c[1]),l===w||l===h){let v=p();return v&&d.size>0?(a(b),d.size===0&&o&&(o=!1,b.up([[P,u]]))):!v&&!o&&d.size>0&&(o=!0,b.up([[F,u]])),!0}return l===y?!0:l===k?(b.down([c]),!0):l===T}}function R(e){return{describeKind:"derived",...e}}function te(e){return e<0?0:e}function j(e){return e[1]}function ne(e){if(typeof e!="number"||!Number.isFinite(e))throw new TypeError("backoff strategy must return a finite number");return e<0?0:e}function Q(e){let t=e?.count,n=e?.backoff;if(n!==void 0&&t===void 0)throw new RangeError("retry({ backoff }) requires explicit count to prevent unbounded retries; pass { count: <n>, backoff: ... }");let r=t!==void 0?t:0;if(r<0)throw new RangeError("retry count must be >= 0");let s=n===void 0?null:typeof n=="string"?q(n):n;return{maxRetries:r,strategy:s}}function J(e){let t={};return e?.count!==void 0&&(t.count=e.count),typeof e?.backoff=="string"&&(t.backoff=e.backoff),Object.keys(t).length>0?t:void 0}function X(e,t,n){let r=0,s=!1,d=null,o,i=new _;function u(){o?.(),o=void 0}function f(a){if(s)return;if(r>=e.maxRetries){u(),n.down([[k,a]]);return}let g=e.strategy===null?0:e.strategy(r,a,d);if(g==null){u(),n.down([[k,a]]);return}let c;try{c=ne(g)}catch{u(),n.down([[k,a]]);return}d=c,r+=1,u();let m=c>0?c/1e6:1;i.start(m,()=>{s||p()})}function p(){i.cancel(),u();let a;try{a=t()}catch(g){f(g);return}o=a.subscribe(g=>{if(!s)for(let c of g){let m=c[0];if(m===y)n.down([[y]]);else if(m===w)r=0,d=null,n.emit(c[1]);else if(m===h)n.down([[h]]);else if(m===T)u(),n.down([[T]]);else if(m===k){f(j(c));return}else n.down([c])}})}return p(),()=>{s=!0,i.cancel(),u()}}function Oe(e,t){return typeof e=="function"?oe(e,t):re(e,t)}function re(e,t){let n=Q(t);return B(r=>X(n,()=>e,r),{...R(),initial:e.cache,meta:{...N("retry",J(t))}})}function oe(e,t){let n=Q(t);return B(r=>X(n,e,r),{...R(),initial:t?.initial,meta:{...N("retry",J(t))}})}var W=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};function xe(e){let t=Math.max(1,e?.failureThreshold??5),n=te(e?.cooldownNs??30*1e9),r=e?.cooldown??null,s=Math.max(1,e?.halfOpenMax??1),d=e?.now??I,o="closed",i=0,u=0,f=0,p=n,a=0;function g(){if(!r)return n;let b=r(u);return b!==null?b:n}function c(){o="open",p=g(),f=d(),a=0}return{canExecute(){return o==="closed"?!0:o==="open"?d()-f>=p?(o="half-open",a=1,!0):!1:a<s?(a++,!0):!1},recordSuccess(){o==="half-open"?(o="closed",i=0,u=0):o==="closed"&&(i=0)},recordFailure(b){if(o==="half-open"){u++,c();return}o==="closed"&&(i++,i>=t&&c())},get state(){return o},get failureCount(){return i},reset(){o="closed",i=0,u=0,a=0}}}function Be(e,t){let n=t?.onOpen??"skip";return r=>{let s=E([],(d,o)=>{function i(){s.meta.breakerState.down([[w,e.state]])}let u=r.subscribe(f=>{for(let p of f){let a=p[0];a===y?o.down([[y]]):a===w?e.canExecute()?(i(),o.emit(p[1])):(i(),n==="error"?o.down([[k,new W]]):o.down([[h]])):a===h?o.down([[h]]):a===T?(e.recordSuccess(),i(),o.down([[T]])):a===k?(e.recordFailure(j(p)),i(),o.down([p])):o.down([p])}});return i(),u},{...R(),meta:{breakerState:e.state,...N("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:r.cache});return{node:s,breakerState:s.meta.breakerState}}}function ie(e,t,n){if(e<=0)throw new RangeError("capacity must be > 0");if(t<0)throw new RangeError("refillPerSecond must be >= 0");let r=n?.clock??I,s=e,d=r();function o(i){if(t>0){let u=i-d;s=Math.min(e,s+u/1e9*t)}d=i}return{available(){return o(r()),s},tryConsume(i=1){if(i<=0)return!0;let u=r();return o(u),s>=i?(s-=i,!0):!1},putBack(i=1){i<=0||(o(r()),s=Math.min(e,s+i))}}}var G=class extends Error{name="RateLimiterOverflowError";constructor(t){super(`rateLimiter buffer overflow (maxBuffer=${t})`)}};function Se(e,t){let{maxEvents:n,windowNs:r}=t;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let s=t.maxBuffer;if(s===void 0)throw new RangeError("rateLimiter requires explicit maxBuffer (use Infinity to opt in to unbounded)");let d=s===1/0;if(!d&&(!Number.isInteger(s)||s<1))throw new RangeError("maxBuffer must be a positive integer (or Infinity for unbounded)");let o=t.onOverflow??"drop-newest",i=n*1e9/r,u=B(f=>{let p=ie(n,i),a=d?se():ue(s),g=new _,c=!1,m=0,b=1e9/i,l=u.meta.droppedCount;function v(){l.emit(m)}l.cache!==0&&v();function z(){for(;a.size>0;)if(p.tryConsume(1))f.emit(a.shift());else{g.start(Math.max(1,b/1e6),z);return}}function S(){m+=1,v()}function L(){for(c=!0,g.cancel();a.size>0;)a.shift();m=0}let Z=e.subscribe(H=>{for(let O of H){if(c)return;let x=O[0];if(x===y)f.down([[y]]);else if(x===w){if(!d&&a.size>=s)if(o==="drop-newest")S();else if(o==="drop-oldest")a.shift(),a.push(O[1]),S();else{S(),L(),f.down([[k,new G(s)]]);return}else a.push(O[1]);z()}else if(x===h)f.down([[h]]);else if(x===T)L(),f.down([[T]]);else if(x===k)L(),f.down([O]);else if(x===C){L(),f.down([O]);return}else f.down([O])}});return()=>{c=!0,g.cancel(),Z()}},{...R(),initial:e.cache,meta:{droppedCount:0,...N("rateLimiter",t)}});return{node:u,droppedCount:u.meta.droppedCount}}function ue(e){let t=new Y(e);return{push:n=>t.push(n),shift:()=>t.shift(),get size(){return t.size}}}function se(){let e=[];return{push:t=>{e.push(t)},shift:()=>e.shift(),get size(){return e.length}}}function Ce(e,t){let n=t?.initialStatus??"pending",r=E([],(s,d)=>{let o=n;return r.meta.status.down([[w,n]]),r.meta.error.down([[w,null]]),e.subscribe(u=>{for(let f of u){let p=f[0];if(p===y)d.down([[y]]);else if(p===w)o==="errored"?D(()=>{r.meta.error.down([[w,null]]),r.meta.status.down([[w,"running"]])}):r.meta.status.down([[w,"running"]]),o="running",d.emit(f[1]);else if(p===h)d.down([[h]]);else if(p===T)r.meta.status.down([[w,"completed"]]),o="completed",d.down([[T]]);else if(p===k){let a=j(f);D(()=>{r.meta.error.down([[w,a]]),r.meta.status.down([[w,"errored"]])}),o="errored",d.down([f])}else d.down([f])}})},{...R(),meta:{status:n,error:null,...N("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:e.cache});return{node:r,status:r.meta.status,error:r.meta.error}}var U=class extends Error{name="TimeoutError";constructor(t){super(`Timed out after ${t/1e6}ms`)}};function de(e){return e!=null&&typeof e=="object"&&"cache"in e&&typeof e.subscribe=="function"}function fe(e){return e!=null&&typeof e.then=="function"}function ae(e){return e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function"}function Ee(e,t){return B(n=>{let r,s;function d(){s?.(),s=void 0,de(t)||fe(t)||ae(t)?r=$(t).subscribe(i=>{n.down(i);for(let u of i){let f=u[0];if(f===T||f===k||f===C){r=void 0;return}}}):(n.emit(t),n.down([[T]]))}return s=e.subscribe(o=>{for(let i of o){let u=i[0];if(u===y)n.down([[y]]);else if(u===w)n.emit(i[1]);else if(u===h)n.down([[h]]);else if(u===T)n.down([[T]]);else if(u===k){d();return}else if(u===C){r?.(),n.down([i]);return}else n.down([i])}}),()=>{s?.(),r?.()}},{...R(),initial:e.cache,meta:{...N("fallback")}})}function Ae(e,t){if(t<=0)throw new RangeError("timeoutNs must be > 0");return B(n=>{let r=!1,s=new _;function d(){let i=t/1e6;s.start(i,()=>{r||(r=!0,o(),n.down([[k,new U(t)]]))})}let o=e.subscribe(i=>{for(let u of i){if(r)return;let f=u[0];if(f===y)n.down([[y]]);else if(f===w)d(),n.emit(u[1]);else if(f===h)n.down([[h]]);else if(f===T){s.cancel(),r=!0,n.down([[T]]);return}else if(f===k){s.cancel(),r=!0,n.down([u]);return}else if(f===C){s.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return d(),()=>{r=!0,s.cancel(),o()}},{...R(),initial:e.cache,meta:{...N("timeout",{timeoutNs:t})}})}export{ee as a,Oe as b,W as c,xe as d,Be as e,ie as f,G as g,Se as h,Ce as i,U as j,Ee as k,Ae as l};
|
package/dist/chunk-MC4UYY2X.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as l,b as s,d,e as m,h as f,i as b,k as c,l as p}from"./chunk-IUB4NYI2.js";import{a as n,b as o}from"./chunk-4VVTGLXJ.js";import{b as S}from"./chunk-QYADASLV.js";var R={};S(R,{NS_PER_MS:()=>n,NS_PER_SEC:()=>o,resilientPipeline:()=>O});function O(k,e={}){let t=k;if(e.rateLimit!=null){let r={...e.rateLimit,maxBuffer:e.rateLimit.maxBuffer??1/0};t=f(t,r).node}e.budget!=null&&e.budget.length>0&&(t=l(t,e.budget));let a;if(e.breaker!=null){let r=d(e.breaker),y=e.breakerOnOpen??"skip",u=m(r,{onOpen:y})(t);t=u.node,a=u.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");t=p(t,e.timeoutMs*1e6)}e.retry!=null&&(t=s(t,e.retry)),e.fallback!==void 0&&(t=c(t,e.fallback));let i=b(t,{initialStatus:e.initialStatus??"pending"});return{node:i.node,status:i.status,error:i.error,breakerState:a}}export{O as a,R as b};
|
package/dist/chunk-XEUANKBO.js
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import{a as Fe}from"./chunk-HAWKGIXM.js";import{d as Pe}from"./chunk-5XRI6RM3.js";import{t as Z}from"./chunk-EWF7KCDJ.js";import{c as _e}from"./chunk-NQI2C36M.js";import{g as $e,i as le}from"./chunk-N7UIBZCW.js";import{b as q}from"./chunk-D27JNOLZ.js";import{a as Me}from"./chunk-ZJ7SM3G2.js";import{a as ue}from"./chunk-VJJLIEAL.js";import{f as Oe,i as we}from"./chunk-7JRF5YEK.js";import{b as S,s as U,t as Ce,x as _}from"./chunk-L7WY6TZS.js";import{b as Ae}from"./chunk-35JTVPOX.js";import{b as X}from"./chunk-TZQPPQEQ.js";import{C as Se,m as z}from"./chunk-IA7DUNGB.js";import{D as Ne,E as A,F as Q,G as b,H as $,o as V}from"./chunk-LYCLF26R.js";import{b as F,i as P,j as W}from"./chunk-CK2E7BTU.js";import{b as tt}from"./chunk-QYADASLV.js";var wt={};tt(wt,{DEFAULT_DECAY_RATE:()=>D,DEFAULT_EXECUTE_PROMPT:()=>de,DEFAULT_QUEUE_CONFIGS:()=>ee,DEFAULT_SEVERITY_WEIGHTS:()=>L,DEFAULT_TRIAGE_PROMPT:()=>ce,DEFAULT_VERIFY_PROMPT:()=>pe,HarnessGraph:()=>re,QUEUE_NAMES:()=>k,actuatorExecutor:()=>Ve,affectedTaskFilter:()=>pt,autoSolidify:()=>it,beforeAfterCompare:()=>dt,codeChangeBridge:()=>ft,createIntakeBridge:()=>ut,defaultErrorClassifier:()=>te,defaultLlmExecutor:()=>Qe,defaultLlmVerifier:()=>Ue,dispatchActuator:()=>at,effectivenessTracker:()=>yt,evalIntakeBridge:()=>lt,evalSource:()=>ct,evalVerifier:()=>Le,harnessEvalPair:()=>xt,harnessLoop:()=>It,harnessProfile:()=>Nt,harnessTrace:()=>St,notifyEffect:()=>mt,priorityScore:()=>ht,refineExecutor:()=>fe,resolvePromptFn:()=>B,strategyKey:()=>j,strategyModel:()=>me});function rt(e,t){return{outcome:"success",detail:`actuator applied ${t.intervention} for ${st(t.summary)}`,artifact:e}}function nt(e,t){let o=e instanceof Error?e.message:String(e);return{outcome:"failure",detail:`actuator threw on ${t.intervention}: ${o}`}}function ot(e){return`actuator skipped ${e.intervention} (shouldApply returned false)`}function st(e,t=80){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Ve(e){let t=e.name??"actuator-executor",o=e.toOutput??rt,s=e.onError??nt,n=e.skipDetail??ot;return d=>{let r=S(d,i=>i!=null,{name:`${t}/gate-in`}),a=_(r,i=>e.shouldApply&&!e.shouldApply(i)?Q(c=>(c.down([[F,{outcome:"failure",detail:n(i)}],[P]]),()=>{}),{name:`${t}/skip`}):Q(c=>{let m=new AbortController,f=!1,l=null,g=R=>{f||(f=!0,c.down([[F,R],[P]]),l?.(),l=null)},y;try{let R=e.apply(i,{signal:m.signal});y=z(R,{signal:m.signal})}catch(R){return g(s(R,i)),()=>{m.abort()}}return l=y.subscribe(R=>{for(let E of R){if(f)return;if(E[0]===F){g(o(E[1],i));return}if(E[0]===W){g(s(E[1],i));return}if(E[0]===P){g(s(new Error("actuator inner completed without emitting DATA"),i));return}}}),f&&l&&(l(),l=null),()=>{m.abort(),l?.(),l=null}},{name:`${t}/inner`}),{name:t});return S(a,i=>i!=null,{name:`${t}/gate-out`})}}function at(e){let t=e.name??"dispatch-actuator",o=e.default??null,s=o!=null;return Ve({apply:(n,d)=>{let r=Object.hasOwn(e.routes,n.intervention)?e.routes[n.intervention]:o;if(!r)throw new Error(`dispatchActuator: no route for intervention '${n.intervention}'`);return r(n,d)},shouldApply:n=>Object.hasOwn(e.routes,n.intervention)||s,skipDetail:n=>`no route for intervention '${n.intervention}'`,name:t})}function it(e){let t=e.name??"auto-solidify",o=e.extract??(n=>n.execution.artifact??null),s=e.predicate??(()=>!0);return Q(n=>{let d=null,r=!1,a=()=>{r||(r=!0,d?.(),d=null)},i=c=>{r||(n.down([[W,c]]),a())};return d=e.verifyResults.subscribe(c=>{if(!r)for(let m of c){if(r)return;if(m[0]!==F){if(m[0]===P){n.down([[P]]),a();return}continue}let f=m[1];if(f==null||!f.verified)continue;let l;try{l=s(f)}catch(y){i(y);return}if(!l)continue;let g;try{g=o(f)}catch(y){i(y);return}if(g!=null){try{e.write(g,f)}catch(y){i(y);return}n.down([[F,g]])}}}),r&&d&&(d(),d=null),()=>{a()}},{name:t})}function ut(e,t,o,s){return $([e],([n])=>{if(n==null)return;let d=o(n);for(let r of d)t.publish(r)},{name:s?.name??"intake-bridge"})}function lt(e,t,o){let s=o?.defaultSeverity??"medium";return $([e],([n])=>{if(n==null)return;let d=Array.isArray(n)?n:[n];for(let r of d)for(let a of r.tasks)if(!(a.valid&&a.judge_scores?.every(i=>i.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){t.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${r.model})`,evidence:`Run ${r.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:s});continue}if(a.judge_scores)for(let i of a.judge_scores)i.pass||t.publish({source:"eval",summary:`${a.task_id}: ${i.claim} (model: ${r.model})`,evidence:i.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:s})}},{name:o?.name??"eval-intake-bridge"})}function ct(e,t){return _(e,()=>z(t()))}function dt(e,t){return b([e,t],([o,s])=>{let n=o,d=s,r=new Map(n.tasks.map(l=>[l.task_id,l])),a=new Map(d.tasks.map(l=>[l.task_id,l])),i=new Set([...r.keys(),...a.keys()]),c=[],m=[],f=[];for(let l of i){let g=r.get(l),y=a.get(l),R=g?.valid??!1,E=y?.valid??!1,I=g?.judge_scores?g.judge_scores.filter(w=>w.pass).length:void 0,N=y?.judge_scores?y.judge_scores.filter(w=>w.pass).length:void 0,O=I!==void 0&&N!==void 0?N-I:void 0;c.push({taskId:l,before:R,after:E,scoreDiff:O}),R&&!E&&m.push(l),!R&&E&&f.push(l)}return{newFailures:m,resolved:f,taskDeltas:c,overallImproved:f.length>m.length}},{name:"eval-delta"})}function pt(e,t){let o=t==null?null:Array.isArray(t)?A(t):t,s=[e];return o&&s.push(o),b(s,n=>{let d=n[0],r=o?new Set(n[1]):null,a=new Set;for(let i of d)for(let c of i.affectsEvalTasks??[])(r==null||r.has(c))&&a.add(c);return[...a].sort()},{name:"affected-task-filter"})}function ft(e,t,o,s){let n=s?.defaultSeverity??"high";function d(a){let i=[];for(let c of a.lintErrors??[])i.push({source:"code-change",summary:`Lint: ${c.rule} in ${c.file}:${c.line}`,evidence:c.message,affectsAreas:[c.file],severity:n});for(let c of a.testFailures??[])i.push({source:"test",summary:`Test failure: ${c.testId}`,evidence:c.message,affectsAreas:[c.file],affectsEvalTasks:[c.testId],severity:n});return i}let r=o??d;return $([e],([a])=>{if(a!=null)for(let i of r(a))t.publish(i)},{name:s?.name??"code-change-bridge"})}function mt(e,t,o){return $([e.latest],([s])=>{s!=null&&t(s)},{name:o?.name??"notify-effect"})}var k=["auto-fix","needs-decision","investigation","backlog"],ee={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},L={critical:100,high:70,medium:40,low:10},D=Math.LN2/(168*3600);function j(e,t){return`${e}\u2192${t}`}var gt=/\b(parse|json|config|validation|syntax)\b/i,te=e=>gt.test(e.detail)?"self-correctable":"structural",ce=`You are a triage classifier for a reactive collaboration harness.
|
|
2
|
-
|
|
3
|
-
Given an intake item, classify it and output JSON:
|
|
4
|
-
{
|
|
5
|
-
"rootCause": "composition" | "missing-fn" | "bad-docs" | "schema-gap" | "regression" | "unknown",
|
|
6
|
-
"intervention": "template" | "catalog-fn" | "docs" | "wrapper" | "schema-change" | "investigate",
|
|
7
|
-
"route": "auto-fix" | "needs-decision" | "investigation" | "backlog",
|
|
8
|
-
"priority": <number 0-100>,
|
|
9
|
-
"triageReasoning": "<one sentence>"
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
Strategy model (past effectiveness):
|
|
13
|
-
{{strategy}}
|
|
14
|
-
|
|
15
|
-
Intake item:
|
|
16
|
-
{{item}}`,de=`You are an implementation agent.
|
|
17
|
-
|
|
18
|
-
Given a triaged issue with root cause and intervention type, produce a fix.
|
|
19
|
-
|
|
20
|
-
Issue:
|
|
21
|
-
{{item}}
|
|
22
|
-
|
|
23
|
-
Output JSON:
|
|
24
|
-
{
|
|
25
|
-
"outcome": "success" | "failure" | "partial",
|
|
26
|
-
"detail": "<description of what was done or what failed>"
|
|
27
|
-
}`,pe=`You are a QA reviewer.
|
|
28
|
-
|
|
29
|
-
Given an execution result, verify whether the fix is correct.
|
|
30
|
-
|
|
31
|
-
Execution:
|
|
32
|
-
{{execution}}
|
|
33
|
-
|
|
34
|
-
Original issue:
|
|
35
|
-
{{item}}
|
|
36
|
-
|
|
37
|
-
Output JSON:
|
|
38
|
-
{
|
|
39
|
-
"verified": true/false,
|
|
40
|
-
"findings": ["<finding1>", ...],
|
|
41
|
-
"errorClass": "self-correctable" | "structural" // only if verified=false
|
|
42
|
-
}`;function B(e,t,o){if(typeof e=="function")return e;let s=e??t;return n=>o(s,n)}function yt(e){let t=X({name:e?.name??"effectiveness-entries"}),o=b([t.entries],([r])=>new Map(r),{name:`${e?.name??"effectiveness"}-snapshot`,equals:(r,a)=>{let i=r,c=a;if(i.size!==c.size)return!1;for(let[m,f]of i){let l=c.get(m);if(!l||f.attempts!==l.attempts||f.successes!==l.successes)return!1}return!0}});function s(r,a){let i=t.get(r),c=(i?.attempts??0)+1,m=(i?.successes??0)+(a?1:0);t.set(r,{key:r,attempts:c,successes:m,successRate:m/c})}function n(r){return t.get(r)}let d=Se(o);return{node:o,record:s,lookup:n,dispose:()=>{d(),t.dispose()}}}function Tt(e){let{best:t,score:o,status:s}=e,n=Number.isFinite(o)?o.toFixed(3):String(o),d=t??void 0;return s==="converged"?{outcome:"success",detail:`refineLoop converged at score ${n}`,artifact:d}:s==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${n}`,artifact:d}:{outcome:"failure",detail:`refineLoop errored (status=${s})`,artifact:d}}function fe(e){let t=e.name??"refine-executor",o=e.toOutput??Tt;return s=>{let n=S(s,r=>r!=null,{name:`${t}/gate-in`}),d=_(n,r=>{let a=Fe(e.seedFrom(r),e.evaluator,e.strategy,{...e.refine,dataset:e.datasetFor(r),name:`${t}/inner`});return b([a.status,a.best,a.score],([i,c,m])=>{let f=i;return f!=="converged"&&f!=="budget"&&f!=="errored"?null:o({best:c,score:m,status:f})},{name:`${t}/output`})},{name:t});return S(d,r=>r!=null,{name:`${t}/gate-out`})}}function Et(e){if(e.length===0)return Number.NEGATIVE_INFINITY;let t=0;for(let o of e)t+=o.score;return t/e.length}function vt(e){let{passCount:t,total:o,meanScore:s,threshold:n,missingArtifact:d}=e,r=Number.isFinite(s)?s.toFixed(3):String(s),a=!d&&o>0&&s>=n,i=d?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${t}/${o} eval tasks passed; mean score ${r} \u2265 ${n}`]:o===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${t}/${o} eval tasks passed; mean score ${r} < threshold ${n}`];return a?{verified:!0,findings:i}:{verified:!1,findings:i,errorClass:"structural"}}function Rt(e){return e.artifact??null}function Le(e){let t=e.name??"eval-verifier",o=e.threshold??.5,s=e.toOutput??vt,n=e.extractArtifact??Rt;return d=>{let r=S(d,i=>i!=null&&i[0]!=null&&i[1]!=null,{name:`${t}/gate-in`}),a=_(r,i=>{let[c,m]=i,f=n(c,m);if(f==null)return A(s({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:o,missingArtifact:!0}));let l=A([f],{name:`${t}/candidates`}),g=A(e.datasetFor(m),{name:`${t}/dataset`}),y=e.evaluator(l,g);return b([y],([R])=>{let E=R;if(E==null)return null;let I=Et(E),N=E.filter(O=>O.score>=o).length;return s({scores:E,meanScore:I,passCount:N,total:E.length,threshold:o})},{name:`${t}/output`})},{name:t});return S(a,i=>i!=null,{name:`${t}/gate-out`})}}function xt(e){let t=e.name??"harness-pair",o=fe({name:`${t}-exec`,seedFrom:e.seedFrom,evaluator:e.evaluator,strategy:e.strategy,datasetFor:e.datasetFor,refine:e.refine}),s=Le({name:`${t}-verify`,evaluator:e.evaluator,datasetFor:e.datasetFor,threshold:e.threshold});return{executor:o,verifier:s}}function me(){let e=X({name:"strategy-entries"}),t=b([e.entries],([r])=>{let a=r;return new Map(a)},{name:"strategy-model",equals:(r,a)=>{let i=r,c=a;if(i.size!==c.size)return!1;for(let[m,f]of i){let l=c.get(m);if(!l||f.attempts!==l.attempts||f.successes!==l.successes)return!1}return!0}});function o(r,a,i){let c=j(r,a),m=e.get(c),f=(m?.attempts??0)+1,l=(m?.successes??0)+(i?1:0);e.set(c,{rootCause:r,intervention:a,attempts:f,successes:l,successRate:l/f})}function s(r,a){return e.get(j(r,a))}let n=t.subscribe(()=>{});function d(){n()}return{node:t,record:o,lookup:s,dispose:d}}function ht(e,t,o,s,n){let d={...L,...n?.severityWeights},r=n?.decayRate??D,a=n?.effectivenessThreshold??.7,i=n?.effectivenessBoost??15,c=[e,t,o];return s&&c.push(s),b(c,m=>{let f=m[0],l=m[1],g=m[2],y=s?m[3]:0,R=d[f.severity??"medium"],E=(V()-g)/1e9,I=Me(R,E,r,0),N=j(f.rootCause,f.intervention),O=l.get(N);return O&&O.successRate>=a&&(I+=i),I+=y*20,I},{name:"priority-score"})}var De="intake",bt="triage-output",je="retry",Ge="verify-results",He="__unrouted";function Qe(e,t){let o=B(t,de,(s,n)=>s.replace("{{item}}",JSON.stringify(n)));return s=>Z(e,[s],o,{name:"execute",format:"json"})}function Ue(e,t){let o=B(t,pe,(s,n)=>{let[d,r]=n;return s.replace("{{execution}}",JSON.stringify(d)).replace("{{item}}",JSON.stringify(r))});return s=>Z(e,[s],n=>n==null?"":o(n),{name:"verify",format:"json"})}var re=class extends we{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(t,o,s,n,d,r,a,i,c){super(t),this.queues=o,this.queueTopics=s,this.jobs=n,this.gates=d,this.strategy=r,this.totalRetries=a,this.totalReingestions=i,this.priorityScores=c}get intake(){return this.queues.topic(De)}get verifyResults(){return this.queues.topic(Ge)}get retry(){return this.queues.topic(je)}get unrouted(){return this.queues.topic(He)}stageNodes(){let t=this.queues,o=r=>t.has(r)?`queues::${r}::latest`:null,s=r=>r==null?[]:[r],n=k.flatMap(r=>s(o(r))),d=[];for(let[r]of this.gates)d.push(`gates::${r}/gate`);return[{label:"INTAKE",paths:s(o("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:n},{label:"GATE",paths:d},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:s(o("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function It(e,t){let o=t.adapter,s=t.maxRetries??2,n=t.retainedLimit??1e3,d=t.errorClassifier??te,r=new Map;for(let u of k)r.set(u,{...ee[u],...t.queues?.[u]});let a=$e(`${e}/queues`,{defaultTopicOptions:{retainedLimit:n}}),i=a.topic(De),c=a.topic(bt),m=a.topic(je),f=a.topic(Ge),l=new Map;for(let u of k)l.set(u,a.topic(u));let g=a.topic(He),y=me(),R=U(i.latest,y.node),E=B(t.triagePrompt,ce,(u,p)=>{let[T,x]=p;return u.replace("{{strategy}}",JSON.stringify(Array.from(x.entries()))).replace("{{item}}",JSON.stringify(T))}),I=Z(o,[R],u=>{let p=u;return!p||!p[0]?"":E(p)},{name:"triage",format:"json"}),N=U(I,R),w=$([N],([u])=>{if(u==null)return;let[p,T]=u;if(!p?.route)return;let x=T?.[0],C={...p,...x};c.publish(C)}).subscribe(()=>{}),Be=new Set(k);for(let u of k)le(`bridge/${u}`,c,l.get(u),{map:p=>p.route===u?p:void 0});le("bridge/__unrouted",c,g,{map:u=>Be.has(u.route)?void 0:u});let G=new Map,ne=new Map;for(let u of k)G.set(u,Pe(`jobs/${u}`));let ge=[];for(let u of k){let p=l.get(u),T=G.get(u),x=new WeakSet,C=$([p.events],([ie])=>{let H=ie??[];for(let h of H){if(x.has(h))continue;x.add(h);let M=T.enqueue(h);ne.set(q(h),{route:u,id:M})}},{name:`jobs/${u}-mirror`});ge.push(C.subscribe(()=>{}))}function ye(u){let p=q(u),T=ne.get(p);T&&(G.get(T.route)?.removeById(T.id),ne.delete(p))}let Te=_e("gates"),Y=new Map;for(let u of k){let p=r.get(u);if(!p.gated)continue;let T=l.get(u),x=Te.approvalGate(`${u}/gate`,T.latest,{maxPending:p.maxPending,startOpen:p.startOpen});Y.set(u,x)}let J=[];for(let u of k)r.get(u).gated&&Y.has(u)?J.push(Y.get(u).node):J.push(l.get(u).latest);J.push(m.latest);let oe=Ce(...J),Ee=(t.executor??Qe(o,t.executePrompt))(oe),se=U(Ee,oe),ve=(t.verifier??Ue(o,t.verifyPrompt))(se),Re=U(ve,se),xe=t.maxReingestions??1,Ye=Math.min(t.maxTotalRetries??s*10,100),Je=Math.min(t.maxTotalReingestions??xe*10,100),he=A(0),be=A(0);function Ke(u,p,T){let x={item:T,outcome:p?.outcome??"failure",detail:p?.detail??"unknown",artifact:p?.artifact};return{item:T,execution:x,verified:u.verified,findings:u.findings??[],errorClass:u.errorClass}}function We(u,p){y.record(p.rootCause,p.intervention,!0),f.publish(u),ye(p)}function ze(u,p){let T=q(p),x=p.$retries??0,C={...p,$retries:x+1,summary:`[RETRY ${x+1}/${s}] ${T} \u2014 Previous attempt failed: ${u.findings.join("; ")}`,relatedTo:[T]};m.publish(C)}function Ie(u,p){y.record(p.rootCause,p.intervention,!1),f.publish(u),ye(p);let T=q(p),x=p.$reingestions??0;x<xe&&ue(be,Je)&&i.publish({source:p.source,summary:`Verification failed for: ${T}`,evidence:u.findings.join(`
|
|
43
|
-
`),affectsAreas:p.affectsAreas,affectsEvalTasks:p.affectsEvalTasks,severity:p.severity??"high",relatedTo:[T],$reingestions:x+1})}let ae=Ne([Re],(u,p)=>{let T=u[0];if(T==null||T.length===0)return;let x=T[T.length-1];if(x==null)return;let[C,ie]=x,[H,h]=ie??[null,null];if(!C||!h)return;if(H==null){Ie({item:h,execution:{item:h,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},h);return}let M=Ke(C,H,h);if(M.verified){We(M,h);return}let Ze=M.errorClass??d({item:h,outcome:H.outcome,detail:M.findings.join("; ")}),et=h.$retries??0;Ze==="self-correctable"&&et<s&&ue(he,Ye)?ze(M,h):Ie(M,h)}),Xe=ae.subscribe(()=>{}),ke=b([ae],()=>null,{name:"reflect",equals:()=>!1}),K;t.priority&&(K=kt(l,y,t));let v=new re(e,a,l,G,Y,y,he,be,K);v.addDisposer(w),v.addDisposer(Xe),v.addDisposer(y.dispose);for(let u of ge)v.addDisposer(u);if(v.add(I,{name:"triage"}),v.add(oe,{name:"execute-input"}),v.add(Ee,{name:"execute"}),v.add(se,{name:"execute-context"}),v.add(ve,{name:"verify"}),v.add(Re,{name:"verify-context"}),v.add(ae,{name:"verify-dispatch"}),v.add(ke,{name:"reflect"}),v.add(y.node,{name:"strategy"}),v.addDisposer(ke.subscribe(()=>{})),K)for(let[u,p]of K)v.add(p,{name:`priority/${u}`}),v.addDisposer(p.subscribe(()=>{}));v.mount("queues",a),v.mount("gates",Te);for(let[u,p]of G)v.mount(`jobs/${u}`,p);return v.tagFactory("harnessLoop",Ae(t)),v}function kt(e,t,o){if(!o.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let s=o.lastInteractionNs,n=o.priority??{},d={...L,...n.severityWeights},r=n.decayRate??D,a=n.effectivenessThreshold??.7,i=n.effectivenessBoost??15,c=new Map;for(let[m,f]of e){let l=b([f.latest,t.node,s],g=>{let y=g[0];if(y==null)return 0;let R=d[y.severity??"medium"]??40,E=(V()-g[2])/1e9,I=R*Math.exp(-r*Math.max(0,E)),N=`${y.rootCause}\u2192${y.intervention}`,w=g[1]?.get(N);return w&&w.successRate>=a&&(I+=i),I},{name:`priority/${m}`});c.set(m,l)}return c}function Nt(e,t){let o=Oe(e,t),s={};for(let n of k){let d=e.queues.has(n)?e.queues.topic(n):null;s[n]=d?.retained().length??0}return{...o,queueDepths:s,strategyEntries:e.strategy.node.cache?.size??0,totalRetries:e.totalRetries.cache??0,totalReingestions:e.totalReingestions.cache??0}}function At(e){let t={};for(let{label:o,paths:s}of e.stageNodes())for(let n of s)t[n]=o;return t}function St(e,t){let o=t?.logger===null?null:t?.logger??console.log,s=t?.detail??"summary",n=V(),d=[],r=[],a=At(e);function i(){return(V()-n)/1e9}function c(m,f,l){let g={elapsed:i(),stage:m,type:f};s!=="summary"&&(g.summary=Ot(l)),s==="full"&&(g.data=l),r.push(g)}for(let[m,f]of Object.entries(a))try{let l=e.observe(m,{format:"stage-log",stageLabels:a,logger:o?g=>o(g):()=>{},includeTypes:["data","error","complete"]});l.onEvent(g=>{g.type==="data"?c(f,"data",g.data):g.type==="error"?c(f,"error",g.data):g.type==="complete"&&c(f,"complete",void 0)}),d.push(l)}catch(l){let g=l instanceof Error?l.message:String(l);c(f,"error",`observe-unavailable: ${m} \u2014 ${g}`),o&&o(`[${i().toFixed(3)}s] ${f.padEnd(9)} \u2717 observe-unavailable: ${g}`)}return{get events(){return r},dispose(){for(let m of d)m.dispose();d.length=0}}}function Ot(e){if(e==null)return"null";if(typeof e=="string")return qe(e,80);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{let t=JSON.stringify(e);return qe(t,120)}catch{return String(e)}}function qe(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}export{Ve as a,at as b,it as c,ut as d,lt as e,ct as f,dt as g,pt as h,ft as i,mt as j,k,ee as l,L as m,D as n,j as o,te as p,ce as q,de as r,pe as s,B as t,yt as u,fe as v,Le as w,xt as x,me as y,ht as z,Qe as A,Ue as B,re as C,It as D,Nt as E,St as F,wt as G};
|
package/dist/chunk-ZJ7SM3G2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function r(t,i,m,u=0){if(!Number.isFinite(t))return u;if(!Number.isFinite(i)||i<=0||!Number.isFinite(m)||m<=0)return Math.max(u,t);let n=t*Math.exp(-m*i);return Math.max(u,n)}export{r as a};
|
package/dist/index-BEHmxORq.d.ts
DELETED
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
import { P as PolicyRuleData, N as Node, A as Actor } from './node-BYInONRr.js';
|
|
2
|
-
import { G as Graph, a as GraphOptions, d as GraphDescribeOptions, b as GraphDescribeOutput, D as DescribeFilter } from './graph-30XSgtVX.js';
|
|
3
|
-
import { P as PolicyGateGraph, a as PolicyViolation } from './index-BC9VybQs.js';
|
|
4
|
-
import { T as TopicGraph } from './index-DszPlZzK.js';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Composable safety layer (roadmap §9.0b).
|
|
8
|
-
*
|
|
9
|
-
* {@link guardedExecution} wraps any {@link Graph} with:
|
|
10
|
-
*
|
|
11
|
-
* - {@link policyGate} — reactive ABAC (Tier 2.3 rename of `policyEnforcer`),
|
|
12
|
-
* policies stored as a `Node` so LLMs / humans can update them at runtime.
|
|
13
|
-
* Now with full transitive dynamic coverage via `watchTopologyTree`.
|
|
14
|
-
* - Scoped {@link GuardedExecutionGraph.scopedDescribe} — delegates to
|
|
15
|
-
* `target.describe({actor})` so callers see only what the actor is
|
|
16
|
-
* allowed to see.
|
|
17
|
-
* - The enforcer's `violations` topic is republished as `violations` on
|
|
18
|
-
* the wrapper, composable with {@link graphLens}.`health` alerts.
|
|
19
|
-
*
|
|
20
|
-
* V1 scope: policies + actor + scoped describe. Budget-as-option is NOT
|
|
21
|
-
* in V1 — it requires a cost-tracking design that hasn't landed yet.
|
|
22
|
-
* Callers who need a budget limit today append a budget-aware
|
|
23
|
-
* {@link PolicyRuleData} to the policies list (check current cost and
|
|
24
|
-
* `deny` when exhausted).
|
|
25
|
-
*
|
|
26
|
-
* @module
|
|
27
|
-
*/
|
|
28
|
-
|
|
29
|
-
/** Options for {@link guardedExecution}. */
|
|
30
|
-
interface GuardedExecutionOptions {
|
|
31
|
-
/**
|
|
32
|
-
* Policies enforced against every guarded write. Static list or a live
|
|
33
|
-
* `Node<readonly PolicyRuleData[]>` (LLM-updatable).
|
|
34
|
-
*
|
|
35
|
-
* **Deny-by-default gotcha:** the underlying `policyFromRules()` denies any
|
|
36
|
-
* action that matches no rule. An empty policies list in `mode: "enforce"`
|
|
37
|
-
* therefore blocks EVERY write AND every `observe` through the stacked
|
|
38
|
-
* guard — including `scopedDescribe()`. If you want a permissive base, add
|
|
39
|
-
* at least `{ effect: "allow", action: "*" }` and layer deny rules on top.
|
|
40
|
-
* In `mode: "audit"` no guards are stacked, so empty policies are safe.
|
|
41
|
-
*/
|
|
42
|
-
policies: readonly PolicyRuleData[] | Node<readonly PolicyRuleData[]>;
|
|
43
|
-
/**
|
|
44
|
-
* Actor whose perspective drives {@link GuardedExecutionGraph.scopedDescribe}
|
|
45
|
-
* and {@link GuardedExecutionGraph.describe} — when omitted, callers must
|
|
46
|
-
* pass `{actor}` explicitly or they get the target's raw describe.
|
|
47
|
-
*/
|
|
48
|
-
actor?: Actor;
|
|
49
|
-
/**
|
|
50
|
-
* `"enforce"` (default) — push guards onto target nodes so disallowed
|
|
51
|
-
* writes throw {@link GuardDenied}.
|
|
52
|
-
* `"audit"` — record would-be denials to the `violations` topic without
|
|
53
|
-
* blocking writes.
|
|
54
|
-
*/
|
|
55
|
-
mode?: "audit" | "enforce";
|
|
56
|
-
/** Ring-buffer cap for the `violations` topic. Default 1000 (inherited from policyGate). */
|
|
57
|
-
violationsLimit?: number;
|
|
58
|
-
/** Wrapper graph name. Default `${target.name}_guarded`. */
|
|
59
|
-
name?: string;
|
|
60
|
-
/** Wrapper graph options. */
|
|
61
|
-
graph?: GraphOptions;
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Wrapper over a target {@link Graph} providing reactive ABAC + scoped
|
|
65
|
-
* describe. Mounts a {@link PolicyGateGraph} under `enforcer`.
|
|
66
|
-
*
|
|
67
|
-
* @category patterns
|
|
68
|
-
*/
|
|
69
|
-
declare class GuardedExecutionGraph extends Graph {
|
|
70
|
-
readonly enforcer: PolicyGateGraph;
|
|
71
|
-
readonly violations: TopicGraph<PolicyViolation>;
|
|
72
|
-
private readonly _target;
|
|
73
|
-
private readonly _defaultActor;
|
|
74
|
-
constructor(target: Graph, opts: GuardedExecutionOptions);
|
|
75
|
-
/**
|
|
76
|
-
* Describe the **target** graph scoped to the configured actor. Returns
|
|
77
|
-
* only nodes the actor is permitted to see (via the target's node guards
|
|
78
|
-
* filtering `describe()` via `actor`).
|
|
79
|
-
*
|
|
80
|
-
* Pass `{actor}` in opts to override the configured actor for this call.
|
|
81
|
-
* Pass any standard {@link GraphDescribeOptions} fields (`detail`,
|
|
82
|
-
* `fields`, `filter`) — they apply to the target's describe.
|
|
83
|
-
*
|
|
84
|
-
* **Mode interaction:**
|
|
85
|
-
* - In `mode: "enforce"` (default), the enforcer stacks a policy-derived
|
|
86
|
-
* guard on every target node. `scopedDescribe({actor})` then filters by
|
|
87
|
-
* the AND of per-node guards AND the stacked policy guard.
|
|
88
|
-
* - In `mode: "audit"`, NO guards are stacked — `scopedDescribe` filters
|
|
89
|
-
* purely by the target's pre-existing per-node guards. If a target has
|
|
90
|
-
* no node-level guards, the policy rules you pass have no effect on
|
|
91
|
-
* visibility (they only populate the `violations` topic on writes).
|
|
92
|
-
*/
|
|
93
|
-
scopedDescribe(opts?: Omit<GraphDescribeOptions, "actor"> & {
|
|
94
|
-
actor?: Actor;
|
|
95
|
-
}): GraphDescribeOutput;
|
|
96
|
-
/** The wrapped graph (escape hatch for tooling). */
|
|
97
|
-
get target(): Graph;
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Wrap a {@link Graph} with {@link policyGate} plus a scoped describe
|
|
101
|
-
* lens. Returns a {@link GuardedExecutionGraph} that can be mounted, diffed,
|
|
102
|
-
* or composed with {@link graphLens}.
|
|
103
|
-
*
|
|
104
|
-
* @param target - The graph to guard.
|
|
105
|
-
* @param opts - See {@link GuardedExecutionOptions}.
|
|
106
|
-
*
|
|
107
|
-
* @example
|
|
108
|
-
* ```ts
|
|
109
|
-
* const guarded = guardedExecution(app, {
|
|
110
|
-
* actor: { type: "human", id: "alice" },
|
|
111
|
-
* policies: [
|
|
112
|
-
* { effect: "allow", action: "read", actorType: "human" },
|
|
113
|
-
* { effect: "deny", action: "write", pathPattern: "system::*" },
|
|
114
|
-
* ],
|
|
115
|
-
* mode: "enforce",
|
|
116
|
-
* });
|
|
117
|
-
*
|
|
118
|
-
* const view = guarded.scopedDescribe({ detail: "standard" });
|
|
119
|
-
* guarded.violations.events.subscribe(msgs => console.log("violations:", msgs));
|
|
120
|
-
* ```
|
|
121
|
-
*
|
|
122
|
-
* @category patterns
|
|
123
|
-
*/
|
|
124
|
-
declare function guardedExecution(target: Graph, opts: GuardedExecutionOptions): GuardedExecutionGraph;
|
|
125
|
-
|
|
126
|
-
declare const index_DescribeFilter: typeof DescribeFilter;
|
|
127
|
-
type index_GuardedExecutionGraph = GuardedExecutionGraph;
|
|
128
|
-
declare const index_GuardedExecutionGraph: typeof GuardedExecutionGraph;
|
|
129
|
-
type index_GuardedExecutionOptions = GuardedExecutionOptions;
|
|
130
|
-
declare const index_guardedExecution: typeof guardedExecution;
|
|
131
|
-
declare namespace index {
|
|
132
|
-
export { index_DescribeFilter as DescribeFilter, index_GuardedExecutionGraph as GuardedExecutionGraph, type index_GuardedExecutionOptions as GuardedExecutionOptions, index_guardedExecution as guardedExecution };
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
export { GuardedExecutionGraph as G, type GuardedExecutionOptions as a, guardedExecution as g, index as i };
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
import { N as Node } from './node-BYInONRr.cjs';
|
|
2
|
-
import { S as StatusValue, C as CircuitState, R as RateLimiterOptions, a as CircuitBreakerOptions, b as RetryOptions, F as FallbackInput, N as NS_PER_MS, c as NS_PER_SEC } from './index-CwP_KAMS.cjs';
|
|
3
|
-
import { B as BudgetConstraint } from './budget-gate-DiP_nK0n.cjs';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Resilience composition with correct nesting order (roadmap §9.0b).
|
|
7
|
-
*
|
|
8
|
-
* {@link resilientPipeline} composes the resilience primitives from
|
|
9
|
-
* `extra/resilience.ts` in the order discovered during the §9.1 eval runs:
|
|
10
|
-
*
|
|
11
|
-
* ```text
|
|
12
|
-
* rateLimit → budget → breaker → timeout → retry → fallback → status
|
|
13
|
-
* ```
|
|
14
|
-
*
|
|
15
|
-
* Note on retry/timeout ordering: `timeout` is applied BEFORE `retry` so each
|
|
16
|
-
* retry attempt resubscribes to a fresh deadline (per-attempt semantics). If
|
|
17
|
-
* `timeout` wrapped `retry`, a single deadline would apply to the entire
|
|
18
|
-
* retry chain — not what callers expect.
|
|
19
|
-
*
|
|
20
|
-
* Every step is optional — omit the option and that layer is skipped. The
|
|
21
|
-
* returned bundle exposes the final `Node<T>` plus the status/error/breaker
|
|
22
|
-
* companions so callers can wire them into dashboards, alerts, or
|
|
23
|
-
* {@link graphLens}.
|
|
24
|
-
*
|
|
25
|
-
* Subsumes the pre-1.0 `resilientFetch` template — that template becomes a
|
|
26
|
-
* preconfigured instance of this factory for the HTTP fetch case.
|
|
27
|
-
*
|
|
28
|
-
* @module
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
/** Options for {@link resilientPipeline}. Every field is optional — omit to skip that layer. */
|
|
32
|
-
interface ResilientPipelineOptions<T> {
|
|
33
|
-
/**
|
|
34
|
-
* Admission control — at most `maxEvents` DATA per `windowNs`. See {@link rateLimiter}.
|
|
35
|
-
*
|
|
36
|
-
* `maxBuffer` is optional at the pipeline layer (defaults to `Infinity`, preserving
|
|
37
|
-
* the historical unbounded behavior). Pass an explicit positive integer to opt in to
|
|
38
|
-
* a bounded queue. Tier 5.2 will surface backpressure-policy options to callers.
|
|
39
|
-
*/
|
|
40
|
-
rateLimit?: Omit<RateLimiterOptions, "maxBuffer"> & {
|
|
41
|
-
maxBuffer?: number;
|
|
42
|
-
};
|
|
43
|
-
/** Cost/constraint gate. See {@link budgetGate}. */
|
|
44
|
-
budget?: ReadonlyArray<BudgetConstraint>;
|
|
45
|
-
/** Circuit breaker — fail-fast when the downstream resource is unhealthy. See {@link circuitBreaker}. */
|
|
46
|
-
breaker?: CircuitBreakerOptions;
|
|
47
|
-
/**
|
|
48
|
-
* Behavior when the breaker is open:
|
|
49
|
-
* - `"skip"` — emit RESOLVED (default, lets downstream drop the beat)
|
|
50
|
-
* - `"error"` — emit a `CircuitOpenError` so `retry`/`fallback` can react
|
|
51
|
-
*
|
|
52
|
-
* Only used when `breaker` is provided.
|
|
53
|
-
*/
|
|
54
|
-
breakerOnOpen?: "skip" | "error";
|
|
55
|
-
/** Retry policy on terminal ERROR. See {@link retry}. */
|
|
56
|
-
retry?: RetryOptions;
|
|
57
|
-
/**
|
|
58
|
-
* Per-attempt deadline in milliseconds. Converted to ns internally. Omit to skip the timeout wrap.
|
|
59
|
-
*
|
|
60
|
-
* Specified in ms (not ns) because callers consistently think in millisecond deadlines;
|
|
61
|
-
* retry/breaker/ratelimit options take ns to match their primitives exactly.
|
|
62
|
-
*/
|
|
63
|
-
timeoutMs?: number;
|
|
64
|
-
/** Final fallback value emitted on terminal ERROR after retry exhausts. See {@link fallback}. */
|
|
65
|
-
fallback?: FallbackInput<T>;
|
|
66
|
-
/** Initial status reported by the status node. Default `"pending"`. */
|
|
67
|
-
initialStatus?: StatusValue;
|
|
68
|
-
}
|
|
69
|
-
/** Output bundle of {@link resilientPipeline}. */
|
|
70
|
-
interface ResilientPipelineBundle<T> {
|
|
71
|
-
/** The final resilient node. Subscribe to this for DATA emissions. */
|
|
72
|
-
node: Node<T>;
|
|
73
|
-
/** Live status: `"pending" | "running" | "completed" | "errored"`. */
|
|
74
|
-
status: Node<StatusValue>;
|
|
75
|
-
/** Last error payload, or `null` when not errored. */
|
|
76
|
-
error: Node<unknown | null>;
|
|
77
|
-
/** Breaker state when `opts.breaker` was provided; `undefined` otherwise. */
|
|
78
|
-
breakerState: Node<CircuitState> | undefined;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Compose a resilient pipeline around `source` in the canonical nesting
|
|
82
|
-
* order — `rateLimit → budget → breaker → timeout → retry → fallback → status`.
|
|
83
|
-
* Omit any option to skip that layer.
|
|
84
|
-
*
|
|
85
|
-
* @param source - Upstream node to wrap.
|
|
86
|
-
* @param opts - See {@link ResilientPipelineOptions}. All fields optional.
|
|
87
|
-
*
|
|
88
|
-
* @example
|
|
89
|
-
* ```ts
|
|
90
|
-
* const safeFetch = resilientPipeline(fetchNode, {
|
|
91
|
-
* rateLimit: { maxEvents: 10, windowNs: NS_PER_SEC },
|
|
92
|
-
* breaker: { failureThreshold: 5 },
|
|
93
|
-
* retry: { count: 3, backoff: "exponential" },
|
|
94
|
-
* timeoutMs: 10_000,
|
|
95
|
-
* fallback: null,
|
|
96
|
-
* });
|
|
97
|
-
* safeFetch.status.subscribe(msgs => console.log(msgs));
|
|
98
|
-
* ```
|
|
99
|
-
*
|
|
100
|
-
* @category patterns
|
|
101
|
-
*/
|
|
102
|
-
declare function resilientPipeline<T>(source: Node<T>, opts?: ResilientPipelineOptions<T>): ResilientPipelineBundle<T>;
|
|
103
|
-
|
|
104
|
-
declare const index_NS_PER_MS: typeof NS_PER_MS;
|
|
105
|
-
declare const index_NS_PER_SEC: typeof NS_PER_SEC;
|
|
106
|
-
type index_ResilientPipelineBundle<T> = ResilientPipelineBundle<T>;
|
|
107
|
-
type index_ResilientPipelineOptions<T> = ResilientPipelineOptions<T>;
|
|
108
|
-
declare const index_resilientPipeline: typeof resilientPipeline;
|
|
109
|
-
declare namespace index {
|
|
110
|
-
export { index_NS_PER_MS as NS_PER_MS, index_NS_PER_SEC as NS_PER_SEC, type index_ResilientPipelineBundle as ResilientPipelineBundle, type index_ResilientPipelineOptions as ResilientPipelineOptions, index_resilientPipeline as resilientPipeline };
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
export { type ResilientPipelineBundle as R, type ResilientPipelineOptions as a, index as i, resilientPipeline as r };
|