agentix-cli 0.110.0 → 0.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +77 -30
  2. package/apps/mac-voice/Sources/AgentXVoice/PanelAnswer.swift +3 -2
  3. package/apps/mac-voice/Sources/AgentXVoice/PillForm.swift +55 -0
  4. package/apps/mac-voice/Sources/AgentXVoice/PillMenu.swift +8 -7
  5. package/apps/mac-voice/Sources/AgentXVoice/SettingsLook.swift +2 -2
  6. package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +5 -6
  7. package/apps/mac-voice/Sources/AgentXVoice/main.swift +7 -6
  8. package/dist/{App-4VWAQOVA.js → App-T4Q7SW6M.js} +2 -2
  9. package/dist/{ChatApp-KOTGUDZH.js → ChatApp-BKUJUIDL.js} +2 -2
  10. package/dist/{agent-CGRHC2IS.js → agent-YZVEXFE7.js} +2 -2
  11. package/dist/{board-dashboard-SAYBNLZW.js → board-dashboard-3TVUCOSI.js} +411 -257
  12. package/dist/board-dashboard-3TVUCOSI.js.map +1 -0
  13. package/dist/{chunk-UVMCAZL7.js → chunk-4FU4BFCH.js} +2 -2
  14. package/dist/{chunk-NIW75USA.js → chunk-4NFDDTGA.js} +2 -2
  15. package/dist/{chunk-2VGYRETU.js → chunk-53OS4TDU.js} +2 -2
  16. package/dist/{chunk-J32LSOBJ.js → chunk-7UNS34CN.js} +2 -2
  17. package/dist/chunk-AV7T3SYT.js +111 -0
  18. package/dist/chunk-AV7T3SYT.js.map +1 -0
  19. package/dist/chunk-DTQQ4DAY.js +154 -0
  20. package/dist/chunk-DTQQ4DAY.js.map +1 -0
  21. package/dist/{chunk-SFPMS55Z.js → chunk-DUBCOGQB.js} +49 -48
  22. package/dist/chunk-DUBCOGQB.js.map +1 -0
  23. package/dist/{chunk-BFOB6ERR.js → chunk-DXWDVKMX.js} +2 -2
  24. package/dist/{chunk-BZKGQMU2.js → chunk-FBODSJU6.js} +2 -2
  25. package/dist/{chunk-UTV4DRAW.js → chunk-GQMUFSKB.js} +14 -14
  26. package/dist/{chunk-UTV4DRAW.js.map → chunk-GQMUFSKB.js.map} +1 -1
  27. package/dist/{chunk-4UCDWEC4.js → chunk-HCTWKWS3.js} +2 -2
  28. package/dist/{chunk-EC6DKMR5.js → chunk-KDD6FPQ6.js} +238 -238
  29. package/dist/chunk-KDD6FPQ6.js.map +1 -0
  30. package/dist/{chunk-5O6PIO7F.js → chunk-LWYKS5JU.js} +2 -2
  31. package/dist/{chunk-QQAZ6EJP.js → chunk-M2L6S3Z5.js} +2 -2
  32. package/dist/{chunk-6F2E5NQA.js → chunk-QJP37VVA.js} +2 -2
  33. package/dist/{chunk-QFP4YZII.js → chunk-RS2T53EC.js} +2 -2
  34. package/dist/{chunk-E5OV6RTG.js → chunk-RXLU6HJ6.js} +3 -3
  35. package/dist/chunk-RXLU6HJ6.js.map +1 -0
  36. package/dist/{chunk-D7M4WQFU.js → chunk-SIOWVLZG.js} +4 -4
  37. package/dist/chunk-SIOWVLZG.js.map +1 -0
  38. package/dist/{chunk-BG6SOGKT.js → chunk-U52IS3AF.js} +2 -2
  39. package/dist/{chunk-RJ7DASOU.js → chunk-UIBUZ2N3.js} +25 -10
  40. package/dist/chunk-UIBUZ2N3.js.map +1 -0
  41. package/dist/{chunk-MJWJ3JVA.js → chunk-WSKQUKCF.js} +2 -2
  42. package/dist/{chunk-S4NZUPIN.js → chunk-WXQQO2PD.js} +2 -2
  43. package/dist/{chunk-FHI5WPFO.js → chunk-WYSNRZV4.js} +4 -4
  44. package/dist/chunk-WYSNRZV4.js.map +1 -0
  45. package/dist/{chunk-CJR26JUI.js → chunk-XEOT2F4C.js} +2 -2
  46. package/dist/{chunk-3Z5P2CWS.js → chunk-XF26QNAW.js} +2 -2
  47. package/dist/{chunk-CJL5OPNQ.js → chunk-Z7L74GGT.js} +2 -2
  48. package/dist/cli.js +1 -1
  49. package/dist/{client-VYMTUZKN.js → client-O7SPKO5X.js} +2 -2
  50. package/dist/config-ZHQYXFOJ.js +2 -0
  51. package/dist/config-mutator-RS2NTDNO.js +2 -0
  52. package/dist/{doctor-GHUPUBET.js → doctor-XP7O45RC.js} +2 -2
  53. package/dist/{grants-Y667GZAU.js → grants-M4K6WXOO.js} +2 -2
  54. package/dist/index.d.ts +68 -15
  55. package/dist/index.js +1 -1
  56. package/dist/{program-V2JEVJAD.js → program-EZLJIVQX.js} +187 -182
  57. package/dist/program-EZLJIVQX.js.map +1 -0
  58. package/dist/{promote-KY3Y2PVU.js → promote-UGWANGI2.js} +2 -2
  59. package/dist/{query-BYCRYDM3.js → query-ZET7Z5FT.js} +2 -2
  60. package/dist/registry-UXWOY52B.js +2 -0
  61. package/dist/request-planner-W5YLKCGG.js +6 -0
  62. package/dist/request-planner-W5YLKCGG.js.map +1 -0
  63. package/dist/{review-candidates-56ZPJNXW.js → review-candidates-GU4S5VQH.js} +2 -2
  64. package/dist/{routing-WKS2CZYF.js → routing-GJ4VXKIC.js} +2 -2
  65. package/dist/schedule-tool-HD4LWKVC.js +2 -0
  66. package/dist/scheduler-3LEHZHWJ.js +2 -0
  67. package/dist/seat-L6XJ2BFA.js +2 -0
  68. package/dist/select-T7CKKLC2.js +2 -0
  69. package/dist/{select-73JC2YBN.js.map → select-T7CKKLC2.js.map} +1 -1
  70. package/dist/{set-enabled-WQAO4BFF.js → set-enabled-U2HGNY2O.js} +2 -2
  71. package/dist/{surface-usage-CH3SHO77.js → surface-usage-HCJTUS6Z.js} +2 -2
  72. package/dist/{tool-QDU6MY6B.js → tool-2FMWZB4N.js} +2 -2
  73. package/dist/{tool-GCPMPPUE.js → tool-TX622HEB.js} +2 -2
  74. package/dist/wiki-MYJBOJSM.js +2 -0
  75. package/dist/workspace-setup-HAV4CQV7.js +2 -0
  76. package/package.json +2 -1
  77. package/dist/board-dashboard-SAYBNLZW.js.map +0 -1
  78. package/dist/chunk-3TY6YJHO.js +0 -153
  79. package/dist/chunk-3TY6YJHO.js.map +0 -1
  80. package/dist/chunk-D7M4WQFU.js.map +0 -1
  81. package/dist/chunk-E5OV6RTG.js.map +0 -1
  82. package/dist/chunk-EC6DKMR5.js.map +0 -1
  83. package/dist/chunk-FHI5WPFO.js.map +0 -1
  84. package/dist/chunk-RJ7DASOU.js.map +0 -1
  85. package/dist/chunk-SFPMS55Z.js.map +0 -1
  86. package/dist/chunk-UDJAODAB.js +0 -100
  87. package/dist/chunk-UDJAODAB.js.map +0 -1
  88. package/dist/config-J6CNV23P.js +0 -2
  89. package/dist/config-mutator-RGC72OEU.js +0 -2
  90. package/dist/program-V2JEVJAD.js.map +0 -1
  91. package/dist/registry-NDFYNQG4.js +0 -2
  92. package/dist/request-planner-YOUVO3BR.js +0 -2
  93. package/dist/request-planner-YOUVO3BR.js.map +0 -1
  94. package/dist/schedule-tool-4L6QAILN.js +0 -2
  95. package/dist/scheduler-65SE3WJJ.js +0 -2
  96. package/dist/seat-EO3EVBH3.js +0 -2
  97. package/dist/select-73JC2YBN.js +0 -2
  98. package/dist/wiki-CQZE5Z5C.js +0 -2
  99. package/dist/workspace-setup-EA3G42NY.js +0 -2
  100. /package/dist/{App-4VWAQOVA.js.map → App-T4Q7SW6M.js.map} +0 -0
  101. /package/dist/{ChatApp-KOTGUDZH.js.map → ChatApp-BKUJUIDL.js.map} +0 -0
  102. /package/dist/{agent-CGRHC2IS.js.map → agent-YZVEXFE7.js.map} +0 -0
  103. /package/dist/{chunk-UVMCAZL7.js.map → chunk-4FU4BFCH.js.map} +0 -0
  104. /package/dist/{chunk-NIW75USA.js.map → chunk-4NFDDTGA.js.map} +0 -0
  105. /package/dist/{chunk-2VGYRETU.js.map → chunk-53OS4TDU.js.map} +0 -0
  106. /package/dist/{chunk-J32LSOBJ.js.map → chunk-7UNS34CN.js.map} +0 -0
  107. /package/dist/{chunk-BFOB6ERR.js.map → chunk-DXWDVKMX.js.map} +0 -0
  108. /package/dist/{chunk-BZKGQMU2.js.map → chunk-FBODSJU6.js.map} +0 -0
  109. /package/dist/{chunk-4UCDWEC4.js.map → chunk-HCTWKWS3.js.map} +0 -0
  110. /package/dist/{chunk-5O6PIO7F.js.map → chunk-LWYKS5JU.js.map} +0 -0
  111. /package/dist/{chunk-QQAZ6EJP.js.map → chunk-M2L6S3Z5.js.map} +0 -0
  112. /package/dist/{chunk-6F2E5NQA.js.map → chunk-QJP37VVA.js.map} +0 -0
  113. /package/dist/{chunk-QFP4YZII.js.map → chunk-RS2T53EC.js.map} +0 -0
  114. /package/dist/{chunk-BG6SOGKT.js.map → chunk-U52IS3AF.js.map} +0 -0
  115. /package/dist/{chunk-MJWJ3JVA.js.map → chunk-WSKQUKCF.js.map} +0 -0
  116. /package/dist/{chunk-S4NZUPIN.js.map → chunk-WXQQO2PD.js.map} +0 -0
  117. /package/dist/{chunk-CJR26JUI.js.map → chunk-XEOT2F4C.js.map} +0 -0
  118. /package/dist/{chunk-3Z5P2CWS.js.map → chunk-XF26QNAW.js.map} +0 -0
  119. /package/dist/{chunk-CJL5OPNQ.js.map → chunk-Z7L74GGT.js.map} +0 -0
  120. /package/dist/{client-VYMTUZKN.js.map → client-O7SPKO5X.js.map} +0 -0
  121. /package/dist/{config-J6CNV23P.js.map → config-ZHQYXFOJ.js.map} +0 -0
  122. /package/dist/{config-mutator-RGC72OEU.js.map → config-mutator-RS2NTDNO.js.map} +0 -0
  123. /package/dist/{doctor-GHUPUBET.js.map → doctor-XP7O45RC.js.map} +0 -0
  124. /package/dist/{grants-Y667GZAU.js.map → grants-M4K6WXOO.js.map} +0 -0
  125. /package/dist/{promote-KY3Y2PVU.js.map → promote-UGWANGI2.js.map} +0 -0
  126. /package/dist/{query-BYCRYDM3.js.map → query-ZET7Z5FT.js.map} +0 -0
  127. /package/dist/{registry-NDFYNQG4.js.map → registry-UXWOY52B.js.map} +0 -0
  128. /package/dist/{review-candidates-56ZPJNXW.js.map → review-candidates-GU4S5VQH.js.map} +0 -0
  129. /package/dist/{routing-WKS2CZYF.js.map → routing-GJ4VXKIC.js.map} +0 -0
  130. /package/dist/{schedule-tool-4L6QAILN.js.map → schedule-tool-HD4LWKVC.js.map} +0 -0
  131. /package/dist/{scheduler-65SE3WJJ.js.map → scheduler-3LEHZHWJ.js.map} +0 -0
  132. /package/dist/{seat-EO3EVBH3.js.map → seat-L6XJ2BFA.js.map} +0 -0
  133. /package/dist/{set-enabled-WQAO4BFF.js.map → set-enabled-U2HGNY2O.js.map} +0 -0
  134. /package/dist/{surface-usage-CH3SHO77.js.map → surface-usage-HCJTUS6Z.js.map} +0 -0
  135. /package/dist/{tool-QDU6MY6B.js.map → tool-2FMWZB4N.js.map} +0 -0
  136. /package/dist/{tool-GCPMPPUE.js.map → tool-TX622HEB.js.map} +0 -0
  137. /package/dist/{wiki-CQZE5Z5C.js.map → wiki-MYJBOJSM.js.map} +0 -0
  138. /package/dist/{workspace-setup-EA3G42NY.js.map → workspace-setup-HAV4CQV7.js.map} +0 -0
@@ -1,12 +1,12 @@
1
- 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 Te,b as gt}from"./chunk-FX3D7YON.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{ja as Ze,ka as et}from"./chunk-D7M4WQFU.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(`
1
+ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-5MUJZODV.js";import{ka as tt,la as nt}from"./chunk-SIOWVLZG.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,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 wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}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 At(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 Rt(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&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(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 Rt(e){e.exec(`
4
+ `)}function Ot(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 _t(e){e.exec(`
9
+ `)}function vt(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 tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";im
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";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
76
+ `)}var I,V=E(()=>{"use strict";et();I=class{db;path;constructor(t={}){this.path=xt(process.cwd(),t.path??".agentx/decisions/decisions.sqlite"),t.readonly||kt(St(this.path),{recursive:!0}),this.db=new Tt(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"),Rt(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=Et("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 tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";im
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: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
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:At(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 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)}
102
+ )`).run(t,t,r).changes}}});var ke=E(()=>{"use strict"});function Se(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 xe(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 Nt(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 Nt(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=x(e),{probs:o,repaired:s}=Se(t.probabilities,n,r),i=xe(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"?Mt:Lt}function P(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 Mt,Lt,z=E(()=>{"use strict";Mt=O.object({noul:O.number()}),Lt=O.object({probabilities:O.record(O.string(),O.unknown())})});function se(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Dt(n);return{type:"object",additionalProperties:!1,required:["answers"],properties:{answers:{type:"object",additionalProperties:!1,required:Object.keys(e),properties:t}}}}function Dt(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=x(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
- `),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 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-UTV4DRAW.js.map
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=x(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 F,J,Y=E(()=>{"use strict";v();F="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 h=de(b),T=Math.max(h*(1-h),1e-8),f=t[d]-h;for(let m=0;m<i;m++){l[m]+=f*e[d][m];for(let w=m;w<i;w++)c[m][w]+=T*e[d][m]*e[d][w]}}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=Ct(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 Ct(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 It(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,w)=>w%n===d),h=u.filter((m,w)=>w%n!==d);if(h.length===0||b.length===0)continue;let T=B(h,{...t,covariates:[]}),f=B(h,t);for(let m of b)l.push(Oe(m)),c.raw.push(m.confidence),c.temperature.push(ue(T,m)),c.covariate.push(ue(f,m))}let p=Object.entries(c).map(([d,b])=>({name:d,logLoss:Qt(b,l),brier:jt(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 Qt(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 jt(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 Pt}from"crypto";function Ie(e,t=De,r=Ce){return e<=t?"no":e>r?"yes":"uncertain"}async function Ut(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}:${Pt(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 w=a[m].answers[p];return w.type==="noul"?w.noul:f.topProb}),b=[...new Set(g.map(f=>f.predicted))],h=[...new Set(d.map(f=>Ie(f,n.low,n.high)))],T=Le(d);return{question:p,type:a[0].answers[p].type,n:o,mean:T,stdev:Ft(d,T),min:Math.min(...d),max:Math.max(...d),distinctAnswers:b,bands:h,crossesThreshold:b.length>1||h.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 Ft(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:Bt,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]??qt(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 qt(e,t,r){if(r.type==="noul")return{noul:Pe(`${e}|${t}|noul`)};let n=x(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 Bt,pe=E(()=>{"use strict";j();v();Bt={probabilitySource:"synthetic",calibratedProbabilities:!1,maxChoiceOptions:255,maxStateChars:24e3,parallelQuestions:!0,images:!1}});function Xn(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??Vt,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??Xt)),n);return{name:"local",capabilities:r,async decide(s){A(s.questions);let i=Date.now(),a=s.model??e.model??$t,u=o(),c=Yt(e.structureMode??"auto",u),l=ie(s.state,s.questions,t),p=P(s.questions),g=e.nRetryMalformedStructure??1,{signal:d,dispose:b}=Kt(s.abortSignal,s.timeoutMs??e.timeoutMs??zt),h={inputTokens:0,outputTokens:0},T=null,f=0,m=null,w="no attempt was made";try{for(let k=0;k<=g;k++){k>0&&f++;let S=await(c==="tool"?Jt(u,s.questions,l.text,T,{model:a,maxTokens:e.maxTokens??Fe,temperature:e.temperature??0,abortSignal:d}):Gt(u,s.questions,l.text,T,{model:a,maxTokens:e.maxTokens??Fe,temperature:e.temperature??0,abortSignal:d}));h={inputTokens:h.inputTokens+S.usage.inputTokens,outputTokens:h.outputTokens+S.usage.outputTokens};let te=p.safeParse(S.answers);if(te.success){m=te.data;break}w=U(te.error),T=["Your previous reply did not match the required structure:",w,"","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): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(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:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),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 Gt(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 Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(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 Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,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),cn(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}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.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
+ ${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.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 sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(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 un(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 en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(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();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),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{}y={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 bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.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??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.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:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.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:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
114
+ //# sourceMappingURL=chunk-GQMUFSKB.js.map