agentix-cli 0.210.0 → 0.211.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 (154) hide show
  1. package/dist/{App-EMCBJ5NE.js → App-RIXKQIO7.js} +2 -2
  2. package/dist/{ChatApp-HIHZEUKS.js → ChatApp-2TKXDJGQ.js} +2 -2
  3. package/dist/{absorb-eval-7CCHO4KZ.js → absorb-eval-5YZOYFF4.js} +2 -2
  4. package/dist/{adapter-J6YO4FLT.js → adapter-Q76GO2I7.js} +2 -2
  5. package/dist/{agent-AETIDS4G.js → agent-GW6Z6OFF.js} +2 -2
  6. package/dist/{board-dashboard-OAAO3ZKR.js → board-dashboard-RPZJBHL3.js} +4 -4
  7. package/dist/{chunk-UQMNYIGT.js → chunk-323KMXT4.js} +2 -2
  8. package/dist/{chunk-DNQEK2KS.js → chunk-6BINQY52.js} +7 -7
  9. package/dist/{chunk-DNQEK2KS.js.map → chunk-6BINQY52.js.map} +1 -1
  10. package/dist/{chunk-CTN4KYE6.js → chunk-6UI7GJSB.js} +2 -2
  11. package/dist/{chunk-4CGAIVLW.js → chunk-6VHORIGB.js} +2 -2
  12. package/dist/{chunk-5GHYIU5L.js → chunk-BQIZN5JU.js} +2 -2
  13. package/dist/{chunk-6FCD7K6G.js → chunk-CUX7BF7B.js} +2 -2
  14. package/dist/{chunk-PK2KOR6H.js → chunk-EPIKS3WL.js} +2 -2
  15. package/dist/{chunk-F3DCWMTS.js → chunk-F3HVONL6.js} +2 -2
  16. package/dist/{chunk-TADIDWYZ.js → chunk-FFOGEFPT.js} +2 -2
  17. package/dist/{chunk-5UXCARLO.js → chunk-FLDMRYZD.js} +2 -2
  18. package/dist/{chunk-H22TBFXT.js → chunk-FLNSBODK.js} +2 -2
  19. package/dist/{chunk-NWY4OF4X.js → chunk-GUID2ZA2.js} +3 -3
  20. package/dist/chunk-GUID2ZA2.js.map +1 -0
  21. package/dist/{chunk-VJVXEVZ7.js → chunk-IH65GDJR.js} +6 -6
  22. package/dist/chunk-IH65GDJR.js.map +1 -0
  23. package/dist/{chunk-EP3XCCZ3.js → chunk-ISRY3GAD.js} +2 -2
  24. package/dist/{chunk-GCR3KWCV.js → chunk-JJC2HBWC.js} +2 -2
  25. package/dist/{chunk-WSHOJMQG.js → chunk-LYY7G6LO.js} +2 -2
  26. package/dist/{chunk-N2DOU7A5.js → chunk-MHRVTFLZ.js} +3 -3
  27. package/dist/{chunk-TAUJUPJN.js → chunk-MKQI5WL2.js} +2 -2
  28. package/dist/{chunk-UEEB3UTU.js → chunk-N47Y5ADQ.js} +10 -10
  29. package/dist/{chunk-UEEB3UTU.js.map → chunk-N47Y5ADQ.js.map} +1 -1
  30. package/dist/{chunk-D55REZL3.js → chunk-OAVJMZLF.js} +2 -2
  31. package/dist/{chunk-KI2M5LXX.js → chunk-PYTNMX2D.js} +2 -2
  32. package/dist/{chunk-426L6XZP.js → chunk-QQKPZKQT.js} +2 -2
  33. package/dist/{chunk-UEYKYTJD.js → chunk-UYG7UOVQ.js} +2 -2
  34. package/dist/{chunk-RTYBNDHE.js → chunk-W4K3DFAX.js} +2 -2
  35. package/dist/{chunk-TNIN3DPC.js → chunk-WNE4GRXY.js} +2 -2
  36. package/dist/{chunk-6L3K7Y7E.js → chunk-XWMHNDED.js} +2 -2
  37. package/dist/{chunk-W3DLKUOV.js → chunk-XWOXXVVX.js} +2 -2
  38. package/dist/{chunk-PTDPY5YN.js → chunk-Y4BNOZWQ.js} +2 -2
  39. package/dist/{chunk-4GS2I57L.js → chunk-Y65DB3PF.js} +2 -2
  40. package/dist/{chunk-TPGQIJOK.js → chunk-YRBJ4KB7.js} +3 -3
  41. package/dist/chunk-YRBJ4KB7.js.map +1 -0
  42. package/dist/{chunk-6X2K2VSD.js → chunk-YZD6EZMU.js} +2 -2
  43. package/dist/{chunk-CXLAXYZG.js → chunk-YZEQLJD2.js} +303 -299
  44. package/dist/chunk-YZEQLJD2.js.map +1 -0
  45. package/dist/{chunk-TARMAPO6.js → chunk-ZWO36TCN.js} +2 -2
  46. package/dist/cli.js +1 -1
  47. package/dist/{client-XITH4RAT.js → client-AIQ7D7VU.js} +2 -2
  48. package/dist/{config-YYD7E5BT.js → config-TSSRDRCK.js} +2 -2
  49. package/dist/config-mutate-XUBGMDIU.js +2 -0
  50. package/dist/{config-mutator-XHSEEKWW.js → config-mutator-G62RKREK.js} +2 -2
  51. package/dist/{contributions-R2BJWBI7.js → contributions-RQZO4V36.js} +2 -2
  52. package/dist/{doctor-2GK4QVSK.js → doctor-DVMX6632.js} +2 -2
  53. package/dist/{failure-candidates-WGSFI7GR.js → failure-candidates-FASPEOBF.js} +2 -2
  54. package/dist/{follow-up-tool-FT5JYKSI.js → follow-up-tool-MS4FSM2J.js} +2 -2
  55. package/dist/hub-RKX3L5LU.js +2 -0
  56. package/dist/index.js +1 -1
  57. package/dist/{org-tool-BTZF5L74.js → org-tool-NA6U3IJJ.js} +2 -2
  58. package/dist/{program-O5MDSQSU.js → program-YEHUSQFX.js} +25 -25
  59. package/dist/{promote-JQYV4QKG.js → promote-OV2OD55V.js} +2 -2
  60. package/dist/{query-RW3BV23C.js → query-6FK2A4K2.js} +2 -2
  61. package/dist/{query-settings-DN6BU3QA.js → query-settings-RE2BTERX.js} +2 -2
  62. package/dist/{registry-CQLEJUHN.js → registry-APVJFCDJ.js} +2 -2
  63. package/dist/{request-planner-M4GOEJUD.js → request-planner-23FPTJLW.js} +2 -2
  64. package/dist/{review-candidates-HZDY5DV3.js → review-candidates-FCRNGU2S.js} +2 -2
  65. package/dist/{routing-IUE6GT6T.js → routing-W7AOH7QM.js} +2 -2
  66. package/dist/schedule-tool-RXX26TI4.js +2 -0
  67. package/dist/scheduler-3CJD7UF4.js +2 -0
  68. package/dist/{seat-OIVGQP4P.js → seat-BIVMGYMR.js} +2 -2
  69. package/dist/{select-TKODF5NC.js → select-LWTPLTCE.js} +2 -2
  70. package/dist/{set-enabled-B3A2VMDN.js → set-enabled-OKG7Q5WY.js} +2 -2
  71. package/dist/{sprint-tool-N4RLQ3EN.js → sprint-tool-YLQADXQH.js} +2 -2
  72. package/dist/{surface-usage-Y7D5W52I.js → surface-usage-Y23TE5AN.js} +2 -2
  73. package/dist/{tool-SBFQKJ4J.js → tool-5T5SSYMB.js} +2 -2
  74. package/dist/{tool-FQY3IU4B.js → tool-XZU2IJUI.js} +2 -2
  75. package/dist/{tool-FUEAREQB.js → tool-YCCQX7BT.js} +2 -2
  76. package/dist/{tool-UL673LK6.js → tool-ZXIRHFRB.js} +2 -2
  77. package/dist/{traces-O4TIZ4SM.js → traces-MKAHGAYG.js} +2 -2
  78. package/dist/{wiki-S6FJAVZ6.js → wiki-2BVHRZX5.js} +2 -2
  79. package/dist/wiki-enrich-BHPD4BOV.js +2 -0
  80. package/package.json +1 -1
  81. package/dist/chunk-CXLAXYZG.js.map +0 -1
  82. package/dist/chunk-NWY4OF4X.js.map +0 -1
  83. package/dist/chunk-TPGQIJOK.js.map +0 -1
  84. package/dist/chunk-VJVXEVZ7.js.map +0 -1
  85. package/dist/config-mutate-F23A3UAU.js +0 -2
  86. package/dist/hub-QBJH2GAV.js +0 -2
  87. package/dist/schedule-tool-WAXHHKSR.js +0 -2
  88. package/dist/scheduler-PPKHYCMH.js +0 -2
  89. package/dist/wiki-enrich-UQKBCRS7.js +0 -2
  90. /package/dist/{App-EMCBJ5NE.js.map → App-RIXKQIO7.js.map} +0 -0
  91. /package/dist/{ChatApp-HIHZEUKS.js.map → ChatApp-2TKXDJGQ.js.map} +0 -0
  92. /package/dist/{absorb-eval-7CCHO4KZ.js.map → absorb-eval-5YZOYFF4.js.map} +0 -0
  93. /package/dist/{adapter-J6YO4FLT.js.map → adapter-Q76GO2I7.js.map} +0 -0
  94. /package/dist/{agent-AETIDS4G.js.map → agent-GW6Z6OFF.js.map} +0 -0
  95. /package/dist/{board-dashboard-OAAO3ZKR.js.map → board-dashboard-RPZJBHL3.js.map} +0 -0
  96. /package/dist/{chunk-UQMNYIGT.js.map → chunk-323KMXT4.js.map} +0 -0
  97. /package/dist/{chunk-CTN4KYE6.js.map → chunk-6UI7GJSB.js.map} +0 -0
  98. /package/dist/{chunk-4CGAIVLW.js.map → chunk-6VHORIGB.js.map} +0 -0
  99. /package/dist/{chunk-5GHYIU5L.js.map → chunk-BQIZN5JU.js.map} +0 -0
  100. /package/dist/{chunk-6FCD7K6G.js.map → chunk-CUX7BF7B.js.map} +0 -0
  101. /package/dist/{chunk-PK2KOR6H.js.map → chunk-EPIKS3WL.js.map} +0 -0
  102. /package/dist/{chunk-F3DCWMTS.js.map → chunk-F3HVONL6.js.map} +0 -0
  103. /package/dist/{chunk-TADIDWYZ.js.map → chunk-FFOGEFPT.js.map} +0 -0
  104. /package/dist/{chunk-5UXCARLO.js.map → chunk-FLDMRYZD.js.map} +0 -0
  105. /package/dist/{chunk-H22TBFXT.js.map → chunk-FLNSBODK.js.map} +0 -0
  106. /package/dist/{chunk-EP3XCCZ3.js.map → chunk-ISRY3GAD.js.map} +0 -0
  107. /package/dist/{chunk-GCR3KWCV.js.map → chunk-JJC2HBWC.js.map} +0 -0
  108. /package/dist/{chunk-WSHOJMQG.js.map → chunk-LYY7G6LO.js.map} +0 -0
  109. /package/dist/{chunk-N2DOU7A5.js.map → chunk-MHRVTFLZ.js.map} +0 -0
  110. /package/dist/{chunk-TAUJUPJN.js.map → chunk-MKQI5WL2.js.map} +0 -0
  111. /package/dist/{chunk-D55REZL3.js.map → chunk-OAVJMZLF.js.map} +0 -0
  112. /package/dist/{chunk-KI2M5LXX.js.map → chunk-PYTNMX2D.js.map} +0 -0
  113. /package/dist/{chunk-426L6XZP.js.map → chunk-QQKPZKQT.js.map} +0 -0
  114. /package/dist/{chunk-UEYKYTJD.js.map → chunk-UYG7UOVQ.js.map} +0 -0
  115. /package/dist/{chunk-RTYBNDHE.js.map → chunk-W4K3DFAX.js.map} +0 -0
  116. /package/dist/{chunk-TNIN3DPC.js.map → chunk-WNE4GRXY.js.map} +0 -0
  117. /package/dist/{chunk-6L3K7Y7E.js.map → chunk-XWMHNDED.js.map} +0 -0
  118. /package/dist/{chunk-W3DLKUOV.js.map → chunk-XWOXXVVX.js.map} +0 -0
  119. /package/dist/{chunk-PTDPY5YN.js.map → chunk-Y4BNOZWQ.js.map} +0 -0
  120. /package/dist/{chunk-4GS2I57L.js.map → chunk-Y65DB3PF.js.map} +0 -0
  121. /package/dist/{chunk-6X2K2VSD.js.map → chunk-YZD6EZMU.js.map} +0 -0
  122. /package/dist/{chunk-TARMAPO6.js.map → chunk-ZWO36TCN.js.map} +0 -0
  123. /package/dist/{client-XITH4RAT.js.map → client-AIQ7D7VU.js.map} +0 -0
  124. /package/dist/{config-YYD7E5BT.js.map → config-TSSRDRCK.js.map} +0 -0
  125. /package/dist/{config-mutate-F23A3UAU.js.map → config-mutate-XUBGMDIU.js.map} +0 -0
  126. /package/dist/{config-mutator-XHSEEKWW.js.map → config-mutator-G62RKREK.js.map} +0 -0
  127. /package/dist/{contributions-R2BJWBI7.js.map → contributions-RQZO4V36.js.map} +0 -0
  128. /package/dist/{doctor-2GK4QVSK.js.map → doctor-DVMX6632.js.map} +0 -0
  129. /package/dist/{failure-candidates-WGSFI7GR.js.map → failure-candidates-FASPEOBF.js.map} +0 -0
  130. /package/dist/{follow-up-tool-FT5JYKSI.js.map → follow-up-tool-MS4FSM2J.js.map} +0 -0
  131. /package/dist/{hub-QBJH2GAV.js.map → hub-RKX3L5LU.js.map} +0 -0
  132. /package/dist/{org-tool-BTZF5L74.js.map → org-tool-NA6U3IJJ.js.map} +0 -0
  133. /package/dist/{program-O5MDSQSU.js.map → program-YEHUSQFX.js.map} +0 -0
  134. /package/dist/{promote-JQYV4QKG.js.map → promote-OV2OD55V.js.map} +0 -0
  135. /package/dist/{query-RW3BV23C.js.map → query-6FK2A4K2.js.map} +0 -0
  136. /package/dist/{query-settings-DN6BU3QA.js.map → query-settings-RE2BTERX.js.map} +0 -0
  137. /package/dist/{registry-CQLEJUHN.js.map → registry-APVJFCDJ.js.map} +0 -0
  138. /package/dist/{request-planner-M4GOEJUD.js.map → request-planner-23FPTJLW.js.map} +0 -0
  139. /package/dist/{review-candidates-HZDY5DV3.js.map → review-candidates-FCRNGU2S.js.map} +0 -0
  140. /package/dist/{routing-IUE6GT6T.js.map → routing-W7AOH7QM.js.map} +0 -0
  141. /package/dist/{schedule-tool-WAXHHKSR.js.map → schedule-tool-RXX26TI4.js.map} +0 -0
  142. /package/dist/{scheduler-PPKHYCMH.js.map → scheduler-3CJD7UF4.js.map} +0 -0
  143. /package/dist/{seat-OIVGQP4P.js.map → seat-BIVMGYMR.js.map} +0 -0
  144. /package/dist/{select-TKODF5NC.js.map → select-LWTPLTCE.js.map} +0 -0
  145. /package/dist/{set-enabled-B3A2VMDN.js.map → set-enabled-OKG7Q5WY.js.map} +0 -0
  146. /package/dist/{sprint-tool-N4RLQ3EN.js.map → sprint-tool-YLQADXQH.js.map} +0 -0
  147. /package/dist/{surface-usage-Y7D5W52I.js.map → surface-usage-Y23TE5AN.js.map} +0 -0
  148. /package/dist/{tool-SBFQKJ4J.js.map → tool-5T5SSYMB.js.map} +0 -0
  149. /package/dist/{tool-FQY3IU4B.js.map → tool-XZU2IJUI.js.map} +0 -0
  150. /package/dist/{tool-FUEAREQB.js.map → tool-YCCQX7BT.js.map} +0 -0
  151. /package/dist/{tool-UL673LK6.js.map → tool-ZXIRHFRB.js.map} +0 -0
  152. /package/dist/{traces-O4TIZ4SM.js.map → traces-MKAHGAYG.js.map} +0 -0
  153. /package/dist/{wiki-S6FJAVZ6.js.map → wiki-2BVHRZX5.js.map} +0 -0
  154. /package/dist/{wiki-enrich-UQKBCRS7.js.map → wiki-enrich-BHPD4BOV.js.map} +0 -0
@@ -3,9 +3,9 @@ import{a as o,b as c}from"./chunk-FCPTN6NF.js";c();var m="[Institutional Wiki";f
3
3
  task_id, agent_id, channel, chat_id, workflow_run_id, workflow_id,
4
4
  workflow_node_id, intent_event_id, intent_decided_by, resume_session_id,
5
5
  model, status, started_at, message_preview, original_message,
6
- resume_origin, resume_attempt, resumed_from, person
7
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'in-flight', ?, ?, ?, ?, ?, ?, ?)
8
- `).run(t,n.agentId,n.channel??null,n.chatId??null,n.workflowRunId??null,n.workflowId??null,n.workflowNodeId??null,n.intentEventId??null,n.intentDecidedBy??null,n.resumeSessionId??null,n.model??null,Date.now(),n.messagePreview??null,n.originalMessage??null,n.resumeOrigin??null,n.resumeAttempt??0,n.resumedFrom??null,n.person??null),t}function h(e,n,t){let s=Date.now();e.prepare(`
6
+ resume_origin, resume_attempt, resumed_from, person, sender
7
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'in-flight', ?, ?, ?, ?, ?, ?, ?, ?)
8
+ `).run(t,n.agentId,n.channel??null,n.chatId??null,n.workflowRunId??null,n.workflowId??null,n.workflowNodeId??null,n.intentEventId??null,n.intentDecidedBy??null,n.resumeSessionId??null,n.model??null,Date.now(),n.messagePreview??null,n.originalMessage??null,n.resumeOrigin??null,n.resumeAttempt??0,n.resumedFrom??null,n.person??null,n.sender??null),t}function h(e,n,t){let s=Date.now();e.prepare(`
9
9
  UPDATE task_traces SET
10
10
  status = ?,
11
11
  final_session_id = ?,
@@ -33,7 +33,7 @@ import{a as o,b as c}from"./chunk-FCPTN6NF.js";c();var m="[Institutional Wiki";f
33
33
  INSERT INTO task_trace_steps (
34
34
  task_id, seq, name, action, status, input_summary, output_summary, error, ms, started_at
35
35
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
36
- `).run(n,i,t.name,t.action??null,t.status??null,t.inputSummary??null,t.outputSummary??null,t.error??null,t.ms??null,s),i})()}function _(e){if(typeof e!="string")return null;try{let n=JSON.parse(e);if(!n||typeof n!="object")return null;let t=s=>Array.isArray(s)?s.filter(r=>typeof r=="string"):[];return{memory:t(n.memory),procedures:t(n.procedures),wiki:n.wiki===!0}}catch{return null}}function l(e){return{taskId:e.task_id,agentId:e.agent_id,channel:e.channel??null,chatId:e.chat_id??null,workflowRunId:e.workflow_run_id??null,workflowId:e.workflow_id??null,workflowNodeId:e.workflow_node_id??null,intentEventId:e.intent_event_id??null,intentDecidedBy:e.intent_decided_by??null,resumeSessionId:e.resume_session_id??null,finalSessionId:e.final_session_id??null,model:e.model??null,status:e.status,startedAt:e.started_at,finishedAt:e.finished_at??null,durationMs:e.duration_ms??null,inputTokens:e.input_tokens??null,outputTokens:e.output_tokens??null,cacheReadTokens:e.cache_read_tokens??null,cacheCreateTokens:e.cache_create_tokens??null,tier2InputTokens:e.tier2_input_tokens??null,tier2OutputTokens:e.tier2_output_tokens??null,tier2CacheReadTokens:e.tier2_cache_read_tokens??null,tier2CacheCreateTokens:e.tier2_cache_create_tokens??null,resumed:e.resumed==null?null:e.resumed===1,jevArm:e.jev_arm??null,numTurns:e.num_turns??null,injectedContext:_(e.injected_context),error:e.error??null,messagePreview:e.message_preview??null,originalMessage:e.original_message??null,finalResponse:e.final_response??null}}function g(e){return{taskId:e.task_id,seq:e.seq,name:e.name,action:e.action??null,status:e.status??null,inputSummary:e.input_summary??null,outputSummary:e.output_summary??null,error:e.error??null,ms:e.ms??null,startedAt:e.started_at}}function b(e,n){let t=e.prepare("SELECT * FROM task_traces WHERE task_id = ?").get(n);if(!t)return null;let s=e.prepare("SELECT * FROM task_trace_steps WHERE task_id = ? ORDER BY seq").all(n);return{task:l(t),steps:s.map(g)}}function T(e){let n=Date.now();return e.prepare(`
36
+ `).run(n,i,t.name,t.action??null,t.status??null,t.inputSummary??null,t.outputSummary??null,t.error??null,t.ms??null,s),i})()}function g(e){if(typeof e!="string")return null;try{let n=JSON.parse(e);if(!n||typeof n!="object")return null;let t=s=>Array.isArray(s)?s.filter(r=>typeof r=="string"):[];return{memory:t(n.memory),procedures:t(n.procedures),wiki:n.wiki===!0}}catch{return null}}function l(e){return{taskId:e.task_id,agentId:e.agent_id,channel:e.channel??null,chatId:e.chat_id??null,workflowRunId:e.workflow_run_id??null,workflowId:e.workflow_id??null,workflowNodeId:e.workflow_node_id??null,intentEventId:e.intent_event_id??null,intentDecidedBy:e.intent_decided_by??null,resumeSessionId:e.resume_session_id??null,finalSessionId:e.final_session_id??null,model:e.model??null,status:e.status,startedAt:e.started_at,finishedAt:e.finished_at??null,durationMs:e.duration_ms??null,inputTokens:e.input_tokens??null,outputTokens:e.output_tokens??null,cacheReadTokens:e.cache_read_tokens??null,cacheCreateTokens:e.cache_create_tokens??null,tier2InputTokens:e.tier2_input_tokens??null,tier2OutputTokens:e.tier2_output_tokens??null,tier2CacheReadTokens:e.tier2_cache_read_tokens??null,tier2CacheCreateTokens:e.tier2_cache_create_tokens??null,resumed:e.resumed==null?null:e.resumed===1,jevArm:e.jev_arm??null,numTurns:e.num_turns??null,injectedContext:g(e.injected_context),error:e.error??null,messagePreview:e.message_preview??null,originalMessage:e.original_message??null,finalResponse:e.final_response??null}}function _(e){return{taskId:e.task_id,seq:e.seq,name:e.name,action:e.action??null,status:e.status??null,inputSummary:e.input_summary??null,outputSummary:e.output_summary??null,error:e.error??null,ms:e.ms??null,startedAt:e.started_at}}function b(e,n){let t=e.prepare("SELECT * FROM task_traces WHERE task_id = ?").get(n);if(!t)return null;let s=e.prepare("SELECT * FROM task_trace_steps WHERE task_id = ? ORDER BY seq").all(n);return{task:l(t),steps:s.map(_)}}function T(e){let n=Date.now();return e.prepare(`
37
37
  UPDATE task_traces
38
38
  SET status = 'canceled',
39
39
  error = 'daemon-restart (orphaned in-flight)',
@@ -78,5 +78,5 @@ import{a as o,b as c}from"./chunk-FCPTN6NF.js";c();var m="[Institutional Wiki";f
78
78
  WHERE started_at >= ? AND cost_usd IS NULL
79
79
  AND COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) > 0
80
80
  GROUP BY agent_id
81
- `).all(n),s={};for(let r of t)r.n>0&&(s[r.agent_id]=r.n);return s}export{p as a,f as b,h as c,R as d,_ as e,b as f,T as g,S as h,C as i,A as j,D as k,y as l,w as m,x as n,O as o,L as p};
82
- //# sourceMappingURL=chunk-VJVXEVZ7.js.map
81
+ `).all(n),s={};for(let r of t)r.n>0&&(s[r.agent_id]=r.n);return s}export{p as a,f as b,h as c,R as d,g as e,b as f,T as g,S as h,C as i,A as j,D as k,y as l,w as m,x as n,O as o,L as p};
82
+ //# sourceMappingURL=chunk-IH65GDJR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/traces.ts","../src/agents/injected-context.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { newEventId } from \"@/intent/ulid\"\nimport { boundInjectedContext } from \"@/agents/injected-context\"\n\n// --- Task trace store ---\n//\n// Improvement plan #2 — per-task observability backed by SQLite. One\n// task_traces row per executeTask invocation, an append-only stream of\n// task_trace_steps inside it. The store is intentionally dumb: it stores\n// what callers give it. Callers (capture sites in src/agents/runtime.ts)\n// are responsible for byte-capping large step payloads so the daemon\n// memory stays bounded under tool-heavy turns.\n//\n// Why a separate store layer (vs writing inline in runtime.ts)?\n// - Tests can exercise the trace lifecycle against a temp SQLite without\n// spinning up the agent runtime.\n// - The HTTP endpoints (GET /task/:id/trace) read through the same\n// functions producers write through, so there's a single source of\n// truth on field names + semantics.\n// - Future capture sites (sdk tier, orchestrator tier) reuse this API\n// without copying SQL.\n//\n// Why ULID for task_id?\n// - URL-safe in HTTP routes (GET /task/:id/trace).\n// - Time-sortable, so listTraces ORDER BY started_at and ORDER BY\n// task_id agree without an explicit timestamp column index.\n// - Already in-tree (src/intent/ulid.ts); no new dep.\n//\n// Cross-DB FK note:\n// intent_event_id and intent_decided_by are logical foreign keys into\n// the intent ledger at .agentx/intent/ledger.sqlite. better-sqlite3\n// doesn't enforce cross-database FKs and we don't ATTACH the ledger\n// here on purpose — the rescue plan's append-only contract on the\n// ledger is honoured by routing all writes through src/intent/ledger.ts.\n// Joins happen at the HTTP / CLI layer when needed.\n\nexport interface TraceStartInput {\n agentId: string\n channel?: string | null\n chatId?: string | null\n messagePreview?: string | null\n /** Full untruncated user message — used by `agentx trace replay <taskId>`\n * to re-fire a recorded task against the current agent config. NULL on\n * rows from before migration v8, in which case replay falls back to\n * messagePreview (which is capped at 200 chars). */\n originalMessage?: string | null\n workflowRunId?: string | null\n workflowId?: string | null\n workflowNodeId?: string | null\n intentEventId?: string | null\n intentDecidedBy?: string | null\n resumeSessionId?: string | null\n model?: string | null\n /** How to re-enter this run after a restart (JSON, see agents/resume). */\n resumeOrigin?: string | null\n /** 0 for a fresh run; n for the n-th resume of a cut-off run. */\n resumeAttempt?: number | null\n /** The cut-off run this one continues. */\n resumedFrom?: string | null\n /** The known person who started the chain (people, #384). */\n person?: string | null\n /** Who sent the message, \"\" when the channel named no one. */\n sender?: string | null\n}\n\nexport interface TraceEndInput {\n status: \"ok\" | \"error\" | \"timeout\" | \"stopped\"\n finalSessionId?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n cacheReadTokens?: number | null\n cacheCreateTokens?: number | null\n tier2InputTokens?: number | null\n tier2OutputTokens?: number | null\n tier2CacheReadTokens?: number | null\n tier2CacheCreateTokens?: number | null\n /** Whether the turn continued a provider session. The resume decision\n * is made after task:started, so it is recorded at the end. Omitted\n * leaves both resumed and resume_session_id untouched. */\n resumed?: boolean | null\n resumeSessionId?: string | null\n /** Request-gate experiment arm: \"treatment\" | \"holdout\". */\n jevArm?: string | null\n /** Runtime-reported turn count (Claude `num_turns`). */\n numTurns?: number | null\n /** Lessons injected into the prompt. See InjectedContext. */\n injectedContext?: InjectedContext | null\n error?: string | null\n /** The agent's final reply text. Stored verbatim so `replay --diff`\n * can compare original output vs the new run's output without\n * reconstructing it from the step ledger. NULL when the response\n * wasn't captured (older rows or non-text outputs). */\n finalResponse?: string | null\n /** Model the turn was billed on. Known only once the turn ends, so the\n * start row usually has none. Omitted leaves the column untouched. */\n model?: string | null\n /** What the run cost in USD (#1162). Omitted leaves the column untouched. */\n costUsd?: number | null\n}\n\n/** Ids of the lessons injected into one task's prompt. Memory facts and\n * procedures are matched per message, so their ids are recorded; the wiki\n * is injected as a whole catalog, so only its presence is. */\nexport interface InjectedContext {\n memory: string[]\n procedures: string[]\n wiki: boolean\n}\n\nexport interface TraceStepInput {\n /** Coarse step kind. Conventional values: \"tool_use\" | \"tool_result\" |\n * \"llm_message\" | \"session_rotation\" | \"error\" | \"preflight\". Free-form\n * strings allowed so future capture sites don't need a schema bump. */\n name: string\n /** Fine-grained name within the kind. For \"tool_use\", this is the tool\n * name (e.g. \"Bash\", \"Edit\"). Optional. */\n action?: string | null\n status?: \"ok\" | \"error\" | \"in-flight\" | null\n /** JSON-stringified input or human-readable summary. Caller-byte-capped. */\n inputSummary?: string | null\n outputSummary?: string | null\n error?: string | null\n /** Step duration when known. Optional — many step kinds are point-in-time. */\n ms?: number | null\n}\n\nexport interface TraceRecord {\n taskId: string\n agentId: string\n channel: string | null\n chatId: string | null\n workflowRunId: string | null\n workflowId: string | null\n workflowNodeId: string | null\n intentEventId: string | null\n intentDecidedBy: string | null\n resumeSessionId: string | null\n finalSessionId: string | null\n model: string | null\n status: string\n startedAt: number\n finishedAt: number | null\n durationMs: number | null\n inputTokens: number | null\n outputTokens: number | null\n cacheReadTokens: number | null\n cacheCreateTokens: number | null\n tier2InputTokens: number | null\n tier2OutputTokens: number | null\n tier2CacheReadTokens: number | null\n tier2CacheCreateTokens: number | null\n /** NULL on rows recorded before migration v12. */\n resumed: boolean | null\n /** NULL when the request gate was not active (or before migration v13). */\n jevArm: string | null\n /** NULL on rows recorded before lesson-impact capture (#98) or when the\n * runtime does not report a turn count. */\n numTurns: number | null\n /** NULL on rows recorded before lesson-impact capture (#98). */\n injectedContext: InjectedContext | null\n error: string | null\n messagePreview: string | null\n /** Full untruncated user message — populated for traces from migration v8\n * onward. NULL on older rows; consumers should fall back to messagePreview. */\n originalMessage: string | null\n /** Agent's final reply text — populated for traces from migration v8\n * onward when the executor records it on end. */\n finalResponse: string | null\n}\n\nexport interface TraceStepRecord {\n taskId: string\n seq: number\n name: string\n action: string | null\n status: string | null\n inputSummary: string | null\n outputSummary: string | null\n error: string | null\n ms: number | null\n startedAt: number\n}\n\nexport interface ListTracesFilters {\n agentId?: string\n channel?: string\n chatId?: string\n workflowRunId?: string\n status?: string\n /** ms epoch */\n since?: number\n /** ms epoch */\n until?: number\n /** Default 100, capped at 1000. */\n limit?: number\n}\n\n/**\n * Insert an in-flight trace row and return its ULID. Callers thread the\n * returned id through the executor and call recordTraceEnd at finish time.\n *\n * `taskId` is optional — when supplied, the caller has already allocated\n * a ULID upstream (e.g. registry.execute generating it before the bus\n * event so the runtime can capture per-step rows under the same id).\n * When omitted, a fresh ULID is allocated here.\n */\nexport function recordTraceStart(\n db: Database.Database,\n input: TraceStartInput,\n taskId: string = newEventId(),\n): string {\n db.prepare(`\n INSERT INTO task_traces (\n task_id, agent_id, channel, chat_id, workflow_run_id, workflow_id,\n workflow_node_id, intent_event_id, intent_decided_by, resume_session_id,\n model, status, started_at, message_preview, original_message,\n resume_origin, resume_attempt, resumed_from, person, sender\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'in-flight', ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n taskId,\n input.agentId,\n input.channel ?? null,\n input.chatId ?? null,\n input.workflowRunId ?? null,\n input.workflowId ?? null,\n input.workflowNodeId ?? null,\n input.intentEventId ?? null,\n input.intentDecidedBy ?? null,\n input.resumeSessionId ?? null,\n input.model ?? null,\n Date.now(),\n input.messagePreview ?? null,\n input.originalMessage ?? null,\n input.resumeOrigin ?? null,\n input.resumeAttempt ?? 0,\n input.resumedFrom ?? null,\n input.person ?? null,\n input.sender ?? null,\n )\n return taskId\n}\n\n/**\n * Finalize a trace. duration_ms is computed from finished_at - started_at\n * inside the UPDATE so the two columns can never disagree. Idempotent —\n * calling twice on the same task_id overwrites the prior end values; the\n * second call's status wins. (Soft-overwrite is intentional: timeout\n * handlers may write before a late stream-completion arrives.)\n */\nexport function recordTraceEnd(db: Database.Database, taskId: string, input: TraceEndInput): void {\n const finishedAt = Date.now()\n db.prepare(`\n UPDATE task_traces SET\n status = ?,\n final_session_id = ?,\n input_tokens = ?,\n output_tokens = ?,\n cache_read_tokens = ?,\n cache_create_tokens = ?,\n tier2_input_tokens = ?,\n tier2_output_tokens = ?,\n tier2_cache_read_tokens = ?,\n tier2_cache_create_tokens = ?,\n resumed = COALESCE(?, resumed),\n resume_session_id = COALESCE(?, resume_session_id),\n jev_arm = COALESCE(?, jev_arm),\n num_turns = COALESCE(?, num_turns),\n injected_context = COALESCE(?, injected_context),\n error = ?,\n final_response = COALESCE(?, final_response),\n model = COALESCE(?, model),\n cost_usd = COALESCE(?, cost_usd),\n finished_at = ?,\n duration_ms = ? - started_at\n WHERE task_id = ?\n `).run(\n input.status,\n input.finalSessionId ?? null,\n input.inputTokens ?? null,\n input.outputTokens ?? null,\n input.cacheReadTokens ?? null,\n input.cacheCreateTokens ?? null,\n input.tier2InputTokens ?? null,\n input.tier2OutputTokens ?? null,\n input.tier2CacheReadTokens ?? null,\n input.tier2CacheCreateTokens ?? null,\n input.resumed == null ? null : input.resumed ? 1 : 0,\n input.resumeSessionId ?? null,\n input.jevArm ?? null,\n input.numTurns ?? null,\n input.injectedContext ? JSON.stringify(boundInjectedContext(input.injectedContext)) : null,\n input.error ?? null,\n input.finalResponse ?? null,\n input.model ?? null,\n input.costUsd ?? null,\n finishedAt,\n finishedAt,\n taskId,\n )\n}\n\n/**\n * Append a step. seq is auto-allocated as MAX(seq)+1 within a transaction\n * so concurrent step writes for the same task_id can't collide. Returns\n * the assigned seq, useful for downstream correlation.\n */\nexport function recordTraceStep(db: Database.Database, taskId: string, input: TraceStepInput): number {\n const startedAt = Date.now()\n const allocateAndInsert = db.transaction((): number => {\n const row = db\n .prepare(\"SELECT MAX(seq) AS max_seq FROM task_trace_steps WHERE task_id = ?\")\n .get(taskId) as { max_seq: number | null } | undefined\n const seq = ((row?.max_seq ?? -1) as number) + 1\n db.prepare(`\n INSERT INTO task_trace_steps (\n task_id, seq, name, action, status, input_summary, output_summary, error, ms, started_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n taskId,\n seq,\n input.name,\n input.action ?? null,\n input.status ?? null,\n input.inputSummary ?? null,\n input.outputSummary ?? null,\n input.error ?? null,\n input.ms ?? null,\n startedAt,\n )\n return seq\n })\n return allocateAndInsert()\n}\n\nexport function parseInjectedContext(raw: unknown): InjectedContext | null {\n if (typeof raw !== \"string\") return null\n try {\n const v = JSON.parse(raw)\n if (!v || typeof v !== \"object\") return null\n const ids = (x: unknown) => (Array.isArray(x) ? x.filter((i): i is string => typeof i === \"string\") : [])\n return { memory: ids(v.memory), procedures: ids(v.procedures), wiki: v.wiki === true }\n } catch {\n return null\n }\n}\n\nfunction rowToTrace(row: Record<string, unknown>): TraceRecord {\n return {\n taskId: row.task_id as string,\n agentId: row.agent_id as string,\n channel: (row.channel as string) ?? null,\n chatId: (row.chat_id as string) ?? null,\n workflowRunId: (row.workflow_run_id as string) ?? null,\n workflowId: (row.workflow_id as string) ?? null,\n workflowNodeId: (row.workflow_node_id as string) ?? null,\n intentEventId: (row.intent_event_id as string) ?? null,\n intentDecidedBy: (row.intent_decided_by as string) ?? null,\n resumeSessionId: (row.resume_session_id as string) ?? null,\n finalSessionId: (row.final_session_id as string) ?? null,\n model: (row.model as string) ?? null,\n status: row.status as string,\n startedAt: row.started_at as number,\n finishedAt: (row.finished_at as number) ?? null,\n durationMs: (row.duration_ms as number) ?? null,\n inputTokens: (row.input_tokens as number) ?? null,\n outputTokens: (row.output_tokens as number) ?? null,\n cacheReadTokens: (row.cache_read_tokens as number) ?? null,\n cacheCreateTokens: (row.cache_create_tokens as number) ?? null,\n tier2InputTokens: (row.tier2_input_tokens as number) ?? null,\n tier2OutputTokens: (row.tier2_output_tokens as number) ?? null,\n tier2CacheReadTokens: (row.tier2_cache_read_tokens as number) ?? null,\n tier2CacheCreateTokens: (row.tier2_cache_create_tokens as number) ?? null,\n resumed: row.resumed == null ? null : row.resumed === 1,\n jevArm: (row.jev_arm as string) ?? null,\n numTurns: (row.num_turns as number) ?? null,\n injectedContext: parseInjectedContext(row.injected_context),\n error: (row.error as string) ?? null,\n messagePreview: (row.message_preview as string) ?? null,\n originalMessage: (row.original_message as string) ?? null,\n finalResponse: (row.final_response as string) ?? null,\n }\n}\n\nfunction rowToStep(row: Record<string, unknown>): TraceStepRecord {\n return {\n taskId: row.task_id as string,\n seq: row.seq as number,\n name: row.name as string,\n action: (row.action as string) ?? null,\n status: (row.status as string) ?? null,\n inputSummary: (row.input_summary as string) ?? null,\n outputSummary: (row.output_summary as string) ?? null,\n error: (row.error as string) ?? null,\n ms: (row.ms as number) ?? null,\n startedAt: row.started_at as number,\n }\n}\n\n/** Fetch a trace + its ordered steps. Returns null if no such task_id. */\nexport function getTrace(\n db: Database.Database,\n taskId: string,\n): { task: TraceRecord; steps: TraceStepRecord[] } | null {\n const row = db.prepare(\"SELECT * FROM task_traces WHERE task_id = ?\").get(taskId) as\n | Record<string, unknown>\n | undefined\n if (!row) return null\n const stepRows = db\n .prepare(\"SELECT * FROM task_trace_steps WHERE task_id = ? ORDER BY seq\")\n .all(taskId) as Record<string, unknown>[]\n return { task: rowToTrace(row), steps: stepRows.map(rowToStep) }\n}\n\n/**\n * Cancel any in-flight trace rows left over from a previous daemon\n * lifetime. Mirrors the intent ledger's startup cleanup (rescue plan\n * Phase 1 commit a8514d9): a hard-killed daemon never gets to fire\n * task:completed, so the row sits \"in-flight\" forever and contaminates\n * triage queries (`agentx trace list --status in-flight`) with stale\n * orphans. Run once at daemon boot before subscribers attach.\n *\n * Returns the number of rows updated. duration_ms is intentionally NOT\n * computed — we don't know when the task actually ended; preserving\n * NULL there is more honest than backdating to \"now\".\n */\nexport function cleanupOrphanedTraces(db: Database.Database): number {\n const now = Date.now()\n const r = db.prepare(`\n UPDATE task_traces\n SET status = 'canceled',\n error = 'daemon-restart (orphaned in-flight)',\n finished_at = ?\n WHERE status = 'in-flight'\n `).run(now)\n return (r.changes ?? 0) as number\n}\n\n// --- Resume after restart (#103) -------------------------------------------\n\n/** A run that was still going when the previous daemon stopped. */\nexport interface InterruptedRun {\n taskId: string\n agentId: string\n channel: string | null\n chatId: string | null\n workflowRunId: string | null\n startedAt: number\n originalMessage: string | null\n resumeOrigin: string | null\n resumeAttempt: number\n /** Tool calls it had made, in order, for the resume note. */\n toolCalls: Array<{ action: string | null; inputSummary: string | null }>\n}\n\n/** Close every run left in flight by the previous daemon, marking it\n * `interrupted` for the resume planner, and return them. One transaction,\n * so a second process booting on the same database gets nothing. */\nexport function takeInterruptedRuns(db: Database.Database, now = Date.now()): InterruptedRun[] {\n const take = db.transaction(() => {\n const rows = db.prepare(`\n SELECT task_id, agent_id, channel, chat_id, workflow_run_id, started_at,\n original_message, resume_origin, resume_attempt\n FROM task_traces WHERE status = 'in-flight' ORDER BY started_at\n `).all() as Array<Record<string, any>>\n db.prepare(`\n UPDATE task_traces\n SET status = 'canceled', error = 'daemon-restart (interrupted)',\n finished_at = ?, resume_decision = 'interrupted'\n WHERE status = 'in-flight'\n `).run(now)\n return rows\n })\n const steps = db.prepare(`\n SELECT action, input_summary FROM task_trace_steps\n WHERE task_id = ? AND name = 'tool_use' ORDER BY seq\n `)\n return take().map((r) => ({\n taskId: r.task_id,\n agentId: r.agent_id,\n channel: r.channel ?? null,\n chatId: r.chat_id ?? null,\n workflowRunId: r.workflow_run_id ?? null,\n startedAt: r.started_at,\n originalMessage: r.original_message ?? null,\n resumeOrigin: r.resume_origin ?? null,\n resumeAttempt: r.resume_attempt ?? 0,\n toolCalls: (steps.all(r.task_id) as Array<Record<string, any>>).map((s) => ({\n action: s.action ?? null, inputSummary: s.input_summary ?? null,\n })),\n }))\n}\n\n/** Claim an interrupted run before deciding what to do with it. Returns\n * false when another process already claimed or decided it, so a run is\n * never resumed — or its chat told — twice. */\nexport function claimResume(db: Database.Database, taskId: string): boolean {\n const r = db.prepare(`\n UPDATE task_traces SET resume_decision = 'deciding'\n WHERE task_id = ? AND resume_decision = 'interrupted'\n `).run(taskId)\n return (r.changes ?? 0) === 1\n}\n\nexport type ResumeDecision = \"resumed\" | \"reported\" | \"skipped\" | \"resume-failed\"\n\nexport function recordResumeDecision(\n db: Database.Database, taskId: string, decision: ResumeDecision, reason: string,\n): void {\n db.prepare(\"UPDATE task_traces SET resume_decision = ?, resume_reason = ? WHERE task_id = ?\")\n .run(decision, reason.slice(0, 500), taskId)\n}\n\n/** Triage / dashboard surface — list traces newest-first, filtered. */\nexport function listTraces(db: Database.Database, filters: ListTracesFilters = {}): TraceRecord[] {\n const where: string[] = []\n const params: unknown[] = []\n if (filters.agentId) { where.push(\"agent_id = ?\"); params.push(filters.agentId) }\n if (filters.channel) { where.push(\"channel = ?\"); params.push(filters.channel) }\n if (filters.chatId) { where.push(\"chat_id = ?\"); params.push(filters.chatId) }\n if (filters.workflowRunId) { where.push(\"workflow_run_id = ?\"); params.push(filters.workflowRunId) }\n if (filters.status) { where.push(\"status = ?\"); params.push(filters.status) }\n if (filters.since !== undefined) { where.push(\"started_at >= ?\"); params.push(filters.since) }\n if (filters.until !== undefined) { where.push(\"started_at <= ?\"); params.push(filters.until) }\n\n const limit = Math.max(1, Math.min(filters.limit ?? 100, 1000))\n const sql = `\n SELECT * FROM task_traces\n ${where.length > 0 ? \"WHERE \" + where.join(\" AND \") : \"\"}\n ORDER BY started_at DESC\n LIMIT ?\n `\n params.push(limit)\n return (db.prepare(sql).all(...params) as Record<string, unknown>[]).map(rowToTrace)\n}\n\n/** Every trace row of these workflow runs, oldest first. Unbounded by\n * design: a report over a few hundred runs needs all of their rows. */\nexport function listTracesForRuns(db: Database.Database, runIds: string[]): TraceRecord[] {\n const out: TraceRecord[] = []\n // SQLite caps bound parameters; stay well under it.\n for (let i = 0; i < runIds.length; i += 500) {\n const chunk = runIds.slice(i, i + 500)\n if (!chunk.length) continue\n const rows = db.prepare(`\n SELECT * FROM task_traces WHERE workflow_run_id IN (${chunk.map(() => \"?\").join(\",\")})\n ORDER BY started_at\n `).all(...chunk) as Record<string, unknown>[]\n out.push(...rows.map(rowToTrace))\n }\n return out\n}\n\n/** The tool calls one run made, in order: what a stop signal's resume plan\n * lists when the agent wrote none (#857). Bounded. */\nexport function traceToolCalls(\n db: Database.Database, taskId: string, limit = 200,\n): Array<{ action: string | null; inputSummary: string | null }> {\n const rows = db.prepare(`\n SELECT action, input_summary FROM task_trace_steps\n WHERE task_id = ? AND name = 'tool_use' ORDER BY seq LIMIT ?\n `).all(taskId, limit) as Array<Record<string, any>>\n return rows.map((s) => ({ action: s.action ?? null, inputSummary: s.input_summary ?? null }))\n}\n\n/**\n * Recorded run cost per agent since `sinceMs` (a month start, for the\n * monthly budget, #1162). Rows without a cost add nothing.\n */\nexport function spendByAgentSince(db: Database.Database, sinceMs: number): Record<string, number> {\n const rows = db.prepare(`\n SELECT agent_id, SUM(cost_usd) AS usd FROM task_traces\n WHERE started_at >= ? AND cost_usd IS NOT NULL\n GROUP BY agent_id\n `).all(sinceMs) as Array<{ agent_id: string; usd: number | null }>\n const out: Record<string, number> = {}\n for (const r of rows) if (r.usd && r.usd > 0) out[r.agent_id] = r.usd\n return out\n}\n\n/** Recorded run cost per (agent, chat) since `sinceMs`, from which spend\n * per project is mapped (#1290). */\nexport function spendByChatSince(db: Database.Database, sinceMs: number): Array<{ agentId: string; chatId: string | null; usd: number }> {\n const rows = db.prepare(`\n SELECT agent_id, chat_id, SUM(cost_usd) AS usd FROM task_traces\n WHERE started_at >= ? AND cost_usd IS NOT NULL\n GROUP BY agent_id, chat_id\n `).all(sinceMs) as Array<{ agent_id: string; chat_id: string | null; usd: number | null }>\n return rows.filter((r) => r.usd && r.usd > 0).map((r) => ({ agentId: r.agent_id, chatId: r.chat_id, usd: r.usd as number }))\n}\n\n/** Runs per agent since `sinceMs` that used tokens but have no price\n * (local models, #1290): a budget does not see them. */\nexport function unpricedRunsByAgentSince(db: Database.Database, sinceMs: number): Record<string, number> {\n const rows = db.prepare(`\n SELECT agent_id, COUNT(*) AS n FROM task_traces\n WHERE started_at >= ? AND cost_usd IS NULL\n AND COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) > 0\n GROUP BY agent_id\n `).all(sinceMs) as Array<{ agent_id: string; n: number }>\n const out: Record<string, number> = {}\n for (const r of rows) if (r.n > 0) out[r.agent_id] = r.n\n return out\n}\n","import type { InjectedContext } from \"@/storage/traces\"\n\n// --- Injected lessons per task (#98) ---\n//\n// Which memory facts, procedures and wiki catalog actually reached the\n// prompt. Candidates are not enough: the request-context selector can drop\n// a whole layer, and the layer budgets in buildAgentContext can cut a layer\n// short. So a lesson counts as injected only when its text is in the\n// assembled context. Only ids are recorded, never content, and the lists\n// are capped, so the trace row stays small.\n\nexport const MAX_INJECTED_IDS = 20\nconst MAX_ID_LENGTH = 80\n\nexport interface InjectionCandidates {\n memory?: Array<{ id: string; content: string }>\n procedures?: Array<{ id: string; title: string }>\n /** The wiki catalog block offered to the prompt, if any. */\n wikiContext?: string\n}\n\n/** The first line of the wiki catalog block; see buildWikiContext. */\nconst WIKI_MARKER = \"[Institutional Wiki\"\n\nfunction capIds(ids: string[]): string[] {\n return [...new Set(ids)].slice(0, MAX_INJECTED_IDS).map((id) => id.slice(0, MAX_ID_LENGTH))\n}\n\nexport function injectedContextOf(assembled: string, candidates: InjectionCandidates): InjectedContext {\n const text = assembled ?? \"\"\n return {\n memory: capIds((candidates.memory ?? []).filter((m) => m.content && text.includes(m.content)).map((m) => m.id)),\n procedures: capIds(\n (candidates.procedures ?? []).filter((p) => text.includes(`[Known procedure: ${p.title}]`)).map((p) => p.id),\n ),\n wiki: Boolean(candidates.wikiContext) && text.includes(WIKI_MARKER),\n }\n}\n\n/** Clamp an InjectedContext from any source to the recorded bounds. */\nexport function boundInjectedContext(ctx: InjectedContext): InjectedContext {\n return { memory: capIds(ctx.memory), procedures: capIds(ctx.procedures), wiki: ctx.wiki === true }\n}\n"],"mappings":"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","names":["init_ulid","WIKI_MARKER","capIds","ids","id","injectedContextOf","assembled","candidates","text","m","p","boundInjectedContext","ctx","recordTraceStart","db","input","taskId","newEventId","recordTraceEnd","finishedAt","boundInjectedContext","recordTraceStep","startedAt","seq","parseInjectedContext","raw","v","ids","x","i","rowToTrace","row","rowToStep","getTrace","stepRows","cleanupOrphanedTraces","now","takeInterruptedRuns","take","rows","steps","s","claimResume","recordResumeDecision","decision","reason","listTraces","filters","where","params","limit","sql","listTracesForRuns","runIds","out","chunk","traceToolCalls","spendByAgentSince","sinceMs","spendByChatSince","r","unpricedRunsByAgentSince"]}
@@ -1,4 +1,4 @@
1
- import{c as w}from"./chunk-4GS2I57L.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
1
+ import{c as w}from"./chunk-Y65DB3PF.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
2
2
  ${a.content}`),t.previous??""].join(`
3
3
  `),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
4
4
  `).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
33
33
  {"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
34
34
  `)+`
35
35
  `}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
36
- //# sourceMappingURL=chunk-EP3XCCZ3.js.map
36
+ //# sourceMappingURL=chunk-ISRY3GAD.js.map
@@ -1,4 +1,4 @@
1
- import{b as W,c as K}from"./chunk-PTDPY5YN.js";import{h as z,j as Z}from"./chunk-3UOTLMXD.js";import{a as I,b as V}from"./chunk-FCPTN6NF.js";import{a as H,b as De}from"./chunk-7I7IEX4S.js";import{d as Y}from"./chunk-QIJLFPWE.js";import{execFile as tt}from"child_process";import{writeFileSync as Ee,mkdirSync as P,existsSync as D,readFileSync as nt}from"fs";import{resolve as _}from"path";var Ne=["off","shadow","authoritative"],xe={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},Se="INTENT_LEDGER_MODE";function q(n,e=process.env){let t=Q(e[xe[n]]);if(t)return t;let r=Q(e[Se]);return r||"off"}function Q(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return Ne.includes(e)?e:null}V();import we from"better-sqlite3";import{existsSync as ut,mkdirSync as $e}from"fs";import{dirname as Oe,resolve as Le}from"path";var T=class{db;path;constructor(e={}){this.path=Le(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),$e(Oe(this.path),{recursive:!0}),this.db=new we(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ce(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
1
+ import{b as W,c as K}from"./chunk-Y4BNOZWQ.js";import{h as z,j as Z}from"./chunk-3UOTLMXD.js";import{a as I,b as V}from"./chunk-FCPTN6NF.js";import{a as H,b as De}from"./chunk-7I7IEX4S.js";import{d as Y}from"./chunk-QIJLFPWE.js";import{execFile as tt}from"child_process";import{writeFileSync as Ee,mkdirSync as P,existsSync as D,readFileSync as nt}from"fs";import{resolve as _}from"path";var Ne=["off","shadow","authoritative"],xe={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},Se="INTENT_LEDGER_MODE";function q(n,e=process.env){let t=Q(e[xe[n]]);if(t)return t;let r=Q(e[Se]);return r||"off"}function Q(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return Ne.includes(e)?e:null}V();import we from"better-sqlite3";import{existsSync as ut,mkdirSync as $e}from"fs";import{dirname as Oe,resolve as Le}from"path";var T=class{db;path;constructor(e={}){this.path=Le(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),$e(Oe(this.path),{recursive:!0}),this.db=new we(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ce(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
2
2
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let r=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
3
3
  FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return r?j(r):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
4
4
  FROM intent_events WHERE id = ?`).get(e);return t?j(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
@@ -142,4 +142,4 @@ ${k(O(ye(c.block,F(o.brief,i.prompt)),i.report),i.expectExitZero)}`,i.maxOutputT
142
142
  `);return t.length<=e?t.join(`
143
143
  `):t.slice(-e).join(`
144
144
  `)}function st(n,e,t){return new Promise((r,i)=>{tt("/bin/sh",["-c",n],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(o,s,a)=>{if(o&&o.killed){i(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}r({stdout:String(s??""),stderr:String(a??""),code:o?typeof o.code=="number"?o.code:1:0})})})}export{T as a,te as b,St as c,wt as d,Ye as e,$t as f,Ot as g,w as h,de as i,q as j,pt as k,re as l,se as m,At as n,et as o,it as p,Ie as q,Te as r,Re as s,B as t,U as u};
145
- //# sourceMappingURL=chunk-GCR3KWCV.js.map
145
+ //# sourceMappingURL=chunk-JJC2HBWC.js.map
@@ -1,4 +1,4 @@
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 ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Yb as tt,Zb as nt}from"./chunk-NWY4OF4X.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(`
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 ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Yb as tt,Zb as nt}from"./chunk-GUID2ZA2.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
4
  `)}function Ot(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
111
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
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
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-WSHOJMQG.js.map
114
+ //# sourceMappingURL=chunk-LYY7G6LO.js.map
@@ -1,4 +1,4 @@
1
- import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-D55REZL3.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-WSHOJMQG.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
1
+ import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-OAVJMZLF.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-LYY7G6LO.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
2
2
 
3
3
  ## Shared wiki (other agents' articles)
4
4
 
@@ -51,5 +51,5 @@ ${o}
51
51
 
52
52
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
53
 
54
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-YYD7E5BT.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
- //# sourceMappingURL=chunk-N2DOU7A5.js.map
54
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-TSSRDRCK.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
+ //# sourceMappingURL=chunk-MHRVTFLZ.js.map
@@ -1,4 +1,4 @@
1
- import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-AFRHKA7B.js";import{b as Bt,c as Kt}from"./chunk-VJVXEVZ7.js";import{b as Et,f as jt,g as Ct,j as Lt,l as Ut,m as Ht,s as qt}from"./chunk-GCR3KWCV.js";import{a as Ft}from"./chunk-GV7S5BAX.js";import{c as _t}from"./chunk-SZDACK6O.js";import{b as Ot,d as Dt,e as Mt}from"./chunk-5ONH4ITT.js";import{e as Tt,g as Wt,h as Nt,i as Le}from"./chunk-JRAG37V5.js";import{a as Rt,b as Ce,d as Fe,e as xt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Pt}from"./chunk-A7JSRDJL.js";import{c as vt,d as $t}from"./chunk-AHWWJ7AF.js";import{y as At,z as $r}from"./chunk-WSHOJMQG.js";import{b as St,f as vr}from"./chunk-72SZI2UW.js";import{Fa as Ir,ta as je}from"./chunk-NWY4OF4X.js";import{j as Ee,r as br}from"./chunk-UEEB3UTU.js";import{existsSync as Sr,mkdirSync as Jt,readFileSync as Ar,writeFileSync as Rr,renameSync as xr}from"fs";import{resolve as zt,dirname as Pr}from"path";var Yt=class{filePath;log;constructor(e={}){let t=e.baseDir??zt(process.cwd(),".agentx");this.filePath=zt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Sr(this.filePath))return{version:1,overrides:{}};try{let e=Ar(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Jt(Pr(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Rr(t,JSON.stringify(e,null,2)),xr(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Xt,writeFileSync as He,appendFileSync as Or,mkdirSync as Dr,existsSync as en,statSync as Mr}from"fs";import{resolve as ge}from"path";var Gt="[Agent Memory \u2014 persistent facts from past conversations]",Tr=2400;function Vt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Wr(n,e=Date.now()){let t=Dt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Vt(t,Tt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Nr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Pt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Nt(n,e);return{line:`- [${n.category}] ${Vt(o,Wt(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Qt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Gt.length,a=!1;for(let i of n){let d=e.length>0?Mt(i.content,e):null,u,c,p=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),u=Wr(d,t),c=d.id}else u=Nr(i,t),d&&(u.line+=` [differs from wiki ${d.id}]`);let f=u.unverified&&!a?Le.length:0;if(s+f+u.line.length>Tr)break;r.push({fact:i,...u,...c?{wikiRef:c}:{}}),s+=f+u.line.length,f&&(a=!0)}return r}function Zt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Gt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
1
+ import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-AFRHKA7B.js";import{b as Bt,c as Kt}from"./chunk-IH65GDJR.js";import{b as Et,f as jt,g as Ct,j as Lt,l as Ut,m as Ht,s as qt}from"./chunk-JJC2HBWC.js";import{a as Ft}from"./chunk-GV7S5BAX.js";import{c as _t}from"./chunk-SZDACK6O.js";import{b as Ot,d as Dt,e as Mt}from"./chunk-5ONH4ITT.js";import{e as Tt,g as Wt,h as Nt,i as Le}from"./chunk-JRAG37V5.js";import{a as Rt,b as Ce,d as Fe,e as xt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Pt}from"./chunk-A7JSRDJL.js";import{c as vt,d as $t}from"./chunk-AHWWJ7AF.js";import{y as At,z as $r}from"./chunk-LYY7G6LO.js";import{b as St,f as vr}from"./chunk-72SZI2UW.js";import{Fa as Ir,ta as je}from"./chunk-GUID2ZA2.js";import{j as Ee,r as br}from"./chunk-N47Y5ADQ.js";import{existsSync as Sr,mkdirSync as Jt,readFileSync as Ar,writeFileSync as Rr,renameSync as xr}from"fs";import{resolve as zt,dirname as Pr}from"path";var Yt=class{filePath;log;constructor(e={}){let t=e.baseDir??zt(process.cwd(),".agentx");this.filePath=zt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Sr(this.filePath))return{version:1,overrides:{}};try{let e=Ar(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Jt(Pr(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Rr(t,JSON.stringify(e,null,2)),xr(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Xt,writeFileSync as He,appendFileSync as Or,mkdirSync as Dr,existsSync as en,statSync as Mr}from"fs";import{resolve as ge}from"path";var Gt="[Agent Memory \u2014 persistent facts from past conversations]",Tr=2400;function Vt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Wr(n,e=Date.now()){let t=Dt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Vt(t,Tt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Nr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Pt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Nt(n,e);return{line:`- [${n.category}] ${Vt(o,Wt(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Qt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Gt.length,a=!1;for(let i of n){let d=e.length>0?Mt(i.content,e):null,u,c,p=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),u=Wr(d,t),c=d.id}else u=Nr(i,t),d&&(u.line+=` [differs from wiki ${d.id}]`);let f=u.unverified&&!a?Le.length:0;if(s+f+u.line.length>Tr)break;r.push({fact:i,...u,...c?{wikiRef:c}:{}}),s+=f+u.line.length,f&&(a=!0)}return r}function Zt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Gt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
2
2
  `)}var tn=200,Er=7,nn=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ge(e,".agentx/memory"),this.ledger=new Ot(ge(e,".agentx/wiki")),en(this.memoryDir)||Dr(this.memoryDir,{recursive:!0})}filePath(e){return ge(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ce(t.content)||ne(t.content))return!1;let r=t.source.trust??Rt(t.source.channel),o=t.review??xt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Or(this.filePath(e),JSON.stringify(s)+`
3
3
  `),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!en(t))return[];try{let{mtimeMs:r,size:o}=Mr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Xt(t,"utf-8").split(`
4
4
  `).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(_e);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ge(this.memoryDir,`${t}_bm25_cache.json`),i=$t(s,a),d=vt(e,i),u=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,m)=>{let y=u.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Zt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Qt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&He(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
@@ -39,4 +39,4 @@ ${n.text}`}async function Pe(n,e){let t=n.channels[e.channel],r={channel:e.chann
39
39
  `).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(wt(this.file))try{let e=JSON.parse(yt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){nr(sr(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${ar(4).toString("hex")}.tmp`;or(t,JSON.stringify(e,null,2)+`
40
40
  `,{encoding:"utf-8",mode:384}),rr(t,this.file)}};import{extname as li}from"path";var ur=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,lr=/<agentx-artifact>[\s\S]*$/i;function zu(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(ur,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let u=d.mime,c=u.startsWith("image/")?"image":u==="application/pdf"?"pdf":u.startsWith("text/")?"text":"file";r.push({type:c,filename:d.filename,mime:u})}}catch{}return""});return{text:(t?s.replace(lr,""):s).trim(),artifacts:r}}function Yu(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(ur,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(lr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ci={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},Gu={bytes:20*1024*1024,perMessage:20,pathChars:512};function Vu(n){return ci[li(n).toLowerCase()]??null}var pi=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ![what it shows](https://...)."].join(`
41
41
  `);function Qu(n,e,t){return n==="app"&&e&&t!==!1?pi:void 0}import{lstatSync as bt,mkdirSync as fi,readdirSync as gi,realpathSync as kt,unlinkSync as mi}from"fs";import{join as De,resolve as cr}from"path";var pr=".agentx/outbox",hi=7*24*60*60*1e3;function wi(n,e){try{let t=kt(cr(e,n)),r=De(t,pr);return kt(r)===r&&bt(r).isDirectory()?r:null}catch{return null}}function tl(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=kt(cr(t,n));bt(De(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||fi(De(o,pr),{recursive:!0})}catch{return 0}let r=wi(n,t);return r?fr(r,(e.now??Date.now())-(e.maxAgeMs??hi)):0}function fr(n,e){let t=0;for(let r of gi(n)){let o=De(n,r);try{let s=bt(o);s.isDirectory()?t+=fr(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(mi(o),t++)}catch{}}return t}export{Yt as a,nn as b,rn as c,Ei as d,Fr as e,ji as f,Lr as g,_i as h,Li as i,Ui as j,Hi as k,Bi as l,Ki as m,qi as n,Br as o,Ji as p,zi as q,Qi as r,Je as s,Qr as t,Zi as u,Xi as v,Zr as w,ea as x,cn as y,ra as z,oa as A,fn as B,gn as C,ro as D,ua as E,la as F,fa as G,ga as H,x as I,re as J,S as K,Ye as L,bo as M,Qe as N,U as O,et as P,nt as Q,ft as R,Ts as S,Es as T,mt as U,Lo as V,Gs as W,mu as X,hu as Y,wu as Z,yu as _,ku as $,Qs as aa,Zs as ba,bu as ca,Iu as da,vu as ea,$u as fa,Ru as ga,xu as ha,Pu as ia,Tu as ja,Wu as ka,Nu as la,Ou as ma,Du as na,Mu as oa,Eu as pa,ju as qa,oi as ra,Cu as sa,Fu as ta,_u as ua,Lu as va,dr as wa,zu as xa,Yu as ya,Gu as za,Vu as Aa,Qu as Ba,pr as Ca,tl as Da};
42
- //# sourceMappingURL=chunk-TAUJUPJN.js.map
42
+ //# sourceMappingURL=chunk-MKQI5WL2.js.map
@@ -10,10 +10,10 @@ import{a as _}from"./chunk-QIJLFPWE.js";function c(e){e.exec(`
10
10
  queued_at INTEGER NOT NULL
11
11
  );
12
12
  CREATE INDEX IF NOT EXISTS idx_queued_messages_agent ON queued_messages(agent_id, queued_at);
13
- `)}function U(e,t){e.prepare(`
13
+ `)}function b(e,t){e.prepare(`
14
14
  INSERT INTO queued_messages (agent_id, channel, chat_id, person, sender, message_preview, queued_at)
15
15
  VALUES (?, ?, ?, ?, ?, ?, ?)
16
- `).run(t.agentId,t.channel,t.chatId,t.person??null,t.sender?.slice(0,120)??null,t.messagePreview==null?null:String(t.messagePreview).replace(/\s+/g," ").trim().slice(0,200),t.queuedAt)}function b(e,t,a,n,s){return e.prepare("DELETE FROM queued_messages WHERE agent_id = ? AND channel = ? AND chat_id = ? AND queued_at <= ?").run(t,a,n,s).changes??0}function v(e){return e.prepare("DELETE FROM queued_messages").run().changes??0}function M(e){return e.prepare("SELECT id, agent_id, channel, chat_id, person, sender, message_preview, queued_at FROM queued_messages ORDER BY queued_at, id LIMIT 500").all().map(a=>({id:a.id,agentId:a.agent_id,channel:a.channel,chatId:a.chat_id,person:a.person??null,sender:a.sender??null,messagePreview:a.message_preview??null,queuedAt:a.queued_at}))}var N=_(()=>{"use strict"});function l(e){e.exec(`
16
+ `).run(t.agentId,t.channel,t.chatId,t.person??null,t.sender?.slice(0,120)??null,t.messagePreview==null?null:String(t.messagePreview).replace(/\s+/g," ").trim().slice(0,200),t.queuedAt)}function v(e,t,a,n,s){return e.prepare("DELETE FROM queued_messages WHERE agent_id = ? AND channel = ? AND chat_id = ? AND queued_at <= ?").run(t,a,n,s).changes??0}function M(e){return e.prepare("DELETE FROM queued_messages").run().changes??0}function q(e){return e.prepare("SELECT id, agent_id, channel, chat_id, person, sender, message_preview, queued_at FROM queued_messages ORDER BY queued_at, id LIMIT 500").all().map(a=>({id:a.id,agentId:a.agent_id,channel:a.channel,chatId:a.chat_id,person:a.person??null,sender:a.sender??null,messagePreview:a.message_preview??null,queuedAt:a.queued_at}))}var N=_(()=>{"use strict"});function l(e){e.exec(`
17
17
  CREATE TABLE IF NOT EXISTS forge_comments (
18
18
  channel TEXT NOT NULL,
19
19
  chat_id TEXT NOT NULL,
@@ -23,9 +23,9 @@ import{a as _}from"./chunk-QIJLFPWE.js";function c(e){e.exec(`
23
23
  PRIMARY KEY (channel, chat_id, comment_id)
24
24
  );
25
25
  CREATE INDEX IF NOT EXISTS idx_forge_comments_chat ON forge_comments(channel, chat_id, at);
26
- `)}function S(e,t){e.prepare("INSERT OR IGNORE INTO forge_comments (channel, chat_id, comment_id, agent_id, at) VALUES (?, ?, ?, ?, ?)").run(t.channel,t.chatId,t.commentId.slice(0,64),t.agentId?.slice(0,120)??null,t.at)}function y(e,t,a){return a.length===0?[]:e.prepare(`SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments
27
- WHERE channel = ? AND chat_id IN (${a.map(()=>"?").join(",")}) ORDER BY at DESC`).all(t,...a)}function x(e,t,a,n,s,r=5){return e.prepare(`SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments
28
- WHERE channel = ? AND chat_id = ? AND at >= ? AND at <= ? ORDER BY at DESC LIMIT ?`).all(t,a,n,s,r)}var m=_(()=>{"use strict"});import{createRequire as L}from"module";import{mkdirSync as p}from"fs";import{dirname as A,resolve as D}from"path";function R(e){let t=String(e?.message??e),a=process.versions.modules,s=`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${a}).`;return/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(t)?`${t} ${s}`:`${t} ${s}`}function O(e=!1){if(u)return u;try{return u=I("better-sqlite3"),u}catch(t){return e||console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${R(t)}`),null}}function Q(e={}){if(e.disabled)return null;if(o)return o;let t=D(process.cwd(),e.path??".agentx/db.sqlite"),a=O(e.quiet);if(!a)return null;try{p(A(t),{recursive:!0});let n=new a(t);return n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL"),n.pragma("foreign_keys = ON"),X(n),o=n,o}catch(n){return e.quiet||console.error(`[storage/sqlite] openDb failed at ${t}: ${R(n)}`),null}}function X(e){e.exec(`
26
+ `)}function y(e,t){e.prepare("INSERT OR IGNORE INTO forge_comments (channel, chat_id, comment_id, agent_id, at) VALUES (?, ?, ?, ?, ?)").run(t.channel,t.chatId,t.commentId.slice(0,64),t.agentId?.slice(0,120)??null,t.at)}function x(e,t,a){return a.length===0?[]:e.prepare(`SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments
27
+ WHERE channel = ? AND chat_id IN (${a.map(()=>"?").join(",")}) ORDER BY at DESC`).all(t,...a)}function F(e,t,a,n,s,r=5){return e.prepare(`SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments
28
+ WHERE channel = ? AND chat_id = ? AND at >= ? AND at <= ? ORDER BY at DESC LIMIT ?`).all(t,a,n,s,r)}var m=_(()=>{"use strict"});import{createRequire as L}from"module";import{mkdirSync as p}from"fs";import{dirname as A,resolve as D}from"path";function R(e){let t=String(e?.message??e),a=process.versions.modules,s=`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${a}).`;return/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(t)?`${t} ${s}`:`${t} ${s}`}function O(e=!1){if(u)return u;try{return u=I("better-sqlite3"),u}catch(t){return e||console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${R(t)}`),null}}function W(e={}){if(e.disabled)return null;if(o)return o;let t=D(process.cwd(),e.path??".agentx/db.sqlite"),a=O(e.quiet);if(!a)return null;try{p(A(t),{recursive:!0});let n=new a(t);return n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL"),n.pragma("foreign_keys = ON"),X(n),o=n,o}catch(n){return e.quiet||console.error(`[storage/sqlite] openDb failed at ${t}: ${R(n)}`),null}}function X(e){e.exec(`
29
29
  CREATE TABLE IF NOT EXISTS schema_version (
30
30
  v INTEGER PRIMARY KEY
31
31
  );
@@ -196,10 +196,10 @@ import{a as _}from"./chunk-QIJLFPWE.js";function c(e){e.exec(`
196
196
  `},{v:13,sql:`
197
197
  ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;
198
198
  CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);
199
- `}],n=e.transaction(s=>{e.exec(s.sql),e.prepare("INSERT INTO schema_version (v) VALUES (?)").run(s.v)});for(let s of a)s.v>t&&n(s);T(e,"task_traces",h),T(e,"task_traces",f),T(e,"task_traces",g),T(e,"task_history",g),T(e,"task_traces",C),e.exec("CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL"),c(e),l(e)}function W(e,t,a){let n=Date.now(),r=e.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'").get().n<a,i=null;return r||(i=e.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'").get().n+1),e.prepare(`
199
+ `}],n=e.transaction(s=>{e.exec(s.sql),e.prepare("INSERT INTO schema_version (v) VALUES (?)").run(s.v)});for(let s of a)s.v>t&&n(s);T(e,"task_traces",h),T(e,"task_traces",f),T(e,"task_traces",g),T(e,"task_history",g),T(e,"task_traces",C),T(e,"task_traces",k),e.exec("CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL"),c(e),l(e)}function $(e,t,a){let n=Date.now(),r=e.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'").get().n<a,i=null;return r||(i=e.prepare("SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'").get().n+1),e.prepare(`
200
200
  INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)
201
201
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
202
- `).run(t.id,t.conversationId,t.agentId,t.summary,r?"active":"queued",i,n,r?n:null),{id:t.id,status:r?"active":"queued",position:i}}function $(e,t,a="done"){let n=Date.now();e.prepare(`
202
+ `).run(t.id,t.conversationId,t.agentId,t.summary,r?"active":"queued",i,n,r?n:null),{id:t.id,status:r?"active":"queued",position:i}}function K(e,t,a="done"){let n=Date.now();e.prepare(`
203
203
  UPDATE task_queue SET status = ?, finished_at = ?, position = NULL WHERE id = ?
204
204
  `).run(a,n,t);let s=e.prepare(`
205
205
  SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1
@@ -207,8 +207,8 @@ import{a as _}from"./chunk-QIJLFPWE.js";function c(e){e.exec(`
207
207
  UPDATE task_queue SET status = 'active', position = NULL, started_at = ? WHERE id = ?
208
208
  `).run(n,s.id);let r=e.prepare(`
209
209
  SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC
210
- `).all(),i=e.prepare("UPDATE task_queue SET position = ? WHERE id = ?");for(let E=0;E<r.length;E++)i.run(E+1,r[E].id)}}function K(e,t){let a=e.prepare("SELECT * FROM task_queue WHERE id = ?").get(t);return a?{id:a.id,conversationId:a.conversation_id,agentId:a.agent_id,summary:a.summary,status:a.status,position:a.position,createdAt:a.created_at,startedAt:a.started_at,finishedAt:a.finished_at}:null}function V(e,t,a=20){return e.prepare(`
210
+ `).all(),i=e.prepare("UPDATE task_queue SET position = ? WHERE id = ?");for(let E=0;E<r.length;E++)i.run(E+1,r[E].id)}}function V(e,t){let a=e.prepare("SELECT * FROM task_queue WHERE id = ?").get(t);return a?{id:a.id,conversationId:a.conversation_id,agentId:a.agent_id,summary:a.summary,status:a.status,position:a.position,createdAt:a.created_at,startedAt:a.started_at,finishedAt:a.finished_at}:null}function j(e,t,a=20){return e.prepare(`
211
211
  SELECT * FROM task_queue WHERE conversation_id = ?
212
212
  ORDER BY created_at DESC LIMIT ?
213
- `).all(t,a).map(s=>({id:s.id,conversationId:s.conversation_id,agentId:s.agent_id,summary:s.summary,status:s.status,position:s.position,createdAt:s.created_at,startedAt:s.started_at,finishedAt:s.finished_at}))}function j(e,t){let a=Date.now()-t*24*60*60*1e3,n=new Date(a).toISOString(),s=e.prepare("DELETE FROM task_history WHERE started_at < ?").run(n).changes??0,r=e.prepare("DELETE FROM rotations WHERE rotated_at < ?").run(n).changes??0,i=e.prepare("DELETE FROM route_traces WHERE at < ?").run(n).changes??0,E=e.prepare("DELETE FROM task_traces WHERE started_at < ?").run(a).changes??0,d=e.prepare("DELETE FROM forge_comments WHERE at < ?").run(a).changes??0;if(s+r+i+E+d>0)try{e.pragma("incremental_vacuum")}catch{}return{taskHistory:s,rotations:r,routeTraces:i,taskTraces:E,forgeComments:d}}function T(e,t,a){let n=new Set(e.prepare(`PRAGMA table_info(${t})`).all().map(s=>s.name));for(let[s,r]of a)if(!n.has(s))try{e.exec(`ALTER TABLE ${t} ADD COLUMN ${s} ${r}`)}catch(i){if(!/duplicate column name/i.test(String(i?.message)))throw i}}var I,o,u,h,f,g,C,k=_(()=>{"use strict";N();m();I=L(import.meta.url);h=[["resume_origin","TEXT"],["resume_attempt","INTEGER NOT NULL DEFAULT 0"],["resumed_from","TEXT"],["resume_decision","TEXT"],["resume_reason","TEXT"]],f=[["num_turns","INTEGER"],["injected_context","TEXT"]],g=[["person","TEXT"]],C=[["cost_usd","REAL"]]});export{U as a,b,v as c,M as d,N as e,S as f,y as g,x as h,m as i,Q as j,W as k,$ as l,K as m,V as n,j as o,g as p,T as q,k as r};
214
- //# sourceMappingURL=chunk-UEEB3UTU.js.map
213
+ `).all(t,a).map(s=>({id:s.id,conversationId:s.conversation_id,agentId:s.agent_id,summary:s.summary,status:s.status,position:s.position,createdAt:s.created_at,startedAt:s.started_at,finishedAt:s.finished_at}))}function z(e,t){let a=Date.now()-t*24*60*60*1e3,n=new Date(a).toISOString(),s=e.prepare("DELETE FROM task_history WHERE started_at < ?").run(n).changes??0,r=e.prepare("DELETE FROM rotations WHERE rotated_at < ?").run(n).changes??0,i=e.prepare("DELETE FROM route_traces WHERE at < ?").run(n).changes??0,E=e.prepare("DELETE FROM task_traces WHERE started_at < ?").run(a).changes??0,d=e.prepare("DELETE FROM forge_comments WHERE at < ?").run(a).changes??0;if(s+r+i+E+d>0)try{e.pragma("incremental_vacuum")}catch{}return{taskHistory:s,rotations:r,routeTraces:i,taskTraces:E,forgeComments:d}}function T(e,t,a){let n=new Set(e.prepare(`PRAGMA table_info(${t})`).all().map(s=>s.name));for(let[s,r]of a)if(!n.has(s))try{e.exec(`ALTER TABLE ${t} ADD COLUMN ${s} ${r}`)}catch(i){if(!/duplicate column name/i.test(String(i?.message)))throw i}}var I,o,u,h,f,g,C,k,U=_(()=>{"use strict";N();m();I=L(import.meta.url);h=[["resume_origin","TEXT"],["resume_attempt","INTEGER NOT NULL DEFAULT 0"],["resumed_from","TEXT"],["resume_decision","TEXT"],["resume_reason","TEXT"]],f=[["num_turns","INTEGER"],["injected_context","TEXT"]],g=[["person","TEXT"]],C=[["cost_usd","REAL"]],k=[["sender","TEXT"]]});export{b as a,v as b,M as c,q as d,N as e,y as f,x as g,F as h,m as i,W as j,$ as k,K as l,V as m,j as n,z as o,g as p,T as q,U as r};
214
+ //# sourceMappingURL=chunk-N47Y5ADQ.js.map