agentix-cli 0.75.1 → 0.75.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.
Files changed (61) hide show
  1. package/dist/{agent-UOOL6R4V.js → agent-B46X7Y6V.js} +2 -2
  2. package/dist/{board-dashboard-CDBPGUU3.js → board-dashboard-W64VXH6Y.js} +2 -2
  3. package/dist/{chunk-OEUII2QP.js → chunk-2HMI5PJG.js} +2 -2
  4. package/dist/{chunk-5B5J3WVW.js → chunk-55RM7V4N.js} +2 -2
  5. package/dist/{chunk-SKIDVXWG.js → chunk-663BLK67.js} +2 -2
  6. package/dist/{chunk-APYG4RB3.js → chunk-6CCJMHBA.js} +2 -2
  7. package/dist/{chunk-6O2MCBOD.js → chunk-7ZO2UZRI.js} +11 -11
  8. package/dist/{chunk-L3MEAKL7.js → chunk-CAVAMWI5.js} +2 -2
  9. package/dist/{chunk-BAPRRPNU.js → chunk-F2RIMHW5.js} +2 -2
  10. package/dist/{chunk-6HPJKD3X.js → chunk-KHEI4VNM.js} +13 -13
  11. package/dist/{chunk-6HPJKD3X.js.map → chunk-KHEI4VNM.js.map} +1 -1
  12. package/dist/{chunk-VCE2DBHB.js → chunk-KIXYU2DD.js} +4 -4
  13. package/dist/{chunk-KEJOBB5E.js → chunk-NWL5KPBJ.js} +2 -2
  14. package/dist/chunk-PBUJBWOF.js +152 -0
  15. package/dist/chunk-PBUJBWOF.js.map +1 -0
  16. package/dist/{chunk-WC4TPXD3.js → chunk-Q2FFZX7Y.js} +2 -2
  17. package/dist/{chunk-ISBM2C3D.js → chunk-RGTHA2EI.js} +2 -2
  18. package/dist/{chunk-UBGQ7AOG.js → chunk-TS4JCBSP.js} +2 -2
  19. package/dist/{chunk-66VSATH3.js → chunk-UJ5JLS6Z.js} +2 -2
  20. package/dist/cli.js +1 -1
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +1 -1
  23. package/dist/{program-6MNNHNMY.js → program-3DBXC6DX.js} +2 -2
  24. package/dist/{promote-KSYTHPYB.js → promote-PMMUU4G2.js} +2 -2
  25. package/dist/{query-GRLLX7RG.js → query-CB6FV6JU.js} +2 -2
  26. package/dist/{registry-WJRF3D5H.js → registry-A2LPURNS.js} +2 -2
  27. package/dist/{request-planner-G2NJIXQY.js → request-planner-44WOTYCY.js} +2 -2
  28. package/dist/{review-candidates-F5QKVUQ4.js → review-candidates-BZLS37MN.js} +2 -2
  29. package/dist/{routing-XIDQWGKT.js → routing-CPLPRA2E.js} +2 -2
  30. package/dist/{seat-DNI7G7B2.js → seat-CBAZAYGY.js} +2 -2
  31. package/dist/{select-L45K2452.js → select-4CW3CXBU.js} +2 -2
  32. package/dist/wiki-4LKOLCP4.js +2 -0
  33. package/package.json +1 -1
  34. package/dist/chunk-DIHLL45I.js +0 -152
  35. package/dist/chunk-DIHLL45I.js.map +0 -1
  36. package/dist/wiki-WWVSDXSX.js +0 -2
  37. /package/dist/{agent-UOOL6R4V.js.map → agent-B46X7Y6V.js.map} +0 -0
  38. /package/dist/{board-dashboard-CDBPGUU3.js.map → board-dashboard-W64VXH6Y.js.map} +0 -0
  39. /package/dist/{chunk-OEUII2QP.js.map → chunk-2HMI5PJG.js.map} +0 -0
  40. /package/dist/{chunk-5B5J3WVW.js.map → chunk-55RM7V4N.js.map} +0 -0
  41. /package/dist/{chunk-SKIDVXWG.js.map → chunk-663BLK67.js.map} +0 -0
  42. /package/dist/{chunk-APYG4RB3.js.map → chunk-6CCJMHBA.js.map} +0 -0
  43. /package/dist/{chunk-6O2MCBOD.js.map → chunk-7ZO2UZRI.js.map} +0 -0
  44. /package/dist/{chunk-L3MEAKL7.js.map → chunk-CAVAMWI5.js.map} +0 -0
  45. /package/dist/{chunk-BAPRRPNU.js.map → chunk-F2RIMHW5.js.map} +0 -0
  46. /package/dist/{chunk-VCE2DBHB.js.map → chunk-KIXYU2DD.js.map} +0 -0
  47. /package/dist/{chunk-KEJOBB5E.js.map → chunk-NWL5KPBJ.js.map} +0 -0
  48. /package/dist/{chunk-WC4TPXD3.js.map → chunk-Q2FFZX7Y.js.map} +0 -0
  49. /package/dist/{chunk-ISBM2C3D.js.map → chunk-RGTHA2EI.js.map} +0 -0
  50. /package/dist/{chunk-UBGQ7AOG.js.map → chunk-TS4JCBSP.js.map} +0 -0
  51. /package/dist/{chunk-66VSATH3.js.map → chunk-UJ5JLS6Z.js.map} +0 -0
  52. /package/dist/{program-6MNNHNMY.js.map → program-3DBXC6DX.js.map} +0 -0
  53. /package/dist/{promote-KSYTHPYB.js.map → promote-PMMUU4G2.js.map} +0 -0
  54. /package/dist/{query-GRLLX7RG.js.map → query-CB6FV6JU.js.map} +0 -0
  55. /package/dist/{registry-WJRF3D5H.js.map → registry-A2LPURNS.js.map} +0 -0
  56. /package/dist/{request-planner-G2NJIXQY.js.map → request-planner-44WOTYCY.js.map} +0 -0
  57. /package/dist/{review-candidates-F5QKVUQ4.js.map → review-candidates-BZLS37MN.js.map} +0 -0
  58. /package/dist/{routing-XIDQWGKT.js.map → routing-CPLPRA2E.js.map} +0 -0
  59. /package/dist/{seat-DNI7G7B2.js.map → seat-CBAZAYGY.js.map} +0 -0
  60. /package/dist/{select-L45K2452.js.map → select-4CW3CXBU.js.map} +0 -0
  61. /package/dist/{wiki-WWVSDXSX.js.map → wiki-4LKOLCP4.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{a as o}from"./chunk-66VSATH3.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
- //# sourceMappingURL=chunk-L3MEAKL7.js.map
1
+ import{a as o}from"./chunk-UJ5JLS6Z.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
+ //# sourceMappingURL=chunk-CAVAMWI5.js.map
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-WJRF3D5H.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-A2LPURNS.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-BAPRRPNU.js.map
126
+ //# sourceMappingURL=chunk-F2RIMHW5.js.map
@@ -1,12 +1,12 @@
1
- import{a as Te,b as ft}from"./chunk-FX3D7YON.js";import{a as et,b as tt,c as nt,d as S,e as A,f as N}from"./chunk-72SZI2UW.js";import{a as ne,b as He}from"./chunk-FCPTN6NF.js";import{o as we,p as Ke}from"./chunk-5MUJZODV.js";import{C as We,D as Ze}from"./chunk-CXZ4YDHJ.js";import{a as rt,b as ot,c as st,d as it,e as at,f as ct,g as ut,h as lt,i as dt,j as pt,k as mt,l as bt}from"./chunk-RGDKHYY2.js";import{a as E,b as Ye,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function gt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import yt from"better-sqlite3";import{createHash as ht}from"crypto";import{mkdirSync as wt}from"fs";import{dirname as Tt,resolve as Et}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function kt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function xt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&Rt(e),t<2&&At(e),t<3&&St(e)}function St(e){e.exec(`
1
+ import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{C as Ze,D as et}from"./chunk-CXZ4YDHJ.js";import{a as ot,b as st,c as it,d as at,e as ct,f as ut,g as lt,h as dt,i as pt,j as mt,k as bt,l as ft}from"./chunk-RGDKHYY2.js";import{a as E,b as Ke,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function yt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import ht from"better-sqlite3";import{createHash as wt}from"crypto";import{mkdirSync as Tt}from"fs";import{dirname as Et,resolve as kt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function xt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function St(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&_t(e),t<2&&Rt(e),t<3&&At(e)}function At(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
- `)}function At(e){e.exec(`
4
+ `)}function Rt(e){e.exec(`
5
5
  ALTER TABLE decision_calls ADD COLUMN action TEXT;
6
6
  ALTER TABLE decision_calls ADD COLUMN explored INTEGER NOT NULL DEFAULT 0;
7
7
  CREATE INDEX IF NOT EXISTS idx_decision_calls_action ON decision_calls (seat, action, explored);
8
8
  INSERT INTO schema_version (v) VALUES (2);
9
- `)}function Rt(e){e.exec(`
9
+ `)}function _t(e){e.exec(`
10
10
  CREATE TABLE IF NOT EXISTS decision_calls (
11
11
  id TEXT NOT NULL PRIMARY KEY,
12
12
  ts INTEGER NOT NULL,
@@ -73,7 +73,7 @@ import{a as Te,b as ft}from"./chunk-FX3D7YON.js";import{a as et,b as tt,c as nt,
73
73
  CREATE INDEX IF NOT EXISTS idx_decision_links_ref ON decision_links (ref_kind, ref_id);
74
74
 
75
75
  INSERT INTO schema_version (v) VALUES (1);
76
- `)}var I,V=E(()=>{"use strict";He();I=class{db;path;constructor(t={}){this.path=Et(process.cwd(),t.path??".agentx/decisions/decisions.sqlite"),t.readonly||wt(Tt(this.path),{recursive:!0}),this.db=new yt(this.path,{readonly:t.readonly??!1}),t.readonly||(this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),xt(this.db))}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordCall(t){let r=t.ts??Date.now(),n=ne(r),o=JSON.stringify(t.state??null),s=ht("sha256").update(o).digest("hex");return this.db.transaction(()=>{this.db.prepare(`INSERT INTO decision_calls
76
+ `)}var I,V=E(()=>{"use strict";We();I=class{db;path;constructor(t={}){this.path=kt(process.cwd(),t.path??".agentx/decisions/decisions.sqlite"),t.readonly||Tt(Et(this.path),{recursive:!0}),this.db=new ht(this.path,{readonly:t.readonly??!1}),t.readonly||(this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),St(this.db))}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordCall(t){let r=t.ts??Date.now(),n=ne(r),o=JSON.stringify(t.state??null),s=wt("sha256").update(o).digest("hex");return this.db.transaction(()=>{this.db.prepare(`INSERT INTO decision_calls
77
77
  (id, ts, seat, mode, backend, model, structure_mode, answer_mode,
78
78
  state_hash, state_json, questions_json, latency_ms,
79
79
  input_tokens, output_tokens, retries, truncated, error, features_json)
@@ -95,20 +95,20 @@ import{a as Te,b as ft}from"./chunk-FX3D7YON.js";import{a as et,b as tt,c as nt,
95
95
  LEFT JOIN decision_incumbent i ON i.call_id = c.id AND i.question = a.question
96
96
  WHERE ${r.join(" AND ")}
97
97
  ORDER BY c.ts DESC
98
- ${t.limit?"LIMIT ?":""}`;return t.limit&&n.push(t.limit),this.db.prepare(o).all(...n).map(i=>{let a=JSON.parse(i.answer_json),u=Q(a);return{callId:i.call_id,seat:i.seat,ts:i.ts,backend:i.backend,model:i.model,structureMode:i.structure_mode,question:i.question,type:a.type,predicted:u.predicted,confidence:u.confidence,probabilities:u.probabilities,incumbent:i.incumbent??void 0,truth:i.truth??void 0,features:kt(i.features_json),mode:i.mode,action:i.action??void 0,explored:i.explored===1}}).filter(i=>!t.labeledOnly||i.truth!==void 0)}pruneState(t,r){return this.db.prepare(`UPDATE decision_calls SET state_json = NULL
98
+ ${t.limit?"LIMIT ?":""}`;return t.limit&&n.push(t.limit),this.db.prepare(o).all(...n).map(i=>{let a=JSON.parse(i.answer_json),u=Q(a);return{callId:i.call_id,seat:i.seat,ts:i.ts,backend:i.backend,model:i.model,structureMode:i.structure_mode,question:i.question,type:a.type,predicted:u.predicted,confidence:u.confidence,probabilities:u.probabilities,incumbent:i.incumbent??void 0,truth:i.truth??void 0,features:xt(i.features_json),mode:i.mode,action:i.action??void 0,explored:i.explored===1}}).filter(i=>!t.labeledOnly||i.truth!==void 0)}pruneState(t,r){return this.db.prepare(`UPDATE decision_calls SET state_json = NULL
99
99
  WHERE seat = ? AND state_json IS NOT NULL
100
100
  AND id NOT IN (
101
101
  SELECT id FROM decision_calls WHERE seat = ? ORDER BY ts DESC LIMIT ?
102
- )`).run(t,t,r).changes}}});var ke=E(()=>{"use strict"});function xe(e,t,r={}){let n=r.normalize??!0,o=r.epsilon??1e-6,s=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},i=e===null||typeof e!="object"||Array.isArray(e);for(let c of Object.keys(s))t.includes(c)||(i=!0);let a={},u=0;for(let c of t){if(!(c in s)){a[c]=o,u+=o,i=!0;continue}let l=Number(s[c]);if(!Number.isFinite(l)||l<0){a[c]=0,i=!0;continue}a[c]=l,u+=l}if(t.length===0)return{probs:a,repaired:i};if(u<=0){let c=1/t.length;for(let l of t)a[l]=c;return{probs:a,repaired:!0}}if(n){for(let c of t)a[c]=a[c]/u;Math.abs(u-1)>1e-6&&(i=!0)}return{probs:a,repaired:i}}function Se(e){let t=Object.values(e);return t.length===0?0:Math.max(...t)}function oe(e){let t=Object.values(e).filter(s=>Number.isFinite(s)&&s>0),r=Object.keys(e).length;if(r<=1)return 1;let n=t.reduce((s,i)=>s+i,0);if(n<=0)return 0;let o=0;for(let s of t){let i=s/n;o-=i*Math.log(i)}return _t(1-o/Math.log(r))}function Ae(e){let t=0,r=0;for(let[n,o]of Object.entries(e)){let s=Number(n);!Number.isFinite(s)||!Number.isFinite(o)||o<=0||(t+=o,r+=s*o)}return t>0?r/t:0}function re(e){return oe(e)}function _t(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}function _(e,t,r={}){if(e.type==="noul"){let c=Number(t.noul),l=Number.isFinite(c)&&c>=0&&c<=1;return{answer:{type:"noul",noul:l?c:.5},repaired:!l}}let n=S(e),{probs:o,repaired:s}=xe(t.probabilities,n,r),i=Se(o),a=oe(o);if(e.type==="choice"){let c=n[0];for(let l of n)o[l]>o[c]&&(c=l);return{answer:{type:"choice",choice:c,confidence:re(o),probabilities:o,pMax:i,negEntropy:a},repaired:s}}let u={};return e.criteria.forEach((c,l)=>{u[String(l)]=c}),{answer:{type:"score",score:Ae(o),confidence:re(o),legend:u,probabilities:o,pMax:i,negEntropy:a},repaired:s}}var j=E(()=>{"use strict";N()});import{z as O}from"zod";function Re(e){return e.type==="noul"?Ot:Nt}function F(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Re(n);return O.object(t)}function U(e){return e.issues.map(t=>`- ${t.path.length>0?t.path.join("."):"(root)"}: ${t.message}`).join(`
103
- `)}var Ot,Nt,z=E(()=>{"use strict";Ot=O.object({noul:O.number()}),Nt=O.object({probabilities:O.record(O.string(),O.unknown())})});function se(e){let t={};for(let[r,n]of Object.entries(e))t[r]=vt(n);return{type:"object",additionalProperties:!1,required:["answers"],properties:{answers:{type:"object",additionalProperties:!1,required:Object.keys(e),properties:t}}}}function vt(e){if(e.type==="noul")return{type:"object",additionalProperties:!1,required:["noul"],properties:{noul:{type:"number",minimum:0,maximum:1,description:"Probability the answer is yes."}}};let t=S(e),r={};for(let n of t)r[n]={type:"number",minimum:0,maximum:1};return{type:"object",additionalProperties:!1,required:["probabilities"],properties:{probabilities:{type:"object",additionalProperties:!1,required:t,properties:r,description:"One probability per option. Must sum to 1."}}}}function G(e,t){let r=typeof e=="string"?e:JSON.stringify(e,null,2)??"null";return r.length<=t?{text:r,truncated:!1}:{text:`${r.slice(0,t)}
102
+ )`).run(t,t,r).changes}}});var ke=E(()=>{"use strict"});function xe(e,t,r={}){let n=r.normalize??!0,o=r.epsilon??1e-6,s=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},i=e===null||typeof e!="object"||Array.isArray(e);for(let c of Object.keys(s))t.includes(c)||(i=!0);let a={},u=0;for(let c of t){if(!(c in s)){a[c]=o,u+=o,i=!0;continue}let l=Number(s[c]);if(!Number.isFinite(l)||l<0){a[c]=0,i=!0;continue}a[c]=l,u+=l}if(t.length===0)return{probs:a,repaired:i};if(u<=0){let c=1/t.length;for(let l of t)a[l]=c;return{probs:a,repaired:!0}}if(n){for(let c of t)a[c]=a[c]/u;Math.abs(u-1)>1e-6&&(i=!0)}return{probs:a,repaired:i}}function Se(e){let t=Object.values(e);return t.length===0?0:Math.max(...t)}function oe(e){let t=Object.values(e).filter(s=>Number.isFinite(s)&&s>0),r=Object.keys(e).length;if(r<=1)return 1;let n=t.reduce((s,i)=>s+i,0);if(n<=0)return 0;let o=0;for(let s of t){let i=s/n;o-=i*Math.log(i)}return Ot(1-o/Math.log(r))}function Ae(e){let t=0,r=0;for(let[n,o]of Object.entries(e)){let s=Number(n);!Number.isFinite(s)||!Number.isFinite(o)||o<=0||(t+=o,r+=s*o)}return t>0?r/t:0}function re(e){return oe(e)}function Ot(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}function _(e,t,r={}){if(e.type==="noul"){let c=Number(t.noul),l=Number.isFinite(c)&&c>=0&&c<=1;return{answer:{type:"noul",noul:l?c:.5},repaired:!l}}let n=S(e),{probs:o,repaired:s}=xe(t.probabilities,n,r),i=Se(o),a=oe(o);if(e.type==="choice"){let c=n[0];for(let l of n)o[l]>o[c]&&(c=l);return{answer:{type:"choice",choice:c,confidence:re(o),probabilities:o,pMax:i,negEntropy:a},repaired:s}}let u={};return e.criteria.forEach((c,l)=>{u[String(l)]=c}),{answer:{type:"score",score:Ae(o),confidence:re(o),legend:u,probabilities:o,pMax:i,negEntropy:a},repaired:s}}var j=E(()=>{"use strict";v()});import{z as O}from"zod";function Re(e){return e.type==="noul"?vt:Nt}function P(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Re(n);return O.object(t)}function F(e){return e.issues.map(t=>`- ${t.path.length>0?t.path.join("."):"(root)"}: ${t.message}`).join(`
103
+ `)}var vt,Nt,z=E(()=>{"use strict";vt=O.object({noul:O.number()}),Nt=O.object({probabilities:O.record(O.string(),O.unknown())})});function se(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Mt(n);return{type:"object",additionalProperties:!1,required:["answers"],properties:{answers:{type:"object",additionalProperties:!1,required:Object.keys(e),properties:t}}}}function Mt(e){if(e.type==="noul")return{type:"object",additionalProperties:!1,required:["noul"],properties:{noul:{type:"number",minimum:0,maximum:1,description:"Probability the answer is yes."}}};let t=S(e),r={};for(let n of t)r[n]={type:"number",minimum:0,maximum:1};return{type:"object",additionalProperties:!1,required:["probabilities"],properties:{probabilities:{type:"object",additionalProperties:!1,required:t,properties:r,description:"One probability per option. Must sum to 1."}}}}function G(e,t){let r=typeof e=="string"?e:JSON.stringify(e,null,2)??"null";return r.length<=t?{text:r,truncated:!1}:{text:`${r.slice(0,t)}
104
104
  \u2026[truncated: ${r.length-t} more characters]`,truncated:!0}}function _e(e){let t=[];for(let[r,n]of Object.entries(e)){let o=[`### ${r}`];if(n.instructions&&o.push(n.instructions),n.type==="noul")o.push("Type: yes/no. Report `noul` \u2014 the probability the answer is yes."),n.criteria?.true&&o.push(`- yes means: ${n.criteria.true}`),n.criteria?.false&&o.push(`- no means: ${n.criteria.false}`);else if(n.type==="choice"){o.push("Type: choice. Report `probabilities` over exactly these options:");for(let[s,i]of Object.entries(n.criteria))o.push(i?`- ${s}: ${i}`:`- ${s}`)}else o.push("Type: score. Report `probabilities` over exactly these levels:"),n.criteria.forEach((s,i)=>{o.push(`- "${i}": ${s}`)});t.push(o.join(`
105
105
  `))}return t.join(`
106
106
 
107
107
  `)}function ie(e,t,r){let n=G(e,r);return{text:["## State",n.text,"","## Questions",_e(t)].join(`
108
108
  `),truncated:n.truncated}}function ae(e){let t={};for(let[r,n]of Object.entries(e)){if(n.type==="noul"){t[r]={noul:.5};continue}let o={},s=S(n);for(let i of s)o[i]=Number((1/s.length).toFixed(4));t[r]={probabilities:o}}return["","## Output","Reply with this JSON object and nothing else:",JSON.stringify({answers:t},null,2)].join(`
109
- `)}var B,J,Y=E(()=>{"use strict";N();B="answer_questions",J=["You answer questions about a piece of state by reporting a probability distribution for each one.","","Rules:","- Answer every question. Never add a question that was not asked.","- For a yes/no question, report `noul`: the probability the answer is yes, between 0 and 1.","- For every other question, report `probabilities`: one number per listed option, summing to 1.","- Use only the exact option names given. Never invent one.","- Spread the distribution when the state genuinely does not settle the question. A flat"," distribution is a useful answer; a confident wrong one is not.","- Output the structure only. No prose, no explanation, no code fences."].join(`
110
- `)});function Oe(e){return e.predicted===e.truth?1:0}function le(e){let t=Math.min(1-K,Math.max(K,e));return Math.log(t/(1-t))}function de(e){if(e>=0)return 1/(1+Math.exp(-e));let t=Math.exp(e);return t/(1+t)}function ce(e,t){let r=e.features?.[t];if(r!=null)return String(r);let n=e[t];return n==null?"(none)":String(n)}function Ne(e,t){let r=t.minLevelCount??5,n={};for(let a of t.covariates){let u=new Map;for(let l of e){let p=ce(l,a);u.set(p,(u.get(p)??0)+1)}let c=[...u.entries()].filter(([,l])=>l>=r).map(([l])=>l).sort();n[a]=c.slice(1)}let o=["intercept","logitConfidence"];for(let a of t.covariates)for(let u of n[a])o.push(`${a}=${u}`);let s=[],i=[];for(let a of e){let u=[1,le(a.confidence)];for(let c of t.covariates){let l=ce(a,c);for(let p of n[c])u.push(l===p?1:0)}s.push(u),i.push(Oe(a))}return{X:s,y:i,names:o,levels:n}}function ve(e,t,r={}){let n=r.l2??1,o=r.iterations??25,s=e.length,i=s>0?e[0].length:0,a=new Array(i).fill(0);if(s===0||i===0)return a;for(let u=0;u<o;u++){let c=Array.from({length:i},()=>new Array(i).fill(0)),l=new Array(i).fill(0);for(let d=0;d<s;d++){let b=0;for(let m=0;m<i;m++)b+=a[m]*e[d][m];let g=de(b),w=Math.max(g*(1-g),1e-8),f=t[d]-g;for(let m=0;m<i;m++){l[m]+=f*e[d][m];for(let h=m;h<i;h++)c[m][h]+=w*e[d][m]*e[d][h]}}for(let d=0;d<i;d++){d>0&&(c[d][d]+=n,l[d]-=n*a[d]);for(let b=0;b<d;b++)c[d][b]=c[b][d]}let p=Mt(c,l);if(!p)break;let y=0;for(let d=0;d<i;d++)a[d]+=p[d],y+=Math.abs(p[d]);if(y<1e-8)break}return a}function Mt(e,t){let r=t.length,n=e.map((s,i)=>[...s,t[i]]);for(let s=0;s<r;s++){let i=s;for(let a=s+1;a<r;a++)Math.abs(n[a][s])>Math.abs(n[i][s])&&(i=a);if(Math.abs(n[i][s])<1e-12)return null;[n[s],n[i]]=[n[i],n[s]];for(let a=0;a<r;a++){if(a===s)continue;let u=n[a][s]/n[s][s];if(u!==0)for(let c=s;c<=r;c++)n[a][c]-=u*n[s][c]}}let o=new Array(r);for(let s=0;s<r;s++)o[s]=n[s][r]/n[s][s];return o}function P(e,t){let r=e.filter(o=>o.truth!==void 0),n=Ne(r,t);return{weights:ve(n.X,n.y),names:n.names,levels:n.levels,covariates:t.covariates,n:r.length}}function ue(e,t){let r=e.weights[0]+e.weights[1]*le(t.confidence),n=2;for(let o of e.covariates){let s=ce(t,o);for(let i of e.levels[o]??[])s===i&&(r+=e.weights[n]),n++}return de(r)}function Lt(e,t,r={}){let n=r.folds??5,o=r.minN??100,s=e.filter(d=>d.truth!==void 0),i={insufficient:s.length<o,n:s.length,minN:o,folds:n,scores:[]};if(i.insufficient)return i;let a=r.rng??Math.random,u=[...s];for(let d=u.length-1;d>0;d--){let b=Math.floor(a()*(d+1));[u[d],u[b]]=[u[b],u[d]]}let c={raw:[],temperature:[],covariate:[]},l=[];for(let d=0;d<n;d++){let b=u.filter((m,h)=>h%n===d),g=u.filter((m,h)=>h%n!==d);if(g.length===0||b.length===0)continue;let w=P(g,{...t,covariates:[]}),f=P(g,t);for(let m of b)l.push(Oe(m)),c.raw.push(m.confidence),c.temperature.push(ue(w,m)),c.covariate.push(ue(f,m))}let p=Object.entries(c).map(([d,b])=>({name:d,logLoss:Dt(b,l),brier:Ct(b,l)})),y=[...p].sort((d,b)=>d.logLoss-b.logLoss)[0]?.name;return{...i,scores:p,best:y,model:y==="covariate"?P(s,t):P(s,{...t,covariates:[]})}}function Dt(e,t){if(e.length===0)return 0;let r=0;for(let n=0;n<e.length;n++){let o=Math.min(1-K,Math.max(K,e[n]));r+=t[n]===1?-Math.log(o):-Math.log(1-o)}return r/e.length}function Ct(e,t){if(e.length===0)return 0;let r=0;for(let n=0;n<e.length;n++)r+=(e[n]-t[n])**2;return r/e.length}var K,Me=E(()=>{"use strict";K=1e-6});import{randomBytes as It}from"crypto";function Ie(e,t=De,r=Ce){return e<=t?"no":e>r?"yes":"uncertain"}async function Qt(e,t,r,n={}){let o=Math.max(2,n.samples??15),s=D(e),i=Date.now(),a=await Promise.all(Array.from({length:o},(p,y)=>s.decide({state:Qe(t,`${y}:${It(4).toString("hex")}`),questions:r,model:n.model}))),u=Object.keys(r),c=a.reduce((p,y)=>({inputTokens:p.inputTokens+y.usage.inputTokens,outputTokens:p.outputTokens+y.usage.outputTokens}),{inputTokens:0,outputTokens:0}),l=u.map(p=>{let y=a.map(f=>Q(f.answers[p])),d=y.map((f,m)=>{let h=a[m].answers[p];return h.type==="noul"?h.noul:f.topProb}),b=[...new Set(y.map(f=>f.predicted))],g=[...new Set(d.map(f=>Ie(f,n.low,n.high)))],w=Le(d);return{question:p,type:a[0].answers[p].type,n:o,mean:w,stdev:jt(d,w),min:Math.min(...d),max:Math.max(...d),distinctAnswers:b,bands:g,crossesThreshold:b.length>1||g.length>1,samples:d}});return{backend:e,model:a[0].model,samples:o,meanStdev:Le(l.map(p=>p.stdev)),unstable:l.filter(p=>p.crossesThreshold).map(p=>p.question),questions:l,usage:c,totalMs:Date.now()-i}}function Qe(e,t){return e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e,uid:t}:{uid:t,state:e}}function Le(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}function jt(e,t){return e.length<2?0:Math.sqrt(e.reduce((r,n)=>r+(n-t)**2,0)/e.length)}var De,Ce,je=E(()=>{"use strict";C();V();De=.3,Ce=.7});function H(e={}){return{name:"mock",capabilities:Ft,async decide(t){if(e.fail)throw e.fail;A(t.questions);let r=JSON.stringify(t.state??null),n={},o=!1;for(let[i,a]of Object.entries(t.questions)){let u=e.answers?.[i]??Ut(r,i,a),c=_(a,u);n[i]=c.answer,c.repaired&&(o=!0)}let s="probabilities";return{model:t.model??"mock",answers:n,usage:{inputTokens:r.length,outputTokens:0},meta:{backend:"mock",structureMode:"mock",answerMode:s,repaired:o,retries:0,stateTruncated:!1,latencyMs:e.latencyMs??0}}}}}function Ut(e,t,r){if(r.type==="noul")return{noul:Fe(`${e}|${t}|noul`)};let n=S(r),o=n.map(a=>Fe(`${e}|${t}|${a}`)+.001),s=o.reduce((a,u)=>a+u,0),i={};return n.forEach((a,u)=>{i[a]=o[u]/s}),{probabilities:i}}function Fe(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t/4294967296}var Ft,pe=E(()=>{"use strict";j();N();Ft={probabilitySource:"synthetic",calibratedProbabilities:!1,maxChoiceOptions:255,maxStateChars:24e3,parallelQuestions:!0,images:!1}});function Un(e,t){let r=me[e];if(!r)return[`Unknown provider "${e}" \u2014 capabilities unknown`];if(!t?.length)return[];let n=[],o=[];for(let s of t)s in r&&!r[s]&&o.push(s);return o.length&&n.push(`Provider "${e}" lacks: ${o.join(", ")}. Some features will be degraded.`),n}var me,Ue=E(()=>{"use strict";me={"claude-code":{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6,structuredOutput:!1,logprobs:!1},claude:{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6,structuredOutput:!0,logprobs:!1},openai:{streaming:!0,tools:!0,vision:!0,thinking:!1,maxContext:128e3,structuredOutput:!0,logprobs:!0},deepseek:{streaming:!0,tools:!0,vision:!1,thinking:!0,maxContext:128e3,structuredOutput:!0,logprobs:!0},ollama:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:32e3,structuredOutput:!1,logprobs:!1},demo:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:8e3,structuredOutput:!1,logprobs:!1},custom:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:32e3,structuredOutput:!1,logprobs:!1}}});function W(e={}){if(e.answerMode&&e.answerMode!=="probabilities")throw new Error(`local decision backend supports answerMode "probabilities" only (got "${e.answerMode}")`);let t=e.maxStateChars??qt,r={probabilitySource:"verbalized",calibratedProbabilities:!1,maxChoiceOptions:255,maxStateChars:t,parallelQuestions:!0,images:!1},n=null,o=()=>(n||(n=e.providerFactory?e.providerFactory():we(e.provider??Bt)),n);return{name:"local",capabilities:r,async decide(s){A(s.questions);let i=Date.now(),a=s.model??e.model??Pt,u=o(),c=zt(e.structureMode??"auto",u),l=ie(s.state,s.questions,t),p=F(s.questions),y=e.nRetryMalformedStructure??1,{signal:d,dispose:b}=Jt(s.abortSignal,s.timeoutMs??e.timeoutMs??Xt),g={inputTokens:0,outputTokens:0},w=null,f=0,m=null,h="no attempt was made";try{for(let k=0;k<=y;k++){k>0&&f++;let x=await(c==="tool"?$t(u,s.questions,l.text,w,{model:a,maxTokens:e.maxTokens??Be,temperature:e.temperature??0,abortSignal:d}):Vt(u,s.questions,l.text,w,{model:a,maxTokens:e.maxTokens??Be,temperature:e.temperature??0,abortSignal:d}));g={inputTokens:g.inputTokens+x.usage.inputTokens,outputTokens:g.outputTokens+x.usage.outputTokens};let te=p.safeParse(x.answers);if(te.success){m=te.data;break}h=U(te.error),w=["Your previous reply did not match the required structure:",h,"","Reply again with the corrected structure only."].join(`
111
- `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:g,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function $t(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:B,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:B}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===B),u=a&&a.type==="tool_use"?a.input:null;return{answers:Pe(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Vt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
- `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Pe(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Pe(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function zt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Jt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,Pt,qt,Be,Xt,be=E(()=>{"use strict";Ke();Ue();ft();j();Y();N();z();Bt="claude-code",Pt="claude-haiku-4-5-20251001",qt=24e3,Be=2e3,Xt=3e4});import{readFileSync as Gt}from"fs";import{homedir as Yt}from"os";import{join as Kt}from"path";function v(e={}){let t=(e.baseUrl??Ht).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??Zt,s=e.maxChoiceOptions??en,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),on(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:y,dispose:d}=sn(a.abortSignal,a.timeoutMs??e.timeoutMs??Wt);try{let b={"Content-Type":"application/json"},g=rn(e.apiKeyEnv,e.apiKeyFile);g&&(b.Authorization=`Bearer ${g}`);let w=await p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:nn(a.questions)}),signal:y});if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await w.json(),m=F(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
- ${U(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function nn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:tn[n.type]};return t}function rn(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Kt(Yt(),t.slice(2)):t;if(!Z.has(n))try{let o=Gt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function on(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function sn(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Ht,Wt,Zt,en,tn,Z,fe=E(()=>{"use strict";j();N();z();Y();Ht="http://127.0.0.1:8000/v1",Wt=3e4,Zt=6e3,en=50;tn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var qe={};Ye(qe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>B,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>gt,agreement:()=>rt,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>lt,askSeat:()=>pn,band:()=>Ie,bootstrapInterval:()=>pt,brier:()=>at,buildDesign:()=>Ne,calibrationReport:()=>mt,choice:()=>tt,compareCalibrators:()=>Lt,confidenceFor:()=>re,configureDecisions:()=>cn,coverageCurve:()=>ut,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>v,decisionsRuntime:()=>ln,describeIssues:()=>U,ece:()=>st,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>ve,fitRecalibrator:()=>P,fitTemperature:()=>dt,getDecisionBackend:()=>D,getSeatMode:()=>Ve,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ct,logit:()=>le,mce:()=>it,measureConsistency:()=>Qt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>et,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>F,recordSeatOutcome:()=>dn,registerBuiltinDecisionBackends:()=>an,registerDecisionBackend:()=>R,reliabilityBins:()=>ot,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>un,score:()=>nt,seatEnvVar:()=>$e,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function an(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>v(t)),R("jev",()=>v({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>v({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var Xe=E(()=>{"use strict";ke();N();j();z();C();Y();V();bt();Me();je();ze();pe();be();fe();C();pe();be();fe()});function cn(e){T={...ye,...T,...e},ee=!0}function un(){T={...ye,seats:{}},ee=!1}function mn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(Ze(),he(We)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=(Xe(),he(qe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function ln(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return bn.includes(t)?t:null}function $e(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Ve(e,t=process.env){mn();let r=ge(t[$e(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function dn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function pn(e,t,r,n={}){let o=Ve(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=fn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return gn(e,o,t,r,i,n,s,a,u),yn(e,i,u),null}}function fn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ge(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function gn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ge(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ge(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function yn(e,t,r){let n=Date.now();n-Je<6e4||(Je=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,bn,Je,ze=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;bn=["off","shadow","active"];Je=0});export{D as a,Ee as b,C as c,I as d,V as e,Lt as f,Me as g,Qt as h,je as i,me as j,Un as k,Ue as l,an as m,Xe as n,cn as o,un as p,ln as q,ge as r,$e as s,Ve as t,dn as u,pn as v,ze as w};
114
- //# sourceMappingURL=chunk-6HPJKD3X.js.map
109
+ `)}var U,J,Y=E(()=>{"use strict";v();U="answer_questions",J=["You answer questions about a piece of state by reporting a probability distribution for each one.","","Rules:","- Answer every question. Never add a question that was not asked.","- For a yes/no question, report `noul`: the probability the answer is yes, between 0 and 1.","- For every other question, report `probabilities`: one number per listed option, summing to 1.","- Use only the exact option names given. Never invent one.","- Spread the distribution when the state genuinely does not settle the question. A flat"," distribution is a useful answer; a confident wrong one is not.","- Output the structure only. No prose, no explanation, no code fences."].join(`
110
+ `)});function Oe(e){return e.predicted===e.truth?1:0}function le(e){let t=Math.min(1-K,Math.max(K,e));return Math.log(t/(1-t))}function de(e){if(e>=0)return 1/(1+Math.exp(-e));let t=Math.exp(e);return t/(1+t)}function ce(e,t){let r=e.features?.[t];if(r!=null)return String(r);let n=e[t];return n==null?"(none)":String(n)}function ve(e,t){let r=t.minLevelCount??5,n={};for(let a of t.covariates){let u=new Map;for(let l of e){let p=ce(l,a);u.set(p,(u.get(p)??0)+1)}let c=[...u.entries()].filter(([,l])=>l>=r).map(([l])=>l).sort();n[a]=c.slice(1)}let o=["intercept","logitConfidence"];for(let a of t.covariates)for(let u of n[a])o.push(`${a}=${u}`);let s=[],i=[];for(let a of e){let u=[1,le(a.confidence)];for(let c of t.covariates){let l=ce(a,c);for(let p of n[c])u.push(l===p?1:0)}s.push(u),i.push(Oe(a))}return{X:s,y:i,names:o,levels:n}}function Ne(e,t,r={}){let n=r.l2??1,o=r.iterations??25,s=e.length,i=s>0?e[0].length:0,a=new Array(i).fill(0);if(s===0||i===0)return a;for(let u=0;u<o;u++){let c=Array.from({length:i},()=>new Array(i).fill(0)),l=new Array(i).fill(0);for(let d=0;d<s;d++){let b=0;for(let m=0;m<i;m++)b+=a[m]*e[d][m];let y=de(b),w=Math.max(y*(1-y),1e-8),f=t[d]-y;for(let m=0;m<i;m++){l[m]+=f*e[d][m];for(let h=m;h<i;h++)c[m][h]+=w*e[d][m]*e[d][h]}}for(let d=0;d<i;d++){d>0&&(c[d][d]+=n,l[d]-=n*a[d]);for(let b=0;b<d;b++)c[d][b]=c[b][d]}let p=Lt(c,l);if(!p)break;let g=0;for(let d=0;d<i;d++)a[d]+=p[d],g+=Math.abs(p[d]);if(g<1e-8)break}return a}function Lt(e,t){let r=t.length,n=e.map((s,i)=>[...s,t[i]]);for(let s=0;s<r;s++){let i=s;for(let a=s+1;a<r;a++)Math.abs(n[a][s])>Math.abs(n[i][s])&&(i=a);if(Math.abs(n[i][s])<1e-12)return null;[n[s],n[i]]=[n[i],n[s]];for(let a=0;a<r;a++){if(a===s)continue;let u=n[a][s]/n[s][s];if(u!==0)for(let c=s;c<=r;c++)n[a][c]-=u*n[s][c]}}let o=new Array(r);for(let s=0;s<r;s++)o[s]=n[s][r]/n[s][s];return o}function B(e,t){let r=e.filter(o=>o.truth!==void 0),n=ve(r,t);return{weights:Ne(n.X,n.y),names:n.names,levels:n.levels,covariates:t.covariates,n:r.length}}function ue(e,t){let r=e.weights[0]+e.weights[1]*le(t.confidence),n=2;for(let o of e.covariates){let s=ce(t,o);for(let i of e.levels[o]??[])s===i&&(r+=e.weights[n]),n++}return de(r)}function Dt(e,t,r={}){let n=r.folds??5,o=r.minN??100,s=e.filter(d=>d.truth!==void 0),i={insufficient:s.length<o,n:s.length,minN:o,folds:n,scores:[]};if(i.insufficient)return i;let a=r.rng??Math.random,u=[...s];for(let d=u.length-1;d>0;d--){let b=Math.floor(a()*(d+1));[u[d],u[b]]=[u[b],u[d]]}let c={raw:[],temperature:[],covariate:[]},l=[];for(let d=0;d<n;d++){let b=u.filter((m,h)=>h%n===d),y=u.filter((m,h)=>h%n!==d);if(y.length===0||b.length===0)continue;let w=B(y,{...t,covariates:[]}),f=B(y,t);for(let m of b)l.push(Oe(m)),c.raw.push(m.confidence),c.temperature.push(ue(w,m)),c.covariate.push(ue(f,m))}let p=Object.entries(c).map(([d,b])=>({name:d,logLoss:Ct(b,l),brier:It(b,l)})),g=[...p].sort((d,b)=>d.logLoss-b.logLoss)[0]?.name;return{...i,scores:p,best:g,model:g==="covariate"?B(s,t):B(s,{...t,covariates:[]})}}function Ct(e,t){if(e.length===0)return 0;let r=0;for(let n=0;n<e.length;n++){let o=Math.min(1-K,Math.max(K,e[n]));r+=t[n]===1?-Math.log(o):-Math.log(1-o)}return r/e.length}function It(e,t){if(e.length===0)return 0;let r=0;for(let n=0;n<e.length;n++)r+=(e[n]-t[n])**2;return r/e.length}var K,Me=E(()=>{"use strict";K=1e-6});import{randomBytes as Qt}from"crypto";function Ie(e,t=De,r=Ce){return e<=t?"no":e>r?"yes":"uncertain"}async function jt(e,t,r,n={}){let o=Math.max(2,n.samples??15),s=D(e),i=Date.now(),a=await Promise.all(Array.from({length:o},(p,g)=>s.decide({state:Qe(t,`${g}:${Qt(4).toString("hex")}`),questions:r,model:n.model}))),u=Object.keys(r),c=a.reduce((p,g)=>({inputTokens:p.inputTokens+g.usage.inputTokens,outputTokens:p.outputTokens+g.usage.outputTokens}),{inputTokens:0,outputTokens:0}),l=u.map(p=>{let g=a.map(f=>Q(f.answers[p])),d=g.map((f,m)=>{let h=a[m].answers[p];return h.type==="noul"?h.noul:f.topProb}),b=[...new Set(g.map(f=>f.predicted))],y=[...new Set(d.map(f=>Ie(f,n.low,n.high)))],w=Le(d);return{question:p,type:a[0].answers[p].type,n:o,mean:w,stdev:Pt(d,w),min:Math.min(...d),max:Math.max(...d),distinctAnswers:b,bands:y,crossesThreshold:b.length>1||y.length>1,samples:d}});return{backend:e,model:a[0].model,samples:o,meanStdev:Le(l.map(p=>p.stdev)),unstable:l.filter(p=>p.crossesThreshold).map(p=>p.question),questions:l,usage:c,totalMs:Date.now()-i}}function Qe(e,t){return e!==null&&typeof e=="object"&&!Array.isArray(e)?{...e,uid:t}:{uid:t,state:e}}function Le(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}function Pt(e,t){return e.length<2?0:Math.sqrt(e.reduce((r,n)=>r+(n-t)**2,0)/e.length)}var De,Ce,je=E(()=>{"use strict";C();V();De=.3,Ce=.7});function H(e={}){return{name:"mock",capabilities:Ft,async decide(t){if(e.fail)throw e.fail;A(t.questions);let r=JSON.stringify(t.state??null),n={},o=!1;for(let[i,a]of Object.entries(t.questions)){let u=e.answers?.[i]??Ut(r,i,a),c=_(a,u);n[i]=c.answer,c.repaired&&(o=!0)}let s="probabilities";return{model:t.model??"mock",answers:n,usage:{inputTokens:r.length,outputTokens:0},meta:{backend:"mock",structureMode:"mock",answerMode:s,repaired:o,retries:0,stateTruncated:!1,latencyMs:e.latencyMs??0}}}}}function Ut(e,t,r){if(r.type==="noul")return{noul:Pe(`${e}|${t}|noul`)};let n=S(r),o=n.map(a=>Pe(`${e}|${t}|${a}`)+.001),s=o.reduce((a,u)=>a+u,0),i={};return n.forEach((a,u)=>{i[a]=o[u]/s}),{probabilities:i}}function Pe(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t/4294967296}var Ft,pe=E(()=>{"use strict";j();v();Ft={probabilitySource:"synthetic",calibratedProbabilities:!1,maxChoiceOptions:255,maxStateChars:24e3,parallelQuestions:!0,images:!1}});function Un(e,t){let r=me[e];if(!r)return[`Unknown provider "${e}" \u2014 capabilities unknown`];if(!t?.length)return[];let n=[],o=[];for(let s of t)s in r&&!r[s]&&o.push(s);return o.length&&n.push(`Provider "${e}" lacks: ${o.join(", ")}. Some features will be degraded.`),n}var me,Fe=E(()=>{"use strict";me={"claude-code":{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6,structuredOutput:!1,logprobs:!1},claude:{streaming:!0,tools:!0,vision:!0,thinking:!0,maxContext:1e6,structuredOutput:!0,logprobs:!1},openai:{streaming:!0,tools:!0,vision:!0,thinking:!1,maxContext:128e3,structuredOutput:!0,logprobs:!0},deepseek:{streaming:!0,tools:!0,vision:!1,thinking:!0,maxContext:128e3,structuredOutput:!0,logprobs:!0},ollama:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:32e3,structuredOutput:!1,logprobs:!1},demo:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:8e3,structuredOutput:!1,logprobs:!1},custom:{streaming:!0,tools:!1,vision:!1,thinking:!1,maxContext:32e3,structuredOutput:!1,logprobs:!1}}});function W(e={}){if(e.answerMode&&e.answerMode!=="probabilities")throw new Error(`local decision backend supports answerMode "probabilities" only (got "${e.answerMode}")`);let t=e.maxStateChars??Xt,r={probabilitySource:"verbalized",calibratedProbabilities:!1,maxChoiceOptions:255,maxStateChars:t,parallelQuestions:!0,images:!1},n=null,o=()=>(n||(n=e.providerFactory?e.providerFactory():we(e.provider??Bt)),n);return{name:"local",capabilities:r,async decide(s){A(s.questions);let i=Date.now(),a=s.model??e.model??qt,u=o(),c=Jt(e.structureMode??"auto",u),l=ie(s.state,s.questions,t),p=P(s.questions),g=e.nRetryMalformedStructure??1,{signal:d,dispose:b}=Gt(s.abortSignal,s.timeoutMs??e.timeoutMs??$t),y={inputTokens:0,outputTokens:0},w=null,f=0,m=null,h="no attempt was made";try{for(let k=0;k<=g;k++){k>0&&f++;let x=await(c==="tool"?Vt(u,s.questions,l.text,w,{model:a,maxTokens:e.maxTokens??Ue,temperature:e.temperature??0,abortSignal:d}):zt(u,s.questions,l.text,w,{model:a,maxTokens:e.maxTokens??Ue,temperature:e.temperature??0,abortSignal:d}));y={inputTokens:y.inputTokens+x.usage.inputTokens,outputTokens:y.outputTokens+x.usage.outputTokens};let te=p.safeParse(x.answers);if(te.success){m=te.data;break}h=F(te.error),w=["Your previous reply did not match the required structure:",h,"","Reply again with the corrected structure only."].join(`
111
+ `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:y,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Vt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:U,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:U}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===U),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function zt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
+ `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Jt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Gt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,qt,Xt,Ue,$t,be=E(()=>{"use strict";He();Fe();gt();j();Y();v();z();Bt="claude-code",qt="claude-haiku-4-5-20251001",Xt=24e3,Ue=2e3,$t=3e4});import{readFileSync as Yt}from"fs";import{homedir as Kt}from"os";import{join as Ht}from"path";function N(e={}){let t=(e.baseUrl??Wt).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??en,s=e.maxChoiceOptions??tn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),sn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=an(a.abortSignal,a.timeoutMs??e.timeoutMs??Zt);try{let b={"Content-Type":"application/json"},y=on(e.apiKeyEnv,e.apiKeyFile);y&&(b.Authorization=`Bearer ${y}`);let w=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:rn(a.questions)}),signal:g}),g);if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await qe(w.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
+ ${F(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function rn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:nn[n.type]};return t}function on(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Ht(Kt(),t.slice(2)):t;if(!Z.has(n))try{let o=Yt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function sn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function an(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Wt,Zt,en,tn,nn,Z,fe=E(()=>{"use strict";j();v();z();Y();Wt="http://127.0.0.1:8000/v1",Zt=3e4,en=6e3,tn=50;nn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};Ke(Xe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>U,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>yt,agreement:()=>ot,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>dt,askSeat:()=>mn,band:()=>Ie,bootstrapInterval:()=>mt,brier:()=>ct,buildDesign:()=>ve,calibrationReport:()=>bt,choice:()=>nt,compareCalibrators:()=>Dt,confidenceFor:()=>re,configureDecisions:()=>un,coverageCurve:()=>lt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>dn,describeIssues:()=>F,ece:()=>it,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>pt,getDecisionBackend:()=>D,getSeatMode:()=>ze,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ut,logit:()=>le,mce:()=>at,measureConsistency:()=>jt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>tt,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>pn,registerBuiltinDecisionBackends:()=>cn,registerDecisionBackend:()=>R,reliabilityBins:()=>st,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>ln,score:()=>rt,seatEnvVar:()=>Ve,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function cn(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();ft();Me();je();Je();pe();be();fe();C();pe();be();fe()});function un(e){T={...ye,...T,...e},ee=!0}function ln(){T={...ye,seats:{}},ee=!1}function bn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(et(),he(Ze)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function dn(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return fn.includes(t)?t:null}function Ve(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function ze(e,t=process.env){bn();let r=ge(t[Ve(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function pn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function mn(e,t,r,n={}){let o=ze(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=gn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return yn(e,o,t,r,i,n,s,a,u),hn(e,i,u),null}}function gn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ye(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function yn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ye(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ye(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function hn(e,t,r){let n=Date.now();n-Ge<6e4||(Ge=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,fn,Ge,Je=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;fn=["off","shadow","active"];Ge=0});export{D as a,Ee as b,C as c,I as d,V as e,Dt as f,Me as g,jt as h,je as i,me as j,Un as k,Fe as l,cn as m,$e as n,un as o,ln as p,dn as q,ge as r,Ve as s,ze as t,pn as u,mn as v,Je as w};
114
+ //# sourceMappingURL=chunk-KHEI4VNM.js.map