@directive-run/ai 0.4.0 → 0.4.2
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/anthropic.cjs.map +1 -1
- package/dist/anthropic.js.map +1 -1
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.js.map +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +165 -26
- package/dist/index.d.ts +165 -26
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/{multi-agent-orchestrator-YFs28JsF.d.cts → multi-agent-orchestrator-CFOzWVNd.d.cts} +274 -86
- package/dist/{multi-agent-orchestrator-D-WuP4jP.d.ts → multi-agent-orchestrator-CH-4Fqzg.d.ts} +274 -86
- package/dist/ollama.cjs.map +1 -1
- package/dist/ollama.js.map +1 -1
- package/dist/openai.cjs.map +1 -1
- package/dist/openai.js.map +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +7 -1
- package/dist/testing.d.ts +7 -1
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/package.json +2 -2
package/dist/testing.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { w as MultiAgentOrchestrator, x as MultiAgentOrchestratorOptions, c as AgentOrchestrator, O as OrchestratorOptions, H as HealthMonitor, C as MultiplexedStreamChunk, D as DebugTimeline, ah as TaskRegistration, X as ReflectionEvaluator } from './multi-agent-orchestrator-
|
|
1
|
+
import { w as MultiAgentOrchestrator, x as MultiAgentOrchestratorOptions, c as AgentOrchestrator, O as OrchestratorOptions, H as HealthMonitor, C as MultiplexedStreamChunk, D as DebugTimeline, ah as TaskRegistration, X as ReflectionEvaluator } from './multi-agent-orchestrator-CFOzWVNd.cjs';
|
|
2
2
|
import { o as ApprovalRequest, u as BreakpointModifications, I as InputGuardrailData, O as OutputGuardrailData, M as Message, T as ToolCallGuardrailData, b2 as ToolCall, ad as GuardrailResult, A as AgentLike, b as AgentRunner, R as RunOptions, v as BreakpointRequest, C as Checkpoint, V as DagExecutionContext, X as DagNodeStatus, aN as RerouteEvent, aS as Scratchpad, a1 as DebugEventType, L as CheckpointStore, aj as InMemoryCheckpointStore, W as DagNode, Z as DagPattern, D as DebugEvent, G as GuardrailFn, aa as GuardrailContext } from './types-D5veI9su.cjs';
|
|
3
3
|
import '@directive-run/core';
|
|
4
4
|
import '@directive-run/core/plugins';
|
|
@@ -630,6 +630,12 @@ interface BreakpointCapable {
|
|
|
630
630
|
resumeBreakpoint(id: string, modifications?: BreakpointModifications): void;
|
|
631
631
|
cancelBreakpoint(id: string, reason?: string): void;
|
|
632
632
|
}
|
|
633
|
+
/**
|
|
634
|
+
* Create a breakpoint simulator that auto-resolves breakpoints for testing.
|
|
635
|
+
*
|
|
636
|
+
* @param options - Simulator options including `autoResumeDelay` and `modifications`.
|
|
637
|
+
* @returns An object with `handler`, `hits`, and `attachTo` for test assertions.
|
|
638
|
+
*/
|
|
633
639
|
declare function createBreakpointSimulator(options?: BreakpointSimulatorOptions): {
|
|
634
640
|
handler: (request: BreakpointRequest) => void;
|
|
635
641
|
hits: BreakpointRequest[];
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { w as MultiAgentOrchestrator, x as MultiAgentOrchestratorOptions, c as AgentOrchestrator, O as OrchestratorOptions, H as HealthMonitor, C as MultiplexedStreamChunk, D as DebugTimeline, ah as TaskRegistration, X as ReflectionEvaluator } from './multi-agent-orchestrator-
|
|
1
|
+
import { w as MultiAgentOrchestrator, x as MultiAgentOrchestratorOptions, c as AgentOrchestrator, O as OrchestratorOptions, H as HealthMonitor, C as MultiplexedStreamChunk, D as DebugTimeline, ah as TaskRegistration, X as ReflectionEvaluator } from './multi-agent-orchestrator-CH-4Fqzg.js';
|
|
2
2
|
import { o as ApprovalRequest, u as BreakpointModifications, I as InputGuardrailData, O as OutputGuardrailData, M as Message, T as ToolCallGuardrailData, b2 as ToolCall, ad as GuardrailResult, A as AgentLike, b as AgentRunner, R as RunOptions, v as BreakpointRequest, C as Checkpoint, V as DagExecutionContext, X as DagNodeStatus, aN as RerouteEvent, aS as Scratchpad, a1 as DebugEventType, L as CheckpointStore, aj as InMemoryCheckpointStore, W as DagNode, Z as DagPattern, D as DebugEvent, G as GuardrailFn, aa as GuardrailContext } from './types-D5veI9su.js';
|
|
3
3
|
import '@directive-run/core';
|
|
4
4
|
import '@directive-run/core/plugins';
|
|
@@ -630,6 +630,12 @@ interface BreakpointCapable {
|
|
|
630
630
|
resumeBreakpoint(id: string, modifications?: BreakpointModifications): void;
|
|
631
631
|
cancelBreakpoint(id: string, reason?: string): void;
|
|
632
632
|
}
|
|
633
|
+
/**
|
|
634
|
+
* Create a breakpoint simulator that auto-resolves breakpoints for testing.
|
|
635
|
+
*
|
|
636
|
+
* @param options - Simulator options including `autoResumeDelay` and `modifications`.
|
|
637
|
+
* @returns An object with `handler`, `hits`, and `attachTo` for test assertions.
|
|
638
|
+
*/
|
|
633
639
|
declare function createBreakpointSimulator(options?: BreakpointSimulatorOptions): {
|
|
634
640
|
handler: (request: BreakpointRequest) => void;
|
|
635
641
|
hits: BreakpointRequest[];
|
package/dist/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {t,createModule,createSystem}from'@directive-run/core';import {requirementGuard,createCallbackPlugin,setBridgeFact,getBridgeFact}from'@directive-run/core/adapter-utils';var et=class extends Error{code;guardrailName;guardrailType;userMessage;agentName;constructor(t){super(t.message,{cause:t.cause}),this.name="GuardrailError",this.code=t.code,this.guardrailName=t.guardrailName,this.guardrailType=t.guardrailType,this.userMessage=t.userMessage??t.message,this.agentName=t.agentName,Object.defineProperty(this,"input",{value:t.input,enumerable:false,writable:false,configurable:false}),Object.defineProperty(this,"data",{value:t.data,enumerable:false,writable:false,configurable:false});}toJSON(){return {name:this.name,code:this.code,message:this.message,guardrailName:this.guardrailName,guardrailType:this.guardrailType,userMessage:this.userMessage,agentName:this.agentName}}};function Hn(i){return i instanceof et}var hn="__agent",Ot="__approval",bn="__conversation",kn="__toolCalls",Mt="__breakpoints";var tt="__scratchpad",tn={facts:{[hn]:t.object(),[Ot]:t.object(),[bn]:t.array(),[kn]:t.array(),[Mt]:t.object()},derivations:{},events:{},requirements:{}};var Sr=new Set(["agent_start","agent_complete","agent_error","agent_retry","guardrail_check","constraint_evaluate","resolver_start","resolver_complete","resolver_error","approval_request","approval_response","handoff_start","handoff_complete","pattern_start","pattern_complete","dag_node_update","breakpoint_hit","breakpoint_resumed","derivation_update","scratchpad_update","reflection_iteration","race_start","race_winner","race_cancelled","debate_round","reroute","checkpoint_save","checkpoint_restore","task_start","task_complete","task_error","task_progress","goal_step"]),Un=new Set(["__proto__","constructor","prototype","toString","valueOf","hasOwnProperty"]);function Jt(i={}){let t=i.maxEvents??2e3,u=i.goToSnapshot;if(!Number.isFinite(t)||t<1)throw new Error("[Directive DebugTimeline] maxEvents must be >= 1");let a=[],d=0,f=new Set;return {record(S){let w={...S,id:d++};a.push(w);let v=a.length-t;v>0&&a.splice(0,v);for(let A of f)try{A(w);}catch(Q){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[Directive DebugTimeline] Listener threw:",Q instanceof Error?Q.message:Q);}return w},getEvents(){return [...a]},getEventsForAgent(S){return a.filter(w=>w.agentId===S)},getEventsByType(S){return a.filter(w=>w.type===S)},getEventsAtSnapshot(S){return a.filter(w=>w.snapshotId===S)},getEventsInRange(S,w){return a.filter(v=>v.timestamp>=S&&v.timestamp<=w)},forkFrom(S){let w=-1;for(let v=a.length-1;v>=0;v--)if(a[v].snapshotId!==null&&a[v].snapshotId<=S){w=a[v].id;break}if(w>=0){let v=a.length;for(let A=a.length-1;A>=0;A--)if(a[A].id<=w){v=A+1;break}a=a.slice(0,v);}else a=[];u&&u(S);},export(){return JSON.stringify({version:1,events:a,nextId:d})},import(S){let w;try{w=JSON.parse(S);}catch{throw new Error("[Directive DebugTimeline] Invalid JSON")}if(!w||typeof w!="object")throw new Error("[Directive DebugTimeline] Invalid timeline data");for(let Q of Object.keys(w))if(Un.has(Q))throw new Error(`[Directive DebugTimeline] Blocked key in import: ${Q}`);let v=w;if(!Array.isArray(v.events))throw new Error("[Directive DebugTimeline] Missing events array");let A=[];for(let Q of v.events){if(!Q||typeof Q!="object")continue;for(let Ce of Object.keys(Q))if(Un.has(Ce))throw new Error(`[Directive DebugTimeline] Blocked key in event: ${Ce}`);let F=Q;typeof F.id=="number"&&typeof F.type=="string"&&Sr.has(F.type)&&typeof F.timestamp=="number"&&A.push(Q);}a=A.length>t?A.slice(-t):A,d=typeof v.nextId=="number"?v.nextId:A.length;},clear(){a=[],d=0;},subscribe(S){return f.add(S),()=>{f.delete(S);}},get length(){return a.length}}}function yn(i,t){let u=new Map;return {name:"directive-ai-debug-timeline",onConstraintEvaluate(a,d){i.record({type:"constraint_evaluate",timestamp:Date.now(),snapshotId:t(),constraintId:a,fired:d});},onResolverStart(a,d){u.set(a,Date.now()),i.record({type:"resolver_start",timestamp:Date.now(),snapshotId:t(),resolverId:a,requirementType:d.requirement.type});},onResolverComplete(a){let d=u.get(a);u.delete(a),i.record({type:"resolver_complete",timestamp:Date.now(),snapshotId:t(),resolverId:a,durationMs:d?Date.now()-d:0});},onResolverError(a,d,f){let k=u.get(a);u.delete(a);let S=f instanceof Error?f.message:String(f);i.record({type:"resolver_error",timestamp:Date.now(),snapshotId:t(),resolverId:a,errorMessage:S,durationMs:k?Date.now()-k:0});}}}function gt(i,t,u){return typeof i=="function"?{name:`${u}-guardrail-${t}`,fn:i,critical:true}:i}function Er(i,t){let{backoff:u="exponential",baseDelayMs:a=100,maxDelayMs:d=5e3}=t,f;switch(u){case "exponential":f=a*Math.pow(2,i-1);break;case "linear":f=a*i;break;default:f=a;}return Math.min(f,d)}function Jn(i,t){return t?.aborted?Promise.reject(t.reason??new Error("Aborted")):new Promise((u,a)=>{if(!t){setTimeout(u,i);return}let d=()=>{clearTimeout(f),a(t.reason??new Error("Aborted"));},f=setTimeout(()=>{t.removeEventListener("abort",d),u();},i);t.addEventListener("abort",d,{once:true});})}async function ft(i,t,u,a){let{retry:d}=i,f=Math.max(d?.attempts??1,1),k;for(let S=1;S<=f;S++)try{return await i.fn(t,u)}catch(w){if(k=w instanceof Error?w:new Error(String(w)),S<f){let v=Er(S,d??{});await Jn(v,a);}}return {passed:false,reason:`Guardrail "${i.name}" failed after ${f} attempt(s): ${k.message}`}}function Ar(i,t){let{backoff:u="exponential",baseDelayMs:a=1e3,maxDelayMs:d=3e4}=t,f;switch(u){case "exponential":f=a*Math.pow(2,i-1);break;case "linear":f=a*i;break;default:f=a;}return Math.min(f,d)}async function nn(i,t,u,a,d){let f=Math.max(d?.attempts??1,1),k=d?.isRetryable??(()=>true),S=d?.onRetry,w;for(let v=1;v<=f;v++)try{return await i(t,u,a)}catch(A){if(w=A instanceof Error?A:new Error(String(A)),v<f){let Q=true;try{Q=k(w);}catch{break}if(!Q)break;let F=Ar(v,d??{});try{S?.(v,w,F);}catch{}await Jn(F,a?.signal);}else break}throw w}function Je(i){return getBridgeFact(i,hn)}function We(i,t){setBridgeFact(i,hn,t);}function ut(i){return getBridgeFact(i,Ot)}function rt(i,t){setBridgeFact(i,Ot,t);}function Wt(i){return getBridgeFact(i,bn)}function mt(i,t){setBridgeFact(i,bn,t);}function Kt(i){return getBridgeFact(i,kn)}function ht(i,t){setBridgeFact(i,kn,t);}function st(i){return getBridgeFact(i,Mt)}function at(i,t){setBridgeFact(i,Mt,t);}function nt(i){return {agent:Je(i),approval:ut(i),conversation:Wt(i),toolCalls:Kt(i)}}function Vt(i){let t=Object.create(null);for(let[u,a]of Object.entries(i))t[u]={priority:a.priority??0,when:d=>{let f=nt(d),k={...d,...f};return a.when(k)},require:d=>{let f=nt(d),k={...d,...f};return typeof a.require=="function"?a.require(k):a.require}};return t}function Wn(i,t,u){let a=Object.create(null);for(let[d,f]of Object.entries(i))a[d]={requirement:f.requirement,key:f.key,resolve:async(k,S)=>{let w=nt(S.facts),A={facts:{...S.facts,...w},runAgent:async(Q,F,Ce)=>t(Q,F,nt(u()),Ce),signal:S.signal};await f.resolve(k,A);}};return a}var yt=200,xr=0;function vn(){return `bp_${Date.now().toString(36)}_${(++xr).toString(36)}`}function wn(i,t,u){for(let a of i)if(a.type===t){if(!a.when)return a;try{if(a.when(u))return a}catch{}}return null}function sn(){return {pending:[],resolved:[],cancelled:[]}}var Kn=new Set(["__proto__","constructor","prototype","toString","valueOf","hasOwnProperty"]);function vt(){let i=Date.now().toString(36),t=crypto.randomUUID().slice(0,8);return `ckpt_${i}_${t}`}function an(i){if(!i||typeof i!="object")return false;for(let a of Object.keys(i))if(Kn.has(a))return false;let t=i;if(t.version!==1||typeof t.id!="string"||t.id.length===0||typeof t.createdAt!="string"||typeof t.systemExport!="string"||t.timelineExport!==null&&typeof t.timelineExport!="string"||!t.localState||typeof t.localState!="object")return false;for(let a of Object.keys(t.localState))if(Kn.has(a))return false;let u=t.localState;return !(u.type!=="single"&&u.type!=="multi"||t.orchestratorType!=="single"&&t.orchestratorType!=="multi")}var Rn=class{store=new Map;order=[];maxCheckpoints;retentionMs;preserveLabeled;constructor(t){if(this.maxCheckpoints=t?.maxCheckpoints??100,this.retentionMs=t?.retentionMs??Number.POSITIVE_INFINITY,this.preserveLabeled=t?.preserveLabeled??false,!Number.isFinite(this.maxCheckpoints)||this.maxCheckpoints<1)throw new Error(`[Directive Checkpoint] maxCheckpoints must be >= 1, got ${this.maxCheckpoints}`)}async save(t){if(!an(t))throw new Error("[Directive Checkpoint] Invalid checkpoint data");for(;this.order.length>=this.maxCheckpoints&&this.evictOldest(););let u=this.order.indexOf(t.id);return u>=0&&this.order.splice(u,1),this.store.set(t.id,t),this.order.push(t.id),t.id}async load(t){return this.store.get(t)??null}async list(){return this.order.map(t=>{let u=this.store.get(t);return {id:u.id,label:u.label,createdAt:u.createdAt}})}async delete(t){if(!this.store.has(t))return false;this.store.delete(t);let u=this.order.indexOf(t);return u>=0&&this.order.splice(u,1),true}async clear(){this.store.clear(),this.order.length=0;}async prune(){if(!Number.isFinite(this.retentionMs))return 0;let t=Date.now()-this.retentionMs,u=0,a=[];for(let d of this.order){let f=this.store.get(d);if(!f)continue;if(new Date(f.createdAt).getTime()>=t)break;this.preserveLabeled&&f.label||a.push(d);}for(let d of a){this.store.delete(d);let f=this.order.indexOf(d);f>=0&&this.order.splice(f,1),u++;}return u}evictOldest(){if(this.preserveLabeled)for(let u=0;u<this.order.length;u++){let a=this.order[u],d=this.store.get(a);if(d&&!d.label)return this.order.splice(u,1),this.store.delete(a),true}let t=this.order.shift();return t?(this.store.delete(t),true):false}};function _n(i){if(i.length>1048576)throw new Error(`[Directive] Output too large for JSON extraction (${i.length} chars, max 1048576).`);let t=i.trim();try{return JSON.parse(t)}catch{}let u=t.indexOf("{"),a=t.indexOf("["),d,f,k;if(u===-1&&a===-1)throw new Error("[Directive] No JSON object or array found in output");u===-1?(d=a,f="[",k="]"):a===-1?(d=u,f="{",k="}"):(d=Math.min(u,a),f=d===u?"{":"[",k=d===u?"}":"]");let S=0,w=false,v=false;for(let A=d;A<t.length;A++){let Q=t[A];if(v){v=false;continue}if(Q==="\\"){v=true;continue}if(Q==='"'){w=!w;continue}if(!w){if(Q===f)S++;else if(Q===k&&(S--,S===0)){let F=t.slice(d,A+1);try{return JSON.parse(F)}catch{let Ce=F.replace(/"(?:[^"\\]|\\.)*"/g,Fe=>Fe.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"));return JSON.parse(Ce)}}}}throw new Error("[Directive] No valid JSON found in output")}function Cr(i){return i?i.issues&&i.issues.length>0?i.issues.map(t=>t.message).join("; "):i.message??"Validation failed":"Validation failed"}function Tn(i,t){let{schema:u,maxRetries:a=2,extractJson:d=_n,schemaDescription:f}=t;if(!Number.isFinite(a)||a<0)throw new Error("[Directive] withStructuredOutput: maxRetries must be a non-negative finite number.");let k=f??u.description??"the specified JSON schema";return async(S,w,v)=>{let A={...S,instructions:(S.instructions??"")+`
|
|
1
|
+
import {t,createModule,createSystem}from'@directive-run/core';import {requirementGuard,createCallbackPlugin,setBridgeFact,getBridgeFact}from'@directive-run/core/adapter-utils';var et=class extends Error{code;guardrailName;guardrailType;userMessage;agentName;constructor(t){super(t.message,{cause:t.cause}),this.name="GuardrailError",this.code=t.code,this.guardrailName=t.guardrailName,this.guardrailType=t.guardrailType,this.userMessage=t.userMessage??t.message,this.agentName=t.agentName,Object.defineProperty(this,"input",{value:t.input,enumerable:false,writable:false,configurable:false}),Object.defineProperty(this,"data",{value:t.data,enumerable:false,writable:false,configurable:false});}toJSON(){return {name:this.name,code:this.code,message:this.message,guardrailName:this.guardrailName,guardrailType:this.guardrailType,userMessage:this.userMessage,agentName:this.agentName}}};function Hn(i){return i instanceof et}var hn="__agent",Ot="__approval",bn="__conversation",kn="__toolCalls",Mt="__breakpoints";var tt="__scratchpad",tn={facts:{[hn]:t.object(),[Ot]:t.object(),[bn]:t.array(),[kn]:t.array(),[Mt]:t.object()},derivations:{},events:{},requirements:{}};var Sr=new Set(["agent_start","agent_complete","agent_error","agent_retry","guardrail_check","constraint_evaluate","resolver_start","resolver_complete","resolver_error","approval_request","approval_response","handoff_start","handoff_complete","pattern_start","pattern_complete","dag_node_update","breakpoint_hit","breakpoint_resumed","derivation_update","scratchpad_update","reflection_iteration","race_start","race_winner","race_cancelled","debate_round","reroute","checkpoint_save","checkpoint_restore","task_start","task_complete","task_error","task_progress","goal_step"]),Un=new Set(["__proto__","constructor","prototype","toString","valueOf","hasOwnProperty"]);function Jt(i={}){let t=i.maxEvents??2e3,u=i.goToSnapshot;if(!Number.isFinite(t)||t<1)throw new Error("[Directive DebugTimeline] maxEvents must be >= 1");let a=[],d=0,f=new Set;return {record(S){let w={...S,id:d++};a.push(w);let v=a.length-t;v>0&&a.splice(0,v);for(let A of f)try{A(w);}catch(Q){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[Directive DebugTimeline] Listener threw:",Q instanceof Error?Q.message:Q);}return w},getEvents(){return [...a]},getEventsForAgent(S){return a.filter(w=>w.agentId===S)},getEventsByType(S){return a.filter(w=>w.type===S)},getEventsAtSnapshot(S){return a.filter(w=>w.snapshotId===S)},getEventsInRange(S,w){return a.filter(v=>v.timestamp>=S&&v.timestamp<=w)},forkFrom(S){let w=-1;for(let v=a.length-1;v>=0;v--)if(a[v].snapshotId!==null&&a[v].snapshotId<=S){w=a[v].id;break}if(w>=0){let v=a.length;for(let A=a.length-1;A>=0;A--)if(a[A].id<=w){v=A+1;break}a=a.slice(0,v);}else a=[];u&&u(S);},export(){return JSON.stringify({version:1,events:a,nextId:d})},import(S){let w;try{w=JSON.parse(S);}catch{throw new Error("[Directive DebugTimeline] Invalid JSON")}if(!w||typeof w!="object")throw new Error("[Directive DebugTimeline] Invalid timeline data");for(let Q of Object.keys(w))if(Un.has(Q))throw new Error(`[Directive DebugTimeline] Blocked key in import: ${Q}`);let v=w;if(!Array.isArray(v.events))throw new Error("[Directive DebugTimeline] Missing events array");let A=[];for(let Q of v.events){if(!Q||typeof Q!="object")continue;for(let Ce of Object.keys(Q))if(Un.has(Ce))throw new Error(`[Directive DebugTimeline] Blocked key in event: ${Ce}`);let F=Q;typeof F.id=="number"&&typeof F.type=="string"&&Sr.has(F.type)&&typeof F.timestamp=="number"&&A.push(Q);}a=A.length>t?A.slice(-t):A,d=typeof v.nextId=="number"?v.nextId:A.length;},clear(){a=[],d=0;},subscribe(S){return f.add(S),()=>{f.delete(S);}},get length(){return a.length}}}function yn(i,t){let u=new Map;return {name:"directive-ai-debug-timeline",onConstraintEvaluate(a,d){i.record({type:"constraint_evaluate",timestamp:Date.now(),snapshotId:t(),constraintId:a,fired:d});},onResolverStart(a,d){u.set(a,Date.now()),i.record({type:"resolver_start",timestamp:Date.now(),snapshotId:t(),resolverId:a,requirementType:d.requirement.type});},onResolverComplete(a){let d=u.get(a);u.delete(a),i.record({type:"resolver_complete",timestamp:Date.now(),snapshotId:t(),resolverId:a,durationMs:d?Date.now()-d:0});},onResolverError(a,d,f){let k=u.get(a);u.delete(a);let S=f instanceof Error?f.message:String(f);i.record({type:"resolver_error",timestamp:Date.now(),snapshotId:t(),resolverId:a,errorMessage:S,durationMs:k?Date.now()-k:0});}}}function gt(i,t,u){return typeof i=="function"?{name:`${u}-guardrail-${t}`,fn:i,critical:true}:i}function Er(i,t){let{backoff:u="exponential",baseDelayMs:a=100,maxDelayMs:d=5e3}=t,f;switch(u){case "exponential":f=a*2**(i-1);break;case "linear":f=a*i;break;default:f=a;}return Math.min(f,d)}function Jn(i,t){return t?.aborted?Promise.reject(t.reason??new Error("Aborted")):new Promise((u,a)=>{if(!t){setTimeout(u,i);return}let d=()=>{clearTimeout(f),a(t.reason??new Error("Aborted"));},f=setTimeout(()=>{t.removeEventListener("abort",d),u();},i);t.addEventListener("abort",d,{once:true});})}async function ft(i,t,u,a){let{retry:d}=i,f=Math.max(d?.attempts??1,1),k;for(let S=1;S<=f;S++)try{return await i.fn(t,u)}catch(w){if(k=w instanceof Error?w:new Error(String(w)),S<f){let v=Er(S,d??{});await Jn(v,a);}}return {passed:false,reason:`Guardrail "${i.name}" failed after ${f} attempt(s): ${k.message}`}}function Ar(i,t){let{backoff:u="exponential",baseDelayMs:a=1e3,maxDelayMs:d=3e4}=t,f;switch(u){case "exponential":f=a*2**(i-1);break;case "linear":f=a*i;break;default:f=a;}return Math.min(f,d)}async function nn(i,t,u,a,d){let f=Math.max(d?.attempts??1,1),k=d?.isRetryable??(()=>true),S=d?.onRetry,w;for(let v=1;v<=f;v++)try{return await i(t,u,a)}catch(A){if(w=A instanceof Error?A:new Error(String(A)),v<f){let Q=true;try{Q=k(w);}catch{break}if(!Q)break;let F=Ar(v,d??{});try{S?.(v,w,F);}catch{}await Jn(F,a?.signal);}else break}throw w}function Je(i){return getBridgeFact(i,hn)}function We(i,t){setBridgeFact(i,hn,t);}function ut(i){return getBridgeFact(i,Ot)}function rt(i,t){setBridgeFact(i,Ot,t);}function Wt(i){return getBridgeFact(i,bn)}function mt(i,t){setBridgeFact(i,bn,t);}function Kt(i){return getBridgeFact(i,kn)}function ht(i,t){setBridgeFact(i,kn,t);}function st(i){return getBridgeFact(i,Mt)}function at(i,t){setBridgeFact(i,Mt,t);}function nt(i){return {agent:Je(i),approval:ut(i),conversation:Wt(i),toolCalls:Kt(i)}}function Vt(i){let t=Object.create(null);for(let[u,a]of Object.entries(i))t[u]={priority:a.priority??0,when:d=>{let f=nt(d),k={...d,...f};return a.when(k)},require:d=>{let f=nt(d),k={...d,...f};return typeof a.require=="function"?a.require(k):a.require}};return t}function Wn(i,t,u){let a=Object.create(null);for(let[d,f]of Object.entries(i))a[d]={requirement:f.requirement,key:f.key,resolve:async(k,S)=>{let w=nt(S.facts),A={facts:{...S.facts,...w},runAgent:async(Q,F,Ce)=>t(Q,F,nt(u()),Ce),signal:S.signal};await f.resolve(k,A);}};return a}var yt=200,xr=0;function vn(){return `bp_${Date.now().toString(36)}_${(++xr).toString(36)}`}function wn(i,t,u){for(let a of i)if(a.type===t){if(!a.when)return a;try{if(a.when(u))return a}catch{}}return null}function sn(){return {pending:[],resolved:[],cancelled:[]}}var Kn=new Set(["__proto__","constructor","prototype","toString","valueOf","hasOwnProperty"]);function vt(){let i=Date.now().toString(36),t=crypto.randomUUID().slice(0,8);return `ckpt_${i}_${t}`}function an(i){if(!i||typeof i!="object")return false;for(let a of Object.keys(i))if(Kn.has(a))return false;let t=i;if(t.version!==1||typeof t.id!="string"||t.id.length===0||typeof t.createdAt!="string"||typeof t.systemExport!="string"||t.timelineExport!==null&&typeof t.timelineExport!="string"||!t.localState||typeof t.localState!="object")return false;for(let a of Object.keys(t.localState))if(Kn.has(a))return false;let u=t.localState;return !(u.type!=="single"&&u.type!=="multi"||t.orchestratorType!=="single"&&t.orchestratorType!=="multi")}var Rn=class{store=new Map;order=[];maxCheckpoints;retentionMs;preserveLabeled;constructor(t){if(this.maxCheckpoints=t?.maxCheckpoints??100,this.retentionMs=t?.retentionMs??Number.POSITIVE_INFINITY,this.preserveLabeled=t?.preserveLabeled??false,!Number.isFinite(this.maxCheckpoints)||this.maxCheckpoints<1)throw new Error(`[Directive Checkpoint] maxCheckpoints must be >= 1, got ${this.maxCheckpoints}`)}async save(t){if(!an(t))throw new Error("[Directive Checkpoint] Invalid checkpoint data");for(;this.order.length>=this.maxCheckpoints&&this.evictOldest(););let u=this.order.indexOf(t.id);return u>=0&&this.order.splice(u,1),this.store.set(t.id,t),this.order.push(t.id),t.id}async load(t){return this.store.get(t)??null}async list(){return this.order.map(t=>{let u=this.store.get(t);return {id:u.id,label:u.label,createdAt:u.createdAt}})}async delete(t){if(!this.store.has(t))return false;this.store.delete(t);let u=this.order.indexOf(t);return u>=0&&this.order.splice(u,1),true}async clear(){this.store.clear(),this.order.length=0;}async prune(){if(!Number.isFinite(this.retentionMs))return 0;let t=Date.now()-this.retentionMs,u=0,a=[];for(let d of this.order){let f=this.store.get(d);if(!f)continue;if(new Date(f.createdAt).getTime()>=t)break;this.preserveLabeled&&f.label||a.push(d);}for(let d of a){this.store.delete(d);let f=this.order.indexOf(d);f>=0&&this.order.splice(f,1),u++;}return u}evictOldest(){if(this.preserveLabeled)for(let u=0;u<this.order.length;u++){let a=this.order[u],d=this.store.get(a);if(d&&!d.label)return this.order.splice(u,1),this.store.delete(a),true}let t=this.order.shift();return t?(this.store.delete(t),true):false}};function _n(i){if(i.length>1048576)throw new Error(`[Directive] Output too large for JSON extraction (${i.length} chars, max 1048576).`);let t=i.trim();try{return JSON.parse(t)}catch{}let u=t.indexOf("{"),a=t.indexOf("["),d,f,k;if(u===-1&&a===-1)throw new Error("[Directive] No JSON object or array found in output");u===-1?(d=a,f="[",k="]"):a===-1?(d=u,f="{",k="}"):(d=Math.min(u,a),f=d===u?"{":"[",k=d===u?"}":"]");let S=0,w=false,v=false;for(let A=d;A<t.length;A++){let Q=t[A];if(v){v=false;continue}if(Q==="\\"){v=true;continue}if(Q==='"'){w=!w;continue}if(!w){if(Q===f)S++;else if(Q===k&&(S--,S===0)){let F=t.slice(d,A+1);try{return JSON.parse(F)}catch{let Ce=F.replace(/"(?:[^"\\]|\\.)*"/g,Fe=>Fe.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"));return JSON.parse(Ce)}}}}throw new Error("[Directive] No valid JSON found in output")}function Cr(i){return i?i.issues&&i.issues.length>0?i.issues.map(t=>t.message).join("; "):i.message??"Validation failed":"Validation failed"}function Tn(i,t){let{schema:u,maxRetries:a=2,extractJson:d=_n,schemaDescription:f}=t;if(!Number.isFinite(a)||a<0)throw new Error("[Directive] withStructuredOutput: maxRetries must be a non-negative finite number.");let k=f??u.description??"the specified JSON schema";return async(S,w,v)=>{let A={...S,instructions:(S.instructions??"")+`
|
|
2
2
|
|
|
3
3
|
IMPORTANT: Respond with valid JSON matching `+k+". Output ONLY the JSON object, no additional text or markdown formatting."},Q,F;for(let Ce=0;Ce<=a;Ce++){let Fe=Ce===0?w:`${w}
|
|
4
4
|
|